Example usage for java.nio.file StandardCopyOption REPLACE_EXISTING

List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING

Introduction

In this page you can find the example usage for java.nio.file StandardCopyOption REPLACE_EXISTING.

Prototype

StandardCopyOption REPLACE_EXISTING

To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.

Click Source Link

Document

Replace an existing file if it exists.

Usage

From source file:org.restcomm.connect.tts.awspolly.AWSPollySpeechSyntetizer.java

private URI synthesize(final Object message) throws IOException, SpeechSynthesizerException {

    //retrieve resquest message
    final org.restcomm.connect.tts.api.SpeechSynthesizerRequest request = (org.restcomm.connect.tts.api.SpeechSynthesizerRequest) message;

    //retrieve gender, language and text message
    final String gender = request.gender();
    final String language = request.language();
    final String text = request.text();

    //generate file hash name
    final String hash = HashGenerator.hashMessage(gender, language, text);

    if (language == null) {
        if (logger.isInfoEnabled()) {
            logger.info("There is no suitable speaker to synthesize " + request.language());
        }//  w w w.j a  v a  2 s.com
        throw new IllegalArgumentException("There is no suitable language to synthesize " + request.language());
    }

    // Create speech synthesis request.
    SynthesizeSpeechRequest pollyRequest = new SynthesizeSpeechRequest().withText(text)
            .withVoiceId(VoiceId.valueOf(this.retrieveSpeaker(gender, language)))
            .withOutputFormat(OutputFormat.Pcm).withSampleRate("8000");
    //retrieve audio result
    SynthesizeSpeechResult result = pollyClient.synthesizeSpeech(pollyRequest);

    //create a temporary file
    File srcFile = new File(System.getProperty("java.io.tmpdir") + File.separator + hash + ".pcm");
    File dstFile = new File(System.getProperty("java.io.tmpdir") + File.separator + hash + ".wav");

    //save temporary pcm file
    Files.copy(result.getAudioStream(), srcFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

    //convert pcm file to wav
    new PcmToWavConverterUtils().rawToWave(srcFile, dstFile);

    //return file URI
    return dstFile.toURI();
}

From source file:ch.cyberduck.core.Local.java

public void rename(final Local renamed) throws AccessDeniedException {
    try {/*from w w  w  . j  a v  a 2  s. c  om*/
        Files.move(Paths.get(path), Paths.get(renamed.getAbsolute()), StandardCopyOption.REPLACE_EXISTING);
        path = renamed.getAbsolute();
    } catch (IOException e) {
        throw new LocalAccessDeniedException(String.format("Rename failed for %s", renamed), e);
    }
}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

/**
 * Writes file to disk and copy the contents of the input byte array.
 *
 * @param file   a Path with file path./* ww  w. ja  va2  s.c  om*/
 * @param zipUrl a remote zip url to be saved as file
 * @throws IOException
 */
private void writeZipFile(final Path file, final URL zipUrl) throws URISyntaxException, IOException {
    final URI resourceURI = zipUrl.toURI();
    final Map<String, String> env = new HashMap<>();
    final String resourceUriStr = URLDecoder.decode(resourceURI.toString(), "UTF-8");
    final int indexOfSeparator = resourceUriStr.indexOf("!");
    final ZipFileSystem fs = (ZipFileSystem) FileSystems.newFileSystem(resourceURI, env);
    final Path path = fs.getPath(resourceUriStr.substring(indexOfSeparator + 1));
    try {
        Files.copy(path, file, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        fs.close();
    }
}

From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

public Result saveChangesXML(String changesXMLFileName) {
    try {//from  w ww  .j a va2 s . c om
        File tempFile = File.createTempFile(changesXMLFileName, "changes.xml");
        String changesXMLUrl = artifactsLocation + "/" + changesXMLFileName;
        System.out.println("Downloading " + changesXMLUrl);
        FileUtils.copyURLToFile(new URL(changesXMLUrl), tempFile);

        Path source = Paths.get((String) tempFile.getAbsolutePath());
        new File(new File("").getAbsolutePath() + "/" + Configuration.getInstance().getSavePath() + "/"
                + mcPackage.getPackageName()).mkdirs();
        Path destination = Paths.get(new File("").getAbsolutePath() + "/"
                + Configuration.getInstance().getSavePath() + "/" + mcPackage.getPackageName() + "/"
                + changesXMLFileName + "_" + mcPackage.getStatus() + "_" + System.currentTimeMillis());

        Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
        System.out.println(source.toString() + " renamed to " + destination.toAbsolutePath().toString());
        result.setResultMessage(destination.toAbsolutePath().toString());

    } catch (IOException ex) {
        Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        result.setResultCode("1");
        result.setResultMessage(ex.getMessage());
    }
    return result;
}

From source file:business.services.FileService.java

public File clone(File file) {
    try {/*from   w ww.  ja  v  a 2  s  . co m*/
        FileSystem fileSystem = FileSystems.getDefault();
        // source
        Path source = fileSystem.getPath(uploadPath, file.getFilename());
        // target
        Path path = fileSystem.getPath(uploadPath).normalize();
        String prefix = getBasename(file.getFilename());
        String suffix = getExtension(file.getFilename());
        Path target = Files.createTempFile(path, prefix, suffix).normalize();
        // copy
        log.info("Copying " + source + " to " + target + " ...");
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        // save clone
        File result = file.clone();
        result.setFilename(target.getFileName().toString());
        return save(result);
    } catch (IOException e) {
        log.error(e);
        throw new FileCopyError();
    }
}

From source file:com.streamsets.datacollector.cluster.EmrClusterProvider.java

void replaceFileInJar(String absolutePath, String fileToBeCopied) throws IOException {
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    URI uri = URI.create("jar:file:" + absolutePath);

    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Path externalTxtFile = Paths.get(fileToBeCopied);
        Path pathInZipfile = zipfs.getPath("cluster_sdc.properties");
        Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
    }/*w  w w.  jav a  2 s .  c  o  m*/
}

From source file:it.baeyens.arduino.managers.Manager.java

private static void loadLibraryIndex(boolean download) {
    try {/*www .  j  a v a  2 s  .c  om*/
        URL librariesUrl = new URL(Defaults.LIBRARIES_URL);
        String localFileName = Paths.get(librariesUrl.getPath()).getFileName().toString();
        Path librariesPath = Paths
                .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString());
        File librariesFile = librariesPath.toFile();
        if (!librariesFile.exists() || download) {
            librariesPath.getParent().toFile().mkdirs();
            Files.copy(librariesUrl.openStream(), librariesPath, StandardCopyOption.REPLACE_EXISTING);
        }
        if (librariesFile.exists()) {
            try (InputStreamReader reader = new InputStreamReader(new FileInputStream(librariesFile),
                    Charset.forName("UTF8"))) { //$NON-NLS-1$
                libraryIndex = new Gson().fromJson(reader, LibraryIndex.class);
                libraryIndex.resolve();
            }
        }
    } catch (IOException e) {
        Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to load library index", e)); //$NON-NLS-1$
    }

}

