Example usage for java.nio.file Files copy

List of usage examples for java.nio.file Files copy

Introduction

In this page you can find the example usage for java.nio.file Files copy.

Prototype

public static long copy(InputStream in, Path target, CopyOption... options) throws IOException 

Source Link

Document

Copies all bytes from an input stream to a file.

Usage

From source file:au.org.ands.vocabs.toolkit.provider.harvest.FileHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest./*from  w  w w .  jav a2  s .  c om*/
 * NB: if delete is true, Tomcat must have write access, in order
 * to be able to delete the file successfully. However, a failed
 * deletion will not per se cause the subtask to fail.
 * @param version The version to which access points are to be added.
 * @param format The format of the file(s) to be harvested.
 * @param filePath The path to the file or directory to be harvested.
 * @param outputPath The directory in which to store output files.
 * @param delete True, if successfully harvested files are to be deleted.
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
public final boolean getHarvestFiles(final Version version, final String format, final String filePath,
        final String outputPath, final boolean delete, final HashMap<String, String> results) {
    ToolkitFileUtils.requireDirectory(outputPath);
    Path filePathPath = Paths.get(filePath);
    Path outputPathPath = Paths.get(outputPath);
    if (Files.isDirectory(filePathPath)) {
        logger.debug("Harvesting file(s) from directory " + filePath);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePathPath)) {
            for (Path entry : stream) {
                // Only harvest files. E.g., no recursive
                // directory searching.
                if (Files.isRegularFile(entry)) {
                    logger.debug("Harvesting file:" + entry.toString());
                    Path target = outputPathPath.resolve(entry.getFileName());
                    Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
                    AccessPointUtils.createFileAccessPoint(version, format, target);
                    if (delete) {
                        logger.debug("Deleting file: " + entry.toString());
                        try {
                            Files.delete(entry);
                        } catch (AccessDeniedException e) {
                            logger.error("Unable to delete file: " + entry.toString(), e);
                        }
                    }
                }
            }
        } catch (DirectoryIteratorException | IOException ex) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", ex);
            return false;
        }
    } else {
        logger.debug("Harvesting file: " + filePath);
        try {
            Path target = outputPathPath.resolve(filePathPath.getFileName());
            Files.copy(filePathPath, target, StandardCopyOption.REPLACE_EXISTING);
            AccessPointUtils.createFileAccessPoint(version, format, target);
            if (delete) {
                logger.debug("Deleting file: " + filePathPath.toString());
                try {
                    Files.delete(filePathPath);
                } catch (AccessDeniedException e) {
                    logger.error("Unable to delete file: " + filePathPath.toString(), e);
                }
            }
        } catch (IOException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", e);
            return false;
        }
    }
    // If we reached here, success, so return true.
    return true;
}

From source file:de._692b8c32.cdlauncher.tasks.GithubReleasesDownloadTask.java

