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(Path source, OutputStream out) throws IOException 

Source Link

Document

Copies all bytes from a file to an output stream.

Usage

From source file:gr.upatras.ece.nam.baker.testclasses.MockRepositoryWebClient.java

@Override
public Path fetchPackageFromLocation(String uuid, String packageLocation) {

    logger.info("TEST fetchMetadata after 2sec from (dummy): " + packageLocation);

    try {/*from  w ww . ja v a2s .  c om*/
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {

        URL res = getClass().getResource(packageLocation);
        logger.info("TEST RESOURCE FILE: " + res);

        File sourceFile = new File(res.getFile());

        Path tempDir = Files.createTempDirectory("baker");
        File destFile = new File(tempDir + "/" + uuid + "/bun.tar.gz");
        Files.createDirectory(Paths.get(tempDir + "/" + uuid));
        Path targetPath = destFile.toPath();

        logger.info(" to:" + targetPath);

        Files.copy(sourceFile.toPath(), targetPath);
        if (mockRepositoryBehavior != MockRepositoryBehavior.RETURN_NULLPACKAGEFILE) {
            return targetPath;
        }

    } catch (IOException e) {

        e.printStackTrace();

    }

    return null;

}

From source file:controler.util.FileUtil.java

public static void upload(UploadedFile file, String emplacement, Abonne abonne, File f) throws IOException {
    System.out.println("upload");
    //String vmParam = "irisi.projet.upload.path";
    String fullPath = "";
    if (file != null) {
        String path = System.getProperty(vmParam);
        if (path == null) {
            JsfUtil.addErrorMessage(null, "option JVM manquante \"" + vmParam + "\"");
        } else {/*from w ww . j av a 2s. c  om*/
            File folder = new File(
                    path + "\\" + abonne.getNom() + "XX" + abonne.getId() + "\\" + emplacement + "\\");//creer la path qui va contenir notre fichier
            if (!folder.exists()) {
                folder.mkdirs(); // Cration de l'arborescense (dossier et sous dossier)
            }
            System.out.println("file.getFileName() ==> " + file.getFileName());
            String nameModified = file.getFileName().replace('.', ':');
            String[] str = nameModified.split(":");
            String fileName = str[0];
            String extension = str[1];
            String outputPath = path + "\\" + abonne.getNom() + "XX" + abonne.getId() + "\\" + emplacement
                    + "\\" + fileName + new Date().getTime() + "." + extension;//hna fin kaytht l fichier selectionn
            System.out.println(outputPath);
            File outputFile = new File(outputPath);
            Files.copy(file.getInputstream(), outputFile.toPath());
            JsfUtil.addSuccessMessage(file.getFileName() + " est bien recu.");
        }
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests reloading a keystore that is used in the KeyManager of SSLContext
 *//*  w w  w.j a  v a2  s.  c  om*/
public void testReloadingKeyStore() throws Exception {
    final Path tempDir = createTempDir();
    final Path keystorePath = tempDir.resolve("testnode.jks");
    final Path updatedKeystorePath = tempDir.resolve("testnode_updated.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            keystorePath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.jks"),
            updatedKeystorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.keystore.secure_password", "testnode");
    final Settings settings = Settings.builder().put("path.home", createTempDir())
            .put("xpack.ssl.keystore.path", keystorePath).setSecureSettings(secureSettings).build();
    final Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    //Load HTTPClient only once. Client uses the same store as a truststore
    try (CloseableHttpClient client = getSSLClient(keystorePath, "testnode")) {
        final Consumer<SSLContext> keyMaterialPreChecks = (context) -> {
            try (MockWebServer server = new MockWebServer(context, true)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedKeystorePath, keystorePath);
            } catch (Exception e) {
                throw new RuntimeException("modification failed", e);
            }
        };

        // The new server certificate is not in the client's truststore so SSLHandshake should fail
        final Consumer<SSLContext> keyMaterialPostChecks = (updatedContext) -> {
            try (MockWebServer server = new MockWebServer(updatedContext, true)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path validation failed"));
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier,
                keyMaterialPostChecks);
    }
}

From source file:game.com.HandleDownloadFolderServlet.java

private void handle(HttpServletRequest request, HttpServletResponse response, AjaxResponseEntity responseObject)
        throws Exception {

    String path = getPath(request);
    if (path == null) {
        responseObject.returnCode = 0;//from w w w  .  j  a  v a  2 s .  c o  m
        responseObject.returnMessage = "invalid request";
        return;
    }
    File folder = new File(path);
    if (!folder.exists()) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "path not exist";
        return;
    }
    if (folder.getAbsolutePath().startsWith(AppConfig.OPENSHIFT_DATA_DIR) == false) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "invalid path";
        return;
    }
    try {

        File file = new File(path);

        if (!file.isDirectory()) {
            response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            Files.copy(file.toPath(), response.getOutputStream());
        } else {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"allfiles.zip\"");

            try (ZipOutputStream output = new ZipOutputStream(
                    new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE))) {
                //                    for (File fileId : file.listFiles()) {
                //
                //                        InputStream input = null;
                //                        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                //                        try {
                //                            input = new BufferedInputStream(new FileInputStream(fileId), DEFAULT_BUFFER_SIZE);
                //                            output.putNextEntry(new ZipEntry(fileId.getName()));
                //                            for (int length = 0; (length = input.read(buffer)) > 0;) {
                //                                output.write(buffer, 0, length);
                //                            }
                //                            output.closeEntry();
                //                        } finally {
                //                            if (input != null) {
                //                                try {
                //                                    input.close();
                //                                } catch (Exception logOrIgnore) {
                //                                    logger.error(logOrIgnore.getMessage(), logOrIgnore);
                //                                }
                //                            }
                //                        }
                //                    }
                //                    outputZipStream(output, file);
                addDirToZipArchive(output, file, null);
            }
        }

        responseObject.returnCode = 1;
        responseObject.returnMessage = "success";

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:de.andreasgiemza.jgeagle.options.Options.java

public Options() {
    try {//from   www .  j ava 2  s.  c o  m
        if (!Files.exists(tempDir)) {
            Files.createDirectories(tempDir);
        }

        if (!Files.exists(reposDir)) {
            Files.createDirectories(reposDir);
        }

        if (!Files.exists(optionsFile)) {
            InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream("de/andreasgiemza/jgeagle/resources/JGeagle.properties");
            Files.copy(inputStream, optionsFile);
        }

        properties.load(new FileInputStream(optionsFile.toFile()));
    } catch (IOException ex) {
        Logger.getLogger(Options.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.thoughtworks.go.agent.bootstrapper.DefaultAgentLauncherCreatorImpl.java

private void createTempLauncherJar() {
    try {/*from  w  ww.j  a  v a2  s  . c om*/
        inUseLauncher.getParentFile().mkdirs();
        Files.copy(new File(Downloader.AGENT_LAUNCHER).toPath(), inUseLauncher.toPath());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    LauncherTempFileHandler.startTempFileReaper();
}

From source file:com.surevine.gateway.scm.gatewayclient.GatewayPackage.java

void createTar(final Path tarPath, final Path... paths) throws IOException, ArchiveException {
    ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar",
            Files.newOutputStream(tarPath));
    try {/*  w  ww  . j a v  a  2  s.c o  m*/
        for (Path path : paths) {
            TarArchiveEntry entry = new TarArchiveEntry(path.toFile());
            entry.setName(path.getFileName().toString());
            os.putArchiveEntry(entry);
            Files.copy(path, os);
            os.closeArchiveEntry();
        }
    } finally {
        os.close();
    }
}

From source file:br.unb.cic.bionimbuz.storage.bucket.methods.CloudMethodsAmazonGoogle.java

@Override
public void StorageDownloadFile(BioBucket bucket, String bucketPath, String localPath, String fileName)
        throws Exception {

    switch (bucket.getProvider()) {
    case AMAZON: {

        s3client.setEndpoint(bucket.getEndPoint());
        S3Object object = s3client
                .getObject(new GetObjectRequest(bucket.getName(), bucketPath.substring(1) + fileName));
        InputStream objectData = object.getObjectContent();
        Files.copy(objectData, Paths.get(localPath + fileName));
        objectData.close();//from  w ww.  java2s  . com

        break;
    }
    case GOOGLE: {

        String command = gcloudFolder + "gsutil cp gs://" + bucket.getName() + bucketPath + fileName + " "
                + localPath + fileName;
        ExecCommand(command);

        break;
    }
    default: {
        throw new Exception("Provedor incorreto!");
    }
    }
}

From source file:at.tfr.securefs.module.scan.IKScanServiceModule.java

@Override
public ModuleResult apply(InputStream is, ModuleConfiguration moduleConfiguration) throws ModuleException {

    Path filePath = configuration.getTmpPath().resolve("scanFile_" + UUID.randomUUID());
    try {//from w  ww .ja v  a2s.  c  o m
        try {
            Files.copy(is, filePath);
            return apply(filePath.toString(), moduleConfiguration);
        } finally {
            Files.deleteIfExists(filePath);
        }
    } catch (ModuleException me) {
        throw me;
    } catch (Exception e) {
        throw new ModuleException("cannot process", e);
    }
}

From source file:net.nifheim.beelzebu.coins.common.utils.dependencies.DependencyManager.java

private static File downloadDependency(File libDir, Dependency dependency) throws Exception {
    String fileName = dependency.name().toLowerCase() + "-" + dependency.getVersion() + ".jar";

    File file = new File(libDir, fileName);
    if (file.exists()) {
        return file;
    }//from  ww w.  j av  a  2s . c  om

    URL url = new URL(dependency.getUrl());

    core.getMethods().log("Dependency '" + fileName + "' could not be found. Attempting to download.");
    try (InputStream in = url.openStream()) {
        Files.copy(in, file.toPath());
    }

    if (!file.exists()) {
        throw new IllegalStateException("File not present. - " + file.toString());
    } else {
        core.getMethods().log("Dependency '" + fileName + "' successfully downloaded.");
        return file;
    }
}