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:de.ks.file.FileStoreTest.java

@Test
public void testGetFileReferences() throws Exception {
    Path path = Files.createTempFile("img", ".jpg");

    URL resource = getClass().getResource("/de/ks/idnadrev/entity/img.jpg");
    Path src = Paths.get(resource.toURI());
    Files.copy(src, path, StandardCopyOption.REPLACE_EXISTING);
    File file = path.toFile();//w w  w.j  av  a 2 s  . co  m
    file.deleteOnExit();

    FileReference fileReference = fileStore.getReference(file).get();
    PersistentWork.run(em -> {
        fileStore.scheduleCopy(fileReference, file);
        em.persist(fileReference);
    });
    assertThat(fileReference.getMimeType(), containsString("image"));

    List<FileReference> references = fileStore.getFilesByMimeType(MediaType.ANY_IMAGE_TYPE);
    assertEquals(1, references.size());

    references = fileStore.getFilesByMimeType(MediaType.ANY_AUDIO_TYPE);
    assertEquals(0, references.size());

    references = fileStore.getFilesByMimeType(MediaType.ANY_TYPE);
    assertEquals(1, references.size());
}

From source file:course.cloud.computing.rest.ImageService.java

@POST
@Consumes("image/jpeg")
public Response upload(InputStream in, @HeaderParam("Content-Type") String fileType,
        @HeaderParam("Content-Length") long fileSize) throws IOException {

    System.out.println("Received call to load");
    // Make sure the file is not larger than the maximum allowed size.
    if (fileSize > 1024 * 1024 * MAX_SIZE_IN_MB) {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
                .entity("Image is larger than " + MAX_SIZE_IN_MB + "MB").build());
    }/*from   w ww .  ja  v a 2 s .  c  o m*/

    String fileName = "" + System.currentTimeMillis();
    if (fileType.equals("image/jpeg")) {
        fileName += ".jpg";
    } else {
        fileName += ".png";
    }
    System.out.println("Set new filename to " + fileName);

    File directory = new File("images");
    if (!directory.isDirectory()) {
        boolean created = directory.mkdir();
        if (!created) {
            System.out.println("Unable to create a folder for images");
            return Response.serverError().build();
        }
    }
    java.nio.file.Path path = Paths.get("images");
    Files.copy(in, path.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);
    return Response.status(Status.CREATED).location(URI.create("/" + fileName)).build();
}

From source file:org.jboss.as.test.clustering.modcluster.WorkerFailoverTestCase.java

private void balancerSetup() throws Exception {
    try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(null,
            TestSuiteEnvironment.getServerAddress("node0"), 9990)) {

        /* Configuration backup */
        ModelNode op = createOpNode("path=jboss.server.config.dir", "read-attribute");
        op.get("name").set("path");
        ModelNode response = client.execute(op);
        Assert.assertEquals("Server's configuration file not found!\n" + response.toString(), SUCCESS,
                response.get("outcome").asString());

        balancerConfigFile = response.get("result").asString() + File.separator
                + System.getProperty("jboss.server.config.file.standalone", "standalone.xml");
        Files.copy(Paths.get(balancerConfigFile),
                Paths.get(balancerConfigFile + ".WorkerFailoverTestCase.backup"), REPLACE_EXISTING);

        /* Server configuration */
        op = createOpNode("subsystem=undertow/configuration=filter/mod-cluster=modcluster", "add");
        op.get("management-socket-binding").set("http");
        response = client.execute(op);//from  w  ww .  j a v a  2s.c om
        Assert.assertEquals("Server's configuration failed!\n" + response.toString(), SUCCESS,
                response.get("outcome").asString());

        op = createOpNode("subsystem=undertow/server=default-server/host=default-host/filter-ref=modcluster",
                "add");
        response = client.execute(op);
        Assert.assertEquals("Server's configuration failed!\n" + response.toString(), SUCCESS,
                response.get("outcome").asString());
    }

}

From source file:onl.area51.gfs.grib2.job.GribRetriever.java