From source file:org.apache.drill.yarn.scripts.ScriptUtils.java

/**
 * Copy the standard scripts from source location to the mock distribution
 * directory.//from w ww .j a  v a 2s . c o m
 */

private void copyScripts(File sourceDir) throws IOException {
    File binDir = new File(testDrillHome, "bin");
    for (String script : ScriptUtils.scripts) {
        File source = new File(sourceDir, script);
        File dest = new File(binDir, script);
        copyFile(source, dest);
        dest.setExecutable(true);
    }

    // Create the "magic" wrapper script that simulates the Drillbit and
    // captures the output we need for testing.

    String wrapper = "wrapper.sh";
    File dest = new File(binDir, wrapper);
    try (InputStream is = getClass().getResourceAsStream("/" + wrapper)) {
        Files.copy(is, dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    dest.setExecutable(true);
}

From source file:org.flowerplatform.util.servlet.PublicResourcesServlet.java

/**
* @author Cristian Spiescu/*from  w ww  .  ja v a  2s  .  c o m*/
* @author Sebastian Solomon
* @author Cristina Constantinescu
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedFile = request.getPathInfo();
    if (logger.isTraceEnabled()) {
        logger.trace("Resource requested: {}", requestedFile);
    }

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        send404(request, response);
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.

    // solution for: .../icons/0%.png
    // The URL decoder expects the %to precede a character code
    // replace(%) with %25 before decoding
    // http://stackoverflow.com/questions/6067673/urldecoder-illegal-hex-characters-in-escape-pattern-for-input-string
    requestedFile = requestedFile.replaceAll("%(?![0-9a-fA-F]{2})", "%25");

    requestedFile = URLDecoder.decode(requestedFile, "UTF-8");
    if (requestedFile.startsWith(UtilConstants.PUBLIC_RESOURCES_PATH_PREFIX)) {
        requestedFile = requestedFile.substring(UtilConstants.PUBLIC_RESOURCES_PATH_PREFIX.length());
    }

    // this may be an attempt to see files that are not public, i.e. to go to the
    // parent. From my tests, when you put in the browser (or even telnet) something like
    // parent1/parent2/../bla, it seems to be automatically translated to parent1/bla. However,
    // I wanted to make sure that we are all right
    if (requestedFile.contains("..")) {
        send404(request, response);
        return;
    }

    // we need something like /plugin/file....
    int indexOfSecondSlash = requestedFile.indexOf('/', 1); // 1, i.e. skip the first index
    if (indexOfSecondSlash < 0) {
        send404(request, response);
        return;
    }

    // both variables are prefixed with /
    String plugin = requestedFile.substring(0, indexOfSecondSlash);
    String file = requestedFile.substring(indexOfSecondSlash);

    // if | is supplied => the file is a zip, and we want what's in it
    int indexOfZipSeparator = file.indexOf(UtilConstants.RESOURCE_PATH_SEPARATOR);
    String fileInsideZipArchive = null;
    if (indexOfZipSeparator >= 0 && indexOfZipSeparator < file.length() - 1) { // has | and | is not the last char in the string
        fileInsideZipArchive = file.substring(indexOfZipSeparator + 1);
        file = file.substring(0, indexOfZipSeparator);
    }

    String mapValue = null;
    String mapKey = null;

    // if the file is in a zip, search first in the Temp folder
    if (fileInsideZipArchive != null) {
        mapKey = createMapKey(file, fileInsideZipArchive).intern();
        if (useFilesFromTemporaryDirectory) {
            mapValue = tempFilesMap.get(mapKey);
        }
    } else {
        // we don't need synchronization if the file is not inside archive (so we don't use .intern)
        mapKey = createMapKey(file, fileInsideZipArchive);
    }

    synchronized (mapKey) {
        if (useFilesFromTemporaryDirectory) {
            if (fileInsideZipArchive != null) {
                if (mapValue != null) { // file exists in 'tempFilesMap'
                    if (getTempFile(mapValue).exists()) {
                        response.reset();
                        response.setBufferSize(DEFAULT_BUFFER_SIZE);
                        response.setContentType(fileInsideZipArchive);
                        InputStream input = new FileInputStream(getTempFilePath(mapValue));
                        OutputStream output = response.getOutputStream();
                        IOUtils.copy(input, output);
                        input.close();
                        output.close();
                        logger.debug("File {} served from temp", mapValue);
                        return;
                    } else { // temporary file was deleted from disk
                        logger.debug("File {} found to be missing from temp", mapValue);
                    }
                } else {
                    synchronized (this) {
                        counter++;
                        mapValue = counter + "";
                        tempFilesMap.put(mapKey, mapValue);
                        logger.debug("mapValue '{}' added", mapValue);
                    }
                }
            }
        }

        requestedFile = "platform:/plugin" + plugin + "/" + UtilConstants.PUBLIC_RESOURCES_DIR + file;

        // Get content type by filename from the file or file inside zip
        String contentType = getServletContext()
                .getMimeType(fileInsideZipArchive != null ? fileInsideZipArchive : file);

        // If content type is unknown, then set the default value.
        // For all content types, see:
        // http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(contentType);
        //        response.setHeader("Content-Length", String.valueOf(file.length()));
        //        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

        // Prepare streams.
        URL url;
        InputStream input = null;
        Closeable inputCloseable = null;
        OutputStream output = null;

        try {
            url = new URL(requestedFile);
            try {
                input = url.openConnection().getInputStream();
                inputCloseable = input;
            } catch (IOException e) {
                // may fail if the resource is not available
                send404(request, response);
                return;
            }

            if (fileInsideZipArchive != null) {
                // we need to look for a file in the archive
                Pair<InputStream, Closeable> pair = getInputStreamForFileWithinZip(input, fileInsideZipArchive);
                if (pair == null) {
                    // the file was not found; the input streams are closed in this case
                    send404(request, response);
                    return;
                }

                input = pair.a;
                inputCloseable = pair.b;

                if (useFilesFromTemporaryDirectory) {
                    // write the file from archive in Temp folder
                    if (!UtilConstants.TEMP_FOLDER.exists()) {
                        UtilConstants.TEMP_FOLDER.mkdir();
                    }

                    Files.copy(input, getTempFile(mapValue).toPath(), StandardCopyOption.REPLACE_EXISTING);
                    logger.debug("file '{}' was writen in temp", mapValue);

                    input.close();
                    input = new FileInputStream(getTempFilePath(mapValue));
                }
            }

            output = response.getOutputStream();

            // according to the doc, no need to use Buffered..., because the method buffers internally
            IOUtils.copy(input, output);

        } finally {
            // Gently close streams.
            close(output);
            close(inputCloseable);
            close(input);
        }
    }
}

From source file:org.onosproject.yangutils.utils.io.impl.YangIoUtils.java

/**
 * Copies YANG files to the current project's output directory.
 *
 * @param yangFileInfo list of YANG files
 * @param outputDir project's output directory
 * @param project maven project/*from w  w w. j  a  v a2  s .  c o  m*/
 * @throws IOException when fails to copy files to destination resource directory
 */
public static void copyYangFilesToTarget(Set<YangFileInfo> yangFileInfo, String outputDir, MavenProject project)
        throws IOException {

    List<File> files = getListOfFile(yangFileInfo);

    String path = outputDir + TARGET_RESOURCE_PATH;
    File targetDir = new File(path);
    targetDir.mkdirs();

    for (File file : files) {
        Files.copy(file.toPath(), new File(path + file.getName()).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    }
    Resource rsc = new Resource();
    rsc.setDirectory(outputDir + SLASH + TEMP + SLASH);
    project.addResource(rsc);
}