List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java
@Test public void testOneLineReadFromExactOffsetFullLinesNoTruncate() throws Exception { Path file = createFile(Arrays.asList("Hello1\n", "Hello2\n")); 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 . c om LiveFileChunk chunk = lfr.next(0); Assert.assertNotNull(chunk); Assert.assertFalse(chunk.isTruncated()); Assert.assertEquals(7, chunk.getOffset()); Assert.assertEquals(7, chunk.getLength()); Assert.assertEquals("Hello2\n", readChunk(chunk)); Assert.assertEquals(14, lfr.getOffset()); Assert.assertTrue(lfr.hasNext()); chunk = lfr.next(0); Assert.assertNull(chunk); Assert.assertEquals(14, lfr.getOffset()); Assert.assertTrue(lfr.hasNext()); chunk = lfr.next(0); Assert.assertNull(chunk); Assert.assertEquals(14, lfr.getOffset()); Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString())); Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1); Assert.assertFalse(lfr.hasNext()); lfr.close(); }
From source file:dotaSoundEditor.Controls.ItemPanel.java
@Override protected File promptUserForNewFile(String wavePath) { DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath); String waveString = selectedTreeNode.getUserObject().toString(); String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", ""); JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory())); FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav") : new FileNameExtensionFilter("MP3s", "mp3"); chooser.setAcceptAllFileFilterUsed((false)); chooser.setFileFilter(filter);//from w ww . j a v a2 s . c o m chooser.setMultiSelectionEnabled(false); int chooserRetVal = chooser.showOpenDialog(chooser); if (chooserRetVal == JFileChooser.APPROVE_OPTION) { Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath()); int startIndex = -1; int endIndex = -1; //Get the actual value for the wavestring key-value pair. if (waveString.contains("\"wave\"")) { startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2); endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3); } else //Some wavestrings don't have the "wave" at the beginning for some reason { startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0); endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1); } String waveStringFilePath = waveString.substring(startIndex, endIndex + 1); String waveStringNormalizedFilePath = waveStringFilePath.substring(0, waveStringFilePath.lastIndexOf("\"")); waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", ""); waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", ""); Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath); UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString()); try { new File(destPath.toString()).mkdirs(); Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING); if (waveString.contains("//")) { waveString = waveString .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), ""); } waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath + "\" //Replaced by: " + chosenFile.getFileName().toString()); selectedTreeNode.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.admin.components.PolicyWorkspace.java
protected void clonePolicy(final File policy) { //// ww w . j a v a2 s. c o m // Figure out a new name for the cloned policy // Path policyClone = Paths.get(policy.getAbsolutePath()); Path newFile = this.getNextFilename(policyClone.getParent(), policy.getName()); if (newFile == null) { return; } // // Scan the policy in, replace policy ID's and rule ID's // Object policyData = new XACMLPolicyScanner(policyClone, new XACMLPolicyScanner.SimpleCallback() { @Override public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { rule.setRuleId(((XacmlAdminUI) getUI()).newRuleID()); return CallbackResult.CONTINUE; } @Override public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { policySet.setPolicySetId(((XacmlAdminUI) getUI()).newPolicyID()); policySet.setVersion("1"); return CallbackResult.CONTINUE; } @Override public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { policy.setPolicyId(((XacmlAdminUI) getUI()).newPolicyID()); policy.setVersion("1"); return CallbackResult.CONTINUE; } }).scan(); // // Run the window // this.runPolicyWindow("Clone Policy", newFile.getParent(), newFile.getFileName(), policyData, null); }
From source file:org.eclipse.winery.repository.importing.CSARImporter.java
private void adjustRefFiles(TOSCAMetaFile tmf, Path defsPath, final List<String> errors, final TExtensibleElements ci, final TOSCAComponentId wid) throws IOException { if (ci instanceof TArtifactTemplate) { // convention: Definitions are stored in the "Definitions" directory, therefore going to // levels up (Definitions dir -> root dir) resolves to the root dir // COS01, line 2663 states that the path has to be resolved from the *root* of the CSAR this.adjustArtifactTemplate(defsPath.getParent().getParent(), tmf, (ArtifactTemplateId) wid, (TArtifactTemplate) ci, errors); } else if (ci instanceof TNodeType) { this.adjustNodeType(defsPath.getParent().getParent(), (TNodeType) ci, (NodeTypeId) wid, tmf, errors); } else if (ci instanceof TRelationshipType) { this.adjustRelationshipType(defsPath.getParent().getParent(), (TRelationshipType) ci, (RelationshipTypeId) wid, tmf, errors); } else if (ci instanceof TServiceTemplate) { this.adjustServiceTemplate(defsPath.getParent().getParent(), tmf, (ServiceTemplateId) wid, (TServiceTemplate) ci, errors); }//from w ww. ja v a2 s.c om }
From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java
protected void saveSecure(final PropertiesConfiguration conf) throws ConfigurationException { final File file = conf.getFile(); try {/*from w w w . ja v a 2 s . c o m*/ if (file == null) { throw new ConfigurationException("No file name has been set!"); } else if ((file.createNewFile() || true) && !file.canWrite()) { throw new IOException("Cannot write to file " + file.getAbsolutePath() + ". Is it read-only?"); } } catch (IOException e) { throw new ConfigurationException(e.getMessage(), e); } log.debug("Saving {}", file.getAbsolutePath()); final String fName = file.getName(); try { int lastDot = fName.lastIndexOf('.'); lastDot = lastDot > 0 ? lastDot : fName.length(); final Path configPath = file.toPath(); // Create a tmp file next to the original final Path tmp = Files.createTempFile(configPath.getParent(), fName.substring(0, lastDot) + ".", fName.substring(lastDot)); try { Files.copy(configPath, tmp, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException iox) { log.error("Could not create temp-file {}: {}", tmp, iox.getMessage()); throw iox; } log.trace("using temporary file: {}", tmp); // Save the config to the tmp file conf.save(tmp.toFile()); log.trace("tmp saved, now replacing the original file: {}", configPath); // Replace the original with the tmp file try { try { Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException amnx) { log.trace("atomic move not available: {}, trying without", amnx.getMessage()); Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException iox) { log.error("Could not write to {}, a backup was created in {}", configPath, tmp); throw iox; } log.info("configuration successfully saved to {}", configPath); } catch (final Throwable t) { throw new ConfigurationException("Unable to save the configuration to the file " + fName, t); } }
From source file:io.fabric8.git.internal.GitDataStoreImpl.java
@Override public void importFromFileSystem(String importPath) { IllegalArgumentAssertion.assertNotNull(importPath, "importPath"); Path importBase = Paths.get(importPath); importExportHandler.importFromFileSystem(importBase); importExportHandler.importZipAndArtifacts(importBase.getParent()); }
From source file:org.apache.solr.handler.IndexFetcher.java
/** * The tlog files are moved from the tmp dir to the tlog dir as an atomic filesystem operation. * A backup of the old directory is maintained. If the directory move fails, it will try to revert back the original * tlog directory.//from w ww . j a v a2 s .c o m */ private boolean copyTmpTlogFiles2Tlog(File tmpTlogDir) { Path tlogDir = FileSystems.getDefault().getPath(solrCore.getUpdateHandler().getUpdateLog().getLogDir()); Path backupTlogDir = FileSystems.getDefault().getPath(tlogDir.getParent().toAbsolutePath().toString(), tmpTlogDir.getName()); try { Files.move(tlogDir, backupTlogDir, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { SolrException.log(LOG, "Unable to rename: " + tlogDir + " to: " + backupTlogDir, e); return false; } Path src = FileSystems.getDefault().getPath(backupTlogDir.toAbsolutePath().toString(), tmpTlogDir.getName()); try { Files.move(src, tlogDir, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { SolrException.log(LOG, "Unable to rename: " + src + " to: " + tlogDir, e); // In case of error, try to revert back the original tlog directory try { Files.move(backupTlogDir, tlogDir, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e2) { // bad, we were not able to revert back the original tlog directory throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to rename: " + backupTlogDir + " to: " + tlogDir); } return false; } return true; }
From source file:org.apache.nifi.controller.repository.FileSystemRepository.java
protected boolean archive(final Path curPath) throws IOException { // check if already archived final boolean alreadyArchived = ARCHIVE_DIR_NAME.equals(curPath.getParent().toFile().getName()); if (alreadyArchived) { return false; }/*from www .j a v a 2 s. com*/ final Path archivePath = getArchivePath(curPath); if (curPath.equals(archivePath)) { LOG.warn("Cannot archive {} because it is already archived", curPath); return false; } try { Files.move(curPath, archivePath); return true; } catch (final NoSuchFileException nsfee) { // If the current path exists, try to create archive path and do the move again. // Otherwise, either the content was removed or has already been archived. Either way, // there's nothing that can be done. if (Files.exists(curPath)) { // The archive directory doesn't exist. Create now and try operation again. // We do it this way, rather than ensuring that the directory exists ahead of time because // it will be rare for the directory not to exist and we would prefer to have the overhead // of the Exception being thrown in these cases, rather than have the overhead of checking // for the existence of the directory continually. Files.createDirectories(archivePath.getParent()); Files.move(curPath, archivePath); return true; } return false; } }
From source file:gda.data.scan.datawriter.NexusDataWriter.java
void writeHere(NeXusFileInterface file, INexusTree tree, boolean makeData, boolean attrOnly, List<SelfCreatingLink> links) throws NexusException { if (!tree.isPointDependent() && !makeData) { return;//from www . j av a2s.c o m } String name = tree.getName(); String nxClass = tree.getNxClass(); Boolean dataOpen = false; Boolean loopNodes = true; Boolean attrBelowThisOnly = attrOnly; Boolean nxClassIsSDS = nxClass.equals(NexusExtractor.SDSClassName); Boolean nxClassIsAttr = nxClass.equals(NexusExtractor.AttrClassName); Boolean nxClassIsExternalSDS = nxClass.equals(NexusExtractor.ExternalSDSLink); if (nxClassIsExternalSDS) { if (makeData) { NexusGroupData data = tree.getData(); try { /** * Create a link of the format * "nxfile://" + path to external file relative to nxs file + "#" + address * * The buffer in data contains * "nxfile://" + abs path to external file + "#" + address * * so we need to replace the abs path with the relative path */ String link = new String((byte[]) data.getBuffer(), "UTF-8"); //link is of format nxfile:// + filepath + # + address String[] linkParts = link.split("nxfile://"); if (linkParts.length != 2) { throw new NexusException("Invalid format for external link " + StringUtils.quote(link)); } String[] parts = linkParts[1].split("#"); if (parts.length != 2) { throw new NexusException("Invalid format for external link " + StringUtils.quote(link)); } Path absExtPath = Paths.get(parts[0]); String address = parts[1]; File f = absExtPath.toFile(); if (!f.exists()) logger.warn("file " + absExtPath + " does not exist at time of adding link"); Path nxsFile = Paths.get(nexusFileUrl); Path nxsParent = nxsFile.getParent(); Path relativize = nxsParent.relativize(absExtPath); String relativeLink = "nxfile://" + relativize + "#" + address; file.linkexternaldataset(name, relativeLink); links.add(new ExternalNXlink(name, relativeLink)); } catch (UnsupportedEncodingException e) { throw new NexusException( "supported encoding in creating string for external linking -- this should never happen"); } } return; } if (nxClassIsAttr) { if (makeData) { NexusGroupData data = tree.getData(); if (data != null && data.getBuffer() != null) { if ("axis".equals(name) || "label".equals(name)) { Integer axisno = getIntfromBuffer(data.getBuffer()); axisno += thisPoint.getScanDimensions().length; file.putattr(name, axisno.toString().getBytes(), NexusFile.NX_CHAR); } else { file.putattr(name, data.getBuffer(), data.type); } } } return; } if (attrOnly) { return; } if (!name.isEmpty() && !nxClass.isEmpty()) { if (!nxClassIsSDS) { if (!(file.groupdir().containsKey(name) && file.groupdir().get(name).equals(nxClass))) { file.makegroup(name, nxClass); } file.opengroup(name, nxClass); } NexusGroupData sds = tree.getData(); if (sds != null) { if (sds.dimensions != null) { for (int i : sds.dimensions) { if (i == 0) throw new NexusException("Data for " + name + " is invalid. SDS Dimension = 0"); } } if (makeData) { int[] dataDimMake = generateDataDim(tree.isPointDependent(), tree.isPointDependent() ? scanDimensions : null, sds.dimensions); if (sds.dimensions != null && sds.dimensions.length > 1) { int[] chunks = Arrays.copyOf(dataDimMake, dataDimMake.length); for (int i = 0; i < chunks.length; i++) { if (chunks[i] == -1) chunks[i] = 1; } if (sds.chunkDimensions != null && sds.chunkDimensions.length <= chunks.length) { int lendiff = chunks.length - sds.chunkDimensions.length; for (int i = 0; i < sds.chunkDimensions.length; i++) { chunks[i + lendiff] = dataDimMake[i + lendiff] == -1 ? sds.chunkDimensions[i] : Math.min(sds.chunkDimensions[i], chunks[i + lendiff]); } } int compression = sds.compressionType != null ? sds.compressionType : NexusFile.NX_COMP_LZW_LVL1; file.compmakedata(name, sds.type, dataDimMake.length, dataDimMake, compression, chunks); } else { file.makedata(name, sds.type, dataDimMake.length, dataDimMake); } file.opendata(name); if (!tree.isPointDependent()) { int[] dataDim = generateDataDim(false, null, sds.dimensions); int[] dataStartPos = generateDataStartPos(null, sds.dimensions); file.putslab(sds.getBuffer(), dataStartPos, dataDim); } if (links != null && sds.isDetectorEntryData) { links.add(new SelfCreatingLink(file.getdataID())); } dataOpen = true; attrBelowThisOnly = true; } else { int[] dataDim = generateDataDim(false, dataDimPrefix, sds.dimensions); int[] dataStartPos = generateDataStartPos(dataStartPosPrefix, sds.dimensions); // Open data array. file.opendata(name); file.putslab(sds.getBuffer(), dataStartPos, dataDim); dataOpen = true; // Close data - do not add children as attributes added for first point only loopNodes = false; } } } else { logger.warn("Name or class is empty:"); } try { if (loopNodes) { for (INexusTree branch : tree) { writeHere(file, branch, makeData, attrBelowThisOnly, links); } } } finally { if (dataOpen) { file.closedata(); } if (!name.isEmpty() && !nxClass.isEmpty() && !nxClassIsSDS) { file.closegroup(); } } }
From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java
@Test public void testOneLineReadFromBeginningFullLinesNoTruncate() throws Exception { Path file = createFile(Arrays.asList("Hello1\n", "Hello2\n")); LiveFile lf = new LiveFile(file); LiveFileReader lfr = new SingleLineLiveFileReader( LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf, Charset.defaultCharset(), 0, 10); Assert.assertTrue(lfr.hasNext());/*from w ww .j a v a 2 s . c om*/ LiveFileChunk chunk = lfr.next(0); Assert.assertNotNull(chunk); Assert.assertFalse(chunk.isTruncated()); Assert.assertEquals(0, chunk.getOffset()); Assert.assertEquals(7, chunk.getLength()); Assert.assertEquals("Hello1\n", readChunk(chunk)); Assert.assertEquals(7, lfr.getOffset()); Assert.assertTrue(lfr.hasNext()); chunk = lfr.next(0); Assert.assertNotNull(chunk); Assert.assertFalse(chunk.isTruncated()); Assert.assertEquals(7, chunk.getOffset()); Assert.assertEquals(7, chunk.getLength()); Assert.assertEquals("Hello2\n", readChunk(chunk)); Assert.assertEquals(14, lfr.getOffset()); Assert.assertTrue(lfr.hasNext()); chunk = lfr.next(0); Assert.assertNull(chunk); Assert.assertEquals(14, lfr.getOffset()); Assert.assertTrue(lfr.hasNext()); chunk = lfr.next(0); Assert.assertNull(chunk); Assert.assertEquals(14, lfr.getOffset()); Files.move(file, Paths.get(file.getParent().toString(), UUID.randomUUID().toString())); Thread.sleep(SingleLineLiveFileReader.REFRESH_INTERVAL + 1); Assert.assertFalse(lfr.hasNext()); Assert.assertEquals(14, lfr.getOffset()); // next() after EOF returns null Assert.assertNull(lfr.next(0)); lfr.close(); }