public Path retrieveOffset(Path dir, int offset, boolean forceRetrive) throws IOException {
    LOG.log(Level.INFO, () -> "Looking for GFS file for offset " + offset);
    String ending = String.format("z.pgrb2.0p25.f%03d", offset);

    @SuppressWarnings("ThrowableInstanceNotThrown")
    FTPFile remote = client.files().filter(f -> f.getName().startsWith("gfs.t"))
            .filter(f -> f.getName().endsWith(ending)).peek(f -> LOG.warning(f.getName())).findAny()
            .orElseThrow(() -> new FileNotFoundException("Unable to find GFS file for " + offset));

    Path file = dir.resolve(remote.getName());

    if (forceRetrive || client.isPathRetrievable(file, remote)) {
        LOG.log(Level.INFO, () -> "Retrieving " + remote.getSize() + " bytes to " + file);

        try (InputStream is = client.retrieveFileStream(remote)) {
            Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
        }/*from  w  w  w.j  a v  a  2 s.c o  m*/

        LOG.log(Level.INFO, () -> "Retrieved " + remote.getSize() + " bytes");
    } else {
        LOG.log(Level.INFO, () -> "Skipping retrieval as local file is newer");
    }

    return file;
}

From source file:com.liferay.sync.engine.document.library.handler.DownloadFileHandler.java

protected void copyFile(final SyncFile syncFile, Path filePath, InputStream inputStream, boolean append)
        throws Exception {

    OutputStream outputStream = null;

    Watcher watcher = WatcherManager.getWatcher(getSyncAccountId());

    try {/* w  w  w  .j av  a 2  s .com*/
        Path tempFilePath = FileUtil.getTempFilePath(syncFile);

        boolean exists = FileUtil.exists(filePath);

        if (append) {
            outputStream = Files.newOutputStream(tempFilePath, StandardOpenOption.APPEND);

            IOUtils.copyLarge(inputStream, outputStream);
        } else {
            if (exists && (boolean) getParameterValue("patch")) {
                if (_logger.isDebugEnabled()) {
                    _logger.debug("Patching {}", syncFile.getFilePathName());
                }

                Files.copy(filePath, tempFilePath, StandardCopyOption.REPLACE_EXISTING);

                IODeltaUtil.patch(tempFilePath, inputStream);
            } else {
                Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
            }
        }

        watcher.addDownloadedFilePathName(filePath.toString());

        if (GetterUtil.getBoolean(syncFile.getLocalExtraSettingValue("restoreEvent"))) {

            syncFile.unsetLocalExtraSetting("restoreEvent");

            syncFile.setUiEvent(SyncFile.UI_EVENT_RESTORED_REMOTE);
        } else if (exists) {
            syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_UPDATE);
        } else {
            syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_NEW);
        }

        FileKeyUtil.writeFileKey(tempFilePath, String.valueOf(syncFile.getSyncFileId()), false);

        FileUtil.setModifiedTime(tempFilePath, syncFile.getModifiedTime());

        if (MSOfficeFileUtil.isLegacyExcelFile(filePath)) {
            syncFile.setLocalExtraSetting("lastSavedDate", MSOfficeFileUtil.getLastSavedDate(tempFilePath));
        }

        Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);

        ExecutorService executorService = SyncEngine.getExecutorService();

        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                IODeltaUtil.checksums(syncFile);

                syncFile.setState(SyncFile.STATE_SYNCED);

                SyncFileService.update(syncFile);
            }

        };

        executorService.execute(runnable);
    } catch (FileSystemException fse) {
        if (fse instanceof AccessDeniedException) {
            _logger.error(fse.getMessage(), fse);

            syncFile.setState(SyncFile.STATE_ERROR);
            syncFile.setUiEvent(SyncFile.UI_EVENT_ACCESS_DENIED_LOCAL);

            SyncFileService.update(syncFile);

            return;
        } else if (fse instanceof NoSuchFileException) {
            if (isEventCancelled()) {
                SyncFileService.deleteSyncFile(syncFile);

                return;
            }
        }

        watcher.removeDownloadedFilePathName(filePath.toString());

        String message = fse.getMessage();

        _logger.error(message, fse);

        syncFile.setState(SyncFile.STATE_ERROR);

        if (message.contains("File name too long")) {
            syncFile.setUiEvent(SyncFile.UI_EVENT_FILE_NAME_TOO_LONG);
        }

        SyncFileService.update(syncFile);
    } finally {
        StreamUtil.cleanUp(outputStream);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.SpinnakerProfile.java

/**
 * @param node is the node to find required files in.
 * @return the list of files required by the node to function.
 *///w ww.  jav a2s. c o m
List<String> processRequiredFiles(Node node) {
    List<String> files = new ArrayList<>();

    Consumer<Node> fileFinder = n -> files.addAll(n.localFiles().stream().map(f -> {
        try {
            f.setAccessible(true);
            String fPath = (String) f.get(n);
            if (fPath == null) {
                return null;
            }

            File fFile = new File(fPath);
            String fName = fFile.getName();

            // Hash the path to uniquely flatten all files into the output directory
            Path newName = Paths.get(spinnakerOutputDependencyPath, Math.abs(fPath.hashCode()) + "-" + fName);
            File parent = newName.toFile().getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            } else if (fFile.getParent().equals(parent.toString())) {
                // Don't move paths that are already in the right folder
                return fPath;
            }
            Files.copy(Paths.get(fPath), newName, REPLACE_EXISTING);

            f.set(n, newName.toString());
            return newName.toString();
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to get local files for node " + n.getNodeName(), e);
        } catch (IOException e) {
            throw new HalException(
                    new ProblemBuilder(FATAL, "Failed to backup user file: " + e.getMessage()).build());
        } finally {
            f.setAccessible(false);
        }
    }).filter(Objects::nonNull).collect(Collectors.toList()));
    node.recursiveConsume(fileFinder);

    return files;
}

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

