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:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests the reloading of a key config backed by pem files when there is an exception during reloading. An exception is caused by
 * truncating the key file that is being monitored
 *//*from ww  w . j  av a 2 s. c  om*/
public void testReloadingPEMKeyConfigException() throws Exception {
    Path tempDir = createTempDir();
    Path keyPath = tempDir.resolve("testnode.pem");
    Path certPath = tempDir.resolve("testnode.crt");
    Path clientCertPath = tempDir.resolve("testclient.crt");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.pem"),
            keyPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt"),
            certPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.crt"),
            clientCertPath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.secure_key_passphrase", "testnode");
    Settings settings = Settings.builder().put("xpack.ssl.key", keyPath).put("xpack.ssl.certificate", certPath)
            .putList("xpack.ssl.certificate_authorities", certPath.toString(), clientCertPath.toString())
            .put("path.home", createTempDir()).setSecureSettings(secureSettings).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    final SSLService sslService = new SSLService(settings, env);
    final SSLConfiguration config = sslService.sslConfiguration(Settings.EMPTY);
    new SSLConfigurationReloader(settings, env, sslService, resourceWatcherService) {
        @Override
        void reloadSSLContext(SSLConfiguration configuration) {
            fail("reload should not be called! [pem key reload exception]");
        }
    };

    final SSLContext context = sslService.sslContextHolder(config).sslContext();

    // truncate the file
    try (OutputStream os = Files.newOutputStream(keyPath, StandardOpenOption.TRUNCATE_EXISTING)) {
    }

    // we intentionally don't wait here as we rely on concurrency to catch a failure
    assertThat(sslService.sslContextHolder(config).sslContext(), sameInstance(context));
}

From source file:edu.mit.lib.bagit.Filler.java

private void fillArchive(File dirFile, String relBase, ArchiveOutputStream out) throws IOException {
    for (File file : dirFile.listFiles()) {
        String relPath = relBase + File.separator + file.getName();
        if (file.isDirectory()) {
            fillArchive(file, relPath, out);
        } else {//ww w . j a  v  a  2  s .com
            TarArchiveEntry entry = new TarArchiveEntry(relPath);
            entry.setSize(file.length());
            entry.setModTime(0L);
            out.putArchiveEntry(entry);
            Files.copy(file.toPath(), out);
            out.closeArchiveEntry();
        }
    }
}

From source file:gob.dp.simco.registro.controller.ActaAcuerdoController.java

private String uploadArchive(Part fil) {
    String nameArchive = getFilename(fil);
    String extencion = getFileExtension(getFilename(fil));
    if (StringUtils.isNoneBlank(nameArchive)) {
        String formato = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        String ruta = formato + extencion;
        File file = new File(ConstantesUtil.FILE_SYSTEM + ruta);
        try (InputStream input = fil.getInputStream()) {
            Files.copy(input, file.toPath());
        } catch (IOException ex) {
            log.error(ex);//from ww  w . ja  v a  2 s .co m
        }
        return ruta;
    }
    return null;
}

From source file:edu.mit.lib.bagit.Filler.java

private void fillZip(File dirFile, String relBase, ZipOutputStream zout) throws IOException {
    for (File file : dirFile.listFiles()) {
        String relPath = relBase + File.separator + file.getName();
        if (file.isDirectory()) {
            fillZip(file, relPath, zout);
        } else {/*from   ww  w .  ja v  a 2 s. c  o m*/
            ZipEntry entry = new ZipEntry(relPath);
            entry.setTime(0L);
            zout.putNextEntry(entry);
            Files.copy(file.toPath(), zout);
            zout.closeEntry();
        }
    }
}

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

/**
 * Tests the reloading of a truststore when there is an exception during reloading. An exception is caused by truncating the truststore
 * that is being monitored/*from   ww w . j  a  va  2  s .  co  m*/
 */
