List of usage examples for java.nio.file Files copy
public static long copy(Path source, OutputStream out) throws IOException
From source file:de.elomagic.carafile.client.CaraFileClient.java
/** * Downloads a file into a {@link OutputStream}. * * @param md {@link MetaData} of the file. * @param out The output stream. It's not recommended to use a buffered stream. * @throws IOException Thrown when unable to write file into the output stream or the SHA-1 validation failed. *///ww w . java 2 s .co m public void downloadFile(final MetaData md, final OutputStream out) throws IOException { if (md == null) { throw new IllegalArgumentException("Parameter 'md' must not be null!"); } if (out == null) { throw new IllegalArgumentException("Parameter 'out' must not be null!"); } Map<String, Path> downloadedChunks = new HashMap<>(); Set<String> chunksToDownload = new HashSet<>(); for (ChunkData chunkData : md.getChunks()) { chunksToDownload.add(chunkData.getId()); } try { while (!chunksToDownload.isEmpty()) { PeerChunk pc = peerChunkSelector.getNext(md, chunksToDownload); if (pc == null || pc.getPeerURI() == null) { throw new IOException("No peer found or selected for download"); } Path chunkFile = Files.createTempFile("fs_", ".tmp"); try (OutputStream chunkOut = Files.newOutputStream(chunkFile, StandardOpenOption.APPEND)) { downloadShunk(pc, md, chunkOut); downloadedChunks.put(pc.getChunkId(), chunkFile); chunksToDownload.remove(pc.getChunkId()); chunkOut.flush(); } catch (Exception ex) { Files.deleteIfExists(chunkFile); throw ex; } } MessageDigest messageDigest = DigestUtils.getSha1Digest(); // Write chunk on correct order to file. try (DigestOutputStream dos = new DigestOutputStream(out, messageDigest); BufferedOutputStream bos = new BufferedOutputStream(dos, md.getChunkSize())) { for (ChunkData chunk : md.getChunks()) { Path chunkPath = downloadedChunks.get(chunk.getId()); Files.copy(chunkPath, bos); } } String sha1 = Hex.encodeHexString(messageDigest.digest()); if (!sha1.equalsIgnoreCase(md.getId())) { throw new IOException( "SHA1 validation of file failed. Expected " + md.getId() + " but was " + sha1); } } finally { for (Path path : downloadedChunks.values()) { try { Files.deleteIfExists(path); } catch (IOException ex) { LOG.error("Unable to delete chunk " + path.toString() + "; " + ex.getMessage(), ex); } } } }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * Moves uploaded files from the temp upload directory to the appropriate store folder * Updates the ImportContext tasks and stores with the new location. * Updates the catalog store with the new location. * /* ww w . java 2s.com*/ * @param t ImportTask containing data about a single import */ void moveFile(ImportTask t) { Catalog catalog = geoServer.getCatalog(); StoreInfo store = catalog.getStore(t.getStore().getId(), StoreInfo.class); if (store == null) { LOG.warning("Trying to move files to a non-existant store"); return; } if (!(t.getData() instanceof FileData)) { LOG.warning("Trying to move non-file data"); return; } if (!t.isDirect()) { LOG.warning("Trying to move files from an indirect import"); return; } WorkspaceInfo ws = store.getWorkspace(); //Special behavior for SpatialFile - linked files FileData srcData = (FileData) t.getData(); File srcFile = srcData.getFile().file(); File storeFile; File destDir; FileData destData; File destFile; try { destDir = uploadDir(catalog, ws, store); destFile = new File(destDir, srcData.getFile().file().getName()); if (srcFile.getAbsoluteFile().equals(destFile.getAbsoluteFile())) { LOG.warning("Trying to move file to itself"); return; } destDir.mkdirs(); //Update Store File baseDirectory = catalog.getResourceLoader().getBaseDirectory(); if (store instanceof CoverageStoreInfo) { storeFile = catalog.getResourceLoader().url(((CoverageStoreInfo) store).getURL()); //A CoverageStore needs a single file String url = "file:" + Paths.convert(baseDirectory, destFile); if (!(srcData.getFile().file().getAbsolutePath().equals(storeFile.getAbsolutePath()))) { throw new RuntimeException("CoverageStore file not the same as imported file"); } ((CoverageStoreInfo) store).setURL(url); } else if (store instanceof DataStoreInfo) { storeFile = catalog.getResourceLoader().url(store.getConnectionParameters().get("url").toString()); /* A DataStore may contain multiple files as separate "tables". * Therefore, we use the store dir for the URL, and ensure the file location is * somewhere in this directory. * * If the store file is the same as the destination directory, then we may be in * progress moving files. * * If the store file is a prefix of the source data file, then all is well * * Otherwise, we have a problem and should abort. */ String url = "file:" + Paths.convert(baseDirectory, destDir); if (!(storeFile.equals(destDir.getAbsoluteFile()) || srcData.getFile().file().getAbsolutePath().startsWith(storeFile.getAbsolutePath()))) { throw new RuntimeException("DataStore file not the same as imported file"); } store.getConnectionParameters().put("url", url); } else { throw new RuntimeException("Invalid store type: " + store.getClass()); } //Test if we can actually move the file; otherwise copy the file. boolean move = srcFile.renameTo(srcFile); if (move) { Files.move(srcFile.toPath(), destFile.toPath()); } else { Files.copy(srcFile.toPath(), destFile.toPath()); } //move any supplementary files, update ImportData if (srcData instanceof SpatialFile) { destData = new SpatialFile(destFile); if (((SpatialFile) srcData).getPrjFile() != null) { File prjFile = new File(destDir, ((SpatialFile) srcData).getPrjFile().file().getName()); if (move) { Files.move(((SpatialFile) srcData).getPrjFile().file().toPath(), prjFile.toPath()); } else { Files.copy(((SpatialFile) srcData).getPrjFile().file().toPath(), prjFile.toPath()); } ((SpatialFile) destData).setPrjFile(org.geoserver.platform.resource.Files.asResource(prjFile)); } for (Resource r : ((SpatialFile) srcData).getSuppFiles()) { File suppFile = new File(destDir, r.file().getName()); if (move) { Files.move(r.file().toPath(), suppFile.toPath()); } else { Files.copy(r.file().toPath(), suppFile.toPath()); } ((SpatialFile) destData).getSuppFiles() .add(org.geoserver.platform.resource.Files.asResource(suppFile)); } } else if (srcData instanceof ASpatialFile) { destData = new ASpatialFile(org.geoserver.platform.resource.Files.asResource(destFile)); } else { destData = new FileData(org.geoserver.platform.resource.Files.asResource(destFile)); } } catch (Exception e) { //If this occurs, the store files will be in a temporary folder, so we should abort the import t.setError(e); t.setState(State.ERROR); store.accept(new CascadeDeleteVisitor(catalog)); throw new RuntimeException("Failed to move imported files to uploads directory", e); } //Copy over attributes from srcData destData.setFormat(srcData.getFormat()); destData.setMessage(srcData.getMessage()); destData.setCharsetEncoding(srcData.getCharsetEncoding()); //Update data t.setData(destData); t.setStore(store); //Save the updated store to the catalog catalog.save(store); }
From source file:elh.eus.absa.NLPpipelineWrapper.java
public static int eustaggerCall(String taggerCommand, String string, String fname) { try {//from w ww. j a va 2 s .co m File temp = new File(fname); //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); bw.write(string + "\n"); bw.close(); String[] command = { taggerCommand, temp.getName() }; System.err.println("Eustagger agindua: " + Arrays.toString(command)); ProcessBuilder eustBuilder = new ProcessBuilder().command(command); eustBuilder.directory(new File(temp.getParent())); //.redirectErrorStream(true); Process eustagger = eustBuilder.start(); int success = eustagger.waitFor(); //System.err.println("eustagger succesful? "+success); if (success != 0) { System.err.println("eustaggerCall: eustagger error"); } else { String tagged = fname + ".kaf"; BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream())); //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) { Files.copy(eustagger.getInputStream(), Paths.get(tagged)); } // old eustagger (euslem) else { FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged); } } // // delete all temporal files used in the process. temp.delete(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return -1; } return 0; }
From source file:com.groupon.odo.controllers.ServerMappingController.java
/** * Returns a X509 binary certificate for a given domain name if a certificate has been generated for it * * @param locale/*from ww w. j a va 2 s. c om*/ * @param model * @param response * @param hostname * @throws Exception */ @RequestMapping(value = "/cert/{hostname:.+}", method = { RequestMethod.GET, RequestMethod.HEAD }) public @ResponseBody void getCert(Locale locale, Model model, HttpServletResponse response, @PathVariable String hostname) throws Exception { // Set the appropriate headers so the browser thinks this is a file response.reset(); response.setContentType("application/x-x509-ca-cert"); response.setHeader("Content-Disposition", "attachment;filename=" + hostname + ".cer"); // special handling for hostname=="root" // return the CyberVillians Root Cert in this case if (hostname.equals("root")) { hostname = "cybervillainsCA"; response.setContentType("application/pkix-cert "); } // get the cert for the hostname KeyStoreManager keyStoreManager = com.groupon.odo.bmp.Utils.getKeyStoreManager(hostname); if (hostname.equals("cybervillainsCA")) { // get the cybervillians cert from resources File root = new File("seleniumSslSupport" + File.separator + hostname); // return the root cert Files.copy(new File(root.getAbsolutePath() + File.separator + hostname + ".cer").toPath(), response.getOutputStream()); response.flushBuffer(); } else { // return the cert for the appropriate alias response.getOutputStream().write(keyStoreManager.getCertificateByAlias(hostname).getEncoded()); response.flushBuffer(); } }
From source file:fr.duminy.jbackup.core.ConfigurationManagerTest.java
private void initAndGetLatestArchive(int nbConfigurations) throws Exception { BackupConfiguration config = createConfiguration("config", tempFolder.newFolder().toPath()); Path[] files = new Path[nbConfigurations]; for (int i = 0; i < nbConfigurations; i++) { Path file = Paths.get(config.getTargetDirectory()).resolve("file" + i); Files.copy(ZipArchiveFactoryTest.getArchive(), file); Thread.sleep(1000);/*from w w w . j a va 2s . co m*/ files[i] = file; } Path configFile = ConfigurationManager.getLatestArchive(config); assertThat(configFile).isEqualTo(files[files.length - 1]); }
From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java
/** * Tests the reloading of a keystore when there is an exception during reloading. An exception is caused by truncating the keystore * that is being monitored//from w w w . ja v a 2 s .com */ public void testReloadingKeyStoreException() throws Exception { Path tempDir = createTempDir(); Path keystorePath = tempDir.resolve("testnode.jks"); Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"), keystorePath); MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString("xpack.ssl.keystore.secure_password", "testnode"); Settings settings = Settings.builder().put("xpack.ssl.keystore.path", keystorePath) .setSecureSettings(secureSettings).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! [keystore reload exception]"); } }; final SSLContext context = sslService.sslContextHolder(config).sslContext(); // truncate the keystore try (OutputStream out = Files.newOutputStream(keystorePath, 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:it.unibo.alchemist.model.implementations.environments.OSMEnvironment.java
private void initAll(final String fileName) throws IOException { Objects.requireNonNull(fileName, "define the file with the map: " + fileName); final Optional<URL> file = Optional.of(new File(fileName)).filter(File::exists).map(File::toURI) .map(Unchecked.function(URI::toURL)); final URL resource = Optional.ofNullable(OSMEnvironment.class.getResource(fileName)) .orElseGet(Unchecked.supplier(() -> file.orElseThrow( () -> new FileNotFoundException("No file or resource with name " + fileName)))); final String dir = initDir(resource).intern(); final File workdir = new File(dir); mkdirsIfNeeded(workdir);// ww w .j a v a 2 s . c o m final File mapFile = new File(dir + SLASH + MAPNAME); try (RandomAccessFile fileAccess = new RandomAccessFile(workdir + SLASH + "lock", "rw")) { try (FileLock lock = fileAccess.getChannel().lock()) { if (!mapFile.exists()) { Files.copy(resource.openStream(), mapFile.toPath()); } } } navigators = new EnumMap<>(Vehicle.class); mapLock = new FastReadWriteLock(); final Optional<Exception> error = Arrays.stream(Vehicle.values()).parallel().<Optional<Exception>>map(v -> { try { final String internalWorkdir = workdir + SLASH + v; final File iwdf = new File(internalWorkdir); if (mkdirsIfNeeded(iwdf)) { final GraphHopperAPI gh = initNavigationSystem(mapFile, internalWorkdir, v); mapLock.write(); navigators.put(v, gh); mapLock.release(); } return Optional.empty(); } catch (Exception e) { return Optional.of(e); } }).filter(Optional::isPresent).map(Optional::get).findFirst(); if (error.isPresent()) { throw new IllegalStateException("A error occurred during initialization.", error.get()); } }
From source file:com.ut.healthelink.controller.HealtheConnectController.java
/** * The '/submitFileUpload' POST request will submit the new file and run the file through various validations. If a single validation fails the batch will be put in a error validation status and the file will be removed from the system. The user will receive an error message on the screen letting them know which validations have failed and be asked to upload a new file. * * The following validations will be taken place. - File is not empty - Proper file type (as determined in the configuration set up) - Proper delimiter (as determined in the configuration set up) - Does not exceed file size (as determined in the configuration set up) *///from w w w. ja va 2 s. com @RequestMapping(value = "/submitFileUpload", method = RequestMethod.POST) public @ResponseBody ModelAndView submitFileUpload(RedirectAttributes redirectAttr, HttpSession session, @RequestParam(value = "configId", required = true) Integer configId, @RequestParam(value = "uploadedFile", required = true) MultipartFile uploadedFile) throws Exception { /* Get the organization details for the source (Sender) organization */ User userInfo = (User) session.getAttribute("userDetails"); configuration configDetails = null; configurationTransport transportDetails = null; configurationMessageSpecs messageSpecs = null; String delimChar = null; boolean multipleMessageTypes = false; /* When Multiple Message Types is selected we need to find one config Id attached to the user in order to pull the information to process the file. */ if (configId == 0) { /* Need to get list of available configurations for the user */ List<configuration> configurations = configurationManager .getActiveConfigurationsByUserId(userInfo.getId(), 1); /* Pull the first configuration in the list */ configId = configurations.get(0).getId(); /* Need to get the details of the configuration */ configDetails = configurationManager.getConfigurationById(configId); transportDetails = configurationtransportmanager.getTransportDetails(configId); messageSpecs = configurationManager.getMessageSpecs(configId); delimChar = (String) messageTypeDAO.getDelimiterChar(transportDetails.getfileDelimiter()); multipleMessageTypes = true; } else { /* Need to get the details of the configuration */ configDetails = configurationManager.getConfigurationById(configId); transportDetails = configurationtransportmanager.getTransportDetails(configId); messageSpecs = configurationManager.getMessageSpecs(configId); delimChar = (String) messageTypeDAO.getDelimiterChar(transportDetails.getfileDelimiter()); } try { /* Need to add the file to the batchUploads table */ /* Create the batch name (TransportMethodId+OrgId+MessageTypeId+Date/Time/Seconds) */ DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS"); Date date = new Date(); //adding transport method id to UT batch name String batchName = new StringBuilder().append("1").append(userInfo.getOrgId()) .append(configDetails.getMessageTypeId()).append(dateFormat.format(date)).toString(); /* Upload the file */ Map<String, String> batchResults = null; fileSystem dir = new fileSystem(); dir.setDirByName("/"); //need to write the file first, we will write it to our process folder String uploadedFileName = transactionInManager.copyUplaodedPath(transportDetails, uploadedFile); String oldFilePath = dir.getDir() + transportDetails.getfileLocation(); oldFilePath = oldFilePath.replace("bowlink///", ""); File oldFile = new File(oldFilePath + uploadedFileName); Path source = oldFile.toPath(); String processFilePath = dir.setPath(processPath); String strProcessFile = processFilePath + uploadedFileName; File processFile = new File(strProcessFile); //right now we only support id 2, Base64 if (transportDetails.getEncodingId() == 2) { String strDecode = filemanager.decodeFileToBase64Binary(oldFile); filemanager.writeFile((processFilePath + uploadedFileName), strDecode); } else { processFile = oldFile; } //we decode file and pass it into uploadedFile batchResults = transactionInManager.chkUploadBatchFile(transportDetails, processFile); //we delete the temp file here if (transportDetails.getEncodingId() == 2) { processFile.delete(); } //we set archive path File archiveFile = new File(dir.setPath(archivePath) + batchName + batchResults.get("fileName").substring(batchResults.get("fileName").lastIndexOf("."))); Path archive = archiveFile.toPath(); if (transportDetails.getEncodingId() == 1) { String strEncodedFile = filemanager.encodeFileToBase64Binary(oldFile); Files.move(source, archive, REPLACE_EXISTING); //we replace file with encoded filemanager.writeFile(oldFile.getAbsolutePath(), strEncodedFile); } else { // already encoded Files.copy(source, archive); } /* Submit a new batch */ batchUploads batchUpload = new batchUploads(); batchUpload.setOrgId(userInfo.getOrgId()); batchUpload.setuserId(userInfo.getId()); batchUpload.setutBatchName(batchName); batchUpload.settransportMethodId(1); batchUpload.setoriginalFileName(batchName); batchUpload.setoriginalFileName(batchResults.get("fileName")); batchUpload.setFileLocation(transportDetails.getfileLocation()); batchUpload.setContainsHeaderRow(messageSpecs.getcontainsHeaderRow()); batchUpload.setDelimChar(delimChar); batchUpload.setEncodingId(transportDetails.getEncodingId()); if (multipleMessageTypes == true) { batchUpload.setConfigId(0); } else { batchUpload.setConfigId(configId); } /* Set the status to the batch as SFV (Source Failed Validation) */ batchUpload.setstatusId(1); Integer batchId = (Integer) transactionInManager.submitBatchUpload(batchUpload); List<Integer> errorCodes = new ArrayList<Integer>(); Object emptyFileVal = batchResults.get("emptyFile"); if (emptyFileVal != null) { errorCodes.add(1); } Object wrongSizeVal = batchResults.get("wrongSize"); if (wrongSizeVal != null) { errorCodes.add(2); } Object wrongFileTypeVal = batchResults.get("wrongFileType"); if (wrongFileTypeVal != null) { errorCodes.add(3); } Object wrongDelimVal = batchResults.get("wrongDelim"); if (wrongDelimVal != null) { errorCodes.add(4); } /* Make sure the org doesn't have multiple configurations with different delims, headers, etc */ if (multipleMessageTypes == true) { List<configurationTransport> transportTypes = configurationtransportmanager .getDistinctConfigTransportForOrg(userInfo.getOrgId(), 1); if (transportTypes.size() != 1) { errorCodes.add(5); } } /* If Passed validation update the status to Source Submission Accepted */ if (0 == errorCodes.size()) { /* Get the details of the batch */ batchUploads batch = transactionInManager.getBatchDetails(batchId); batch.setstatusId(2); transactionInManager.submitBatchUploadChanges(batch); /* Redirect to the list of uploaded batches */ redirectAttr.addFlashAttribute("savedStatus", "uploaded"); } else { redirectAttr.addFlashAttribute("savedStatus", "error"); redirectAttr.addFlashAttribute("errorCodes", errorCodes); } try { //log user activity UserActivity ua = new UserActivity(); ua.setUserId(userInfo.getId()); ua.setFeatureId(featureId); ua.setAccessMethod("POST"); ua.setPageAccess("/submitFileUpload"); ua.setActivity("Uploaded a new file"); ua.setBatchUploadId(batchId); usermanager.insertUserLog(ua); } catch (Exception ex) { System.err.println("submitFileUpload = error logging user " + ex.getCause()); ex.printStackTrace(); } ModelAndView mav = new ModelAndView(new RedirectView("upload")); return mav; } catch (Exception e) { throw new Exception("Error occurred uploading a new file. configId: " + configId, e); } }
From source file:fi.helsinki.cs.iot.hub.jsengine.DuktapeJavascriptEngineWrapper.java
public String getEcmaEventLoopFilename() { File file = Paths.get(libdir.toString(), "ecma_eventloop.js").toFile(); if (!file.exists()) { try {/* w ww. ja va 2 s.co m*/ InputStream link = (DuktapeJavascriptEngineWrapper.class.getResourceAsStream("/ecma_eventloop.js")); Files.copy(link, file.getAbsoluteFile().toPath()); return file.getAbsolutePath(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } return file.getAbsolutePath(); }