List of usage examples for java.nio.file Path toAbsolutePath
Path toAbsolutePath();
From source file:com.hortonworks.streamline.streams.actions.storm.topology.StormTopologyActionsImpl.java
private String createJaasFile(String kerberizedNimbusServiceName) { try {//from w w w . j a v a 2 s . c o m Path jaasFilePath = Files.createTempFile("jaas-", UUID.randomUUID().toString()); String filePath = jaasFilePath.toAbsolutePath().toString(); File jaasFile = new StormJaasCreator().create(filePath, kerberizedNimbusServiceName); return jaasFile.getAbsolutePath(); } catch (IOException e) { throw new RuntimeException("Can't create JAAS file to connect to secure nimbus", e); } }
From source file:org.tinymediamanager.core.Utils.java
/** * modified version of commons-io FileUtils.moveFile(); adapted to Java 7 NIO<br> * since renameTo() might not work in first place, retry it up to 5 times.<br> * (better wait 5 sec for success, than always copying a 50gig directory ;)<br> * <b>And NO, we're NOT doing a copy+delete as fallback!</b> * // www .j ava 2 s .c o m * @param srcFile * the file to be moved * @param destFile * the destination file * @throws NullPointerException * if source or destination is {@code null} * @throws FileExistsException * if the destination file exists * @throws IOException * if source or destination is invalid * @throws IOException * if an IO error occurs moving the file */ public static boolean moveFileSafe(final Path srcFile, final Path destFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } // if (!srcFile.equals(destFile)) { if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) { LOGGER.debug("try to move file " + srcFile + " to " + destFile); if (!Files.exists(srcFile)) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (Files.isDirectory(srcFile)) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) { // extra check for windows, where the File.equals is case insensitive // so we know now, that the File is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destFile + "' already exists"); } if (Files.isDirectory(destFile)) { throw new IOException("Destination '" + destFile + "' is a directory"); } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // need atomic fs move for changing cASE Files.move(srcFile, destFile, StandardCopyOption.ATOMIC_MOVE); rename = true;// no exception } catch (AtomicMoveNotSupportedException a) { // if it fails (b/c not on same file system) use that try { Files.move(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING); rename = true; // no exception } catch (IOException e) { LOGGER.warn("rename problem: " + e.getMessage()); } } catch (IOException e) { LOGGER.warn("rename problem: " + e.getMessage()); } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } if (!rename) { LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile); return true; } } return true; // files are equal }
From source file:org.tinymediamanager.core.Utils.java
/** * copy a file, preserving the attributes * * @param srcFile//from ww w. ja v a 2 s . co m * the file to be copied * @param destFile * the target * @param overwrite * overwrite the target? * @return true/false * @throws NullPointerException * if source or destination is {@code null} * @throws FileExistsException * if the destination file exists * @throws IOException * if source or destination is invalid * @throws IOException * if an IO error occurs moving the file */ public static boolean copyFileSafe(final Path srcFile, final Path destFile, boolean overwrite) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } // if (!srcFile.equals(destFile)) { if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) { LOGGER.debug("try to copy file " + srcFile + " to " + destFile); if (!Files.exists(srcFile)) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (Files.isDirectory(srcFile)) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (!overwrite) { if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) { // extra check for windows, where the File.equals is case insensitive // so we know now, that the File is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destFile + "' already exists"); } } if (Files.isDirectory(destFile)) { throw new IOException("Destination '" + destFile + "' is a directory"); } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // replace existing for changing cASE Files.copy(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); rename = true;// no exception } catch (IOException e) { } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } if (!rename) { LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile); return true; } } return true; // files are equal }
From source file:at.tfr.securefs.process.ProcessFilesBean.java
public void copy(Path fromPath, int fromStartIndex, Path toRootPath, CrypterProvider cp, BigInteger newSecret, ProcessFilesData cfd) {/* w w w . j a v a 2 s. c om*/ Path toPath = toRootPath.resolve(fromPath.subpath(fromStartIndex, fromPath.getNameCount())); try { if (Files.isRegularFile(fromPath)) { if (Files.isRegularFile(toPath)) { if (!cfd.isAllowOverwriteExisting()) { throw new SecureFSError("overwrite of existing file not allowed: " + toPath); } if (cfd.isUpdate() && Files.getLastModifiedTime(fromPath).toInstant() .isBefore(Files.getLastModifiedTime(toPath).toInstant())) { log.info("not overwriting from: " + fromPath.toAbsolutePath() + " to: " + toPath.toAbsolutePath()); return; } } // write source to target cfd.setCurrentFromPath(fromPath.toAbsolutePath().toString()); cfd.setCurrentToPath(toPath.toAbsolutePath().toString()); updateCache(cfd); try (OutputStream os = cp.getEncrypter(toPath, newSecret); InputStream is = cp.getDecrypter(fromPath)) { IOUtils.copy(is, os); } log.info("copied from: " + fromPath.toAbsolutePath() + " to: " + toPath.toAbsolutePath()); } if (Files.isDirectory(fromPath)) { Path subDir = Files.createDirectories(toPath); log.info("created subDir: " + subDir.toAbsolutePath()); } } catch (Exception e) { throw new SecureFSError("cannot copy from: " + fromPath + " to: " + toPath, e); } }
From source file:org.bonitasoft.platform.setup.command.configure.BundleConfigurator.java
void copyDriverFile(Path srcDriverFile, Path targetDriverFile, String dbVendor) throws PlatformException { try {// w w w .j a v a2 s.co m final Path targetDriverFolder = targetDriverFile.getParent(); targetDriverFolder.toFile().mkdirs(); Files.copy(srcDriverFile, targetDriverFile); LOGGER.info("Copying your " + dbVendor + " driver file '" + getRelativePath(srcDriverFile) + "' to tomcat lib folder '" + getRelativePath(targetDriverFolder) + "'"); } catch (IOException e) { throw new PlatformException("Fail to copy driver file lib/" + srcDriverFile.getFileName() + " to " + targetDriverFile.toAbsolutePath() + ": " + e.getMessage(), e); } }
From source file:com.netflix.spinnaker.halyard.config.model.v1.node.Node.java
public void stageLocalFiles(Path outputPath) { if (!GlobalApplicationOptions.getInstance().isUseRemoteDaemon()) { return;/* ww w .java 2s . com*/ } localFiles().forEach(f -> { try { f.setAccessible(true); String fContent = (String) f.get(this); if (fContent != null) { CRC32 crc = new CRC32(); crc.update(fContent.getBytes()); String fPath = Paths .get(outputPath.toAbsolutePath().toString(), Long.toHexString(crc.getValue())) .toString(); FileUtils.writeStringToFile(new File(fPath), fContent); f.set(this, fPath); } } catch (IllegalAccessException | IOException e) { throw new RuntimeException("Failed to get local files for node " + this.getNodeName(), e); } finally { f.setAccessible(false); } }); }
From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmSlurmService.java
public Future<Void> downloadJobResult(JobQueueInfo jobQueueInfo) { String fileName = jobQueueInfo.getFileName() + ".txt"; String tmpDirectory = jobQueueInfo.getTmpDirectory(); String outputDirectory = jobQueueInfo.getOutputDirectory(); Path src = Paths.get(tmpDirectory, fileName); Path dest = Paths.get(outputDirectory, fileName); String jsonFileName = jobQueueInfo.getFileName() + ".json"; Path json = Paths.get(tmpDirectory, jsonFileName); Path jsonDest = Paths.get(outputDirectory, jsonFileName); String errorFileName = String.format("error_%s", fileName); Path error = Paths.get(tmpDirectory, errorFileName); Path errorDest = Paths.get(outputDirectory, errorFileName); try {/* w w w . ja v a2 s. c om*/ LOGGER.info("Checking File: " + src.toAbsolutePath().toString()); if (client.remoteFileExistes(src.toAbsolutePath().toString())) { LOGGER.info("Downloading File: " + src.toAbsolutePath().toString()); client.downloadOutput(src.toAbsolutePath().toString(), dest.toAbsolutePath().toString()); client.deleteRemoteFile(src.toAbsolutePath().toString()); LOGGER.info("Checking File: " + json.toAbsolutePath().toString()); if (client.remoteFileExistes(json.toAbsolutePath().toString())) { LOGGER.info("Downloading File: " + json.toAbsolutePath().toString()); client.downloadOutput(json.toAbsolutePath().toString(), jsonDest.toAbsolutePath().toString()); client.deleteRemoteFile(json.toAbsolutePath().toString()); } } else if (client.remoteFileExistes(error.toAbsolutePath().toString())) { LOGGER.info("Downloading File: " + error.toAbsolutePath().toString()); client.downloadOutput(error.toAbsolutePath().toString(), errorDest.toAbsolutePath().toString()); } client.deleteRemoteFile(error.toAbsolutePath().toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } deleteRunSlurmScript(jobQueueInfo); return new AsyncResult<>(null); }
From source file:org.finra.dm.dao.Log4jOverridableConfigurerTest.java
/** * Reads the contents of the resource location, substitutes the filename token (if it exists), and writes the contents of the resource to the local file * system./*from ww w. jav a 2 s . c o m*/ * * @param resourceLocation the resource location of the Log4J configuration. * @param configPath the Log4J configuration path. * @param outputPath the Log4J output path. * * @throws Exception if the file couldn't be written. */ private void writeFileFromResourceLocation(String resourceLocation, Path configPath, Path outputPath) throws Exception { // Get the Log4J configuration contents from the classpath file. String log4JFileContents = IOUtils.toString(resourceLoader.getResource(resourceLocation).getInputStream()); // Change the tokenized output filename (if it exists) and replace it with a random filename to support multiple invocations of the JUnit. log4JFileContents = log4JFileContents.replace(LOG4J_FILENAME_TOKEN, outputPath.toAbsolutePath().toString().replace("\\", "/")); // Write the Log4J configuration to the temporary file. try (FileOutputStream fileOutputStream = new FileOutputStream(configPath.toAbsolutePath().toString())) { IOUtils.write(log4JFileContents, fileOutputStream); } }
From source file:org.tinymediamanager.core.tvshow.TvShowRenamer.java
/** * Renames a MediaFiles<br>// w w w. j a v a 2 s . c o m * gets all episodes of it, creates season folder, updates MFs & DB * * @param mf * the MediaFile * @param show * the tvshow (only needed for path) */ public static void renameMediaFile(MediaFile mf, TvShow show) { // ####################################################### // Assumption: all multi-episodes share the same season!!! // ####################################################### List<TvShowEpisode> eps = TvShowList.getInstance().getTvEpisodesByFile(show, mf.getFile()); if (eps == null || eps.size() == 0) { // FIXME: workaround for r1972 // when moving video file, all NFOs get deleted and a new gets created. // so this OLD NFO is not found anylonger - just delete it if (mf.getType() == MediaFileType.NFO) { Utils.deleteFileSafely(mf.getFileAsPath()); return; } LOGGER.warn("No episodes found for file '" + mf.getFilename() + "' - skipping"); return; } // get first, for isDisc and season TvShowEpisode ep = eps.get(0); // test access rights or return LOGGER.debug("testing file S:" + ep.getSeason() + " E:" + ep.getEpisode() + " MF:" + mf.getFile().getAbsolutePath()); File f = mf.getFile(); boolean testRenameOk = false; for (int i = 0; i < 5; i++) { testRenameOk = f.renameTo(f); // haahaa, try to rename to itself :P if (testRenameOk) { break; // ok it worked, step out } try { if (!f.exists()) { LOGGER.debug("Hmmm... file " + f + " does not even exists; delete from DB"); // delete from MF for (TvShowEpisode e : eps) { e.removeFromMediaFiles(mf); e.saveToDb(); } return; } LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } if (!testRenameOk) { LOGGER.warn("File " + mf.getFileAsPath() + " is not accessible!"); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, mf.getFilename(), "message.renamer.failedrename")); return; } // create SeasonDir // String seasonName = "Season " + String.valueOf(ep.getSeason()); String seasonName = generateSeasonDir(SETTINGS.getRenamerSeasonFoldername(), ep); Path seasonDir = show.getPathNIO(); if (StringUtils.isNotBlank(seasonName)) { seasonDir = show.getPathNIO().resolve(seasonName); if (!Files.exists(seasonDir)) { try { Files.createDirectory(seasonDir); } catch (IOException e) { } } } // rename epFolder accordingly if (ep.isDisc() || mf.isDiscFile()) { // \Season 1\S01E02E03\VIDEO_TS\VIDEO_TS.VOB // ........ \epFolder \disc... \ file Path disc = mf.getFileAsPath().getParent(); Path epFolder = disc.getParent(); // sanity check if (!disc.getFileName().toString().equalsIgnoreCase("BDMV") && !disc.getFileName().toString().equalsIgnoreCase("VIDEO_TS")) { LOGGER.error( "Episode is labeled as 'on BD/DVD', but structure seems not to match. Better exit and do nothing... o_O"); return; } String newFoldername = FilenameUtils.getBaseName(generateFolderename(show, mf)); // w/o extension if (newFoldername != null && !newFoldername.isEmpty()) { Path newEpFolder = seasonDir.resolve(newFoldername); Path newDisc = newEpFolder.resolve(disc.getFileName()); // old disc name try { // if (!epFolder.equals(newEpFolder)) { if (!epFolder.toAbsolutePath().toString().equals(newEpFolder.toAbsolutePath().toString())) { boolean ok = false; try { // create parent if needed if (!Files.exists(newEpFolder.getParent())) { Files.createDirectory(newEpFolder.getParent()); } ok = Utils.moveDirectorySafe(epFolder, newEpFolder); } catch (Exception e) { LOGGER.error(e.getMessage()); MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, epFolder, "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() })); } if (ok) { // iterate over all EPs & MFs and fix new path LOGGER.debug("updating *all* MFs for new path -> " + newEpFolder); for (TvShowEpisode e : eps) { e.updateMediaFilePath(disc, newDisc); e.setPath(newEpFolder.toAbsolutePath().toString()); e.saveToDb(); } } // and cleanup cleanEmptyDir(epFolder); } else { // old and new folder are equal, do nothing } } catch (Exception e) { LOGGER.error("error moving video file " + disc + " to " + newFoldername, e); MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, mf.getFilename(), "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() })); } } } // end isDisc else { MediaFile newMF = new MediaFile(mf); // clone MF if (mf.getType().equals(MediaFileType.TRAILER)) { // move trailer into separate dir - not supported by XBMC Path sample = seasonDir.resolve("sample"); if (!Files.exists(sample)) { try { Files.createDirectory(sample); } catch (IOException e) { } } seasonDir = sample; // change directory storage } String filename = generateFilename(show, mf); LOGGER.debug("new filename should be " + filename); if (StringUtils.isNotBlank(filename)) { Path newFile = seasonDir.resolve(filename); try { // if (!mf.getFile().equals(newFile)) { if (!mf.getFileAsPath().toString().equals(newFile.toString())) { Path oldMfFile = mf.getFileAsPath(); boolean ok = false; try { // create parent if needed if (!Files.exists(newFile.getParent())) { Files.createDirectory(newFile.getParent()); } ok = Utils.moveFileSafe(oldMfFile, newFile); } catch (Exception e) { LOGGER.error(e.getMessage()); MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, oldMfFile, "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() })); } if (ok) { if (mf.getFilename().endsWith(".sub")) { // when having a .sub, also rename .idx (don't care if error) try { Path oldidx = mf.getFileAsPath().resolveSibling( mf.getFilename().toString().replaceFirst("sub$", "idx")); Path newidx = newFile.resolveSibling( newFile.getFileName().toString().replaceFirst("sub$", "idx")); Utils.moveFileSafe(oldidx, newidx); } catch (Exception e) { // no idx found or error - ignore } } newMF.setPath(seasonDir.toString()); newMF.setFilename(filename); // iterate over all EPs and delete old / set new MF for (TvShowEpisode e : eps) { e.removeFromMediaFiles(mf); e.addToMediaFiles(newMF); e.setPath(seasonDir.toString()); e.saveToDb(); } } // and cleanup cleanEmptyDir(oldMfFile.getParent()); } else { // old and new file are equal, keep MF } } catch (Exception e) { LOGGER.error("error moving video file " + mf.getFilename() + " to " + newFile, e); MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, mf.getFilename(), "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() })); } } } }
From source file:org.opennms.test.system.api.NewTestEnvironment.java
/** * Spawns the OpenNMS container, linked to PostgreSQL. *//*from w w w. j a va2 s . c om*/ private void spawnOpenNMS() throws DockerException, InterruptedException, IOException { final ContainerAlias alias = ContainerAlias.OPENNMS; if (!(isEnabled(alias) && isSpawned(alias))) { return; } final Path overlayRoot = initializeOverlayRoot(); final Path opennmsOverlay = overlayRoot.resolve("opennms-overlay"); final Path opennmsLogs = overlayRoot.resolve("opennms-logs"); final Path opennmsKarafLogs = overlayRoot.resolve("opennms-karaf-logs"); Files.createDirectories(opennmsOverlay); Files.createDirectories(opennmsLogs); Files.createDirectories(opennmsKarafLogs); if (this.overlayDirectory != null) { Files.find(this.overlayDirectory, 10, (path, attr) -> { return path.toFile().isFile(); }).forEach(path -> { final Path relative = Paths .get(this.overlayDirectory.toFile().toURI().relativize(path.toFile().toURI()).getPath()); final Path to = Paths.get(opennmsOverlay.toString(), relative.toString()); LOG.debug("Copying {} to {}", path.toAbsolutePath(), to.toAbsolutePath()); try { Files.createDirectories(to.getParent()); Files.copy(path.toAbsolutePath(), to.toAbsolutePath()); } catch (final Exception e) { throw new RuntimeException(e); } }); } final List<String> binds = new ArrayList<>(); binds.add(opennmsOverlay.toString() + ":/opennms-docker-overlay"); binds.add(opennmsLogs.toString() + ":/var/log/opennms"); binds.add(opennmsKarafLogs.toString() + ":/opt/opennms/data/log"); final List<String> links = new ArrayList<>(); links.add(String.format("%s:postgres", containerInfoByAlias.get(ContainerAlias.POSTGRES).name())); // Link to the Elasticsearch container, if enabled if (isEnabled(ContainerAlias.ELASTICSEARCH_1)) { links.add(String.format("%s:elasticsearch", containerInfoByAlias.get(ContainerAlias.ELASTICSEARCH_1).name())); } else if (isEnabled(ContainerAlias.ELASTICSEARCH_2)) { links.add(String.format("%s:elasticsearch", containerInfoByAlias.get(ContainerAlias.ELASTICSEARCH_2).name())); } else if (isEnabled(ContainerAlias.ELASTICSEARCH_5)) { links.add(String.format("%s:elasticsearch", containerInfoByAlias.get(ContainerAlias.ELASTICSEARCH_5).name())); } Builder builder = HostConfig.builder().privileged(true).publishAllPorts(true).links(links).binds(binds); spawnContainer(alias, builder, Collections.emptyList()); }