@Test
public void testFileTransferLargeFile() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path tmp = Paths.get(System.getProperty("java.io.tmpdir"));
    StringBuilder message = new StringBuilder();
    for (int i = 0; i < 100000; ++i) {
        message.append("Hello World");
    }/*w  ww. j a va  2 s.com*/
    Path large = Files.createTempFile(null, ".txt");
    try {
        Files.copy(new ByteArrayInputStream(message.toString().getBytes(StandardCharsets.UTF_8)), large,
                StandardCopyOption.REPLACE_EXISTING);
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(tmp, 1))
                        // 1 byte = force transfer
                        .setDirectoryListingEnabled(true))));

        HttpGet get = new HttpGet(
                DefaultServer.getDefaultServerURL() + "/path/" + large.getFileName().toString());
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/plain", headers[0].getValue());
        Assert.assertTrue(response, response.equals(message.toString()));

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:fi.helsinki.cs.iot.kahvihub.admin.ServiceHttpRequestHandler.java

private File copyPluginFile(File file) {
    /* //w w w .  ja v  a 2 s.c  om
     * TODO A number of features would need to be added, first it would be nice to have
     * separate folders for native and javascript plugins
     * then we need to make sure to manage different plugins version
     * Update them if necessary (similar to apps and services)
     */
    if (file != null && file.exists() && !file.isDirectory()) {
        try {
            String filename = file.getName();
            File nfile = new File(libFolder + filename);
            Files.copy(file.toPath(), nfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            return nfile;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    return null;
}

From source file:edu.harvard.iq.dataverse.ThemeWidgetFragment.java

/**
 * Copy uploaded file to temp area, until we are ready to save
 * Copy filename into Dataverse logo //  w  ww .ja v a 2  s  .  c o  m
 * @param event 
 */

public void handleImageFileUpload(FileUploadEvent event) {

    logger.finer("entering fileUpload");
    if (this.tempDir == null) {
        createTempDir();
        logger.finer("created tempDir");
    }
    UploadedFile uFile = event.getFile();
    try {
        uploadedFile = new File(tempDir, uFile.getFileName());
        if (!uploadedFile.exists()) {
            uploadedFile.createNewFile();
        }
        logger.finer("created file");
        Files.copy(uFile.getInputstream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        logger.finer("copied inputstream to file");
        editDv.getDataverseTheme().setLogo(uFile.getFileName());

    } catch (IOException e) {
        logger.finer("caught IOException");
        logger.throwing("ThemeWidgetFragment", "handleImageFileUpload", e);
        throw new RuntimeException("Error uploading logo file", e); // improve error handling
    }
    // If needed, set the default values for the logo
    if (editDv.getDataverseTheme().getLogoFormat() == null) {
        editDv.getDataverseTheme().setLogoFormat(DataverseTheme.ImageFormat.SQUARE);
    }
    logger.finer("end handelImageFileUpload");
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ?????./*from  ww w .j a  v  a2 s .c  o  m*/
 * 
 * @param metadata ?urlTree
 * @param ctx urlTree
 */
@Override
public void save(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx) throws BadContentException {

    String localFileName = metadata.getAbsolutePath();

    logger.debug("saving " + localFileName);
    Path f = this.generateFileObj(localFileName);

    InputStream b = metadata.getData();
    // null?????????
    if (b == null) {
        return;
    }
    try {
        Path parent = f.getParent();

        // ???????
        if (Files.notExists(parent)) {
            Files.createDirectories(parent);
        }
        Files.copy(b, f, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException(e);
    }
}