List of usage examples for java.nio.file Files move
public static Path move(Path source, Path target, CopyOption... options) throws IOException
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public void deploy(String name) throws XMLConfigException, FileNotFoundException { Path configurationArchivePath = getConfigurationPath(name); Path current = Paths.get(XMLConfig.getBaseConfigPath()); Path staging = current.getParent().resolve("deploy"); Path destination = current.getParent().resolve(name); if (LOCK.tryLock()) { if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) { try { ZipInputStream configurationArchive = new ZipInputStream( Files.newInputStream(configurationArchivePath, StandardOpenOption.READ)); LOG.debug("Starting deploy of configuration " + name); ZipEntry zipEntry = null; for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) { if (!Files.isDirectory(cfgFile)) { Path target = staging.resolve(current.relativize(cfgFile)); Files.createDirectories(target); Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING); }// ww w. j a va 2 s .co m } LOG.debug("Staging new config " + name); while ((zipEntry = configurationArchive.getNextEntry()) != null) { Path entryPath = staging.resolve(zipEntry.getName()); LOG.debug("Adding resource: " + entryPath); if (zipEntry.isDirectory()) { entryPath.toFile().mkdirs(); } else { Path parent = entryPath.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING); } } //**** Deleting old config dir LOG.debug("Removing old config: " + current); Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); LOG.debug("Deploy new config " + name + " in path " + destination); Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE); setXMLConfigBasePath(destination.toString()); LOG.debug("Deploy complete"); deployListeners.forEach(l -> l.onDeploy(destination)); } catch (Exception e) { if (Objects.nonNull(staging) && Files.exists(staging)) { LOG.error("Deploy failed, rollback to previous configuration", e); try { Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); setXMLConfigBasePath(current.toString()); } catch (IOException | InvalidSyntaxException rollbackException) { LOG.error("Failed to delete old configuration", e); } } else { LOG.error("Deploy failed", e); } throw new XMLConfigException("Deploy failed", e); } finally { LOCK.unlock(); } } else { throw new FileNotFoundException(configurationArchivePath.toString()); } } else { throw new IllegalStateException("A deploy is already in progress"); } }
From source file:ch.cyberduck.core.Local.java
public void rename(final Local renamed) throws AccessDeniedException { try {/*from w w w .j a v a 2s . c om*/ Files.move(Paths.get(path), Paths.get(renamed.getAbsolute()), StandardCopyOption.REPLACE_EXISTING); path = renamed.getAbsolute(); } catch (IOException e) { throw new LocalAccessDeniedException(String.format("Rename failed for %s", renamed), e); } }
From source file:org.nuxeo.ecm.core.io.download.TestDownloadService.java
@Test public void testTransientCleanup() throws IOException { // transfert temporary file into a blob Path path = Files.createTempFile("pfouh", "pfouh"); FileBlob blob = new FileBlob("pfouh"); Files.move(path, blob.getFile().toPath(), REPLACE_EXISTING); // store the blob for downloading String key = downloadService.storeBlobs(Collections.singletonList(blob)); // mock request ByteArrayOutputStream out = new ByteArrayOutputStream(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); // mock response HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream sos = new ServletOutputStream() { @Override/*from w w w. j a v a 2 s . c o m*/ public void write(int b) throws IOException { out.write(b); } }; @SuppressWarnings("resource") PrintWriter printWriter = new PrintWriter(sos); when(response.getOutputStream()).thenReturn(sos); when(response.getWriter()).thenReturn(printWriter); NuxeoPrincipal principal = new UserPrincipal("bob", Collections.singletonList("members"), false, false); // do tests while logged in LoginStack loginStack = ClientLoginModule.getThreadLocalLogin(); loginStack.push(principal, null, null); try { downloadService.downloadBlob(request, response, key, "download"); } finally { loginStack.pop(); } // the file is gone assertFalse(blob.getFile().exists()); }
From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java
public Result saveChangesXML(String changesXMLFileName) { try {/*from w ww. j a va 2s .c o m*/ File tempFile = File.createTempFile(changesXMLFileName, "changes.xml"); String changesXMLUrl = artifactsLocation + "/" + changesXMLFileName; System.out.println("Downloading " + changesXMLUrl); FileUtils.copyURLToFile(new URL(changesXMLUrl), tempFile); Path source = Paths.get((String) tempFile.getAbsolutePath()); new File(new File("").getAbsolutePath() + "/" + Configuration.getInstance().getSavePath() + "/" + mcPackage.getPackageName()).mkdirs(); Path destination = Paths.get(new File("").getAbsolutePath() + "/" + Configuration.getInstance().getSavePath() + "/" + mcPackage.getPackageName() + "/" + changesXMLFileName + "_" + mcPackage.getStatus() + "_" + System.currentTimeMillis()); Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING); System.out.println(source.toString() + " renamed to " + destination.toAbsolutePath().toString()); result.setResultMessage(destination.toAbsolutePath().toString()); } catch (IOException ex) { Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex); result.setResultCode("1"); result.setResultMessage(ex.getMessage()); } return result; }
From source file:org.holodeckb2b.ebms3.submit.core.MessageSubmitter.java
/** * Helper method to copy or move the payloads to an internal directory so they will be kept available during the * processing of the message (which may include resending). * //from ww w. j a v a 2 s. c o m * @param um The meta data on the submitted user message * @param pmode The P-Mode that governs the processing this user message * @throws IOException When the payload could not be moved/copied to the internal payload storage * @throws DatabaseException When the new payload locations couldn't be saved to the database */ private void moveOrCopyPayloads(EntityProxy<UserMessage> um, boolean move) throws IOException, DatabaseException { // Path to the "temp" dir where to store payloads during processing String intPlDir = HolodeckB2BCoreInterface.getConfiguration().getTempDirectory() + "plcout"; // Create the directory if needed Path pathPlDir = Paths.get(intPlDir); if (!Files.exists(pathPlDir)) { log.debug("Create the directory [" + intPlDir + "] for storing payload files"); Files.createDirectories(pathPlDir); } Collection<IPayload> payloads = um.entity.getPayloads(); if (!Utils.isNullOrEmpty(payloads)) { for (IPayload ip : payloads) { Payload p = (Payload) ip; Path srcPath = Paths.get(p.getContentLocation()); // Ensure that the filename in the temp directory is unique Path destPath = Paths.get(Utils.preventDuplicateFileName(intPlDir + "/" + srcPath.getFileName())); if (move) { log.debug("Moving payload [" + p.getContentLocation() + "] to internal directory"); Files.move(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING); } else { log.debug("Copying payload [" + p.getContentLocation() + "] to internal directory"); Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING); } log.debug("Payload moved/copied to internal directory"); p.setContentLocation(destPath.toString()); } // Update the database with new locations MessageUnitDAO.updateMessageUnitInfo(um); } }
From source file:schemacrawler.tools.integration.maven.SchemaCrawlerMojo.java
/** * {@inheritDoc}/*w w w .j a va 2s . c o m*/ * * @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale) */ @Override protected void executeReport(final Locale locale) throws MavenReportException { final Log logger = getLog(); try { fixClassPath(); final Sink sink = getSink(); logger.info(sink.getClass().getName()); final Path outputFile = executeSchemaCrawler(); final Consumer<? super String> outputLine = line -> { sink.rawText(line); sink.rawText("\n"); sink.flush(); }; final OutputFormat outputFormat = getOutputFormat(); sink.comment("BEGIN SchemaCrawler Report"); if (outputFormat == TextOutputFormat.html || outputFormat == GraphOutputFormat.htmlx) { Files.lines(outputFile).forEach(outputLine); } else if (outputFormat instanceof TextOutputFormat) { sink.rawText("<pre>"); Files.lines(outputFile).forEach(outputLine); sink.rawText("</pre>"); } else if (outputFormat instanceof GraphOutputFormat) { final Path graphFile = Paths.get(getReportOutputDirectory().getAbsolutePath(), "schemacrawler." + outputFormat.getFormat()); Files.move(outputFile, graphFile, StandardCopyOption.REPLACE_EXISTING); sink.figure(); sink.figureGraphics(graphFile.getFileName().toString()); sink.figure_(); } sink.comment("END SchemaCrawler Report"); sink.flush(); } catch (final Exception e) { throw new MavenReportException("Error executing SchemaCrawler command " + command, e); } }
From source file:org.jboss.as.test.clustering.modcluster.WorkerFailoverTestCase.java
@After public void stopContainers() throws Exception { LOGGER.trace("*** undeploy applications"); if (undeployedApp == null || !undeployedApp.equals(DEPLOYMENT_1)) deployer.undeploy(DEPLOYMENT_1); if (undeployedApp == null || !undeployedApp.equals(DEPLOYMENT_2)) deployer.undeploy(DEPLOYMENT_2); LOGGER.trace("*** stopping container"); controller.stop(CONTAINER_1);/*from ww w . j a va 2 s. c o m*/ controller.stop(CONTAINER_2); controller.stop(BALANCER); LOGGER.trace("*** reseting test configuration"); Files.move(Paths.get(worker1ConfigFile + ".WorkerFailoverTestCase.backup"), Paths.get(worker1ConfigFile), REPLACE_EXISTING); Files.move(Paths.get(worker2ConfigFile + ".WorkerFailoverTestCase.backup"), Paths.get(worker2ConfigFile), REPLACE_EXISTING); Files.move(Paths.get(balancerConfigFile + ".WorkerFailoverTestCase.backup"), Paths.get(balancerConfigFile), REPLACE_EXISTING); }
From source file:ubic.basecode.ontology.OntologyLoader.java
/** * Load an ontology into memory. Use this type of model when fast access is critical and memory is available. * If load from URL fails, attempt to load from disk cache under @cacheName. * /*from w ww. ja v a2 s.c o m*/ * @param url * @param spec e.g. OWL_MEM_TRANS_INF * @param cacheName unique name of this ontology, will be used to load from disk in case of failed url connection * @return */ public static OntModel loadMemoryModel(String url, OntModelSpec spec, String cacheName) { StopWatch timer = new StopWatch(); timer.start(); OntModel model = getMemoryModel(url, spec); URLConnection urlc = null; int tries = 0; while (tries < MAX_CONNECTION_TRIES) { try { urlc = new URL(url).openConnection(); // help ensure mis-configured web servers aren't causing trouble. urlc.setRequestProperty("Accept", "application/rdf+xml"); try { HttpURLConnection c = (HttpURLConnection) urlc; c.setInstanceFollowRedirects(true); } catch (ClassCastException e) { // not via http, using a FileURLConnection. } if (tries > 0) { log.info("Retrying connecting to " + url + " [" + tries + "/" + MAX_CONNECTION_TRIES + " of max tries"); } else { log.info("Connecting to " + url); } urlc.connect(); // Will error here on bad URL if (urlc instanceof HttpURLConnection) { String newUrl = urlc.getHeaderField("Location"); if (StringUtils.isNotBlank(newUrl)) { log.info("Redirect to " + newUrl); urlc = new URL(newUrl).openConnection(); // help ensure mis-configured web servers aren't causing trouble. urlc.setRequestProperty("Accept", "application/rdf+xml"); urlc.connect(); } } break; } catch (IOException e) { // try to recover. log.error(e + " retrying?"); tries++; } } if (urlc != null) { try (InputStream in = urlc.getInputStream();) { Reader reader; if (cacheName != null) { // write tmp to disk File tempFile = getTmpDiskCachePath(cacheName); if (tempFile == null) { reader = new InputStreamReader(in); } else { tempFile.getParentFile().mkdirs(); Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); reader = new FileReader(tempFile); } } else { // Skip the cache reader = new InputStreamReader(in); } assert reader != null; try (BufferedReader buf = new BufferedReader(reader);) { model.read(buf, url); } log.info("Load model: " + timer.getTime() + "ms"); } catch (IOException e) { log.error(e.getMessage(), e); } } if (cacheName != null) { File f = getDiskCachePath(cacheName); File tempFile = getTmpDiskCachePath(cacheName); File oldFile = getOldDiskCachePath(cacheName); if (model.isEmpty()) { // Attempt to load from disk cache if (f == null) { throw new RuntimeException( "Ontology cache directory required to load from disk: ontology.cache.dir"); } if (f.exists() && !f.isDirectory()) { try (BufferedReader buf = new BufferedReader(new FileReader(f));) { model.read(buf, url); // We successfully loaded the cached ontology. Copy the loaded ontology to oldFile // so that we don't recreate indices during initialization based on a false change in // the ontology. Files.copy(f.toPath(), oldFile.toPath(), StandardCopyOption.REPLACE_EXISTING); log.info("Load model from disk: " + timer.getTime() + "ms"); } catch (IOException e) { log.error(e.getMessage(), e); throw new RuntimeException( "Ontology failed load from URL (" + url + ") and disk cache: " + cacheName); } } else { throw new RuntimeException("Ontology failed load from URL (" + url + ") and disk cache does not exist: " + cacheName); } } else { // Model was successfully loaded into memory from URL with given cacheName // Save cache to disk (rename temp file) log.info("Caching ontology to disk: " + cacheName); if (f != null) { try { // Need to compare previous to current so instead of overwriting we'll move the old file f.createNewFile(); Files.move(f.toPath(), oldFile.toPath(), StandardCopyOption.REPLACE_EXISTING); Files.move(tempFile.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { log.error(e.getMessage(), e); } } else { log.warn("Ontology cache directory required to save to disk: ontology.cache.dir"); } } } assert !model.isEmpty(); return model; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java
private void moveDirectory(final File existingDB, final File newDB) throws IOException { LOGGER.info("[" + getClass().getSimpleName() + "] Moving Location database from: " + newDB + ", to: " + existingDB);/*w w w. j a v a 2 s .co m*/ for (final File file : existingDB.listFiles()) { file.setReadable(true, true); file.setWritable(true, false); file.delete(); } existingDB.delete(); Files.move(newDB.toPath(), existingDB.toPath(), StandardCopyOption.ATOMIC_MOVE); }
From source file:org.wso2.carbon.event.input.adapter.file.FileEventAdapter.java
public void processFiles() { try {/*from w ww . j av a 2s .c o m*/ // collect file in the source directory File folder = new File(this.sourcePath); File[] listOfFiles = folder.listFiles(); //String patternString = ".*\\.csv$"; for (int i = 0; i < listOfFiles.length; i++) { boolean isMatch = Pattern.matches(filenameRegex, listOfFiles[i].getName()); if (isMatch) { BufferedReader in = null; ExecutorService executor = null; try { // initialize thread pool executor = Executors.newFixedThreadPool(this.threads); // loading file in = new BufferedReader(new FileReader(listOfFiles[i].toPath().toString())); String line = null; // skip lines int lineSkipped = 0; while (lineSkipped < this.skipLine && (line = in.readLine()) != null) { lineSkipped = lineSkipped + 1; } // process line by line int lineCount = 0; String jsonArray = ""; line = null; while ((line = in.readLine()) != null) { lineCount = lineCount + 1; jsonArray = jsonArray + formatLineToWSO2JSONEvent(line) + ","; if (lineCount % this.batchSize == 0) { executor.execute(new eventProcessorThread(this.eventAdapterListener, this.tenantId, "[" + jsonArray + "]")); jsonArray = ""; } } executor.execute(new eventProcessorThread(this.eventAdapterListener, this.tenantId, "[" + jsonArray + "]")); executor.shutdown(); // wait until all threads completes while (!executor.isTerminated()) { } } catch (Exception e) { e.printStackTrace(); } finally { // release resources executor = null; in.close(); in = null; //System.gc(); // move current file to archive location Files.move(listOfFiles[i].toPath(), new File(this.arcPath + "/" + listOfFiles[i].getName()).toPath(), REPLACE_EXISTING); } } } } catch (Exception ex) { ex.printStackTrace(); } }