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:ddf.catalog.impl.operations.OperationsCrudSupport.java

void generateMetacardAndContentItems(StorageRequest storageRequest, List<ContentItem> incomingContentItems,
        Map<String, Metacard> metacardMap, List<ContentItem> contentItems, Map<String, Path> tmpContentPaths)
        throws IngestException {
    for (ContentItem contentItem : incomingContentItems) {
        try {//  ww w .ja v a 2  s. com
            Path tmpPath = null;
            long size;
            try (InputStream inputStream = contentItem.getInputStream()) {
                if (inputStream == null) {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }

                String sanitizedFilename = InputValidation.sanitizeFilename(contentItem.getFilename());
                tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename),
                        FilenameUtils.getExtension(sanitizedFilename));
                Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING);
                size = Files.size(tmpPath);
                tmpContentPaths.put(contentItem.getId(), tmpPath);
            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, contentItem.getFilename(), tmpPath);

            if (!InputValidation.checkForClientSideVulnerableMimeType(mimeTypeRaw)) {
                throw new IngestException("Unsupported mime type.");
            }

            String fileName = updateFileExtension(mimeTypeRaw, contentItem.getFilename());
            Metacard metacard = generateMetacard(mimeTypeRaw, contentItem.getId(), fileName,
                    (Subject) storageRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT), tmpPath);
            metacardMap.put(metacard.getId(), metacard);

            ContentItem generatedContentItem = new ContentItemImpl(metacard.getId(),
                    com.google.common.io.Files.asByteSource(tmpPath.toFile()), mimeTypeRaw, fileName, size,
                    metacard);
            contentItems.add(generatedContentItem);
        } catch (Exception e) {
            tmpContentPaths.values().forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static void forceUpdate() throws IOException, VcdiffDecodeException {
    File backupFile = new File(DATA_DIR, "helios.jar.bak");
    try {//from   w w  w.  jav  a  2s .  c o  m
        Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException exception) {
        // We're going to wrap it so end users know what went wrong
        throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)",
                IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()),
                exception);
    }
    URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber");
    HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection();
    if (connection.getResponseCode() == 200) {
        boolean aborted = false;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(connection.getInputStream(), outputStream);
        String version = new String(outputStream.toByteArray(), "UTF-8");
        System.out.println("Latest version: " + version);
        int intVersion = Integer.parseInt(version);

        loop: while (true) {
            int buildNumber = loadHelios().buildNumber;
            int oldBuildNumber = buildNumber;
            System.out.println("Current Helios version is " + buildNumber);

            if (buildNumber < intVersion) {
                while (buildNumber <= intVersion) {
                    buildNumber++;
                    URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json");
                    HttpURLConnection con = (HttpURLConnection) status.openConnection();
                    if (con.getResponseCode() == 200) {
                        JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject();
                        if (object.get("result").asString().equals("SUCCESS")) {
                            JsonArray artifacts = object.get("artifacts").asArray();
                            for (JsonValue value : artifacts.values()) {
                                JsonObject artifact = value.asObject();
                                String name = artifact.get("fileName").asString();
                                if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) {
                                    JOptionPane.showMessageDialog(null,
                                            "Bootstrapper is out of date. Patching cannot continue");
                                    aborted = true;
                                    break loop;
                                }
                            }
                            URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber
                                    + "/artifact/target/delta.patch");
                            con = (HttpURLConnection) url.openConnection();
                            if (con.getResponseCode() == 200) {
                                File dest = new File(DATA_DIR, "delta.patch");
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                copy(con.getInputStream(), byteArrayOutputStream);
                                FileOutputStream fileOutputStream = new FileOutputStream(dest);
                                fileOutputStream.write(byteArrayOutputStream.toByteArray());
                                fileOutputStream.close();
                                File cur = IMPL_FILE;
                                File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber);
                                if (cur.renameTo(old)) {
                                    VcdiffDecoder.decode(old, dest, cur);
                                    old.delete();
                                    dest.delete();
                                    continue loop;
                                } else {
                                    throw new IllegalArgumentException("Could not rename");
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Server returned response code " + con.getResponseCode() + " "
                                        + con.getResponseMessage() + "\nAborting patch process",
                                null, JOptionPane.INFORMATION_MESSAGE);
                        aborted = true;
                        break loop;
                    }
                }
            } else {
                break;
            }
        }

        if (!aborted) {
            int buildNumber = loadHelios().buildNumber;
            System.out.println("Running Helios version " + buildNumber);
            JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!");
            Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() });
        } else {
            try {
                Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException exception) {
                // We're going to wrap it so end users know what went wrong
                throw new IOException("Critical Error! Could not restore Helios implementation to original copy"
                        + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details",
                        exception);
            }
        }
        System.exit(0);
    } else {
        throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
    }
}

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;//from   w w w  .j  a v a  2  s.  c  om
    }

    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:de.dentrassi.rpm.builder.YumMojo.java

