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:it.infn.ct.ToscaIDCInterface.java

/**
 * GetStatus of TOSCA submission.//from ww  w  .j  a va2s.  c  om
 *
 * @return Status o TOSCA UUID
 */
public final String getStatus() {
    LOG.debug("Entering IDC getStatus ...");

    // Load command parameters from <task_id>.json file
    loadJSONTask();

    String status = toscaCommand.getTargetStatus();
    try {
        toscaEndPoint = new URL(tiiDB.toscaEndPoint(toscaCommand));
    } catch (MalformedURLException ex) {
        LOG.error("Unable to get endpoint from command: '" + toscaCommand + "'");
    }
    LOG.debug("tosca endpoint: '" + toscaEndPoint + "'");
    String tUUID = tiiDB.getToscaId(toscaCommand);
    LOG.debug("tosca UUID: '" + tUUID + "'");
    String tToken = tiiDB.getToken(toscaCommand);
    LOG.debug("tosca Token: '" + tToken + "'");
    String toscaDeploymentInfo = getToscaDeployment(tUUID, tToken);
    LOG.debug("tosca deployment info: '" + toscaDeploymentInfo + "'");
    try {
        status = getDocumentValue(toscaDeploymentInfo, "status");
    } catch (ParseException ex) {
        LOG.error("Unable to parse deployment result: '" + toscaDeploymentInfo + "'");
    }
    // Do status mapping (orchestrator->JSAGA style)
    // Check for DONE status; this saves the informative file
    if (status.equals("CREATE_COMPLETE")) {
        status = "DONE";
        // When deployment is done save in runtime data outputs field
        informtativeFile = getInfoFilePath();
        try {
            String outputs = getDocumentValue(toscaDeploymentInfo, "outputs");
            LOG.debug("Output for deployment having UUID: '" + tUUID + "' is: '" + outputs + "'");
            saveInformativeFile(outputs);
            toscaCommand.setRunTimeData("tosca_outputs", informtativeFile, "TOSCA deployiment outputs field",
                    "file://", "plain/text");
            LOG.debug("Successfully generated informativeFile at: '" + informtativeFile
                    + "' and registered it on runtime data");
        } catch (Exception ex) {
            LOG.error(
                    "Unable to parse deployment info: '" + toscaDeploymentInfo + "' looking for outputs field");
        }
        // Now make a informative file copy to output file if specified
        if (output.length() > 0) {
            try {
                Files.copy(Paths.get(informtativeFile), Paths.get(getOutputDirPath(), output),
                        REPLACE_EXISTING);
            } catch (Exception IOException) {
                LOG.error("Unable to make copy of file: '" + informtativeFile + "' " + "to file: '"
                        + getOutputDirPath() + LS + output);
            }
        } else {
            LOG.debug("No output  file specified, the orchestrator " + "'outputs' field will be not reported");
        }
    } else if (status.equals("CREATE_FAILED")) {
        status = "ABORT";
        // Now make a informative file copy to output file if specified
        if (error.length() > 0) {
            try {
                Files.copy(Paths.get(informtativeFile), Paths.get(getOutputDirPath(), error), REPLACE_EXISTING);
            } catch (Exception IOException) {
                LOG.error("Unable to make copy of file: '" + informtativeFile + "' " + "to file: '"
                        + getOutputDirPath() + LS + error);
            }
        } else {
            LOG.debug("No error file specified, the orchestrator " + "report will be not available");
        }
    } else if (status.equals("CREATE_IN_PROGRESS")) {
        status = "RUNNING";
    } else {
        // status = "UNKNOWN";
        LOG.error("Unhespected ToscaIDC status: '" + status + "'");
    }
    LOG.debug("Status of deployment having id: '" + tUUID + "' is: '" + status + "'");
    // update target status
    tiiDB.updateToscaStatus(toscaCommand.getTargetId(), status);
    LOG.debug("Leaving IDC getStatus");
    return status;
}

From source file:com.microfocus.application.automation.tools.pc.PcClient.java