public void testTrustStoreReloadException() throws Exception {
    Path tempDir = createTempDir();
    Path trustStorePath = tempDir.resolve("testnode.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            trustStorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.truststore.secure_password", "testnode");
    Settings settings = Settings.builder().put("xpack.ssl.truststore.path", trustStorePath)
            .put("path.home", createTempDir()).setSecureSettings(secureSettings).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    final SSLService sslService = new SSLService(settings, env);
    final SSLConfiguration config = sslService.sslConfiguration(Settings.EMPTY);
    new SSLConfigurationReloader(settings, env, sslService, resourceWatcherService) {
        @Override
        void reloadSSLContext(SSLConfiguration configuration) {
            fail("reload should not be called! [truststore reload exception]");
        }
    };

    final SSLContext context = sslService.sslContextHolder(config).sslContext();

    // truncate the truststore
    try (OutputStream os = Files.newOutputStream(trustStorePath, StandardOpenOption.TRUNCATE_EXISTING)) {
    }

    // we intentionally don't wait here as we rely on concurrency to catch a failure
    assertThat(sslService.sslContextHolder(config).sslContext(), sameInstance(context));
}

From source file:br.ufc.deti.ecgweb.domain.exam.EcgService.java

@Transactional(timeout = 0)
public void importEcg(Long patientId, File file, String ecgFileKey) throws IOException {

    System.out.println("Map Size=" + uploadFileMap.size());

    EcgFileType type = EcgFileType.HL7;/*from  ww w.  j a  v a2  s  .c om*/

    lock.lock();
    try {
        if (getUploadFile(patientId) != null) {
            //Has upload file occurring
            throw new ServiceUploadDuplicatedActionException();
        } else {
            addUploadFile(patientId, file);
        }
    } finally {
        lock.unlock();
    }

    System.out.println("Map Size=" + uploadFileMap.size());

    AbstractEcgFormat hl7 = new HL7FormatImpl();
    hl7.loadInformationFromFile(file);

    String newfileName = ecgFileKey;

    Patient patient = patientRepository.findOne(patientId);

    EcgFile ecgFile = new EcgFile();
    ecgFile.setDate(LocalDateTime.now());
    ecgFile.setFileName(newfileName);
    ecgFile.setType(type);
    ecgFileRepository.save(ecgFile);

    Ecg ecg = new Ecg();
    ecg.setBaseLine(hl7.getBaseLine());
    ecg.setGain(hl7.getGain());
    ecg.setSampleRate(hl7.getSampleRate());
    ecg.setFinished(Boolean.FALSE);
    ecg.setFile(ecgFile);
    ecgRepository.save(ecg);

    for (int i = 0; i < hl7.getNumberOfChannels(); i++) {

        EcgChannel channel = new EcgChannel();
        channel.setLeadType(hl7.getChannelType(i));

        long count = 0;
        List<EcgSignal> signals = hl7.getChannelSignals(i);
        for (EcgSignal signal : signals) {
            count++;
            /*if (count == 30000) {
            break;
            }*/

            EcgSignal signal_ = new EcgSignal();
            signal_.setSampleIdx(signal.getSampleIdx());
            signal_.setyIntensity(signal.getyIntensity());

            ecgSignalRepository.save(signal_);
            channel.addSignal(signal_);

            if (count % 10000 == 0) {
                System.out.println(patientId + " : signal:" + count);
            }
        }
        channel.setEcg(ecg);
        ecgChannelRepository.save(channel);

        ecg.addChannel(channel);
        ecgRepository.save(ecg);
    }

    patient.addEcgExam(ecg);
    patientRepository.save(patient);

    ecg.setFinished(Boolean.TRUE);
    ecgRepository.save(ecg);

    Path pathIn = FileSystems.getDefault().getPath(file.getAbsolutePath());
    Path pathOut = FileSystems.getDefault().getPath("/home/ecgs/" + newfileName);

    Files.copy(pathIn, pathOut);
    Files.deleteIfExists(pathIn);

    lock.lock();
    try {
        removeUploadFile(patientId);
    } finally {
        lock.unlock();
    }

    System.out.println("Map Size=" + uploadFileMap.size());
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy given {@code srcFile} to given {@code destDir}.
 *
 * @param srcFile//from   w  w w .java  2  s  . c om
 * @param destDir destination directory, must exist
 * @return
 * @throws RuntimeIOException
 */
@Nonnull
public static Path copyToDirectory(@Nonnull Path srcFile, @Nonnull Path destDir) throws RuntimeIOException {
    Preconditions.checkArgument(Files.exists(srcFile), "Src %s not found");
    Preconditions.checkArgument(!Files.isDirectory(srcFile), "Src %s is a directory");
    Preconditions.checkArgument(Files.exists(destDir), "Dest %s not found");
    Preconditions.checkArgument(Files.isDirectory(destDir), "Dest %s is not a directory");
    try {
        return Files.copy(srcFile, destDir.resolve(srcFile.getFileName()));
    } catch (IOException e) {
        throw new RuntimeIOException("Exception copying " + srcFile.getFileName() + " to " + srcFile, e);
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

@Nonnull
public static Path copyArtifactToDirectory(@Nonnull Path sourceDir, @Nonnull String artifactId,
        @Nonnull Path dest) throws RuntimeIOException {
    Path source = findArtifact(sourceDir, artifactId);
    try {/*from w ww  .j  a  v  a 2s .  c o  m*/
        return Files.copy(source, dest.resolve(source.getFileName()));
    } catch (IOException e) {
        throw new RuntimeIOException("Exception copying " + source.getFileName() + " to " + sourceDir, e);
    }
}

From source file:io.personium.core.model.impl.fs.DavCmpFsImpl.java

/**
 * Newly create the resource./*from w  w w .j  ava2 s.c  o  m*/
 * @param contentType ContentType of the generated file
 * @param inputStream Stream of generated file
 * @return ResponseBuilder
 */
private ResponseBuilder doPutForCreate(final String contentType, final InputStream inputStream) {
    // check the resource count
    checkChildResourceCount();

    InputStream input = inputStream;
    if (PersoniumUnitConfig.isDavEncryptEnabled()) {
        // Perform encryption.
        DataCryptor cryptor = new DataCryptor(getCellId());
        input = cryptor.encode(inputStream);
    }

    BufferedInputStream bufferedInput = new BufferedInputStream(input);
    try {
        // create new directory.
        Files.createDirectories(Paths.get(this.fsPath));
        // store the file content.
        File newFile = new File(getContentFilePath());
        Files.copy(bufferedInput, newFile.toPath());
        long writtenBytes = newFile.length();
        String encryptionType = DataCryptor.ENCRYPTION_TYPE_NONE;
        if (PersoniumUnitConfig.isDavEncryptEnabled()) {
            writtenBytes = ((CipherInputStream) input).getReadLengthBeforEncryption();
            encryptionType = DataCryptor.ENCRYPTION_TYPE_AES;
        }
        // create new metadata file.
        this.metaFile = DavMetadataFile.prepareNewFile(this, DavCmp.TYPE_DAV_FILE);
        this.metaFile.setContentType(contentType);
        this.metaFile.setContentLength(writtenBytes);
        this.metaFile.setEncryptionType(encryptionType);
        this.metaFile.save();
    } catch (IOException ex) {
        throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex);
    }
    this.isPhantom = false;
    return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_CREATED).header(HttpHeaders.ETAG, getEtag());
}

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

/**
 * Tests the reloading of a trust config backed by pem files when there is an exception during reloading. An exception is caused by
 * truncating the certificate file that is being monitored
 *//*w w  w .  j  av  a 2s .  co m*/
public void testPEMTrustReloadException() throws Exception {
    Path tempDir = createTempDir();
    Path clientCertPath = tempDir.resolve("testclient.crt");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.crt"),
            clientCertPath);
    Settings settings = Settings.builder()
            .putList("xpack.ssl.certificate_authorities", clientCertPath.toString())
            .put("path.home", createTempDir()).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    final SSLService sslService = new SSLService(settings, env);
    final SSLConfiguration config = sslService.sslConfiguration(Settings.EMPTY);
    new SSLConfigurationReloader(settings, env, sslService, resourceWatcherService) {
        @Override
        void reloadSSLContext(SSLConfiguration configuration) {
            fail("reload should not be called! [pem trust reload exception]");
        }
    };

    final SSLContext context = sslService.sslContextHolder(config).sslContext();

    // write bad file
    Path updatedCert = tempDir.resolve("updated.crt");
    try (OutputStream os = Files.newOutputStream(updatedCert)) {
        os.write(randomByte());
    }
    atomicMoveIfPossible(updatedCert, clientCertPath);

    // we intentionally don't wait here as we rely on concurrency to catch a failure
    assertThat(sslService.sslContextHolder(config).sslContext(), sameInstance(context));

}