private void addSinglePackage(final Path path, final Context context) throws IOException {
    final String checksum = makeChecksum(path);
    final String fileName = path.getFileName().toString();
    final String location = "packages/" + fileName;
    final FileInformation fileInformation = new FileInformation(Files.getLastModifiedTime(path).toInstant(),
            Files.size(path), location);

    final RpmInformation rpmInformation;
    try (RpmInputStream ris = new RpmInputStream(Files.newInputStream(path))) {
        rpmInformation = RpmInformations.makeInformation(ris);
    }/*from www  .j  a v  a2  s. com*/

    context.addPackage(fileInformation, rpmInformation, singletonMap(SHA256, checksum), SHA256);

    Files.copy(path, this.packagesPath.toPath().resolve(fileName), StandardCopyOption.COPY_ATTRIBUTES);
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * writes unchanged file to disk./*from ww  w  .  j a va2 s. c  o m*/
 *
 * @param sourceFile - file to read from
 * @param destFile - file to write to
 * @throws IOException when IO Exception occurs.
 */
private static void writeUntouchedImage(Path sourceFile, Path destFile) throws IOException {
    Files.copy(sourceFile, destFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.kegare.caveworld.util.CaveUtils.java

public static boolean archiveDirZip(final File dir, final File dest) {
    final Path dirPath = dir.toPath();
    final String parent = dir.getName();
    Map<String, String> env = Maps.newHashMap();
    env.put("create", "true");
    URI uri = dest.toURI();/*w  ww .ja va 2  s . c o  m*/

    try {
        uri = new URI("jar:" + uri.getScheme(), uri.getPath(), null);
    } catch (Exception e) {
        return false;
    }

    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Files.createDirectory(zipfs.getPath(parent));

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, zipfs.getPath(parent, dirPath.relativize(file).toString()),
                                StandardCopyOption.REPLACE_EXISTING);

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Files.createDirectory(zipfs.getPath(parent, dirPath.relativize(dir).toString()));

                        return FileVisitResult.CONTINUE;
                    }
                });
            } else {
                Files.copy(file.toPath(), zipfs.getPath(parent, file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();

        return false;
    }
}

From source file:com.ibm.ecm.extension.aspera.AsperaPlugin.java

private Path copyResource(final String subFolder, final String resourceName, final String toSubFolder)
        throws AsperaPluginException {
    final Path path = toSubFolder.isEmpty() ? Paths.get(resourcesRoot, resourceName)
            : Paths.get(resourcesRoot, toSubFolder, resourceName);
    final InputStream resource = this.getClass()
            .getResourceAsStream("/aspera/" + subFolder + (subFolder.isEmpty() ? "" : "/") + resourceName);
    try {//from   www .j a v  a  2  s  .c om
        Files.copy(resource, path, StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e) {
        throw new AsperaPluginException("Failed to copy the plugin resource file: " + path, e);
    }

    return path;
}

From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java

@ApiOperation(value = "Add a file uploads to property")
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {})
public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId,
        @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) {
    LOGGER.info("uploadPost called");

    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    String baseUrl = config.getString("calipso.baseurl");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;/*from   w  w w  . j av a 2s.  c o  m*/
    BinaryFile bf = new BinaryFile();
    try {
        if (itr.hasNext()) {

            mpf = request.getFile(itr.next());
            LOGGER.info("Uploading {}", mpf.getOriginalFilename());

            bf.setName(mpf.getOriginalFilename());
            bf.setFileNameExtention(
                    mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1));

            bf.setContentType(mpf.getContentType());
            bf.setSize(mpf.getSize());

            // request targets specific path?
            StringBuffer uploadsPath = new StringBuffer('/')
                    .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class))
                    .append('/').append(subjectId).append("/uploads/").append(propertyName);
            bf.setParentPath(uploadsPath.toString());
            LOGGER.info("Saving image entity with path: " + bf.getParentPath());
            bf = binaryFileService.create(bf);

            LOGGER.info("file name: {}", bf.getNewFilename());
            bf = binaryFileService.findById(bf.getId());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File storageDirectory = new File(fileUploadDirectory + bf.getParentPath());

            if (!storageDirectory.exists()) {
                storageDirectory.mkdirs();
            }

            LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File newFile = new File(storageDirectory, bf.getNewFilename());
            newFile.createNewFile();
            LOGGER.info("newFile path: {}", newFile.getAbsolutePath());
            Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename());
            ImageIO.write(thumbnail, "png", thumbnailFile);
            bf.setThumbnailSize(thumbnailFile.length());

            bf = binaryFileService.update(bf);

            // attach file
            // TODO: add/update to collection
            Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName);
            Class clazz = fileField.getType();
            if (BinaryFile.class.isAssignableFrom(clazz)) {
                T target = this.service.findById(subjectId);
                BeanUtils.setProperty(target, propertyName, bf);
                this.service.update(target);
            }

            bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId());
            bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId());
            bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId());
            bf.setDeleteType("DELETE");
            bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />");

        }

    } catch (Exception e) {
        LOGGER.error("Could not upload file(s) ", e);
    }

    return bf;
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

