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.CatalogFrameworkImpl.java

private 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 {//from   ww w .  ja  v a2 s . c o m
            Path tmpPath = null;
            long size;
            try {
                if (contentItem.getInputStream() != null) {
                    tmpPath = Files.createTempFile(FilenameUtils.getBaseName(contentItem.getFilename()),
                            FilenameUtils.getExtension(contentItem.getFilename()));
                    Files.copy(contentItem.getInputStream(), tmpPath, StandardCopyOption.REPLACE_EXISTING);
                    size = Files.size(tmpPath);
                    tmpContentPaths.put(contentItem.getId(), tmpPath);
                } else {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }
            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            } finally {
                IOUtils.closeQuietly(contentItem.getInputStream());
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, contentItem.getFilename(), tmpPath);

            String fileName = updateFileExtension(mimeTypeRaw, contentItem.getFilename());
            Metacard metacard = generateMetacard(mimeTypeRaw, contentItem.getId(), fileName, size,
                    (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().stream().forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*from   w w  w .  j a v  a2 s.  c  om*/
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:adalid.util.velocity.BaseBuilder.java

private void copy(String source, String target) throws IOException {
    Path sourcePath = Paths.get(source);
    Path targetPath = Paths.get(target);
    //overwrite existing file, if exists
    CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES };
    Files.copy(sourcePath, targetPath, options);
}

From source file:ddf.test.itests.catalog.TestCatalog.java

@Test
public void testContentDirectoryMonitor() throws Exception {
    final String TMP_PREFIX = "tcdm_";
    Path tmpDir = Files.createTempDirectory(TMP_PREFIX);
    tmpDir.toFile().deleteOnExit();// ww w.  j  a va  2  s.  c  o m
    Path tmpFile = Files.createTempFile(tmpDir, TMP_PREFIX, "_tmp.xml");
    tmpFile.toFile().deleteOnExit();
    Files.copy(this.getClass().getClassLoader().getResourceAsStream("metacard5.xml"), tmpFile,
            StandardCopyOption.REPLACE_EXISTING);

    Map<String, Object> cdmProperties = new HashMap<>();
    cdmProperties.putAll(getMetatypeDefaults("content-core-directorymonitor",
            "org.codice.ddf.catalog.content.monitor.ContentDirectoryMonitor"));
    cdmProperties.put("monitoredDirectoryPath", tmpDir.toString() + "/");
    createManagedService("org.codice.ddf.catalog.content.monitor.ContentDirectoryMonitor", cdmProperties);

    long startTime = System.nanoTime();
    ValidatableResponse response = null;
    do {
        response = executeOpenSearch("xml", "q=*SysAdmin*");
        if (response.extract().xmlPath().getList("metacards.metacard").size() == 1) {
            break;
        }
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
        }
    } while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) < TimeUnit.MINUTES.toMillis(1));
    response.body("metacards.metacard.size()", equalTo(1));
}

From source file:managedBean.MbVNotas.java