public boolean downloadTrendReportAsPdf(String trendReportId, String directory) throws PcException {

    try {//from w  w w. j av  a 2s.  co  m
        logger.println(String.format("%s - %s: %s %s", dateFormatter.getDate(),
                Messages.DownloadingTrendReport(), trendReportId, Messages.InPDFFormat()));
        InputStream in = restProxy.getTrendingPDF(trendReportId);
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = directory + IOUtils.DIR_SEPARATOR + "trendReport" + trendReportId + ".pdf";
        Path destination = Paths.get(filePath);
        Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);
        logger.println(String.format("%s - %s: %s %s", dateFormatter.getDate(), Messages.TrendReport(),
                trendReportId, Messages.SuccessfullyDownloaded()));
    } catch (Exception e) {

        logger.println(String.format("%s - %s: %s", dateFormatter.getDate(),
                Messages.FailedToDownloadTrendReport(), e.getMessage()));
        throw new PcException(e.getMessage());
    }

    return true;

}

From source file:com.joyent.manta.client.MantaClient.java

/**
 * Copies Manta object's data to a temporary file on the file system and return
 * a reference to the file using a NIO {@link Path}. This method is memory
 * efficient because it uses streams to do the copy.
 *
 * @param path The fully qualified path of the object. i.e. /user/stor/foo/bar/baz
 * @return reference to the temporary file as a {@link Path} object
 * @throws IOException when there is a problem getting the object over the network
 *//*from   w  w w. ja va2 s. c  om*/
public Path getToTempPath(final String path) throws IOException {
    try (InputStream is = getAsInputStream(path)) {
        final Path temp = Files.createTempFile("manta-object", "tmp");

        Files.copy(is, temp, StandardCopyOption.REPLACE_EXISTING);

        return temp;
    }
}

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

@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" })
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  2  s .com
    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:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" })
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 ww  w.  j  a  v a  2 s. 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);
    }

    //        Map<String, Object> files= new HashMap<String, Object>();
    //files.put("files", list);
    return bf;
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Copy file that will displayed in Jmol
 * @param doc XML document/*from  w  w  w . j  a v  a  2  s.co  m*/
 * @param rootElt Root element
 * @param xreader XPath reader for the document
 * @param dataDirPath Path to directory that contains analysis data
 * @param dirPath Path to experiment directory
 * @return XML element for Jmol data
 * @throws IOException 
 */
private Element pullJmolFile(Document doc, Node rootElt, XPathReader xreader, String dataDirPath,
        String dirPath) throws IOException {
    Element jmolElt = doc.createElement("jmol");

    String mainStructureRelPath = (String) xreader
            .read("ibiomes/directory/AVUs/AVU[@id='MAIN_3D_STRUCTURE_FILE']", XPathConstants.STRING);
    if (mainStructureRelPath != null && mainStructureRelPath.length() > 0) {
        String dataFileNewName = mainStructureRelPath.replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
        String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
        Files.copy(Paths.get(dirPath + PATH_FOLDER_SEPARATOR + mainStructureRelPath),
                Paths.get(dataFileDestPath), StandardCopyOption.REPLACE_EXISTING);
        //set read permissions
        if (!Utils.isWindows()) {
            Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            permissions.add(PosixFilePermission.OWNER_EXECUTE);
            permissions.add(PosixFilePermission.GROUP_READ);
            permissions.add(PosixFilePermission.OTHERS_READ);
            Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
        }
        jmolElt.setAttribute("path", dataFileNewName);
        jmolElt.setAttribute("name", mainStructureRelPath);

        NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dirPath + PATH_FOLDER_SEPARATOR
                + mainStructureRelPath + "']/AVUs/AVU", XPathConstants.NODESET);
        MetadataAVUList avuList = parseMetadata(avuNodes);
        String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
        if (description != null && description.length() > 0)
            jmolElt.setAttribute("description", description);
        rootElt.appendChild(jmolElt);

        return jmolElt;
    } else
        return null;
}

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