@Override
public void doWork() {
    setProgress(-1);//from  ww  w .j  a v  a2s  .c  o  m

    try {
        String realUrl = null;
        HttpClient client = HttpClients.createDefault();
        if (version.getValue() == null) {
            Pattern pattern = Pattern
                    .compile("<ul class=\"release-downloads\"> <li> <a href=\"([^\"]*)\" rel=\"nofollow\">");
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    client.execute(new HttpGet(baseUrl + "latest")).getEntity().getContent()))) {
                Matcher matcher = pattern
                        .matcher(reader.lines().collect(Collectors.joining(" ")).replace("  ", ""));
                if (matcher.find()) {
                    realUrl = baseUrl.substring(0,
                            baseUrl.indexOf('/', baseUrl.indexOf('/', baseUrl.indexOf('/') + 1) + 1))
                            + matcher.group(1);
                }
            }
        } else {
            realUrl = baseUrl + "download/" + version.getValue() + "/OpenRA-" + version.getValue() + ".zip";
        }

        if (realUrl == null) {
            throw new RuntimeException("Failed to find real url");
        } else {
            try (InputStream stream = client.execute(new HttpGet(realUrl)).getEntity().getContent()) {
                Files.copy(stream, cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:de.yaio.services.metaextract.server.controller.MetaExtractFacade.java

/**
 * extract metadata from the inputStream depending on the extension of fileName
 *
 * @param input                 content to extract the metadata from
 * @param fileName              extension to get extension and mimetype to support extraction
 * @param lang                  language-key to support extraction
 * @return                      extracted metadata from the different extractors
 * @throws IOException          possible errors while reading and copying tmpFiles
 * @throws ExtractorException   possible errors while running extractor
 *///from   w  w  w.j  a  va 2  s.  c  o  m
public ExtractedMetaData extractMetaData(final InputStream input, final String fileName, final String lang)
        throws IOException, ExtractorException {
    List<Extractor> extractors = new ArrayList<>();
    extractors.add(extractor1);
    extractors.add(extractor2);

    File tmpFile = File.createTempFile("metaextractor", "." + FilenameUtils.getExtension(fileName));
    tmpFile.deleteOnExit();
    Files.copy(input, tmpFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);

    ExtractedMetaData extractedMetaData = new ExtractedMetaData();

    for (Extractor extractor : extractors) {
        try {
            ExtractedMetaDataVersion extractedMetaDataVersion = extractor.extractMetaData(tmpFile, lang);

            String content = extractedMetaDataVersion.getContent();
            if (StringUtils.isNotBlank(content)) {
                extractedMetaData.getVersions().put(extractor.getClass().toString(), extractedMetaDataVersion);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    LOGGER.info(
            "done extract metadat for file:" + fileName + " with lang:" + lang + " to " + extractedMetaData);

    return extractedMetaData;
}

From source file:com.googlecode.download.maven.plugin.internal.cache.DownloadCache.java

public void install(URI uri, File outputFile, String md5, String sha1, String sha512) throws Exception {
    if (md5 == null) {
        md5 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("MD5"));
    }//from  www .  j a  v a  2  s. com
    if (sha1 == null) {
        sha1 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA1"));
    }
    if (sha512 == null) {
        sha512 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA-512"));
    }
    String entry = getEntry(uri, md5, sha1, sha512);
    if (entry != null) {
        return; // entry already here
    }
    String fileName = outputFile.getName() + '_' + DigestUtils.md5Hex(uri.toString());
    Files.copy(outputFile.toPath(), new File(this.basedir, fileName).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    // update index
    this.index.put(uri, fileName);
}

From source file:org.cloudfoundry.dependency.in.InAction.java

private Mono<Void> writeArchive(InputStream content) {
    try (InputStream in = content) {
        Files.createDirectories(this.destination);
        Files.copy(in, getArchiveFile(), StandardCopyOption.REPLACE_EXISTING);
        return Mono.empty();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }/*from w  ww  . j a  va  2  s  .  co  m*/
}

From source file:easyproject.bean.CommentBean.java

public String doUpdateFile() throws IOException {
    String path = "/Users/csalas/NetBeansProjects/easyprojectSpring/web/uploaded/";
    String urlPath = "http://localhost:8080/easyprojectSpring/uploaded/";
    String fileName = String.valueOf(System.currentTimeMillis()) + getFilename(file);
    Comment comment = new Comment();
    message = "Ha subido el fichero: <a href='" + urlPath + fileName + "'>" + fileName + "</a>";

    file.write(getFilename(file));/*w  w w .  j a  v  a 2  s .c o  m*/
    comment.setCommentText(message);
    comment.setId(String.valueOf(System.currentTimeMillis()));
    comment.setUserName(userBean.getUser().getName());

    int indexOf = userBean.getProjectSelected().getListTasks().indexOf(userBean.getTaskSelected());
    userBean.getProjectSelected().getListTasks().get(indexOf).getComments().add(comment);

    File dowloadFile = new File(
            "/Applications/NetBeans/glassfish-4.1/glassfish/domains/domain1/generated/jsp/SpringMongoJSF/"
                    + getFilename(file));
    File newFile = new File(path + fileName);
    Path sourcePath = dowloadFile.toPath();
    Path newtPath = newFile.toPath();
    Files.copy(sourcePath, newtPath, REPLACE_EXISTING);

    userBean.getProjectSelected().getListTasks().get(indexOf).getFiles().add(urlPath + getFilename(file));

    projectService.editProject(userBean.getProjectSelected());

    message = "";
    return "";
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@After
public void tearDown() throws IOException {
    // Dump the contents of the file system
    Path dumpStart = fs.getPath("/");
    Files.walkFileTree(dumpStart, new SimpleFileVisitor<Path>() {
        @Override/* www. j  a  v a2  s .  c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("> " + file);
            System.out.println(new String(Files.readAllBytes(file), StandardCharsets.UTF_8));

            // Copy the file if wanted
            if (DUMP_DIRECTORY != null) {
                Path dumpTarget = Paths.get(DUMP_DIRECTORY, name.getMethodName());
                Path target = dumpTarget.resolve(dumpStart.relativize(file).toString());
                Files.createDirectories(target.getParent());
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:eu.eexcess.partnerwizard.webservice.WizardRESTService.java

@POST
@Path("updateConfigAndDeploy")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public boolean updateConfigAndDeploy(PartnerConfiguration config) {
    LOGGER.info("REST wizard/updateConfigAndDeploy called");
    if (config == null) {
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }/*from  w  w w  .ja v  a 2  s  . c o  m*/
    LOGGER.info("REST wizard/updateConfigAndDeploy config:\n" + config.toString());
    if (config.getTransformerClass() != null && !config.getTransformerClass().isEmpty()) {
        String artifactId = config.getTransformerClass();
        artifactId = artifactId.substring(artifactId.lastIndexOf(".") + 1);
        artifactId = artifactId.replace("Transformer", "");
        String copyTargetPath = Bean.PATH_BUILD_SANDBOX + artifactId + "\\src\\main\\resources\\";
        String dateString = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());

        LOGGER.info("artifactId:" + artifactId);
        LOGGER.info("copyTargetPath:" + copyTargetPath);

        // backup old config
        Charset charset = StandardCharsets.UTF_8;
        try {
            Files.copy(
                    Paths.get(copyTargetPath + "partner-config.json"), Paths.get(Bean.PATH_BUILD_SANDBOX
                            + artifactId + "-" + dateString + ".old.partner-config.json"),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // neues config reinkopieren
        try {
            String newFile = mapper.writeValueAsString(config);
            Files.write(Paths.get(copyTargetPath + "partner-config.json"), newFile.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // new config saving
        try {
            String newFile = mapper.writeValueAsString(config);
            Files.write(
                    Paths.get(Bean.PATH_BUILD_SANDBOX + artifactId + "-" + dateString + ".partner-config.json"),
                    newFile.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // build new version

        ArrayList<String> commands = new ArrayList<String>();
        commands.add("cd " + Bean.PATH_BUILD_SANDBOX);
        commands.add("cd " + artifactId);
        commands.add("mvn install -DskipTests");
        commands.add("cd target");
        String warName = "eexcess-partner-" + artifactId + "-*";
        commands.add("del %TOMCAT%webapps\\" + warName + "*.war");
        commands.add("rd /S /Q %TOMCAT%webapps\\" + warName);
        commands.add("xcopy " + warName + ".war %TOMCAT%webapps\\ /Y");
        this.cmdExecute(commands);

    }
    return true;
}

From source file:com.liferay.sync.engine.util.SyncClientUpdater.java

public static void update(SyncVersion syncVersion) throws Exception {
    if (syncVersion == null) {
        syncVersion = getLatestSyncVersion();
    }/*from w  ww.j a va 2 s  .  c  o  m*/

    if (syncVersion == null) {
        return;
    }

    HttpResponse httpResponse = execute(syncVersion.getUrl());

    if (httpResponse == null) {
        return;
    }

    HttpEntity httpEntity = httpResponse.getEntity();
    Path filePath = getFilePath(httpResponse);

    Files.copy(httpEntity.getContent(), filePath, StandardCopyOption.REPLACE_EXISTING);

    Desktop desktop = Desktop.getDesktop();

    desktop.open(filePath.toFile());
}

From source file:io.druid.indexer.HdfsClasspathSetupTest.java

@Before
public void setUp() throws IOException {
    // intermedatePath and finalClasspath are relative to hdfsTmpDir directory.
    intermediatePath = new Path(String.format("/tmp/classpath/%s", UUIDUtils.generateUuid()));
    finalClasspath = new Path(String.format("/tmp/intermediate/%s", UUIDUtils.generateUuid()));
    dummyJarFile = tempFolder.newFile("dummy-test.jar");
    Files.copy(new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
}