Example usage for java.nio.file Path resolveSibling

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

Introduction

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

Prototype

default Path resolveSibling(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this path's #getParent parent path in exactly the manner specified by the #resolveSibling(Path) resolveSibling method.

Usage

From source file:org.apache.taverna.databundle.DataBundles.java

protected static Path withExtension(Path path, String extension) {
    String filename = path.getFileName().toString();
    return path.resolveSibling(withExtensionFilename(filename, extension));
}

From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java

private static String changeImageUrls(String contextPath, String cssSourceCode, String cssPath) {
    Matcher matcher = CSS_URL_PATTERN.matcher(cssSourceCode);
    StringBuffer sb = new StringBuffer();

    Path basePath = Paths.get(contextPath + cssPath);

    while (matcher.find()) {
        String url = matcher.group(2);
        url = url.trim();//  www  .j a v  a2s . co  m
        if (url.equals("#default#VML") || url.startsWith("data:")) {
            continue;
        }
        Path pa = basePath.resolveSibling(url).normalize();
        matcher.appendReplacement(sb, "$1" + pa.toString().replace("\\", "/") + "$3$4");
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.apache.taverna.databundle.DataBundles.java

private static Path anyExtension(Path directory, String fileName) throws IOException {
    Path path = directory.resolve(fileName);

    // Prefer the fileName as it is
    if (Files.exists(path))
        return path;
    // Strip any existing extension
    String fileNameNoExt = filenameWithoutExtension(path);
    Path withoutExt = path.resolveSibling(fileNameNoExt);
    if (Files.exists(withoutExt))
        return withoutExt;

    // Check directory for path.*
    for (Path p : newDirectoryStream(directory, fileNameNoExt + ".*"))
        /*//from   ww w. jav  a2  s  .c om
         * We'll just return the first one
         * 
         * TODO: Should we fail if there's more than one?
         */
        return p;

    /*
     * Nothing? Then let's give the existing one; perhaps it is to be
     * created.
     */
    return path;
}

From source file:at.tugraz.sss.serv.SSFileU.java

private static void formatAudioAndVideoFileName(final File file) throws Exception {

    final Path pathToFile = file.toPath();
    String fileName = pathToFile.getFileName().toString().toLowerCase();
    final SSFileExtE fileExt = SSFileExtE.ext(fileName);

    if (!SSFileExtE.isAudioOrVideoFileExt(fileExt)) {
        return;/*  ww  w.j  a v  a  2 s .com*/
    }

    fileName = SSStrU.replaceAllBlanksSpecialCharactersDoubleDots(fileName, SSStrU.underline);

    try {
        Files.move(pathToFile, pathToFile.resolveSibling(fileName));
    } catch (FileAlreadyExistsException error) {
        System.out.println("file " + pathToFile.resolveSibling(fileName) + " already exists!");
    }
}

From source file:org.apache.taverna.databundle.DataBundles.java

public static ErrorDocument getError(Path path) throws IOException {
    if (path == null)
        return null;

    Path errorPath = withExtension(path, DOT_ERR);
    List<String> errorList = readAllLines(errorPath, UTF8);
    int split = errorList.indexOf("");
    if (split == -1 || errorList.size() <= split)
        throw new IOException("Invalid error document: " + errorPath);

    ErrorDocument errorDoc = new ErrorDocument();

    for (String cause : errorList.subList(0, split))
        errorDoc.getCausedBy().add(path.resolveSibling(cause));

    errorDoc.setMessage(errorList.get(split + 1));

    StringBuilder errorTrace = new StringBuilder();
    for (String line : errorList.subList(split + 2, errorList.size())) {
        errorTrace.append(line);/* ww  w  . j  a v a  2  s  .c o m*/
        errorTrace.append("\n");
    }
    if (errorTrace.length() > 0)
        // Delete last \n
        errorTrace.deleteCharAt(errorTrace.length() - 1);
    errorDoc.setTrace(errorTrace.toString());
    return errorDoc;
}

From source file:com.reactive.hzdfs.dll.JarFileSharingService.java

@Override
protected FileChunkHandler newWriteHandler(String dirPath) throws IOException {
    return new BufferedStreamChunkHandler(dirPath) {
        /**//from   w  ww.j  ava 2s  .  c o  m
         * Override the default behaviour to keep a backup
         * @throws IOException 
         */
        @Override
        protected void moveExistingFile() throws IOException {
            //super.moveExistingFile();

            try {
                if (file.exists()) {
                    Path fp = file.toPath();
                    Path backupFile = Files.move(fp,
                            fp.resolveSibling(file.getName() + ".bkp."
                                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())),
                            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

                    log.info("Backup file created- " + backupFile);
                }

                file.createNewFile();
            } catch (IOException e) {
                log.warn("Backup not taken. Going with default replace and copy. error => " + e.getMessage());
                log.debug("", e);
                super.moveExistingFile();
            }

        }
    };
}

From source file:com.kumarvv.setl.Setl.java

/**
 * load dataSources from default db.json file when def file skips them
 *
 * @param def/* ww  w. j  a  v  a 2s. co m*/
 */
protected void loadDataStores(final Def def) {
    if (def == null || def.getFilePath() == null) {
        return;
    }

    Path dbPath = def.getFilePath().resolveSibling("db.json");
    if (dbPath == null || !dbPath.toFile().exists()) {
        // resolve from parent folders
        Path parent = def.getFilePath().getParent();
        while (parent != null) {
            dbPath = parent.resolveSibling("db.json");
            if (dbPath != null && dbPath.toFile().exists()) {
                break;
            }
            parent = parent.getParent();
        }
        if (dbPath == null || !dbPath.toFile().exists()) {
            return;
        }
    }

    try {
        Def dbDef = new ObjectMapper().readValue(dbPath.toFile(), Def.class);

        if (def.getFromDS() == null && dbDef.getFromDS() != null) {
            def.setFromDS(new DS());
            def.getFromDS().setUrl(dbDef.getFromDS().getUrl());
            def.getFromDS().setUsername(dbDef.getFromDS().getUsername());
            def.getFromDS().setPassword(dbDef.getFromDS().getPassword());
        }
        if (def.getToDS() == null && dbDef.getToDS() != null) {
            def.setToDS(new DS());
            def.getToDS().setUrl(dbDef.getToDS().getUrl());
            def.getToDS().setUsername(dbDef.getToDS().getUsername());
            def.getToDS().setPassword(dbDef.getToDS().getPassword());
        }
    } catch (Exception e) {
        Logger.error("DB.json error: {}", e.getMessage());
        // just ignore
    }
}

From source file:cz.muni.fi.editor.typemanager.TypeServiceImpl.java

private void createBackup(Path target) throws IOException {
    if (Files.exists(target)) {
        String newName = getBaseName(target.getFileName().toString()) + "."
                + LocalDateTime.now().format(formatter) + ".xml";

        Files.move(target, target.resolveSibling(newName));

        Files.createFile(target);
    }//from  w  w w.  ja  v a 2  s. c om
}

From source file:net.sf.jabref.logic.exporter.FileSaveSession.java

@Override
public void commit(Path file) throws SaveException {
    if (file == null) {
        return;//  ww  w  .j a v a 2  s . c  o  m
    }
    if (backup && Files.exists(file)) {
        Path fileName = file.getFileName();
        Path backupFile = file.resolveSibling(fileName + BACKUP_EXTENSION);
        try {
            FileUtil.copyFile(file.toFile(), backupFile.toFile(), true);
        } catch (IOException ex) {
            LOGGER.error("Problem copying file", ex);
            throw SaveException.BACKUP_CREATION;
        }
    }
    try {
        if (useLockFile) {
            try {
                if (FileBasedLock.createLockFile(file)) {
                    // Oops, the lock file already existed. Try to wait it out:
                    if (!FileBasedLock.waitForFileLock(file, 10)) {
                        throw SaveException.FILE_LOCKED;
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Error when creating lock file.", ex);
            }
        }

        FileUtil.copyFile(temporaryFile.toFile(), file.toFile(), true);
    } catch (IOException ex2) {
        // If something happens here, what can we do to correct the problem? The file is corrupted, but we still
        // have a clean copy in tmp. However, we just failed to copy tmp to file, so it's not likely that
        // repeating the action will have a different result.
        // On the other hand, our temporary file should still be clean, and won't be deleted.
        throw new SaveException("Save failed while committing changes: " + ex2.getMessage(),
                Localization.lang("Save failed while committing changes: %0", ex2.getMessage()));
    } finally {
        if (useLockFile) {
            FileBasedLock.deleteLockFile(file);
        }
    }
    try {
        Files.delete(temporaryFile);
    } catch (IOException e) {
        LOGGER.warn("Cannot delete temporary file", e);
    }
}

From source file:es.upv.grycap.coreutils.fiber.http.HttpDataFetcher.java

/**
 * Allows fetching and saving a bunch of objects to the specified directory from a server that uses a REST or REST-like API 
 * where each object is retrieved from the URL formed appending the object's identifier to the path of the the base URL, and 
 * optionally from a server that uses a parameter to identify the objects. Supports additional configuration options to name
 * the fetched objects./*  w ww  . j av  a2 s.  c  o m*/
 * @param baseUrl - base URL from where the objects will be fetched
 * @param queryParam - if defined, a query parameter will be appended to the base URL with the identifier of the request
 * @param ids - a list with the identifiers of the all requests that will be attempted
 * @param prefix - optionally prepend this prefix to the filenames of the saved files
 * @param suffix - optionally append this suffix to the filenames of the saved files
 * @param outdir - directory where the files will be stored
 * @return A {@link CompletableFuture} that allows cancellation. Once each fetch operation is completed, its status is updated
 *         in the future with one of the possible values provided by the enumeration {@link FetchStatus}.
 * @throws IOException If an error occurs during the execution of the method that prevents fetching or saving the files.
 */
public FecthFuture fetchToDir(final URL baseUrl, final @Nullable String queryParam, final List<String> ids,
        final @Nullable String prefix, final @Nullable String suffix, final File outdir) throws IOException {
    // check mandatory parameters
    requireNonNull(baseUrl, "A valid URL expected");
    final FecthFuture toBeCompleted = new FecthFuture(
            requireNonNull(ids, "A valid list of identifiers expected").stream().map(StringUtils::trimToNull)
                    .filter(Objects::nonNull).distinct().collect(Collectors.toList()));
    requireNonNull(outdir, "A valid output directory expected");
    checkArgument((outdir.isDirectory() && outdir.canWrite()) || outdir.mkdirs(),
            new StringBuilder("Cannot write to the output directory: ").append(outdir.getAbsolutePath())
                    .toString());
    // get optional parameters
    final Optional<String> queryParam2 = ofNullable(trimToNull(queryParam));
    final String prefix2 = ofNullable(prefix).orElse("");
    final String suffix2 = ofNullable(suffix).orElse("");
    try (final CloseableHttpAsyncClient asyncHttpClient = createFiberCloseableHttpAsyncClient()) {
        asyncHttpClient.start();
        final UrlBuilder urlBuilder = getUrlBuilder(baseUrl);
        // an explanation is needed since this code is instrumented by Quasar and Comsat: requests are created during the first part of
        // this lambda expression (map), but they are not executed until the get() method is called in the second part of the expression
        // (forEach). Here that parallel stream is used to block and wait for the requests to complete. In case that a single stream is
        // used, each request will be created and executed sequentially. Therefore, the alternative to parallel stream is to separate
        // the lambda expression in two loops, creating the requests in the first loop and calling get() in the second one.
        toBeCompleted.monList.parallelStream().map(m -> {
            try {
                // create output file
                final File outfile = new File(outdir,
                        new StringBuilder(prefix2).append(m.id).append(suffix2).append(".partial").toString());
                checkState(outfile.createNewFile(), new StringBuilder("Cannot create the output file: ")
                        .append(outfile.getAbsolutePath()).toString());
                // create the HTTP request               
                final HttpHost target = URIUtils.extractHost(baseUrl.toURI());
                final HttpRequest request = new BasicHttpRequest("GET",
                        urlBuilder.buildRelativeUrl(queryParam2.isPresent() ? null : m.id,
                                queryParam2.isPresent() ? of(queryParam2.get(), m.id) : null));
                final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(target, request);
                // create the consumer
                final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(outfile) {
                    @Override
                    protected File process(final HttpResponse response, final File file,
                            final ContentType contentType) throws Exception {
                        final StatusLine status = response.getStatusLine();
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug(
                                    new StringBuilder("Got file: statusCode=").append(status.getStatusCode())
                                            .append(", file=").append(file.getAbsolutePath()).toString());
                        if (status.getStatusCode() != HttpStatus.SC_OK)
                            throw new ClientProtocolException(
                                    new StringBuilder("Object fetch failed: ").append(status).toString());
                        return file;
                    }
                };
                // prepare request
                m.future = asyncHttpClient.execute(producer, consumer, new FutureCallback<File>() {
                    @Override
                    public void cancelled() {
                        toBeCompleted.update(m.id, FetchStatus.CANCELLED);
                        LOGGER.info("Task cancelled");
                    }

                    @Override
                    public void completed(final File result) {
                        try {
                            final Path path = result.toPath();
                            Files.move(path, path.resolveSibling(removeEnd(result.getName(), ".partial")),
                                    REPLACE_EXISTING);
                            toBeCompleted.update(m.id, FetchStatus.COMPLETED);
                        } catch (IOException ex) {
                            toBeCompleted.update(m.id, FetchStatus.FAILED);
                            LOGGER.error("Fecth failed to move file to its final destination with error", ex);
                        }
                    }

                    @Override
                    public void failed(final Exception ex) {
                        toBeCompleted.update(m.id, FetchStatus.FAILED);
                        LOGGER.error("Fecth failed with error", ex);
                    }
                });
            } catch (Exception e) {
                LOGGER.error(new StringBuilder("Failed to fetch object with id: ").append(m.id).toString(), e);
            }
            return m;
        }).forEach(m -> {
            try {
                // submit requests and wait for completion
                m.future.get();
            } catch (Exception ignore) {
                /* exceptions are handled in the callback functions */ }
        });
    }
    return toBeCompleted;
}