List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java
protected void moveFile(SyncWatchEvent syncWatchEvent) throws Exception { Path targetFilePath = Paths.get(syncWatchEvent.getFilePathName()); if (FileUtil.notExists(targetFilePath) || sanitizeFileName(targetFilePath) || isInErrorState(targetFilePath)) { return;/* w w w . j a v a 2s . c om*/ } Path parentTargetFilePath = targetFilePath.getParent(); SyncFile parentSyncFile = SyncFileService.fetchSyncFile(parentTargetFilePath.toString()); if ((parentSyncFile == null) || (!parentSyncFile.isSystem() && (parentSyncFile.getTypePK() == 0))) { queueSyncWatchEvent(parentTargetFilePath.toString(), syncWatchEvent); return; } Path sourceFilePath = Paths.get(syncWatchEvent.getPreviousFilePathName()); SyncFile sourceSyncFile = SyncFileService.fetchSyncFile(sourceFilePath.toString()); SyncFile targetSyncFile = SyncFileService.fetchSyncFile(targetFilePath.toString()); if ((sourceSyncFile == null) || (targetSyncFile != null)) { if (Files.isDirectory(targetFilePath)) { addFolder(syncWatchEvent); } else { addFile(syncWatchEvent); } return; } else if (isPendingTypePK(sourceSyncFile)) { queueSyncWatchEvent(sourceSyncFile.getFilePathName(), syncWatchEvent); return; } String fileType = sourceSyncFile.getType(); if (fileType.equals(SyncFile.TYPE_FILE)) { SyncFileService.moveFileSyncFile(targetFilePath, parentSyncFile.getTypePK(), _syncAccountId, sourceSyncFile); } else { SyncFileService.moveFolderSyncFile(targetFilePath, parentSyncFile.getTypePK(), _syncAccountId, sourceSyncFile); } renameFile(syncWatchEvent); }
From source file:dotaSoundEditor.Controls.EditorPanel.java
protected File promptUserForNewFile(String wavePath) { JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory())); FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3s and WAVs", "mp3", "wav"); chooser.setAcceptAllFileFilterUsed((false)); chooser.setFileFilter(filter);/* ww w . j a v a 2s . c o m*/ chooser.setMultiSelectionEnabled(false); int chooserRetVal = chooser.showOpenDialog(chooser); if (chooserRetVal == JFileChooser.APPROVE_OPTION) { DefaultMutableTreeNode selectedFile = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath); Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath()); //Strip caps and spaces out of filenames. The item sound parser seems to have trouble with them. String destFileName = chosenFile.getFileName().toString().toLowerCase().replace(" ", "_"); Path destPath = Paths.get(installDir, "/dota/sound/" + getCustomSoundPathString() + destFileName); UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString()); try { new File(destPath.toString()).mkdirs(); Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING); String waveString = selectedFile.getUserObject().toString(); int startIndex = -1; int endIndex = -1; if (waveString.contains("\"wave\"")) { startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 2); endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 3); } else //Some wavestrings don't have the "wave" at the beginning for some reason { startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 0); endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 1); } String waveStringFilePath = waveString.substring(startIndex, endIndex + 1); waveString = waveString.replace(waveStringFilePath, "\"" + getCustomSoundPathString() + destFileName + "\""); selectedFile.setUserObject(waveString); //Write out modified tree to scriptfile. ScriptParser parser = new ScriptParser(this.currentTreeModel); String scriptString = getCurrentScriptString(); Path scriptPath = Paths.get(scriptString); parser.writeModelToFile(scriptPath.toString()); //Update UI ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString); ((DefaultTreeModel) currentTree.getModel()) .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()); JOptionPane.showMessageDialog(this, "Sound file successfully replaced."); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } return null; }
From source file:org.apache.openaz.xacml.std.pap.StdEngine.java
@Override public void updateGroup(PDPGroup group) throws PAPException { if (group == null || group.getId() == null) { throw new PAPException("Group or id is null"); }/* ww w . jav a2 s.c o m*/ if (group.getName() == null || group.getName().trim().length() == 0) { throw new PAPException("New name for group cannot be null or blank"); } StdPDPGroup existingGroup = (StdPDPGroup) getGroup(group.getId()); if (existingGroup == null) { throw new PAPException("Update found no existing group with id '" + group.getId() + "'"); } // We do dramatically different things when the Name changes // because the Name is essentially the identity of the group (as the User knows it) so when the // Identity changes we have to change the group ID. if (group.getName().equals(existingGroup.getName())) { // update the disk try { ((StdPDPGroup) group).saveGroupConfiguration(); } catch (IOException e) { throw new PAPException( "Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); } // update the group in the set by simply replacing the old instance with the new one this.groups.remove(existingGroup); this.groups.add((StdPDPGroup) group); } else { // the name/identity of the group has changed // generate the new id String newId = createNewPDPGroupId(group.getName()); // make sure no other group uses the new id for (PDPGroup g : groups) { if (g.getId().equals(newId)) { throw new PAPException("Replacement name maps to ID '" + newId + "' which is already in use"); } } ((StdPDPGroup) group).setId(newId); // rename the existing directory to the new id Path oldPath = existingGroup.getDirectory(); Path newPath = Paths.get(oldPath.getParent().toString(), newId); ((StdPDPGroup) group).setDirectory(newPath); try { boolean success = oldPath.toFile().renameTo(newPath.toFile()); if (!success) { throw new PAPException("Unable to rename directory; reason unknown"); } } catch (Exception e) { logger.error("Move '" + oldPath + "' to '" + newPath + "': " + e.getMessage(), e); throw new PAPException( "Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage()); } // update the disk try { ((StdPDPGroup) group).saveGroupConfiguration(); } catch (IOException e) { throw new PAPException( "Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); } // save the new group into the Set groups.remove(existingGroup); groups.add((StdPDPGroup) group); } // perhaps only the group changed, but if the name/id changed it may look to a listener like more than // one group changed(); }
From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java
@Test public void testOneLineReadFromExactOffsetLastLineNoEOLNoTruncate() throws Exception { Path file = createFile(Arrays.asList("Hello1\n", "Hello2")); LiveFile lf = new LiveFile(file); LiveFileReader lfr = new SingleLineLiveFileReader( LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf, Charset.defaultCharset(), 7, 10); Assert.assertTrue(lfr.hasNext());//from www. j av a 2s . co m LiveFileChunk chunk = lfr.next(0); Assert.assertNull(chunk); Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString())); Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1); Assert.assertTrue(lfr.hasNext()); chunk = lfr.next(0); Assert.assertNotNull(chunk); Assert.assertFalse(chunk.isTruncated()); Assert.assertEquals(7, chunk.getOffset()); Assert.assertEquals(6, chunk.getLength()); Assert.assertEquals("Hello2", readChunk(chunk)); Assert.assertEquals(13, lfr.getOffset()); Assert.assertFalse(lfr.hasNext()); Assert.assertEquals(13, lfr.getOffset()); Assert.assertFalse(lfr.hasNext()); lfr.close(); }
From source file:org.apache.storm.localizer.LocalizedResource.java
@Override public long downloadToTempLocation(ClientBlobStore store) throws IOException, KeyNotFoundException, AuthorizationException { String key = getKey();//w ww . j a va 2s . c om ReadableBlobMeta meta = store.getBlobMeta(key); if (!ServerUtils.canUserReadBlob(meta, user, conf)) { throw new AuthorizationException(user + " does not have READ access to " + key); } long version; Path downloadFile; Path finalLocation; try (InputStreamWithMeta in = store.getBlob(key)) { version = in.getVersion(); finalLocation = constructBlobWithVersionFileName(baseDir, getKey(), version); if (uncompressed) { // we need to download to temp file and then unpack into the one requested downloadFile = tmpOutputLocation(); } else { downloadFile = finalLocation; } byte[] buffer = new byte[1024]; int len; LOG.debug("Downloading {} to {}", key, downloadFile); Path parent = downloadFile.getParent(); if (!Files.exists(parent)) { //There is a race here that we can still lose try { Files.createDirectory(parent); } catch (FileAlreadyExistsException e) { //Ignored } } try (FileOutputStream out = new FileOutputStream(downloadFile.toFile())) { while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } } } if (uncompressed) { ServerUtils.unpack(downloadFile.toFile(), finalLocation.toFile()); LOG.debug("Uncompressed {} to: {}", downloadFile, finalLocation); } setBlobPermissions(conf, user, finalLocation); return version; }
From source file:org.roda.core.RodaCoreFactory.java
private static void copyFilesFromClasspath(String classpathPrefix, Path destinationDirectory, boolean removeClasspathPrefixFromFinalPath, List<String> excludePaths) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(classpathPrefix))) .setScanners(new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[] {})))); Set<String> resources = reflections.getResources(Pattern.compile(".*")); LOGGER.info(//from w w w. j a v a 2 s. c o m "Copy files from classpath prefix={}, destination={}, removePrefix={}, excludePaths={}, #resources={}", classpathPrefix, destinationDirectory, removeClasspathPrefixFromFinalPath, excludePaths, resources.size()); for (String resource : resources) { boolean exclude = false; for (String excludePath : excludePaths) { if (resource.startsWith(excludePath)) { exclude = true; break; } } if (exclude) { continue; } InputStream originStream = RodaCoreFactory.class.getClassLoader().getResourceAsStream(resource); Path destinyPath; String resourceFileName = resource; // Removing ":" escape resourceFileName = resourceFileName.replace("::", ":"); if (removeClasspathPrefixFromFinalPath) { destinyPath = destinationDirectory.resolve(resourceFileName.replaceFirst(classpathPrefix, "")); } else { destinyPath = destinationDirectory.resolve(resourceFileName); } try { // create all parent directories Files.createDirectories(destinyPath.getParent()); // copy file Files.copy(originStream, destinyPath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.error("Error copying file from classpath: {} to {} (reason: {})", originStream, destinyPath, e.getMessage()); instantiatedWithoutErrors = false; } finally { RodaUtils.closeQuietly(originStream); } } }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void newListItem() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path list = DataBundles.getPort(inputs, "in1"); DataBundles.createList(list);//www .j ava 2s .c om Path item0 = DataBundles.newListItem(list); assertEquals(list, item0.getParent()); assertTrue(item0.getFileName().toString().contains("0")); assertFalse(Files.exists(item0)); DataBundles.setStringValue(item0, "test"); Path item1 = DataBundles.newListItem(list); assertTrue(item1.getFileName().toString().contains("1")); // Because we've not actually created item1 yet assertEquals(item1, DataBundles.newListItem(list)); DataBundles.setStringValue(item1, "test"); // Check that DataBundles.newListItem can deal with gaps Files.delete(item0); Path item2 = DataBundles.newListItem(list); assertTrue(item2.getFileName().toString().contains("2")); // Check that non-numbers don't interfere Path nonumber = list.resolve("nonumber"); Files.createFile(nonumber); item2 = DataBundles.newListItem(list); assertTrue(item2.getFileName().toString().contains("2")); // Check that extension is stripped Path five = list.resolve("5.txt"); Files.createFile(five); Path item6 = DataBundles.newListItem(list); assertTrue(item6.getFileName().toString().contains("6")); }
From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java
private void checkPathPermissions(Path node, Path nodeMD, int parentLevel, Set<Path> treatedNodes) throws IOException { int nodeLevel = parentLevel; if (!treatedNodes.contains(node)) { if (Files.exists(nodeMD)) { Path permissionMD = Paths.get(nodeMD.toString(), "ortolang-acl-json"); if (Files.exists(permissionMD) && !Files.isDirectory(permissionMD)) { nodeLevel = parseACLLevel(permissionMD); if (nodeLevel < parentLevel) { errors.append("-> unconsistent file acl permission for object: ").append(node) .append("\r\n"); if (fix) { Path aclParent = Paths.get(nodeMD.getParent().toString(), "ortolang-acl-json"); try (OutputStream os = Files.newOutputStream(aclParent)) { Template tpl = Template.findTemplateByLevel(nodeLevel); IOUtils.write(tpl.getJson(), os, "UTF-8"); os.flush();/*ww w . j a va 2s .c o m*/ //noinspection StringConcatenationInsideStringBufferAppend fixed.append("-> new acl [").append(tpl.getName()) .append("] set for parent of object: ").append(node).append("\r\n"); } } for (String sibling : node.getParent().toFile().list()) { if (!sibling.equals(node.toString())) { Path aclSibling = Paths.get(sibling, "ortolang-acl-json"); if (!Files.exists(aclSibling)) { if (fix) { try (OutputStream os = Files.newOutputStream(aclSibling)) { Template tpl = Template.findTemplateByLevel(nodeLevel); IOUtils.write(tpl.getJson(), os, "UTF-8"); os.flush(); //noinspection StringConcatenationInsideStringBufferAppend fixed.append("-> new acl [").append(tpl.getName()) .append("] set for sibling of object: ").append(node) .append("\r\n"); } } treatedNodes.add(node); } } } } } } } treatedNodes.add(node); if (Files.isDirectory(node)) { for (String child : node.toFile().list()) { checkPathPermissions(Paths.get(node.toString(), child), Paths.get(nodeMD.toString(), child), (nodeLevel < 0 ? 0 : nodeLevel), treatedNodes); } } }
From source file:org.apache.taverna.robundle.manifest.Manifest.java
public void populateFromBundle() throws IOException { final Set<Path> potentiallyEmptyFolders = new LinkedHashSet<>(); final Set<URI> existingAggregationsToPrune = new HashSet<>(aggregates.keySet()); walkFileTree(bundle.getRoot(), new SimpleFileVisitor<Path>() { @SuppressWarnings("deprecation") @Override//from w w w . j av a 2 s . c o m public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { super.postVisitDirectory(dir, exc); if (potentiallyEmptyFolders.remove(dir)) { URI uri = relativeToBundleRoot(dir.toUri()); existingAggregationsToPrune.remove(uri); PathMetadata metadata = aggregates.get(uri); if (metadata == null) { metadata = new PathMetadata(); aggregates.put(uri, metadata); } metadata.setFile(withSlash(dir)); metadata.setFolder(withSlash(dir.getParent())); metadata.setProxy(); metadata.setCreatedOn(getLastModifiedTime(dir)); potentiallyEmptyFolders.remove(withSlash(dir.getParent())); return CONTINUE; } return CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.startsWith(RO) || dir.startsWith(META_INF)) return SKIP_SUBTREE; potentiallyEmptyFolders.add(withSlash(dir)); potentiallyEmptyFolders.remove(withSlash(dir.getParent())); return CONTINUE; } @SuppressWarnings("deprecation") @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { potentiallyEmptyFolders.remove(withSlash(file.getParent())); if (file.startsWith(MIMETYPE)) return CONTINUE; if (manifest.contains(file)) // Don't aggregate the manifests return CONTINUE; // super.visitFile(file, attrs); URI uri = relativeToBundleRoot(file.toUri()); existingAggregationsToPrune.remove(uri); PathMetadata metadata = aggregates.get(uri); if (metadata == null) { metadata = new PathMetadata(); aggregates.put(uri, metadata); } metadata.setFile(file); if (metadata.getMediatype() == null) // Don't override if already set metadata.setMediatype(guessMediaType(file)); metadata.setFolder(withSlash(file.getParent())); metadata.setProxy(); metadata.setCreatedOn(getLastModifiedTime(file)); potentiallyEmptyFolders.remove(file.getParent()); return CONTINUE; } }); for (URI preExisting : existingAggregationsToPrune) { PathMetadata meta = aggregates.get(preExisting); if (meta.getFile() != null) /* * Don't remove 'virtual' resources, only aggregations that went * to files */ aggregates.remove(preExisting); } }
From source file:org.apache.cassandra.config.DatabaseDescriptor.java
private static FileStore guessFileStore(String dir) throws IOException { Path path = Paths.get(dir); while (true) { try {//from w w w .j av a2s.co m return Files.getFileStore(path); } catch (IOException e) { if (e instanceof NoSuchFileException) path = path.getParent(); else throw e; } } }