public void guardarPago() {
        try {//from  w w  w. ja  v a2s  . c  om
            if ((!file.getFileName().equals("") && valor != null) && valor.doubleValue() > 0) {
                PagosDao pDao = new PagosDao();
                if (!pDao.existeComprobante(idComprobante)) {
                    Matricula m = new Matricula();
                    pago = new Pago();
                    m.setId(selectedNota.getIdMatricula());
                    pago.setValor(valor);
                    pago.setIdComprobante(idComprobante);
                    pago.setEstado('E');
                    Date fecha = new Date();
                    pago.setFecha(fecha);
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date dateobj = new Date();
                    String nombreCarpeta = selectedNota.getNombresEstudiante().trim();
                    String maest = removeCaractEspeciales(selectedNota.getDescripMaestria()).trim();
                    File directorio = new File("c:/Postgrado/pagos/" + maest + "/" + selectedNota.getIdMatricula()
                            + "-" + nombreCarpeta + "/");
                    if (!directorio.exists()) {
                        directorio.mkdirs();
                    }
                    String filename = selectedNota.getIdMatricula()
                            + (df.format(dateobj).replaceAll(":", "-")).trim();
                    String extension = FilenameUtils.getExtension(file.getFileName());
                    Path ruta = Paths.get(directorio + "/" + filename + "." + extension);
                    InputStream input = file.getInputstream();
                    Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
                    pago.setMatricula(m);
                    pago.setTipoPago(pDao.getTipoPago(idTipoPago));
                    pago.setRutaComprobante(ruta.toString());
                    pDao.registrar(pago);

                    FacesMessage message = new FacesMessage("Succesful", "Datos Guardados correctamente");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                } else {
                    FacesMessage message = new FacesMessage("Error", "El nmero de comprobante ya existe");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                }
            } else {
                valor = BigDecimal.valueOf(0.00);
                FacesMessage message = new FacesMessage("Error", "Ingrese datos");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        } catch (IOException ex) {
            Logger.getLogger(MbVNotas.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage message = new FacesMessage("Error", ex.toString());
            System.out.println(ex.toString());
            FacesContext.getCurrentInstance().addMessage(null, message);
        } catch (Exception ex) {
            Logger.getLogger(MbVNotas.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage message = new FacesMessage("Error", ex.toString());
            System.out.println(ex.toString());
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        idComprobante = "";
        valor = BigDecimal.valueOf(0.00);
        file = null;
    }

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * copies the directories./*from  w w w  .ja  va 2  s  .c  o m*/
 * 
 * @param src
 *            source-directory
 * @param dest
 *            destination-directory
 * @throws IOException
 *             IOException
 */
private void copyFolder(Path src, Path dest) throws IOException {
    if (Files.isDirectory(src)) {
        // if directory not exists, create it
        if (!Files.exists(dest)) {
            Files.createDirectory(dest);
        }
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(src);
        for (Path path : directoryStream) {
            Path srcFile = path;
            Path destFile = Paths.get(dest.toString() + "/" + path.getFileName());
            copyFolder(srcFile, destFile);
        }
    } else {
        Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
    }
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.FeedRestController.java

@POST
@Path("/{feedId}/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)//from   w  ww .  j  av  a 2  s. c o m
@ApiOperation("Uploads a file to be ingested by a feed.")
@ApiResponses({ @ApiResponse(code = 200, message = "The file is ready to be ingested."),
        @ApiResponse(code = 500, message = "The file could not be saved.", response = RestResponseStatus.class) })
public Response uploadFile(@PathParam("feedId") String feedId,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {

    FeedMetadata feed = getMetadataService().getFeedById(feedId, false);
    // Derive path and file
    List<NifiProperty> properties = feed.getProperties();
    String dropzone = null;
    String regexFileFilter = null;

    for (NifiProperty property : properties) {

        if (property.getProcessorType().equals("org.apache.nifi.processors.standard.GetFile")) {
            if (property.getKey().equals("File Filter")) {
                regexFileFilter = property.getValue();
            } else if (property.getKey().equals("Input Directory")) {
                dropzone = property.getValue();
            }
        }
    }
    if (StringUtils.isEmpty(regexFileFilter) || StringUtils.isEmpty(dropzone)) {
        throw new IOException("Unable to upload file with empty dropzone and file");
    }
    File tempTarget = File.createTempFile("kylo-upload", "");
    String fileName = "";
    try {
        Generex fileNameGenerator = new Generex(regexFileFilter);
        fileName = fileNameGenerator.random();

        // Cleanup oddball characters generated by generex
        fileName = fileName.replaceAll("[^A-Za-z0-9\\.\\_\\+\\%\\-\\|]+", "\\.");
        java.nio.file.Path dropZoneTarget = Paths.get(dropzone, fileName);
        File dropZoneFile = dropZoneTarget.toFile();
        if (dropZoneFile.exists()) {
            throw new IOException("File with the name [" + fileName + "] already exists in [" + dropzone + "]");
        }

        Files.copy(fileInputStream, tempTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        Files.move(tempTarget.toPath(), dropZoneTarget);

        // Set read, write
        dropZoneFile.setReadable(true);
        dropZoneFile.setWritable(true);

    } catch (AccessDeniedException e) {
        String errTemplate = "Permission denied attempting to write file [%s] to [%s]. Check with system administrator to ensure this application has write permissions to folder";
        String err = String.format(errTemplate, fileName, dropzone);
        log.error(err);
        throw new InternalServerErrorException(err);

    } catch (Exception e) {
        String errTemplate = "Unexpected exception writing file [%s] to [%s].";
        String err = String.format(errTemplate, fileName, dropzone);
        log.error(err);
        throw new InternalServerErrorException(err);
    }
    return Response.ok("").build();
}

From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java

/**
 * The 'beginOutputProcess' function will start the process to creating the target download transaction
 *
 * @param configDetails//from   w w w  .  j  a  va  2  s. com
 * @param transaction
 * @param transportDetails
 * @param uploadedBatchDetails
 */
public int beginOutputProcess(transactionTarget transaction) throws Exception {

    try {
        int batchId = 0;

        batchUploads uploadedBatchDetails = transactionInManager
                .getBatchDetails(transaction.getbatchUploadId());

        configuration configDetails = configurationManager.getConfigurationById(transaction.getconfigId());

        configurationTransport transportDetails = configurationTransportManager
                .getTransportDetails(transaction.getconfigId());

        /* Check to see what outut transport method was set up */

        /* ERG */
        if (transportDetails.gettransportMethodId() == 2) {

            /* Generate the batch */
            /* (target configuration Details, transaction details, transport Details for target config, Source OrgId, Source Original Filename, mergeable) */
            try {
                batchId = generateBatch(configDetails, transaction, transportDetails,
                        uploadedBatchDetails.getOrgId(), uploadedBatchDetails.getoriginalFileName(), false);

                /* Update the status of the uploaded batch to  TBP (Target Batch Creating in process) (ID = 25) */
                transactionInManager.updateBatchStatus(batchId, 25, "");
            } catch (Exception e) {
                throw new Exception(
                        "Error occurred trying to generate a batch. transactionId: " + transaction.getId(), e);
            }

        } /* File Download || FTP || EMed-Apps */ else if (transportDetails.gettransportMethodId() == 1
                || transportDetails.gettransportMethodId() == 3
                || transportDetails.gettransportMethodId() == 5) {

            boolean createNewFile = true;

            /* 
             If the merge batches option is not checked create the batch right away
             */
            if (transportDetails.getmergeBatches() == false) {

                /* Generate the batch */
                /* (target configuration Details, transaction details, transport Details for target config, Source OrgId, Source Original Filename, mergeable) */
                try {
                    batchId = generateBatch(configDetails, transaction, transportDetails,
                            uploadedBatchDetails.getOrgId(), uploadedBatchDetails.getoriginalFileName(), false);

                    /* Update the status of the uploaded batch to  TBP (Target Batch Creating in process) (ID = 25) */
                    transactionInManager.updateBatchStatus(batchId, 25, "");
                } catch (Exception e) {
                    throw new Exception(
                            "Error occurred trying to generate a batch. transactionId: " + transaction.getId(),
                            e);
                }

            } else {

                /* We want to merge this transaction with the existing created batch if not yet opened (ID = 28) */
                /* 1. Need to see if a mergable batch exists for the org that hasn't been picked up yet */
                int mergeablebatchId = transactionOutDAO.findMergeableBatch(configDetails.getorgId());

                /* If no mergable batch is found create a new batch */
                if (mergeablebatchId == 0) {

                    /* Generate the batch */
                    /* (target configuration Details, transaction details, transport Details for target config, Source OrgId, Source Original Filename, mergeable) */
                    try {
                        batchId = generateBatch(configDetails, transaction, transportDetails,
                                uploadedBatchDetails.getOrgId(), uploadedBatchDetails.getoriginalFileName(),
                                true);

                        /* Update the status of the uploaded batch to  TBP (Target Batch Creating in process) (ID = 25) */
                        transactionInManager.updateBatchStatus(batchId, 25, "");
                    } catch (Exception e) {
                        throw new Exception("Error occurred trying to generate a batch. transactionId: "
                                + transaction.getId(), e);
                    }

                } else {

                    batchId = mergeablebatchId;

                    /* Need to upldate the transaction batchDLId to the new found batch Id */
                    transactionOutDAO.updateTransactionTargetBatchDLId(batchId, transaction.getId());

                    /* Need to add a new entry in the summary table (need to make sure we don't enter duplicates) */
                    batchDownloadSummary summary = new batchDownloadSummary();
                    summary.setbatchId(batchId);
                    summary.settargetConfigId(configDetails.getId());
                    summary.setmessageTypeId(configDetails.getMessageTypeId());
                    summary.settargetOrgId(configDetails.getorgId());
                    summary.settransactionTargetId(transaction.getId());
                    summary.setsourceOrgId(uploadedBatchDetails.getOrgId());

                    try {
                        transactionOutDAO.submitSummaryEntry(summary);
                    } catch (Exception e) {
                        throw new Exception("Error occurred submitting the batch summary. batchId: " + batchId,
                                e);
                    }

                    createNewFile = false;

                }

            }

            /* Generate the file according to transportDetails 
             * 1. we generate output file according to encoding in transportDetails
             * 2. we always save an encrypted copy to archivesOut
             * */
            try {
                boolean encryptMessage = false;
                // we only support base64 for now
                if (transportDetails.getEncodingId() == 2) {
                    encryptMessage = true;
                }
                String generatedFilePath = generateTargetFile(createNewFile, transaction.getId(), batchId,
                        transportDetails, encryptMessage);

                try {
                    //we get dl file info
                    batchDownloads batchDetails = getBatchDetails(batchId);

                    File generatedFile = new File(generatedFilePath);
                    //file extension
                    String fileExt = batchDetails.getoutputFIleName()
                            .substring(batchDetails.getoutputFIleName().lastIndexOf("."));

                    fileSystem fileSystem = new fileSystem();
                    File archiveFile = new File(
                            fileSystem.setPath(archivePath) + batchDetails.getutBatchName() + fileExt);

                    //we check to see if our file is encoded
                    if (!encryptMessage) {
                        //we encode here
                        String strEncodedFile = filemanager.encodeFileToBase64Binary(generatedFile);
                        if (archiveFile.exists()) {
                            archiveFile.delete();
                        }
                        filemanager.writeFile(archiveFile.getAbsolutePath(), strEncodedFile);
                    } else {
                        Files.copy(generatedFile.toPath(), archiveFile.toPath(),
                                StandardCopyOption.REPLACE_EXISTING);
                    }

                } catch (Exception e) {
                    throw new Exception(
                            "Error occurred trying to copy generated file to archiveOut -  batchId: " + batchId,
                            e);
                }
            } catch (Exception e) {
                throw new Exception("Error occurred trying to generate the batch file. batchId: " + batchId, e);
            }
        }

        /* Update the status of the transaction to PP (Pending Pickup) (ID = 18) */
        transactionInManager.updateTransactionStatus(transaction.getbatchUploadId(),
                transaction.gettransactionInId(), 0, 18);

        /* Update the status of the transaction target to PP (Pending Pickup) (ID = 18) */
        updateTransactionTargetStatusOutBound(0, transaction.getId(), 0, 18);

        /* Update the status of the uploaded batch to  TBP (Target Batch Created) (ID = 28) */
        transactionInManager.updateBatchStatus(transaction.getbatchUploadId(), 28, "");

        return batchId;
    } catch (Exception e) {
        throw new Exception("Error occurred during the process of generating output files. transactionId: "
                + transaction.getId(), e);
    }

}

From source file:ddf.test.itests.platform.TestSecurity.java

void getBackupKeystoreFile() throws IOException {
    Files.copy(Paths.get(getKeystoreFilename()), Paths.get(getBackupFilename()), REPLACE_EXISTING);
}

From source file:ddf.test.itests.platform.TestSecurity.java

void restoreKeystoreFile() throws IOException {
    Files.copy(Paths.get(getBackupFilename()), Paths.get(getKeystoreFilename()), REPLACE_EXISTING);
}