private File copyOrphanFileToWorkspace(File file, Workspace workspace) throws URISyntaxException {
    File wsOrphansDirectory = new File(workspaceBaseDirectory,
            workspace.getWorkspaceID() + "/" + orphansDirectoryName);
    File origOrphansDirectory = archiveFileLocationProvider
            .getOrphansDirectory(workspace.getTopNodeArchiveURL().toURI());
    File destPath = new File(wsOrphansDirectory,
            origOrphansDirectory.toPath().relativize(file.getParentFile().toPath()).toString());

    File destFile = null;//from   ww  w .  j  ava  2s .c o m
    try {
        //create directories
        if (destPath.exists()) {
            logger.info("Workspace directory: [" + destPath.toPath().toString() + "] for orphan: ["
                    + file.getName() + "] already exists");
        } else {
            if (destPath.mkdirs()) {
                logger.info("Workspace directory: [" + destPath.toPath().toString() + "] for orphan: ["
                        + file.getName() + "] successfully created");
            } else {
                String errorMessage = "Workspace directory: [" + destPath.toPath().toString()
                        + "] for orphan: [" + file.getName() + "] could not be created";
                throw new IOException(errorMessage);
            }
        }

        if (Files.isSymbolicLink(file.toPath())) {
            file = Files.readSymbolicLink(file.toPath()).toFile();
        }
        destFile = new File(destPath, file.getName());

        Files.copy(file.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        logger.error("Cannot copy metadata file: [" + file.toPath() + "] to workspace directory: ["
                + destPath.toString(), e);
    }
    return destFile;
}

From source file:com.jeet.cli.Admin.java

private static void downloadFile(Map fileMap) {
    System.out.print("Enter File Index(0 to cancel): ");
    String choise = null;/*from  w w w.  j a va  2  s . com*/
    try {
        choise = bufferRead.readLine();
    } catch (IOException ioe) {
        System.err.println("Error in reading option.");
        System.err.println("Please try again.");
        downloadFile(fileMap);
    }
    if (choise != null && NumberUtils.isDigits(choise)) {
        Integer choiseInt = Integer.parseInt(choise);
        if (fileMap.containsKey(choiseInt)) {
            try {
                String key = fileMap.get(choiseInt).toString();
                File file = FileUtil.downloadAndDecryptFile(key);
                String downloadFilePath = Constants.DOWNLOAD_FOLDER + fileMap.get(choiseInt).toString();
                downloadFilePath = downloadFilePath.replaceAll("/", "\\\\");
                Files.copy(file.toPath(), (new File(downloadFilePath)).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
                System.out.println("File Downloaded to: " + downloadFilePath);
            } catch (Exception ex) {
                ex.printStackTrace();
                System.err.println("Error in downlaoding file.");
            }
            askFileListInputs(fileMap);
        } else if (choiseInt.equals(0)) {
            System.out.println("Download file canceled.");
            askFileListInputs(fileMap);
        } else {
            System.err.println("Please select from provided options only.");
            downloadFile(fileMap);
        }
    } else {
        System.err.println("Please enter digits only.");
        downloadFile(fileMap);
    }
}