List of usage examples for java.nio.file Path toAbsolutePath
Path toAbsolutePath();
From source file:com.vmware.admiral.adapter.docker.service.SystemImageRetrievalManagerTest.java
@Test public void testGetFromClassPath() throws Throwable { Path testXenonImagesPath = Files.createTempDirectory("test-xenon-images"); HostInitCommonServiceConfig.startServices(host); waitForServiceAvailability(ConfigurationFactoryService.SELF_LINK); waitForServiceAvailability(UriUtils.buildUriPath(UriUtils .buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE))); // Set expected configuration ConfigurationState config = new ConfigurationState(); config.documentSelfLink = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE); config.key = FileUtil.USER_RESOURCES_PATH_VARIABLE; config.value = testXenonImagesPath.toAbsolutePath().toString(); doPost(config, ConfigurationFactoryService.SELF_LINK); File imageDir = new File(UriUtils.buildUriPath(testXenonImagesPath.toString(), SystemImageRetrievalManager.SYSTEM_IMAGES_PATH)); imageDir.mkdir();//from w ww . j a v a 2 s .c o m byte[] content = IOUtils .toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEST_IMAGE)); AdapterRequest req = new AdapterRequest(); req.resourceReference = host.getUri(); AtomicReference<byte[]> retrievedImageRef = new AtomicReference<>(); TestContext ctx = testCreate(1); retrievalManager.retrieveAgentImage(TEST_IMAGE, req, (image) -> { retrievedImageRef.set(image); ctx.completeIteration(); }); ctx.await(); byte[] image = retrievedImageRef.get(); Assert.assertEquals("Unexpected content", new String(content), new String(image)); }
From source file:org.tinymediamanager.core.Utils.java
/** * modified version of commons-io FileUtils.moveDirectory(); 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> * /* ww w. ja v a2 s . c om*/ * @param srcDir * the directory to be moved * @param destDir * the destination directory * @return true, if successful * @throws IOException * if an IO error occurs moving the file */ public static boolean moveDirectorySafe(Path srcDir, Path destDir) throws IOException { // rip-off from // http://svn.apache.org/repos/asf/commons/proper/io/trunk/src/main/java/org/apache/commons/io/FileUtils.java if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.toAbsolutePath().toString().equals(destDir.toAbsolutePath().toString())) { LOGGER.debug("try to move folder " + srcDir + " to " + destDir); if (!Files.isDirectory(srcDir)) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist, or is not a directory"); } if (Files.exists(destDir) && !Files.isSameFile(destDir, srcDir)) { // extra check for Windows/OSX, where the File.equals is case insensitive // so we know now, that the Dir is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destDir + "' already exists"); } if (!Files.exists(destDir.getParent())) { // create parent folder structure, else renameTo does not work try { Files.createDirectories(destDir.getParent()); } catch (Exception e) { LOGGER.error("could not create directory structure " + destDir.getParent()); // but we try a move anyway... } } // 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(srcDir, destDir, 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(srcDir, destDir, StandardCopyOption.REPLACE_EXISTING); rename = true; // no exception } catch (IOException e) { } } 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"); } } // ok, we tried it 5 times - it still seems to be locked somehow. Continue // with copying as fallback // NOOO - we don't like to have some files copied and some not. if (!rename) { LOGGER.error("Failed to rename directory '" + srcDir + " to " + destDir); LOGGER.error("Movie renaming aborted."); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcDir, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved folder " + srcDir + " to " + destDir); return true; } } return true; // dir are equal }
From source file:com.vmware.admiral.adapter.docker.service.SystemImageRetrievalManagerTest.java
@Test public void testGetFromUserResources() throws Throwable { Path testXenonImagesPath = Files.createTempDirectory("test-xenon-images"); HostInitCommonServiceConfig.startServices(host); waitForServiceAvailability(ConfigurationFactoryService.SELF_LINK); waitForServiceAvailability(UriUtils.buildUriPath(UriUtils .buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE))); // Set expected configuration ConfigurationState config = new ConfigurationState(); config.documentSelfLink = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE); config.key = FileUtil.USER_RESOURCES_PATH_VARIABLE; config.value = testXenonImagesPath.toAbsolutePath().toString(); doPost(config, ConfigurationFactoryService.SELF_LINK); File imageDir = new File(UriUtils.buildUriPath(testXenonImagesPath.toString(), SystemImageRetrievalManager.SYSTEM_IMAGES_PATH)); imageDir.mkdir();//from ww w .jav a2 s. c o m byte[] content = IOUtils .toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEST_IMAGE)); // Basically, rename it so it must be loaded from user resources for sure File tmpFile = new File(UriUtils.buildUriPath(imageDir.getAbsolutePath(), TEST_IMAGE_RES)); tmpFile.createNewFile(); try (OutputStream os = new FileOutputStream(tmpFile)) { os.write(content); } AdapterRequest req = new AdapterRequest(); req.resourceReference = host.getUri(); AtomicReference<byte[]> retrievedImageRef = new AtomicReference<>(); TestContext ctx = testCreate(1); retrievalManager.retrieveAgentImage(TEST_IMAGE_RES, req, (image) -> { retrievedImageRef.set(image); ctx.completeIteration(); }); ctx.await(); byte[] image = retrievedImageRef.get(); Assert.assertEquals("Unexpected content", new String(content), new String(image)); }
From source file:org.finra.herd.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./* w w w . j a v a 2s. c om*/ * * @param resourceLocation the resource location of the Log4J configuration. * @param configPath the Log4J configuration path. * @param outputPath the Log4J output path. * @param refreshInterval the refresh interval in seconds. * * @throws Exception if the file couldn't be written. */ private void writeFileFromResourceLocation(String resourceLocation, Path configPath, Path outputPath, int refreshInterval) 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("\\", "/")); // Update the refresh interval to 1 second. log4JFileContents = log4JFileContents.replace("monitorInterval=\"0\"", "monitorInterval=\"" + refreshInterval + "\""); // Write the Log4J configuration to the temporary file. try (FileOutputStream fileOutputStream = new FileOutputStream(configPath.toAbsolutePath().toString())) { IOUtils.write(log4JFileContents, fileOutputStream); } }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java
private boolean createSiteRepository(String site) { boolean success = true; Path siteRepoPath = Paths.get(rootPath, "sites", site); try {/*from w w w. ja va2 s . c o m*/ Files.deleteIfExists(siteRepoPath); siteRepoPath = Paths.get(siteRepoPath.toAbsolutePath().toString(), ".git"); Repository repository = FileRepositoryBuilder.create(siteRepoPath.toFile()); repository.create(); } catch (IOException e) { logger.error("Error while creating repository for site " + site, e); success = false; } return success; }
From source file:org.finra.dm.dao.Log4jOverridableConfigurerTest.java
/** * Reads the contents of the resource location, substitutes the filename token (if it exists), and inserts the contents of the resource to the database. * * @param resourceLocation the resource location of the Log4J configuration. * @param outputPath the Log4J output path. * @param log4jConfigurationColumn the column name for the Log4J configuration column * @param configEntityKey the configuration entity key. * * @throws Exception if the file contents couldn't be read or the database record couldn't be inserted. *///from ww w. j a v a2s . c o m private void insertDbLog4JConfigurationFromResourceLocation(String resourceLocation, Path outputPath, String log4jConfigurationColumn, String configEntityKey) 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("\\", "/")); // Insert the data. String sql = String.format("INSERT INTO %s (%s, %s) VALUES (?,?)", ConfigurationEntity.TABLE_NAME, ConfigurationEntity.COLUMN_KEY, log4jConfigurationColumn); executePreparedStatement(sql, configEntityKey, log4JFileContents); }
From source file:org.finra.dm.dao.Log4jOverridableConfigurerTest.java
/** * Reads the contents of the resource location, substitutes the filename token (if it exists), and inserts the contents of the resource to the database. * * @param resourceLocation the resource location of the Log4J configuration. * @param outputPath the Log4J output path. * @param log4jConfigurationColumn the column name for the Log4J configuration column * @param configEntityKey the configuration entity key. * * @throws Exception if the file contents couldn't be read or the database record couldn't be inserted. *//* w ww .java 2s . com*/ private void updateDbLog4JConfigurationFromResourceLocation(String resourceLocation, Path outputPath, String log4jConfigurationColumn, String configEntityKey) 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("\\", "/")); // Update the data. String sql = String.format("UPDATE %s SET %s=? WHERE %s=?", ConfigurationEntity.TABLE_NAME, log4jConfigurationColumn, ConfigurationEntity.COLUMN_KEY); executePreparedStatement(sql, log4JFileContents, configEntityKey); }
From source file:org.opencb.cellbase.app.transform.VariationParser.java
private void gzipFile(Path directory, String fileName) throws IOException, InterruptedException { Path unzippedFile = directory.resolve(fileName); if (Files.exists(unzippedFile)) { this.logger.info("Compressing " + unzippedFile.toAbsolutePath()); Process process = Runtime.getRuntime().exec("gzip " + unzippedFile.toAbsolutePath()); process.waitFor();/* www.ja v a2 s.c o m*/ } }
From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java
private void doRun() { while (shouldRun) { Log.fine("Running the file system watcher."); WatchKey key;// w ww .ja v a 2 s . c o m try { key = watcher.take(); } catch (InterruptedException x) { Log.warn("Interuppted the watcher!!!"); try { Thread.sleep(1000); } catch (InterruptedException e) { Log.info("Exit watcher run method."); return; } continue; } Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode()); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); Log.fine("Event is " + kind); // This key is registered only // for ENTRY_CREATE events, // but an OVERFLOW event can // occur regardless if events // are lost or discarded. if (kind == OVERFLOW) { continue; } // The filename is the // context of the event. WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); // Ignore emacs autosave files if (filename.toString().contains(".#")) { continue; } Log.finer("Changed file is {0}", filename); Path directory = (Path) key.watchable(); Log.finer("Changed directory is {0}", directory); Path fullPath = directory.resolve(filename); Log.fine("Changed path is {0}", fullPath); Boolean handlerFound = false; for (IWatchEventHandler handler : watchedByPath.values()) { Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(), handler.getWatchedFolder()); // Ignore private files if (filename.getFileName().startsWith(".")) { continue; } if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString()) || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder()))) && (StringUtils.isEmpty(handler.getExtension()) || fullPath.toString().endsWith(handler.getExtension()))) { String relativePath = filename.getFileName().toString(); Log.info("Handling {0} with watcher {1} for folder {2}", filename, handler.getClass().getName(), handler.getWatchedFolder()); try { handler.handle(relativePath, fullPath.toString(), kind, event); handlerFound = true; } catch (Exception e) { Log.exception(e, "Exception processing path={0} handler={1}", relativePath, handler.getClass().getName()); } } } if (!handlerFound) { Log.info("No handler found for {0}", fullPath); } } // Reset the key -- this step is critical if you want to // receive further watch events. If the key is no longer valid, // the directory is inaccessible so exit the loop. boolean valid = key.reset(); if (!valid) { Log.warn("Key invalid! Exit watch."); break; } } }
From source file:org.codice.ddf.configuration.migration.ExportMigrationContextImplTest.java
@Test public void testGetSystemPropertyReferencedEntryWhenValueIsAbsoluteNotUnderDDFHome() throws Exception { final Path migratablePath = testFolder.newFile("test.cfg").toPath().toRealPath(LinkOption.NOFOLLOW_LINKS); final String migratableName = FilenameUtils.separatorsToUnix(migratablePath.toString()); System.setProperty(PROPERTY_NAME, migratablePath.toAbsolutePath().toString()); final Optional<ExportMigrationEntry> oentry = context.getSystemPropertyReferencedEntry(PROPERTY_NAME, (r, v) -> true);//from ww w . ja v a 2 s .co m Assert.assertThat(oentry, OptionalMatchers.isPresent()); final ExportMigrationEntry entry = oentry.get(); Assert.assertThat(entry.getId(), Matchers.equalTo(MIGRATABLE_ID)); Assert.assertThat(entry.getName(), Matchers.equalTo(migratableName)); Assert.assertThat(entry.getPath(), Matchers.equalTo(migratablePath)); // now check that it is a system property referenced entry that references the proper property // name Assert.assertThat(entry, Matchers.instanceOf(ExportMigrationSystemPropertyReferencedEntryImpl.class)); final ExportMigrationSystemPropertyReferencedEntryImpl sentry = (ExportMigrationSystemPropertyReferencedEntryImpl) entry; Assert.assertThat(sentry.getProperty(), Matchers.equalTo(PROPERTY_NAME)); // finally make sure no warnings or errors were recorded Assert.assertThat(report.hasErrors(), Matchers.equalTo(false)); Assert.assertThat(report.hasWarnings(), Matchers.equalTo(false)); }