List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:dk.dma.ais.utils.filter.AisFilter.java
private PrintStream getNextOutputStram() { if (outFile == null) { throw new Error("No output stream and no out file argument given"); }//ww w. j av a 2 s. c om String filename; if (splitSize == null) { filename = outFile; } else { Path path = Paths.get(outFile); filename = String.format("%06d", fileCounter++) + "." + path.getFileName(); Path dir = path.getParent(); if (dir != null) { filename = dir + "/" + filename; } } if (compress) { filename += ".gz"; } try { if (!compress) { return new PrintStream(filename); } else { return new PrintStream(new GZIPOutputStream(new FileOutputStream(filename))); } } catch (IOException e) { throw new RuntimeException("Failed to open output file: " + filename, e); } }
From source file:company.gonapps.loghut.dao.TagDao.java
public void createTagIndex(String tagName, int year, int month) throws IOException, InvalidTagNameException, TemplateException { if (tagIndexTemplate == null) tagIndexTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/tag_index.ftl"); List<TagDto> tags = getList(tagName, year, month); StringWriter temporaryBuffer = new StringWriter(); Map<String, Object> modelMap = new HashMap<>(); modelMap.put("settings", settingDao); modelMap.put("tags", tags); tagIndexTemplate.process(modelMap, temporaryBuffer); Path postIndexPath = Paths.get(settingDao.getSetting("tags.directory") + "/" + tagName + "/" + String.format("%04d", year) + "/" + String.format("%02d", month) + "/index.html"); rrwl.writeLock().lock();//from w ww . j a v a 2s. c o m Files.createDirectories(postIndexPath.getParent()); try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(postIndexPath.toFile()))) { bufferedWriter.write(temporaryBuffer.toString()); } finally { rrwl.writeLock().unlock(); } }
From source file:licorice.gui.MainPanel.java
private void processBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processBtnActionPerformed SwingUtilities.invokeLater(() -> { try {/*from w w w. j av a 2s .c o m*/ minQual = Integer.parseInt(minQualField.getText()); processBtn.setEnabled(false); //progressBar = new JProgressBar(); progressBar.setMinimum(0); progressBar.setMaximum(100); Path genomePath = Paths.get(prop.getProperty("genome.path")); prop.setProperty("input.default_dir", fc.getCurrentDirectory().getAbsolutePath()); prop.setProperty("minimum.quality", minQual.toString()); prop.setProperty("maximum.nocall.rate", maxNC.toString()); prop.store(new FileOutputStream("licorice.properties"), null); Path inputPath = Paths.get(fileNameField.getText()); if (!inputPath.toFile().exists()) { JOptionPane.showMessageDialog(null, "Input file does not exist"); appendLog("Input file '" + inputPath + "' does not exist"); return; } Path outputPath = inputPath .resolveSibling(FilenameUtils.getBaseName(inputPath.getFileName().toString()) + ".txt"); appendLog("Output in: '" + outputPath.getParent() + "'\n"); appendLog("Analysis Started...\n"); processBtn.setText("Processing..."); SimpleGenomeRef genome = new SimpleGenomeRef(genomePath); GenomeRef.ValidationResult validation = genome.validate(); if (!validation.isValid()) { appendLog("Reference Error: '" + validation.getErrors() + "'\n"); return; } Path effectivePath = ZipUtil.directoryfy(inputPath); Map<String, String> samples = VCFUtils.makeSamplesDictionary(VCFUtils.listVCFFiles(effectivePath)); appendLog("==================================\n"); appendLog("Samples List\n"); appendLog("==================================\n"); appendLog("Sample\tFile"); samples.forEach((k, v) -> appendLog(String.format("%s\t%s\n", k, v))); appendLog("==================================\n"); Path samplesPath = inputPath.resolveSibling( FilenameUtils.getBaseName(inputPath.getFileName().toString()) + ".samples.txt"); appendLog("Samples List in: '" + samplesPath.getParent() + "'\n"); try (PrintStream out = new PrintStream(new FileOutputStream(samplesPath.toFile()))) { out.println("Sample\tFile"); samples.forEach((k, v) -> out.println(String.format("%s\t%s", k, v))); } analysis = new Analysis(genome, minQual, maxNC, false, outputPath, VCFUtils.listVCFFiles(effectivePath)); analysis.progressListener(progress -> progressBar.setValue(progress)); analysis.onFinish(() -> { log.info("Callback called"); appendLog("Analysis Finished.\n"); fileNameField.setText(""); processBtn.setText("Process"); processBtn.setEnabled(true); processBtn.repaint(); this.repaint(); return null; }); analysis.onException((Thread t, Throwable ex) -> { appendLog(ex.getMessage()); appendLog("Analysis Failed!!!"); JOptionPane.showMessageDialog(null, "Analysis Failed!!!"); processBtn.setText("Process"); processBtn.setEnabled(true); processBtn.repaint(); }); } catch (IOException ex) { appendLog(ex.getMessage() + "\n"); log.error(ex.getMessage()); JOptionPane.showMessageDialog(null, "Analysis Failed!!!"); ex.printStackTrace(); } analysis.start(); //progressBar. }); }
From source file:ch.bender.evacuate.Runner.java
/** * run/* w w w. j a v a 2 s . com*/ * <p> * @throws Exception */ public void run() throws Exception { checkDirectories(); initExcludeMatchers(); myEvacuateCandidates = new TreeMap<>(); myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>()); myFutures = new HashSet<>(); myExclusionDirCount = 0; myEvacuationDirCount = 0; myExclusionFileCount = 0; myEvacuationFileCount = 0; Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() { /** * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException) */ @Override public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException { if ("System Volume Information".equals((aFile.getFileName().toString()))) { return FileVisitResult.SKIP_SUBTREE; } throw aExc; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { return Runner.this.visitFile(file, attrs); } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if ("System Volume Information".equals((dir.getFileName()))) { return FileVisitResult.SKIP_SUBTREE; } return Runner.this.preVisitDirectory(dir, attrs); } }); if (myEvacuateCandidates.size() == 0) { myLog.info("No candidates for evacuation found"); } else { StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:"); myEvacuateCandidates.keySet().forEach(p -> sb.append("\n " + p.toString())); myLog.info(sb.toString()); } if (myDryRun) { myLog.debug("DryRun flag is set. Doing nothing"); return; } if (myFutures.size() > 0) { myLog.debug("Waiting for all async tasks to complete"); CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get(); } if (myFailedChainPreparations.size() > 0) { for (Path path : myFailedChainPreparations.keySet()) { myLog.error("exception occured", myFailedChainPreparations.get(path)); } throw new Exception("chain preparation failed. See above error messages"); } for (Path src : myEvacuateCandidates.keySet()) { Path dst = myEvacuateCandidates.get(src); Path dstParent = dst.getParent(); if (Files.notExists(dstParent)) { Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src } if (myMove) { try { myLog.debug( "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\""); Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { myLog.warn("Atomic move not supported. Try copy and then delete"); if (Files.isDirectory(src)) { myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyDirectory(src.toFile(), dst.toFile()); myLog.debug("Delete folder \"" + src.toString() + "\""); FileUtils.deleteDirectory(src.toFile()); } else { myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyFile(src.toFile(), dst.toFile()); myLog.debug("Delete file \"" + src.toString() + "\""); Files.delete(src); } } } else { if (Files.isDirectory(src)) { myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyDirectory(src.toFile(), dst.toFile()); } else { myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\""); FileUtils.copyFile(src.toFile(), dst.toFile()); } } } myLog.info("\nSuccessfully terminated." + "\n Evacuated Skipped" + "\n Files : " + StringUtils.leftPad("" + myEvacuationDirCount, 9) + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n Folders: " + StringUtils.leftPad("" + myEvacuationFileCount, 9) + StringUtils.leftPad("" + myExclusionFileCount, 9)); }
From source file:br.com.thiaguten.archive.ZipArchive.java
/** * Override to make use of the ZipFile class instead of the ZipArchiveInputStream class. * https://commons.apache.org/proper/commons-compress/zip.html *///w ww . ja va 2s. c o m @Override public Path decompress(Path path) throws IOException { Path decompressDir = removeExtension(path); logger.debug("reading archive file " + path); try (ZipFile zipFile = new ZipFile(path.toString())) { // creates a new decompress folder to not override if already exists // if you do not want this behavior, just comment this line decompressDir = createFile(ArchiveAction.DECOMPRESS, decompressDir.getParent(), decompressDir); createDirectories(decompressDir); logger.debug("creating the decompress destination directory " + decompressDir); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { final ZipArchiveEntry zipArchiveEntry = entries.nextElement(); if (zipFile.canReadEntryData(zipArchiveEntry)) { final String entryName = zipArchiveEntry.getName(); final InputStream archiveInputStream = zipFile.getInputStream(zipArchiveEntry); final Path target = Paths.get(decompressDir.toString(), entryName); final Path parent = target.getParent(); if (parent != null && !exists(parent)) { createDirectories(parent); } logger.debug("reading compressed path " + entryName); if (!zipArchiveEntry.isDirectory()) { try (OutputStream outputStream = new BufferedOutputStream(newOutputStream(target))) { logger.debug("writting compressed " + entryName + " file in the decompress directory"); // byte[] content = new byte[(int) zipArchiveEntry.getSize()]; // outputStream.write(content); IOUtils.copy(archiveInputStream, outputStream); } } } } logger.debug("finishing the decompress in the directory: " + decompressDir); } return decompressDir; }
From source file:company.gonapps.loghut.dao.PostDao.java
public void create(PostDto post) throws IOException, TemplateException { if (postTemplate == null) postTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/post.ftl"); StringWriter temporaryBuffer = new StringWriter(); Map<String, Object> modelMap = new HashMap<>(); modelMap.put("settings", settingDao); modelMap.put("post", post); postTemplate.process(modelMap, temporaryBuffer); Path postPath = Paths.get(getPostPathString(post)); rrwl.writeLock().lock();/*from ww w. j ava 2s . c o m*/ Files.createDirectories(postPath.getParent()); try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(postPath.toFile()))) { bufferedWriter.write(temporaryBuffer.toString()); } finally { rrwl.writeLock().unlock(); } }
From source file:gr.upatras.ece.nam.baker.impl.InstalledBunLifecycleMgmt.java
private void startPackageDownloading() { logger.info("Downloading installation package: " + bunMetadata.getPackageLocation()); Path destFile = repoWebClient.fetchPackageFromLocation(installedBun.getUuid(), bunMetadata.getPackageLocation()); if ((destFile != null) && (extractPackage(destFile) == 0)) { installedBun.setStatus(InstalledBunStatus.DOWNLOADED); Path packageLocalPath = destFile.getParent(); installedBun.setPackageLocalPath(packageLocalPath.toString()); } else {//w w w. j a va 2 s.c o m logger.info("FAILED Downloading installation package from: " + bunMetadata.getPackageLocation()); installedBun.setStatus(InstalledBunStatus.FAILED); } }
From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java
@Override public String storeFile(final String UURI, final String tenantID, final byte[] resourceBinary) throws IOException { //Create Unique hash final String hash = hashText(UURI); if (hash == null) { //TODO: Throw exception LOG.error("Unable to create HASH for UID {}", UURI); }//from w ww . ja v a 2 s . c o m //Get Filename (including directories) final String filename = getFilename(hash); //Add Volume to the Path final Path file = Paths.get(VOLUME + "/" + tenantID + filename); //Create the directories. Files.createDirectories(file.getParent()); //Write the contents to the file writeFile(file, resourceBinary); //Returns the relative Path return getRelativePath(file); }
From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java
@Override public String storeFile(final String UURI, final String tenantID, final URI resourceURI) throws IOException { //Create Unique hash final String hash = hashText(UURI); if (hash == null) { //TODO: Throw exception LOG.error("Unable to create HASH for UID {}", UURI); }//from w ww. ja va 2s.c om //Get Filename (including directories) final String filename = getFilename(hash); //Add Volume to the Path final Path file = Paths.get(VOLUME + "/" + tenantID + filename); //Create the directories. Files.createDirectories(file.getParent()); //Convert URI to URL final URL resourceUrl = resourceURI.toURL(); //Write the contents to the file writeFile(file, resourceUrl); return getRelativePath(file); }
From source file:company.gonapps.loghut.dao.PostDao.java
public void createMainIndex(PostDto post) throws IOException, TemplateException { if (mainIndexTemplate == null) mainIndexTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/main_index.ftl"); StringWriter temporaryBuffer = new StringWriter(); Map<String, Object> modelMap = new HashMap<>(); modelMap.put("settings", settingDao); modelMap.put("post", post); mainIndexTemplate.process(modelMap, temporaryBuffer); Path mainIndexPath = Paths.get(getMainIndexPathString()); rrwl.writeLock().lock();/*from w w w . ja v a 2 s . c o m*/ Files.createDirectories(mainIndexPath.getParent()); try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(mainIndexPath.toFile()))) { bufferedWriter.write(temporaryBuffer.toString()); } finally { rrwl.writeLock().unlock(); } }