List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:org.fao.geonet.api.records.formatters.FormatterApi.java
public synchronized Element getPluginLocResources(final ServiceContext context, Path formatDir) throws Exception { final String formatDirPath = formatDir.toString(); Element allLangResources = this.pluginLocs.get(formatDirPath); if (isDevMode(context) || allLangResources == null) { allLangResources = new Element("loc"); Path baseLoc = formatDir.resolve("loc"); if (Files.exists(baseLoc)) { final Element finalAllLangResources = allLangResources; Files.walkFileTree(baseLoc, new SimpleFileVisitor<Path>() { private void addTranslations(String locDirName, Element fileElements) { if (locDirName != null && !locDirName.isEmpty()) { Element resources = finalAllLangResources.getChild(locDirName); if (resources == null) { resources = new Element(locDirName); finalAllLangResources.addContent(resources); }//from ww w . java 2s . co m resources.addContent(fileElements); } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().toLowerCase().endsWith(".xml")) { try { final Element fileElements = Xml.loadFile(file); final String fileName = getNameWithoutExtension(file.getFileName().toString()); fileElements.setName(fileName); final String locDirName = getNameWithoutExtension( file.getParent().getFileName().toString()); addTranslations(locDirName, fileElements); } catch (JDOMException e) { throw new RuntimeException(e); } } else if (file.getFileName().toString().toLowerCase().endsWith(".json")) { try { final String fileName = getNameWithoutExtension(file.getFileName().toString()); final String[] nameParts = fileName.split("-", 2); IsoLanguagesMapper isoLanguagesMapper = context.getBean(IsoLanguagesMapper.class); String lang = isoLanguagesMapper.iso639_1_to_iso639_2(nameParts[0].toLowerCase(), nameParts[0]); final JSONObject json = new JSONObject( new String(Files.readAllBytes(file), Constants.CHARSET)); Element fileElements = new Element(nameParts[1]); final Iterator keys = json.keys(); while (keys.hasNext()) { String key = (String) keys.next(); fileElements.addContent(new Element(key).setText(json.getString(key))); } addTranslations(lang, fileElements); } catch (JSONException e) { throw new RuntimeException(e); } } return super.visitFile(file, attrs); } }); } this.pluginLocs.put(formatDirPath, allLangResources); } return allLangResources; }
From source file:net.sf.jabref.gui.FindUnlinkedFilesDialog.java
/** * Starts the search of unlinked files according to the current dialog * state. <br>/* w ww. j a va2s .co m*/ * <br> * This state is made of: <br> * <li>The value of the "directory"-input-textfield and <li>The file type * selection. <br> * The search will process in a seperate thread and the progress bar behind * the "search" button will be displayed. <br> * <br> * When the search has completed, the * {@link #searchFinishedHandler(CheckableTreeNode)} handler method is * invoked. */ private void startSearch() { Path directory = Paths.get(textfieldDirectoryPath.getText()); if (Files.notExists(directory)) { directory = Paths.get(System.getProperty("user.dir")); } if (!Files.isDirectory(directory)) { directory = directory.getParent(); } //this addtional statement is needed because for the lamdba the variable must be effetively final Path dir = directory; storeLastSelectedDirectory(directory); progressBarSearching.setMinimumSize( new Dimension(buttonScan.getSize().width, progressBarSearching.getMinimumSize().height)); progressBarSearching.setVisible(true); progressBarSearching.setString(""); labelSearchingDirectoryInfo.setVisible(true); buttonScan.setVisible(false); disOrEnableDialog(false); labelSearchingDirectoryInfo.setEnabled(true); final FileFilter selectedFileFilter = (FileFilter) comboBoxFileTypeSelection.getSelectedItem(); threadState.set(true); JabRefExecutorService.INSTANCE.execute(() -> { UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(selectedFileFilter, database); CheckableTreeNode rootNode = crawler.searchDirectory(dir.toFile(), unlinkedPDFFileFilter, threadState, new ChangeListener() { int counter; @Override public void stateChanged(ChangeEvent e) { counter++; progressBarSearching.setString(counter + " files found"); } }); searchFinishedHandler(rootNode); }); }
From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java
@Test public void testMultiLineReadFromBeginningFullLinesNoTruncate() 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, 20); Assert.assertTrue(lfr.hasNext());/*from w ww.j a v a 2 s. com*/ LiveFileChunk chunk = lfr.next(0); Assert.assertNotNull(chunk); Assert.assertFalse(chunk.isTruncated()); Assert.assertEquals(0, chunk.getOffset()); Assert.assertEquals(14, chunk.getLength()); Assert.assertEquals("Hello1\nHello2\n", readChunk(chunk)); 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()); lfr.close(); }
From source file:de.elomagic.mag.MAG.java
private void run(String[] args) { Path configurationFile = Paths.get(System.getProperty("user.dir"), "conf", "configuration.properties"); DefaultParser parser = new DefaultParser(); try {/*from www. jav a 2s. c o m*/ CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption(optionHelp.getOpt())) { printHelp(); } else if (commandLine.hasOption(optionEncrypt.getOpt())) { if (commandLine.hasOption(optionConfig.getOpt())) { String file = commandLine.getOptionValue(optionConfig.getOpt()); configurationFile = Paths.get(file); } encryptConfiguration(configurationFile); } else { boolean initCreateOfConfig = false; if (commandLine.hasOption(optionConfig.getOpt())) { String file = commandLine.getOptionValue(optionConfig.getOpt()); configurationFile = Paths.get(file); LOGGER.info("Using configuration file \"" + file + "\"."); } else if (Files.notExists(configurationFile)) { System.out.println("Creating default configuration file \"" + configurationFile + "\"."); try (InputStream in = getClass().getResourceAsStream(Configuration.DEFAULT_PROPERTIES_FILE)) { Files.createDirectories(configurationFile.getParent()); Files.copy(in, configurationFile, StandardCopyOption.REPLACE_EXISTING); } System.out .println("Configure file \"" + configurationFile + "\" as your needs and start again."); initCreateOfConfig = true; } if (!initCreateOfConfig) { Configuration.loadConfiguration(configurationFile); System.out.println("Use ctrl + c to terminate MAG...."); createCamelMain().run(); System.out.println("MAG was terminated...."); } } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (ParseException e) { LOGGER.error("Parameter syntax error.", e); printHelp(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }
From source file:com.ejie.uda.jsonI18nEditor.Editor.java
public void importResources(Path dir) { Stream<Path> filter; try {/* w ww .j a v a 2 s . com*/ if (!closeCurrentSession()) { return; } if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) { reset(); resourcesDir = dir; filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)); } else { reset(); // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece. Pattern.matches(BUNDLE_REGEX, dir.getFileName().toString()); Pattern regex = Pattern.compile(BUNDLE_REGEX); resourcesDir = dir.getParent(); inputFile = dir; Matcher regexMatcher = regex.matcher(dir.getFileName().toString()); if (regexMatcher.find()) { this.bundle = regexMatcher.group(1); filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path, this.bundle)); } else { showError(MessageBundle.get("resources.open.error.multiple")); return; } // Pattern.matches("BUNDLE_REGEX", dir.getFileName().toString()); // showError(MessageBundle.get("resources.open.error.multiple")); // return; } filter.forEach(path -> { try { Resource resource = Resources.read(path); setupResource(resource); } catch (Exception e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.single", path.toString())); } }); List<String> recentDirs = settings.getListProperty("history"); recentDirs.remove(dir); recentDirs.add(dir.toString()); if (recentDirs.size() > 5) { recentDirs.remove(0); } settings.setProperty("history", recentDirs); editorMenu.setRecentItems(Lists.reverse(recentDirs)); Map<String, String> keys = Maps.newTreeMap(); resources.forEach(resource -> keys.putAll(resource.getTranslations())); // resources.forEach(resource -> { // // // // }); List<String> keyList = Lists.newArrayList(keys.keySet()); translationTree.setModel(new TranslationTreeModel(keyList)); updateUI(); // for (String key : keyList) { // boolean anyEmpty = false; // // for (Resource resource : resources) { // if (StringUtils.isBlank(resource.getTranslation(key))){ // anyEmpty = true; // } // } // // TranslationTreeModel model = (TranslationTreeModel) translationTree.getModel(); // TranslationTreeNode node = model.getNodeByKey(key); // // node // } // keyList.stream().filter(key -> { // // resources.stream().filter(resource -> { // return StringUtils.isNotBlank(resource.getTranslation(key)); // }); // return true; // }); } catch (IOException e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.multiple")); } }
From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java
@Test public void testMultiLineLineReadFromBeginningLastLineNoEOLNoTruncate() 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(), 0, 20); Assert.assertTrue(lfr.hasNext());/*from w w w. java 2 s.co m*/ 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.assertNull(chunk); Assert.assertEquals(7, lfr.getOffset()); 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(13, lfr.getOffset()); Assert.assertEquals("Hello2", readChunk(chunk)); Assert.assertFalse(lfr.hasNext()); Assert.assertEquals(13, lfr.getOffset()); lfr.close(); }
From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java
@Test public void testOneLineReadFromBeginningLastLineNoEOLNoTruncate() 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(), 0, 10); Assert.assertTrue(lfr.hasNext());//from ww w . jav a 2s.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.assertNull(chunk); Assert.assertEquals(7, lfr.getOffset()); 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()); lfr.close(); }
From source file:org.roda.core.storage.fs.FileStorageService.java
private void deleteAllBinaryVersionsUnder(StoragePath storagePath) { Path resourcePath = FSUtils.getEntityPath(basePath, storagePath); Path relativePath = basePath.relativize(resourcePath); Path resourceHistoryDataPath = historyDataPath.resolve(relativePath); if (FSUtils.isDirectory(resourceHistoryDataPath)) { try {/*from w w w . j av a2 s. co m*/ Path resourceHistoryMetadataPath = historyMetadataPath .resolve(historyDataPath.relativize(resourceHistoryDataPath)); trash(resourceHistoryDataPath); trash(resourceHistoryMetadataPath); FSUtils.deleteEmptyAncestorsQuietly(resourceHistoryDataPath, historyDataPath); FSUtils.deleteEmptyAncestorsQuietly(resourceHistoryMetadataPath, historyMetadataPath); } catch (GenericException | NotFoundException e) { LOGGER.warn("Could not delete history under " + resourceHistoryDataPath, e); } } else { Path parent = resourceHistoryDataPath.getParent(); final String baseName = resourceHistoryDataPath.getFileName().toString(); if (FSUtils.exists(parent)) { DirectoryStream<Path> directoryStream = null; try { directoryStream = Files.newDirectoryStream(parent, new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path entry) throws IOException { return entry.getFileName().toString().startsWith(baseName); } }); for (Path p : directoryStream) { trash(p); Path pMetadata = FSUtils.getBinaryHistoryMetadataPath(historyDataPath, historyMetadataPath, p); trash(pMetadata); FSUtils.deleteEmptyAncestorsQuietly(p, historyDataPath); FSUtils.deleteEmptyAncestorsQuietly(pMetadata, historyMetadataPath); } } catch (IOException | GenericException | NotFoundException e) { LOGGER.warn("Could not delete history under " + resourceHistoryDataPath, e); } finally { IOUtils.closeQuietly(directoryStream); } } } }
From source file:org.sleuthkit.autopsy.imagegallery.datamodel.DrawableDB.java
/** * @param dbPath the path to the db file * * @throws SQLException if there is problem creating or configuring the db *//*w w w . ja v a 2s .c o m*/ private DrawableDB(Path dbPath, SleuthkitCase tskCase) throws SQLException, ExceptionInInitializerError, IOException { this.dbPath = dbPath; this.tskCase = tskCase; Files.createDirectories(dbPath.getParent()); if (initializeDBSchema()) { updateFileStmt = prepareStatement( "INSERT OR REPLACE INTO drawable_files (obj_id , path, name, created_time, modified_time, make, model, analyzed) " + "VALUES (?,?,?,?,?,?,?,?)"); insertFileStmt = prepareStatement( "INSERT OR IGNORE INTO drawable_files (obj_id , path, name, created_time, modified_time, make, model, analyzed) " + "VALUES (?,?,?,?,?,?,?,?)"); removeFileStmt = prepareStatement("delete from drawable_files where obj_id = ?"); pathGroupStmt = prepareStatement("select obj_id , analyzed from drawable_files where path = ? ", DrawableAttribute.PATH); nameGroupStmt = prepareStatement("select obj_id , analyzed from drawable_files where name = ? ", DrawableAttribute.NAME); created_timeGroupStmt = prepareStatement( "select obj_id , analyzed from drawable_files where created_time = ? ", DrawableAttribute.CREATED_TIME); modified_timeGroupStmt = prepareStatement( "select obj_id , analyzed from drawable_files where modified_time = ? ", DrawableAttribute.MODIFIED_TIME); makeGroupStmt = prepareStatement("select obj_id , analyzed from drawable_files where make = ? ", DrawableAttribute.MAKE); modelGroupStmt = prepareStatement("select obj_id , analyzed from drawable_files where model = ? ", DrawableAttribute.MODEL); analyzedGroupStmt = prepareStatement("Select obj_id , analyzed from drawable_files where analyzed = ?", DrawableAttribute.ANALYZED); hashSetGroupStmt = prepareStatement( "select drawable_files.obj_id as obj_id, analyzed from drawable_files , hash_sets , hash_set_hits where drawable_files.obj_id = hash_set_hits.obj_id and hash_sets.hash_set_id = hash_set_hits.hash_set_id and hash_sets.hash_set_name = ?", DrawableAttribute.HASHSET); updateGroupStmt = prepareStatement( "insert or replace into groups (seen, value, attribute) values( ?, ? , ?)"); insertGroupStmt = prepareStatement("insert or ignore into groups (value, attribute) values (?,?)"); groupSeenQueryStmt = prepareStatement("select seen from groups where value = ? and attribute = ?"); selectHashSetNamesStmt = prepareStatement("SELECT DISTINCT hash_set_name FROM hash_sets"); insertHashSetStmt = prepareStatement("insert or ignore into hash_sets (hash_set_name) values (?)"); selectHashSetStmt = prepareStatement("select hash_set_id from hash_sets where hash_set_name = ?"); insertHashHitStmt = prepareStatement( "insert or ignore into hash_set_hits (hash_set_id, obj_id) values (?,?)"); for (Category cat : Category.values()) { insertGroup(cat.getDisplayName(), DrawableAttribute.CATEGORY); } initializeImageList(); } else { throw new ExceptionInInitializerError(); } }
From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java
/** * Verify/download/update artifact in cache. Execute post-download actions. *///from w w w .ja v a 2 s . c o m private void materialize(DatasetDescription aDataset) throws IOException { Path root = resolve(aDataset); Collection<ArtifactDescription> artifacts = aDataset.getArtifacts().values(); // First validate if local copies are still up-to-date boolean reload = false; packageValidationLoop: for (ArtifactDescription artifact : artifacts) { Path cachedFile = resolve(aDataset, artifact); if (!Files.exists(cachedFile)) { continue; } if (artifact.getSha1() != null) { String actual = getDigest(cachedFile, "SHA1"); if (!artifact.getSha1().equals(actual)) { LOG.info("Local SHA1 hash mismatch on [" + cachedFile + "] - expected [" + artifact.getSha1() + "] - actual [" + actual + "]"); reload = true; break packageValidationLoop; } else { LOG.info("Local SHA1 hash verified on [" + cachedFile + "] - [" + actual + "]"); } } } // If any of the packages are outdated, clear the cache and download again if (reload) { LOG.info("Clearing local cache for [" + root + "]"); FileUtils.deleteQuietly(root.toFile()); } for (ArtifactDescription artifact : artifacts) { Path cachedFile = resolve(aDataset, artifact); if (Files.exists(cachedFile)) { continue; } if (artifact.getText() != null) { Files.createDirectories(cachedFile.getParent()); LOG.info("Creating [" + cachedFile + "]"); try (Writer out = Files.newBufferedWriter(cachedFile, StandardCharsets.UTF_8)) { out.write(artifact.getText()); } } if (artifact.getUrl() != null) { Files.createDirectories(cachedFile.getParent()); MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } URL source = new URL(artifact.getUrl()); LOG.info("Fetching [" + cachedFile + "]"); URLConnection connection = source.openConnection(); connection.setRequestProperty("User-Agent", "Java"); try (InputStream is = connection.getInputStream()) { DigestInputStream sha1Filter = new DigestInputStream(is, sha1); Files.copy(sha1Filter, cachedFile); if (artifact.getSha1() != null) { String sha1Hex = new String(Hex.encodeHex(sha1Filter.getMessageDigest().digest())); if (!artifact.getSha1().equals(sha1Hex)) { String message = "SHA1 mismatch. Expected [" + artifact.getSha1() + "] but got [" + sha1Hex + "]."; LOG.error(message); throw new IOException(message); } } } } } // Perform a post-fetch action such as unpacking Path postActionCompleteMarker = resolve(aDataset).resolve(".postComplete"); if (!Files.exists(postActionCompleteMarker)) { for (ArtifactDescription artifact : artifacts) { Path cachedFile = resolve(aDataset, artifact); List<ActionDescription> actions = artifact.getActions(); if (actions != null && !actions.isEmpty()) { try { for (ActionDescription action : actions) { LOG.info("Post-download action [" + action.getAction() + "]"); Class<? extends Action_ImplBase> implClass = actionRegistry.get(action.getAction()); if (implClass == null) { throw new IllegalStateException( "Unknown or unsupported action [" + action.getAction() + "]"); } Action_ImplBase impl = implClass.newInstance(); impl.apply(action, aDataset, artifact, cachedFile); } } catch (IllegalStateException e) { throw e; } catch (IOException e) { throw e; } catch (Exception e) { throw new IllegalStateException(e); } } } Files.createFile(postActionCompleteMarker); } }