Example usage for java.nio.file Path resolve

List of usage examples for java.nio.file Path resolve

Introduction

In this page you can find the example usage for java.nio.file Path resolve.

Prototype

default Path resolve(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the #resolve(Path) resolve method.

Usage

From source file:cool.pandora.modeller.ui.handlers.iiif.UploadBagHandler.java

@Override
public void execute() {
    final String message = ApplicationContextUtil.getMessage("bag.message.fileuploaded");
    final DefaultBag bag = bagView.getBag();
    final List<String> payload = bag.getPayloadPaths();
    final Map<String, BagInfoField> map = bag.getInfo().getFieldMap();
    final String basePath = AbstractBagConstants.DATA_DIRECTORY;
    final Path rootDir = bagView.getBagRootPath().toPath();
    for (final String filePath : payload) {
        final String filename = BaggerFileEntity.removeBasePath(basePath, filePath);
        final URI destinationURI = IIIFObjectURI.getDestinationURI(map, filename);
        final Path absoluteFilePath = rootDir.resolve(filePath);
        final File resourceFile = absoluteFilePath.toFile();
        try {//from  w  w  w  .  j av a 2s .  co m
            final InputStream targetStream = new FileInputStream(resourceFile);
            final String contentType = ImageIOUtil.getImageMIMEType(resourceFile);
            try {
                ModellerClient.doStreamPut(destinationURI, targetStream, contentType);
                ApplicationContextUtil.addConsoleMessage(message + " " + destinationURI);
            } catch (final ModellerClientFailedException e) {
                ApplicationContextUtil.addConsoleMessage(getMessage(e));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
    bagView.getControl().invalidate();
}

From source file:at.tfr.securefs.process.ProcessFilesTest.java

Path generateSomeFile(final Path rootDir) throws IOException {
    Path someFile = null;//  w w w .  j ava  2s . c o m
    Path subDir = rootDir;
    for (int i = 0; i < MAX_DIR_DEPTH; i++) {
        subDir = Files.createDirectories(subDir.resolve(SUBDIR_PFX + i));
        someFile = subDir.resolve(FILE_PFX + i + "_" + (MAX_FILE_COUNT - 1) + FILE_END);
    }
    return someFile;
}

From source file:com.spotify.scio.util.RemoteFileUtil.java

private Path getDestination(URI src) throws IOException {
    String scheme = src.getScheme();
    if (scheme == null) {
        scheme = "file";
    }/*from w w w.j  av a 2s .c o  m*/

    // Sparkey expects a pair of ".spi" and ".spl" files with the same path. Hash URI prefix
    // before filename so that URIs with the same remote path have the same local one. E.g.
    // gs://bucket/path/data.spi -> /tmp/fd-gs-a1b2c3d4/data.spi
    // gs://bucket/path/data.spl -> /tmp/fd-gs-a1b2c3d4/data.spl
    String path = src.toString();
    int idx = path.lastIndexOf('/');
    String hash = Hashing.sha1().hashString(path.substring(0, idx), Charsets.UTF_8).toString().substring(0,
            HASH_LENGTH);
    String filename = path.substring(idx + 1);

    String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
    Path parent = Paths.get(tmpDir, String.format("fd-%s-%s", scheme, hash));
    Files.createDirectories(parent);
    return parent.resolve(filename);
}

From source file:de.unirostock.sems.caroweb.Converter.java

private void checkout(HttpServletRequest request, HttpServletResponse response, Path storage, String req)
        throws ServletException, IOException {
    Path target = storage.resolve(req).toAbsolutePath().normalize();
    if (!target.startsWith(storage) || !Files.exists(target)) {
        error(request, response, "you're not allowed to download that file.");
        return;// w ww  . j  a  v a2s  .c  o m
    }

    try {
        String mime = target.toString().endsWith("omex") ? "application/zip"
                : "application/vnd.wf4ever.robundle+zip";

        response.reset();
        response.setBufferSize(CaRoWebutils.DEFAULT_BUFFER_SIZE);
        response.setContentType(mime);
        response.setHeader("Content-Length", String.valueOf(target.toFile().length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + req + "\"");
        response.setHeader("Expires", CaRoWebutils.downloadDateFormater
                .format(new Date(System.currentTimeMillis() + CaRoWebutils.CACHE_TIME * 1000)));
        response.setHeader("Cache-Control", "max-age=" + CaRoWebutils.CACHE_TIME);
        response.setHeader("Last-Modified", CaRoWebutils.downloadDateFormater
                .format(new Date(Files.getLastModifiedTime(target).toMillis())));
        response.setHeader("ETag", GeneralTools.hash(target + "-" + Files.getLastModifiedTime(target)));

        BufferedInputStream input = new BufferedInputStream(new FileInputStream(target.toFile()),
                CaRoWebutils.DEFAULT_BUFFER_SIZE);
        BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
                CaRoWebutils.DEFAULT_BUFFER_SIZE);

        // pass the stream to client
        byte[] buffer = new byte[CaRoWebutils.DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        input.close();
        output.close();

        return;
    } catch (IOException e) {
        // whoops, that's our fault. shouldn't happen. hopefully.
        LOGGER.error("unable to dump file " + target + " (at least not in an expected form)");
    }
    error(request, response, "couldn't dump file");
}

From source file:edu.mit.lib.handbag.Controller.java

private void transmitBag() {
    try {//from w w  w . j  a v  a 2 s.  c om
        URI destUri = new URL(workflowChoiceBox.getValue().getDestinationUrl()).toURI();
        String pkgFormat = workflowChoiceBox.getValue().getPackageFormat();
        boolean localDest = destUri.getScheme().startsWith("file");
        Path destDir = Paths.get(destUri);
        Filler filler = localDest ? new Filler(destDir.resolve(bagName)) : new Filler();
        // add payload files
        for (TreeItem ti : payloadTreeView.getRoot().getChildren()) {
            PathRef pr = (PathRef) ti.getValue();
            if (pr.getRelPath().length() > 0) {
                filler.payload(pr.getRelPath() + pr.getPath().getFileName(), pr.getPath());
            } else {
                filler.payload(pr.getPath());
            }
        }
        // add metadata (currently only bag-info properties supported)
        for (PropertySheet.Item mdItem : metadataPropertySheet.getItems()) {
            MetadataItem item = (MetadataItem) mdItem;
            if (item.getValue() != null && item.getValue().length() > 0) {
                filler.metadata(item.getRealName(), item.getValue());
            }
        }
        if (localDest) {
            filler.toPackage(pkgFormat);
        } else {
            // send to URL - TODO
        }
        reset(true);
    } catch (IOException | URISyntaxException exp) {
    }
}

From source file:dk.dma.msiproxy.common.repo.RepositoryService.java

/**
 * Creates two levels of sub-folders within the {@code rootFolder} based on
 * a MD5 hash of the {@code target}./*from w w w.  j av  a 2s.com*/
 *
 * @param rootFolder the root folder within the repository root
 * @param target the target name used for the hash
 * @param includeTarget whether to create a sub-folder for the target or not
 * @param createFolders whether or not to create the folders
 * @return the sub-folder associated with the target
 */
public Path getHashedSubfolder(String rootFolder, String target, boolean includeTarget, boolean createFolders)
        throws IOException {
    byte[] bytes = target.getBytes("utf-8");

    // MD5 hash the ID
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("This should never happen");
    }
    md.update(bytes);
    bytes = md.digest();
    String hash = String.valueOf(Integer.toHexString(bytes[0] & 0xff));
    while (hash.length() < 2) {
        hash = "0" + hash;
    }

    Path folder = getRepoRoot();

    // Add the root folder
    if (StringUtils.isNotBlank(rootFolder)) {
        folder = folder.resolve(rootFolder);
    }

    // Add two hashed sub-folder levels
    folder = folder.resolve(hash.substring(0, 1)).resolve(hash.substring(0, 2));

    // Check if we should create a sub-folder for the target as well
    if (includeTarget) {
        folder = folder.resolve(target);
    }

    // Create the folder if it does not exist
    if (createFolders && !Files.exists(folder)) {
        Files.createDirectories(folder);
    }
    return folder;
}

From source file:at.ac.univie.isc.asio.platform.FileSystemConfigStore.java

/**
 * @param root base working directory//from w  w w .ja  v  a  2  s .  c om
 * @param timeout maximum time allowed to acquire internal lock
 */
public FileSystemConfigStore(final Path root, final Timeout timeout) {
    this.timeout = timeout;
    log.info(Scope.SYSTEM.marker(), "initializing in <{}>", root);
    lock = new ReentrantLock();
    try {
        this.root = Files.createDirectories(root.resolve(STORE_FOLDER)).toAbsolutePath();
        touch();
    } catch (IOException cause) {
        throw new FileSystemAccessFailure("cannot create configuration store folder", cause);
    }
}

From source file:org.tallison.cc.CCGetter.java

private void fetch(CCIndexRecord r, Path rootDir, BufferedWriter writer) throws IOException {
    Path targFile = rootDir.resolve(r.getDigest().substring(0, 2) + "/" + r.getDigest());

    if (Files.isRegularFile(targFile)) {
        writeStatus(r, FETCH_STATUS.ALREADY_IN_REPOSITORY, writer);
        logger.info("already retrieved:" + targFile.toAbsolutePath());
        return;/* w  w w  . j  av  a 2  s.co m*/
    }

    String url = AWS_BASE + r.getFilename();
    URI uri = null;
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        logger.warn("Bad url: " + url);
        writeStatus(r, FETCH_STATUS.BAD_URL, writer);
        return;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpHost target = new HttpHost(uri.getHost());
    String urlPath = uri.getRawPath();
    if (uri.getRawQuery() != null) {
        urlPath += "?" + uri.getRawQuery();
    }
    HttpGet httpGet = null;
    try {
        httpGet = new HttpGet(urlPath);
    } catch (Exception e) {
        logger.warn("bad path " + uri.toString(), e);
        writeStatus(r, FETCH_STATUS.BAD_URL, writer);
        return;
    }
    if (proxyHost != null && proxyPort > -1) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);
    }
    httpGet.addHeader("Range", r.getOffsetHeader());
    HttpCoreContext coreContext = new HttpCoreContext();
    CloseableHttpResponse httpResponse = null;
    URI lastURI = null;
    try {
        httpResponse = httpClient.execute(target, httpGet, coreContext);
        RedirectLocations redirectLocations = (RedirectLocations) coreContext
                .getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
        if (redirectLocations != null) {
            for (URI redirectURI : redirectLocations.getAll()) {
                lastURI = redirectURI;
            }
        } else {
            lastURI = httpGet.getURI();
        }
    } catch (IOException e) {
        logger.warn("IOException for " + uri.toString(), e);
        writeStatus(r, FETCH_STATUS.FETCHED_IO_EXCEPTION, writer);
        return;
    }
    lastURI = uri.resolve(lastURI);

    if (httpResponse.getStatusLine().getStatusCode() != 200
            && httpResponse.getStatusLine().getStatusCode() != 206) {
        logger.warn("Bad status for " + uri.toString() + " : " + httpResponse.getStatusLine().getStatusCode());
        writeStatus(r, FETCH_STATUS.FETCHED_NOT_200, writer);
        return;
    }
    Path tmp = null;
    Header[] headers = null;
    boolean isTruncated = false;
    try {
        //this among other parts is plagiarized from centic9's CommonCrawlDocumentDownload
        //probably saved me hours.  Thank you, Dominik!
        tmp = Files.createTempFile("cc-getter", "");
        try (InputStream is = new GZIPInputStream(httpResponse.getEntity().getContent())) {
            WARCRecord warcRecord = new WARCRecord(new FastBufferedInputStream(is), "", 0);
            ArchiveRecordHeader archiveRecordHeader = warcRecord.getHeader();
            if (archiveRecordHeader.getHeaderFields().containsKey(WARCConstants.HEADER_KEY_TRUNCATED)) {
                isTruncated = true;
            }
            headers = LaxHttpParser.parseHeaders(warcRecord, "UTF-8");

            Files.copy(warcRecord, tmp, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        writeStatus(r, null, headers, 0L, isTruncated, FETCH_STATUS.FETCHED_IO_EXCEPTION_READING_ENTITY,
                writer);
        deleteTmp(tmp);
        return;
    }

    String digest = null;
    long tmpLength = 0l;
    try (InputStream is = Files.newInputStream(tmp)) {
        digest = base32.encodeAsString(DigestUtils.sha1(is));
        tmpLength = Files.size(tmp);
    } catch (IOException e) {
        writeStatus(r, null, headers, tmpLength, isTruncated, FETCH_STATUS.FETCHED_IO_EXCEPTION_SHA1, writer);
        logger.warn("IOException during digesting: " + tmp.toAbsolutePath());
        deleteTmp(tmp);
        return;
    }

    if (Files.exists(targFile)) {
        writeStatus(r, digest, headers, tmpLength, isTruncated, FETCH_STATUS.ALREADY_IN_REPOSITORY, writer);
        deleteTmp(tmp);
        return;
    }
    try {
        Files.createDirectories(targFile.getParent());
        Files.copy(tmp, targFile);
    } catch (IOException e) {
        writeStatus(r, digest, headers, tmpLength, isTruncated,
                FETCH_STATUS.FETCHED_EXCEPTION_COPYING_TO_REPOSITORY, writer);
        deleteTmp(tmp);

    }
    writeStatus(r, digest, headers, tmpLength, isTruncated, FETCH_STATUS.ADDED_TO_REPOSITORY, writer);
    deleteTmp(tmp);
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Before
public void createSymlinksScenario() throws IOException, URISyntaxException {
    Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("windows"));

    /**/* w  ww. j a v  a 2  s  . c  o  m*/
     * Creating following structure for test:
     *
     * $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/page.html
     * $ROOT_PATH/newDir/innerDir/
     * $ROOT_PATH/newDir/innerDir/page.html
     * $ROOT_PATH/newSymlink -> $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/innerSymlink -> $ROOT_PATH/newDir/innerDir/
     *
     */
    Path filePath = Paths.get(getClass().getResource("page.html").toURI());
    Path rootPath = filePath.getParent();

    Path newDir = rootPath.resolve("newDir");
    Files.createDirectories(newDir);

    Path innerDir = newDir.resolve("innerDir");
    Files.createDirectories(innerDir);

    Files.copy(filePath, newDir.resolve(filePath.getFileName()));
    Files.copy(filePath, innerDir.resolve(filePath.getFileName()));

    Path newSymlink = rootPath.resolve("newSymlink");

    Files.createSymbolicLink(newSymlink, newDir);

    Path innerSymlink = newDir.resolve("innerSymlink");

    Files.createSymbolicLink(innerSymlink, innerDir);
}

From source file:io.spikex.core.integration.MainTest.java

@Test
public void testConfModified() throws InterruptedException, ResourceException, IOException {
    Path homePath = Paths.get("build/resources/test/node1");
    System.setProperty("spikex.home", homePath.toAbsolutePath().toString());
    new Main().start(new String[0]);
    ////from   w  ww.j  av a  2 s  .com
    // Update Spike.x configuration (simulate update of module)
    //
    Thread.sleep(5500L); // Wait 5.5 seconds - re-init is throttled
    URI base = homePath.resolve("conf").toAbsolutePath().toUri();
    YamlResource confResource = YamlResource.builder(base).name("spikex").version(Version.none()).build()
            .load();

    List<Map> modules = new ArrayList();
    Map<String, String> module1 = new HashMap();
    module1.put("id", "io.spikex~spikex-test2~0.8.0");
    modules.add(module1);
    Map<String, String> module2 = new HashMap();
    module2.put("id", "io.spikex~spikex-test1~0.8.0");
    modules.add(module2);

    YamlDocument conf = confResource.getData().get(0);
    conf.setValue("modules", modules);
    confResource.save();
    Thread.sleep(2000L); // Wait a while so that file change is noticed
}