@Test
public void testContentDirectoryMonitor() throws Exception {
    startFeature(true, "content-core-directorymonitor");
    final String TMP_PREFIX = "tcdm_";
    Path tmpDir = Files.createTempDirectory(TMP_PREFIX);
    tmpDir.toFile().deleteOnExit();//from www.j av a 2s .  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",
            "ddf.content.core.directorymonitor.ContentDirectoryMonitor"));
    cdmProperties.put("monitoredDirectoryPath", tmpDir.toString() + "/"); // Must end with /
    cdmProperties.put("directive", "STORE_AND_PROCESS");
    createManagedService("ddf.content.core.directorymonitor.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:datavis.Gui.java

/** 
 * Returns a new PSAWWB data list containing data pulled from TCOON's website
 * @param station The station number, e.g., 33 for Port Lavaca
 * @param interval The number of seconds between data samples, e.g., 86400
 * @param start Date range start date/*from w w w .j a v a 2s.c o m*/
 * @param end Date range end date. Defaults to 1 year if null
 * @return A fresh DataList
 */
public static DataList_PWL_SURGE_ATP_WTP_WSD_BPR getDataFromServer(int station, int interval, Date start,
        Date end) throws UnsupportedEncodingException {
    String dateString = new String(), pattern = new String("%25Y%25j%2B%25H%25M");
    DateFormat format = new SimpleDateFormat("MM.dd.yyyy");
    File temp = null;
    URL url;

    if (interval % 360 != 0 || interval < 360)
        interval = 0; // default to monthly
    if (interval >= 86400)
        pattern = "%25m-%25d-%25Y";
    if (start == null || end == null)
        dateString = "now,-1y";
    else
        dateString = format.format(start) + "-" + format.format(end);
    try {
        temp = File.createTempFile("TCOON", null);
        temp.deleteOnExit();
        url = new URL(String.format(
                "http://lighthouse.tamucc.edu/pd?stnlist=%03d&serlist=pwl,surge,atp,wtp,wsd,bpr&when=%s&whentz=UTC0&-action=csv&unit=metric&elev=stnd&interval=%s&datefmt=%s&rm=0&na=0",
                station, dateString, interval > 0 ? String.valueOf(interval) : "monthly", pattern));
        Files.copy(url.openStream(), temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
    }

    return new DataList_PWL_SURGE_ATP_WTP_WSD_BPR(temp.getAbsolutePath());
}

From source file:io.sloeber.core.managers.Manager.java

/**
 * copy a url locally taking into account redirections
 *
 * @param url/* w w  w .j  a v a  2s  .c  o  m*/
 * @param localFile
 */
@SuppressWarnings("nls")
private static void myCopy(URL url, File localFile) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        conn.addRequestProperty("User-Agent", "Mozilla");
        conn.addRequestProperty("Referer", "google.com");

        // normally, 3xx is redirect
        int status = conn.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)

                Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(),
                        REPLACE_EXISTING);
        } else {
            Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING);
        }

    } catch (Exception e) {
        Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e));
    }
}

From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java

private boolean saveXml2Package(String xml, String uuid) throws IOException {
    uuid = UuidUtil.removeCurlies(uuid);
    //xml file/*w ww . j  a v a2s . c o  m*/
    String folder = Constant.UPLOAD_FOLDER;

    File temp = new File(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_FILE_NAME);
    InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
    //InputStream in = doc.newInputStream();
    Path a = temp.toPath();
    Files.copy(in, a, java.nio.file.StandardCopyOption.REPLACE_EXISTING);

    //copy xml file into zip file
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    Path path = null;
    path = Paths.get(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_ZIP_NAME);
    URI uri = URI.create("jar:" + path.toUri());

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        Files.copy(Paths.get(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_FILE_NAME),
                fs.getPath(Constant.XML_OUTPUT_FILE_NAME), StandardCopyOption.REPLACE_EXISTING);
    }

    return true;
}