List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:org.kurento.room.test.AutodiscoveryKmsUrlTest.java
@Test public void test() throws IOException { Path backup = null;// w ww. j a va2 s.c o m Path configFile = Paths.get(StandardSystemProperty.USER_HOME.value(), ".kurento", "config.properties"); System.setProperty("kms.uris", "[\"autodiscovery\"]"); try { if (Files.exists(configFile)) { backup = configFile.getParent().resolve("config.properties.old"); Files.move(configFile, backup); log.debug("Backed-up old config.properties"); } Files.createDirectories(configFile.getParent()); try (BufferedWriter writer = Files.newBufferedWriter(configFile, StandardCharsets.UTF_8)) { writer.write("kms.url.provider: " + TestKmsUrlProvider.class.getName() + "\r\n"); } String contents = new String(Files.readAllBytes(configFile)); log.debug("Config file contents:\n{}", contents); ConfigurableApplicationContext app = KurentoRoomServerApp.start(new String[] { "--server.port=7777" }); NotificationRoomManager notifRoomManager = app.getBean(NotificationRoomManager.class); final RoomManager roomManager = notifRoomManager.getRoomManager(); final KurentoClientSessionInfo kcSessionInfo = new DefaultKurentoClientSessionInfo("participantId", "roomName"); new Thread(new Runnable() { @Override public void run() { roomManager.joinRoom("userName", "roomName", false, kcSessionInfo, "participantId"); } }).start(); try { Boolean result = queue.poll(10, TimeUnit.SECONDS); if (result == null) { fail("Event in KmsUrlProvider not called"); } else { if (!result) { fail("Test failed"); } } } catch (InterruptedException e) { fail("KmsUrlProvider was not called"); } } finally { Files.delete(configFile); if (backup != null) { Files.move(backup, configFile); } } }
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); }// w ww . j a v a2s . c o 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:org.roda.core.storage.fs.FSUtils.java
/** * Copies a directory/file from one path to another * //from ww w. jav a 2s . co m * @param sourcePath * source path * @param targetPath * target path * @param replaceExisting * true if the target directory/file should be replaced if it already * exists; false otherwise * @throws AlreadyExistsException * @throws GenericException */ public static void copy(final Path sourcePath, final Path targetPath, boolean replaceExisting) throws AlreadyExistsException, GenericException { // check if we can replace existing if (!replaceExisting && FSUtils.exists(targetPath)) { throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath); } // ensure parent directory exists or can be created try { if (targetPath != null) { Files.createDirectories(targetPath.getParent()); } } catch (IOException e) { throw new GenericException("Error while creating target directory parent folder", e); } if (FSUtils.isDirectory(sourcePath)) { try { Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, targetPath.resolve(sourcePath.relativize(file))); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { throw new GenericException("Error while copying one directory into another", e); } } else { try { CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] {}; Files.copy(sourcePath, targetPath, copyOptions); } catch (IOException e) { throw new GenericException("Error while copying one file into another", e); } } }
From source file:ee.ria.xroad.confproxy.util.OutputBuilder.java
/** * Opens a stream for writing the configuration file describes by the metadata to the target location. * @param targetPath location to write the file to * @param metadata describes the configuration file * @return output stream for writing the file * @throws Exception if errors during file operations occur *//*from w w w. j a v a 2 s . c om*/ private FileOutputStream createFileOutputStream(final Path targetPath, final ConfigurationPartMetadata metadata) throws Exception { Path filepath = targetPath .resolve(Paths.get(metadata.getInstanceIdentifier(), metadata.getContentLocation())); Files.createDirectories(filepath.getParent()); Path newFile = Files.createFile(filepath); log.debug("Copying file '{}' to directory '{}'", newFile.toAbsolutePath(), targetPath); return new FileOutputStream(newFile.toAbsolutePath().toFile()); }
From source file:org.datavec.image.recordreader.VideoRecordReader.java
@Override public void initialize(InputSplit split) throws IOException, InterruptedException { if (imageLoader == null) { imageLoader = new NativeImageLoader(height, width); }// w ww . j a v a2 s .c o m if (split instanceof FileSplit) { URI[] locations = split.locations(); if (locations != null && locations.length >= 1) { if (locations.length > 1) { List<File> allFiles = new ArrayList<>(); for (URI location : locations) { File iter = new File(location); if (iter.isDirectory()) { allFiles.add(iter); if (appendLabel) { File parentDir = iter.getParentFile(); String name = parentDir.getName(); if (!labels.contains(name)) labels.add(name); } } else { File parent = iter.getParentFile(); if (!allFiles.contains(parent) && containsFormat(iter.getAbsolutePath())) { allFiles.add(parent); if (appendLabel) { File parentDir = iter.getParentFile(); String name = parentDir.getName(); if (!labels.contains(name)) labels.add(name); } } } } iter = allFiles.iterator(); } else { File curr = new File(locations[0]); if (!curr.exists()) throw new IllegalArgumentException("Path " + curr.getAbsolutePath() + " does not exist!"); if (curr.isDirectory()) iter = FileUtils.iterateFiles(curr, null, true); else iter = Collections.singletonList(curr).iterator(); } } } else if (split instanceof InputStreamInputSplit) { InputStreamInputSplit split2 = (InputStreamInputSplit) split; InputStream is = split2.getIs(); URI[] locations = split2.locations(); INDArray load = imageLoader.asMatrix(is); record = RecordConverter.toRecord(load); if (appendLabel) { Path path = Paths.get(locations[0]); String parent = path.getParent().toString(); record.add(new DoubleWritable(labels.indexOf(parent))); } is.close(); } }
From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java
/** * Creates a test file at the given path from the specified resource. * * @param path the path of the test file to create in the specified directory * @param resource the resource to copy to the test file * @return a path corresponding to the test file created (relativized from ${ddf.home}) * @throws IOException if an I/O error occurs while creating the test file *///from www. j a va 2s .co m public Path createFileFromResource(Path path, String resource) throws IOException { return createFileFromResource(path.getParent(), path.getFileName().toString(), resource); }
From source file:ch.ifocusit.livingdoc.plugin.publish.HtmlPostProcessor.java
private Function<String, String> replaceCrossReferenceTargets(Path pagePath) { return (content) -> replaceAll(content, PAGE_TITLE_PATTERN, (matchResult) -> { String htmlTarget = matchResult.group(1); String referencedPageTitle = htmlTarget; if (htmlTarget.indexOf(".") > -1) { Path referencedPagePath = pagePath.getParent() .resolve(Paths.get(htmlTarget.substring(0, htmlTarget.lastIndexOf('.')) + ".adoc")); referencedPageTitle = getPageTitle(referencedPagePath); }/*from w ww. ja v a2 s. c om*/ return "<ri:page ri:content-title=\"" + referencedPageTitle + "\""; }); }
From source file:org.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java
/** * Starts up monitoring of the configuration for changes. */// www. ja va 2s .c o m private void monitorForChanges() { if (monitorRunning) { return; } final Path path = Paths.get(configPath); if (!path.toFile().exists()) { LOGGER.debug("Configuration {} does not exist, disabling monitoring", configPath); return; } final Path directoryPath = path.getParent(); try { final WatchService watchService = FileSystems.getDefault().newWatchService(); directoryPath.register(watchService, ENTRY_MODIFY); monitorThread = new Thread(new Runnable() { @Override public void run() { try { for (;;) { WatchKey key; try { key = watchService.take(); } catch (final InterruptedException e) { LOGGER.debug("Interrupted the configuration monitor thread."); break; } for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } // If the configuration file triggered this event, reload it final Path changed = (Path) event.context(); if (changed.equals(path.getFileName())) { LOGGER.info("Configuration {} has been updated, reloading.", path); try { loadConfiguration(); } catch (final IOException e) { LOGGER.error("Failed to reload configuration {}", configPath, e); } } // reset the key final boolean valid = key.reset(); if (!valid) { LOGGER.debug("Monitor of {} is no longer valid", path); break; } } } } finally { try { watchService.close(); } catch (final IOException e) { LOGGER.error("Failed to stop configuration monitor", e); } } monitorRunning = false; } }); } catch (final IOException e) { LOGGER.error("Failed to start configuration monitor", e); } monitorThread.start(); monitorRunning = true; }
From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java
public void run() { DateTime start = new DateTime(); try {//from w w w .j a v a2s . c o m FileService svc = new FileService(new URL(fileServiceUrl)); BindingProvider binding = (BindingProvider) svc.getFileServicePort(); binding.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username); binding.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password); for (Path path : files) { if (write) { if (!path.toFile().exists()) { System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir=" + Paths.get("./").toAbsolutePath()); continue; } System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + path); svc.getFileServicePort().write(path.toString(), IOUtils.toByteArray(Files.newInputStream(path))); } Path out = path.resolveSibling( path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out"); if (read) { System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out); if (out.getParent() != null) { Files.createDirectories(out.getParent()); } byte[] arr = svc.getFileServicePort().read(path.toString()); IOUtils.write(arr, Files.newOutputStream(out)); } if (write && read) { long inputChk = FileUtils.checksumCRC32(path.toFile()); long outputChk = FileUtils.checksumCRC32(out.toFile()); if (inputChk != outputChk) { throw new IOException(Thread.currentThread() + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out); } System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : " + inputChk + " / " + outputChk); } if (delete) { boolean deleted = svc.getFileServicePort().delete(path.toString()); if (!deleted) { throw new IOException( Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path); } else { System.out.println(Thread.currentThread() + ": Deleted File: in=" + path); } } } } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } }
From source file:LocalDemoAppSetup.java
@Test public void appSetup() { final Config config = ConfigFactory.load(); final File orientdbHome = new File( config.getString(ConfigUtils.configPath(CONFIG_NAMESPACE, "orientdb", "server", "home", "dir"))); orientdbHome.mkdirs();//from w w w.java2 s. co m log.logp(INFO, getClass().getName(), "providesEmbeddedOrientDBServiceConfig", String.format("orientdbHome.exists() = %s", orientdbHome.exists())); final Path defaultDistributedDBConfigFile = Paths.get(orientdbHome.toPath().toAbsolutePath().toString(), "config", "default-distributed-db-config.json"); log.info(String.format("defaultDistributedDBConfigFile = %s", defaultDistributedDBConfigFile)); if (!Files.exists(defaultDistributedDBConfigFile)) { try { Files.createDirectories(defaultDistributedDBConfigFile.getParent()); } catch (final IOException ex) { throw new RuntimeException(ex); } try (final InputStream is = getClass() .getResourceAsStream("/orientdb/config/default-distributed-db-config.json")) { try (final OutputStream os = new FileOutputStream(defaultDistributedDBConfigFile.toFile())) { IOUtils.copy(is, os); } log.info(String.format("copied over defaultDistributedDBConfigFile : %s", defaultDistributedDBConfigFile)); } catch (final IOException e) { throw new RuntimeException(e); } } }