List of usage examples for java.nio.file FileVisitResult TERMINATE
FileVisitResult TERMINATE
To view the source code for java.nio.file FileVisitResult TERMINATE.
Click Source Link
From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("SchemaDist plugin started"); try {/*from www . jav a 2s .c om*/ processArtifactItems(); } catch (InvalidVersionSpecificationException e) { handleFailure(e); } final File outDir = initializeOutDir(outputDirectory); CatalogManager catalogManager = new CatalogManager(); catalogManager.setVerbosity(999); for (ArtifactItem artifactItem : artifactItems) { Artifact artifact = artifactItem.getArtifact(); getLog().info("SchemaDist unpacking artifact " + artifact); File workDir = new File(workDirectory, artifact.getArtifactId()); initializeOutDir(workDir); artifactItem.setWorkDir(workDir); unpack(artifactItem, workDir); if (translateSchemaLocation) { String catalogPath = artifactItem.getCatalog(); File catalogFile = new File(workDir, catalogPath); if (!catalogFile.exists()) { throw new MojoExecutionException("No catalog file " + catalogPath + " in artifact " + artifact); } Catalog catalog = new Catalog(catalogManager); catalog.setupReaders(); try { // UGLY HACK. On Windows, file names like d:\abc\def\catalog.xml eventually get treated very strangely // (resulting in names like "file:<current-working-dir>d:\abc\def\catalog.xml" that are obviously wrong) // Prefixing such names with "file:/" helps. String prefix; if (catalogFile.isAbsolute() && !catalogFile.getPath().startsWith("/")) { prefix = "/"; } else { prefix = ""; } String fileName = "file:" + prefix + catalogFile.getPath(); getLog().debug("Calling parseCatalog with: " + fileName); catalog.parseCatalog(fileName); } catch (MalformedURLException e) { throw new MojoExecutionException( "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e); } catch (IOException e) { throw new MojoExecutionException( "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e); } artifactItem.setResolveCatalog(catalog); } } for (ArtifactItem artifactItem : artifactItems) { Artifact artifact = artifactItem.getArtifact(); getLog().info("SchemaDist processing artifact " + artifact); final File workDir = artifactItem.getWorkDir(); FileVisitor<Path> fileVisitor = new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // nothing to do return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException { String fileName = filePath.getFileName().toString(); if (fileName.endsWith(".xsd")) { getLog().debug("Processing file " + filePath); try { processXsd(filePath, workDir, outDir); } catch (MojoExecutionException | MojoFailureException e) { throw new RuntimeException(e.getMessage(), e); } } else if (fileName.endsWith(".wsdl")) { getLog().debug("Processing file " + filePath); try { processWsdl(filePath, workDir, outDir); } catch (MojoExecutionException | MojoFailureException e) { throw new RuntimeException(e.getMessage(), e); } } else { getLog().debug("Skipping file " + filePath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.TERMINATE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // nothing to do return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(workDir.toPath(), fileVisitor); } catch (IOException e) { throw new MojoExecutionException("Error processing files of artifact " + artifact, e); } } getLog().info("SchemaDist plugin finished"); }
From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java
@Override public void deRegisterApp(String appId) { appId = appId.trim();/*from ww w . j ava 2 s. co m*/ // find and stop any running instances stopApp(appId); // remove app from mapping apps.remove(appId); // get app directory from config and remove files for app_id File configDir = getAppConfigDirectory(); File appDir = new File(configDir.getAbsolutePath() + File.separator + appId); try { Files.walkFileTree(appDir.toPath(), new FileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (dir.toFile().delete()) { return FileVisitResult.CONTINUE; } else { return FileVisitResult.TERMINATE; } } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toFile().delete()) { return FileVisitResult.CONTINUE; } else { return FileVisitResult.TERMINATE; } } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.TERMINATE; } }); } catch (IOException e) { e.printStackTrace(); } appDir.delete(); File appInfoFile = new File(configDir.getAbsolutePath() + File.separator + appId + CONFIG_FILE_EXT); appInfoFile.delete(); }
From source file:com.nridge.connector.fs.con_fs.core.FileCrawler.java
/** * Invoked for a file in a directory.//from w w w. ja v a 2 s . c o m * Unless overridden, this method returns {@link java.nio.file.FileVisitResult#CONTINUE * CONTINUE}. * * @param aPath Path instance. * @param aFileAttributes File attribute instance. */ @Override public FileVisitResult visitFile(Path aPath, BasicFileAttributes aFileAttributes) throws IOException { Logger appLogger = mAppMgr.getLogger(this, "visitFile"); String pathFileName = aPath.toAbsolutePath().toString(); if (mCrawlIgnore.isMatchedNormalized(pathFileName)) appLogger.debug(String.format("Ignoring File: %s", pathFileName)); else { File fsFile = aPath.toFile(); if ((fsFile.canRead()) && (mBag != null)) { String crawlType = mCrawlQueue.getCrawlType(); if (StringUtils.equals(crawlType, Connector.CRAWL_TYPE_INCREMENTAL)) { String docId = generateDocumentId(aPath); boolean docExistsInIndex = documentExistsInIndex(docId); if (docExistsInIndex) { Date incDate = mCrawlQueue.getCrawlLastModified(); FileTime lastModifiedTime = aFileAttributes.lastModifiedTime(); Date lmDate = new Date(lastModifiedTime.toMillis()); if (lmDate.after(incDate)) processFile(aPath, aFileAttributes); } else processFile(aPath, aFileAttributes); } else processFile(aPath, aFileAttributes); } else appLogger.warn(String.format("Access Failed: %s", pathFileName)); } if (mAppMgr.isAlive()) return FileVisitResult.CONTINUE; else return FileVisitResult.TERMINATE; }
From source file:net.sourceforge.pmd.docs.RuleDocGenerator.java
/** * Searches for the source file of the given ruleset. This provides the information * for the "editme" link./*from w ww . j a v a2 s . c om*/ * * @param ruleset the ruleset to search for. * @return * @throws IOException */ private String getRuleSetSourceFilepath(RuleSet ruleset) throws IOException { final String rulesetFilename = FilenameUtils.normalize(StringUtils.chomp(ruleset.getFileName())); final List<Path> foundPathResult = new LinkedList<>(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String path = file.toString(); if (path.contains("src") && path.endsWith(rulesetFilename)) { foundPathResult.add(file); return FileVisitResult.TERMINATE; } return super.visitFile(file, attrs); } }); if (!foundPathResult.isEmpty()) { Path foundPath = foundPathResult.get(0); foundPath = root.relativize(foundPath); // Note: the path is normalized to unix path separators, so that the editme link // uses forward slashes return FilenameUtils.normalize(foundPath.toString(), true); } return StringUtils.chomp(ruleset.getFileName()); }
From source file:net.sourceforge.pmd.docs.RuleDocGenerator.java
private String getRuleClassSourceFilepath(String ruleClass) throws IOException { final String relativeSourceFilename = ruleClass.replaceAll("\\.", Matcher.quoteReplacement(File.separator)) + ".java"; final List<Path> foundPathResult = new LinkedList<>(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override/* w w w.ja v a 2s.c o m*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String path = file.toString(); if (path.contains("src") && path.endsWith(relativeSourceFilename)) { foundPathResult.add(file); return FileVisitResult.TERMINATE; } return super.visitFile(file, attrs); } }); if (!foundPathResult.isEmpty()) { Path foundPath = foundPathResult.get(0); foundPath = root.relativize(foundPath); return FilenameUtils.normalize(foundPath.toString(), true); } return FilenameUtils.normalize(relativeSourceFilename, true); }
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
protected void deleteSubDomain(final File subdomain) { String message = "Are you sure you want to delete subdomain\n" + subdomain.getName() + "\nThis will remove <B>ALL</B> of its subdomains and policy files."; ConfirmDialog dialog = ConfirmDialog.getFactory().create("Confirm SubDomain Deletion", message, "Delete", "Cancel"); dialog.setContentMode(ContentMode.HTML); dialog.show(getUI(), new ConfirmDialog.Listener() { private static final long serialVersionUID = 1L; @Override/*from w ww . ja v a 2 s. co m*/ public void onClose(ConfirmDialog dialog) { if (dialog.isConfirmed()) { // // Iterate the subdomain // try { Files.walkFileTree(Paths.get(subdomain.getAbsolutePath()), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path deleteFile, BasicFileAttributes attrs) throws IOException { try { boolean removeFromTree = deleteFile.getFileName().toString().endsWith(".xml"); Files.delete(deleteFile); if (removeFromTree) { self.treeWorkspace.removeItem(deleteFile.toFile()); } if (logger.isDebugEnabled()) { logger.debug("Deleted file: " + deleteFile.toString()); } } catch (IOException e) { logger.error("Failed to delete file: " + deleteFile.toString(), e); return FileVisitResult.TERMINATE; } return super.visitFile(deleteFile, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { try { Files.delete(dir); self.treeWorkspace.removeItem(dir.toFile()); if (logger.isDebugEnabled()) { logger.debug("Deleted dir: " + dir.toString()); } } catch (IOException e) { logger.error("Failed to delete directory: " + dir.toString(), e); return FileVisitResult.TERMINATE; } return super.postVisitDirectory(dir, exc); } }); } catch (IOException e) { logger.error("Failed to walk subdomain: " + subdomain.getAbsolutePath(), e); } } } }, true); }
From source file:org.eclipse.winery.repository.importing.CSARImporter.java
/** * Import an extracted CSAR from a directory * /*from www. j a va 2s . co m*/ * @param path the root path of an extracted CSAR file * @param overwrite if true: contents of the repo are overwritten * @param asyncWPDParsing true if WPD should be parsed asynchronously to speed up the import. * Required, because JUnit terminates the used ExecutorService * @throws InvalidCSARException * @throws IOException */ void importFromDir(final Path path, final List<String> errors, final boolean overwrite, final boolean asyncWPDParsing) throws IOException { Path toscaMetaPath = path.resolve("xml/TOSCA-Metadata/TOSCA.meta"); if (!Files.exists(toscaMetaPath)) { toscaMetaPath = path.resolve("TOSCA-Metadata/TOSCA.meta"); } if (!Files.exists(toscaMetaPath)) { errors.add("TOSCA.meta does not exist"); return; } final TOSCAMetaFileParser tmfp = new TOSCAMetaFileParser(); final TOSCAMetaFile tmf = tmfp.parse(toscaMetaPath); // we do NOT do any sanity checks, of TOSAC.meta // and just start parsing if (tmf.getEntryDefinitions() != null) { // we obey the entry definitions and "just" import that // imported definitions are added recursively Path defsPath = path.resolve(tmf.getEntryDefinitions()); this.importDefinitions(tmf, defsPath, errors, overwrite, asyncWPDParsing); this.importSelfServiceMetaData(tmf, path, defsPath, errors); } else { // no explicit entry definitions found // we import all available definitions // The specification says (cos01, Section 16.1, line 2935) that all definitions are contained // in the "Definitions" directory // The alternative is to go through all entries in the TOSCA Meta File, but there is no // guarantee that this list is complete Path definitionsDir = path.resolve("Definitions"); if (!Files.exists(definitionsDir)) { errors.add("No entry definitions defined and Definitions directory does not exist."); return; } final List<IOException> exceptions = new ArrayList<IOException>(); Files.walkFileTree(definitionsDir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { if (dir.endsWith("Definitions")) { return FileVisitResult.CONTINUE; } else { return FileVisitResult.SKIP_SUBTREE; } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { try { CSARImporter.this.importDefinitions(tmf, file, errors, overwrite, asyncWPDParsing); } catch (IOException e) { exceptions.add(e); return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } }); if (!exceptions.isEmpty()) { // something went wrong during parsing // we rethrow the exception throw exceptions.get(0); } } this.importNamespacePrefixes(path); }
From source file:org.fao.geonet.kernel.harvest.harvester.localfilesystem.LocalFsHarvesterFileVisitor.java
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (cancelMonitor.get()) { return FileVisitResult.TERMINATE; }//from w w w . j a v a2 s . c o m try { if (file != null && file.getFileName() != null && file.getFileName().toString() != null && (file.getFileName().toString().endsWith(".xml") || MEFLib.isValidArchiveExtensionForMEF(file.getFileName().toString()))) { result.totalMetadata++; if (LOGGER.isDebugEnabled() && result.totalMetadata % 1000 == 0) { long elapsedTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); LOGGER.debug(result.totalMetadata + "records inserted in " + elapsedTime + " s (" + result.totalMetadata / elapsedTime + " records/s)."); } Path filePath = file.toAbsolutePath().normalize(); if (MEFLib.isValidArchiveExtensionForMEF(file.getFileName().toString())) { processMef(file, filePath); return FileVisitResult.CONTINUE; } Element xml; try { LOGGER.debug("reading file: " + filePath); xml = Xml.loadFile(file); } catch (JDOMException e) { // JDOM problem LOGGER.debug("Error loading XML from file " + filePath + ", ignoring"); if (LOGGER.isDebugEnabled()) { LOGGER.error(e); } result.badFormat++; return FileVisitResult.CONTINUE; // skip this one } catch (Throwable e) { // some other error LOGGER.debug("Error retrieving XML from file " + filePath + ", ignoring"); if (LOGGER.isDebugEnabled()) { LOGGER.error(e); } result.unretrievable++; return FileVisitResult.CONTINUE; // skip this one } // transform using importxslt if not none if (transformIt) { try { xml = Xml.transform(xml, thisXslt); } catch (Exception e) { LOGGER.debug("Cannot transform XML from file " + filePath + ", ignoring. Error was: " + e.getMessage()); result.badFormat++; return FileVisitResult.CONTINUE; // skip this one } } String schema = null; try { schema = dataMan.autodetectSchema(xml, null); } catch (Exception e) { result.unknownSchema++; } if (schema == null) { return FileVisitResult.CONTINUE; } try { params.getValidate().validate(dataMan, context, xml); } catch (Exception e) { LOGGER.debug("Cannot validate XML from file " + filePath + ", ignoring. Error was: " + e.getMessage()); result.doesNotValidate++; return FileVisitResult.CONTINUE; // skip this one } String uuid = getUuidFromFile(xml, filePath, schema); if (uuid == null || uuid.equals("")) { result.badFormat++; return FileVisitResult.CONTINUE; } String id = dataMan.getMetadataId(uuid); String changeDate = new ISODate(System.currentTimeMillis(), false).getDateAndTime(); if (id == null) { // For new record change date will be the time of metadata xml date change or the date when // the record was harvested (if can't be obtained the metadata xml date change) String createDate; // or the last modified date of the file if (params.checkFileLastModifiedForUpdate) { createDate = new ISODate(Files.getLastModifiedTime(file).toMillis(), false) .getDateAndTime(); } else { try { createDate = dataMan.extractDateModified(schema, xml); } catch (Exception ex) { LOGGER.error( "LocalFilesystemHarvester - addMetadata - can't get metadata modified date for metadata uuid= " + uuid + " using current date for modified date"); createDate = new ISODate().toString(); } } LOGGER.debug("adding new metadata"); id = addMetadata(xml, schema, uuid, createDate); } else { // Check last modified date of the file with the record change date // to check if an update is required if (params.checkFileLastModifiedForUpdate) { Date fileDate = new Date(Files.getLastModifiedTime(file).toMillis()); final AbstractMetadata metadata = repo.findOne(id); ISODate modified = new ISODate(); if (metadata != null && metadata.getDataInfo() != null) { modified = metadata.getDataInfo().getChangeDate(); } Date recordDate = modified.toDate(); changeDate = new ISODate(fileDate.getTime(), false).getDateAndTime(); LOGGER.debug(" File date is: " + filePath + "filePath / record date is: " + modified); if (DateUtils.truncate(recordDate, Calendar.SECOND) .before(DateUtils.truncate(fileDate, Calendar.SECOND))) { LOGGER.debug(" Db record is older than file. Updating record with id: " + id); updateMedata(xml, id, changeDate); } else { LOGGER.debug( " Db record is not older than last modified date of file. No need for update."); result.unchangedMetadata++; } } else { id = dataMan.getMetadataId(uuid); if (id == null) { // For new record change date will be the time of metadata xml date change or the date when // the record was harvested (if can't be obtained the metadata xml date change) String createDate; // or the last modified date of the file if (params.checkFileLastModifiedForUpdate) { createDate = new ISODate(Files.getLastModifiedTime(file).toMillis(), false) .getDateAndTime(); } else { try { createDate = dataMan.extractDateModified(schema, xml); } catch (Exception ex) { LOGGER.error( "LocalFilesystemHarvester - addMetadata - can't get metadata modified date for metadata uuid= " + uuid + ", using current date for modified date"); createDate = new ISODate().toString(); } } LOGGER.debug("adding new metadata"); id = harvester.addMetadata(xml, uuid, schema, localGroups, localCateg, createDate, aligner, false); listOfRecordsToIndex.add(Integer.valueOf(id)); result.addedMetadata++; } else { // Check last modified date of the file with the record change date // to check if an update is required if (params.checkFileLastModifiedForUpdate) { Date fileDate = new Date(Files.getLastModifiedTime(file).toMillis()); final AbstractMetadata metadata = repo.findOne(id); final ISODate modified; if (metadata != null && metadata.getDataInfo() != null) { modified = metadata.getDataInfo().getChangeDate(); } else { modified = new ISODate(); } Date recordDate = modified.toDate(); changeDate = new ISODate(fileDate.getTime(), false).getDateAndTime(); LOGGER.debug( " File date is: " + fileDate.toString() + " / record date is: " + modified); if (DateUtils.truncate(recordDate, Calendar.SECOND) .before(DateUtils.truncate(fileDate, Calendar.SECOND))) { LOGGER.debug(" Db record is older than file. Updating record with id: " + id); harvester.updateMetadata(xml, id, localGroups, localCateg, changeDate, aligner); listOfRecordsToIndex.add(Integer.valueOf(id)); result.updatedMetadata++; } else { LOGGER.debug( " Db record is not older than last modified date of file. No need for update."); result.unchangedMetadata++; } } else { LOGGER.debug(" updating existing metadata, id is: " + id); try { changeDate = dataMan.extractDateModified(schema, xml); } catch (Exception ex) { LOGGER.error( "LocalFilesystemHarvester - updateMetadata - can't get metadata modified date for " + "metadata id= " + id + ", using current date for modified date"); changeDate = new ISODate().toString(); } harvester.updateMetadata(xml, id, localGroups, localCateg, changeDate, aligner); listOfRecordsToIndex.add(Integer.valueOf(id)); result.updatedMetadata++; } } updateMedata(xml, id, changeDate); } } listOfRecords.add(Integer.valueOf(id)); } } catch (Throwable e) { LOGGER.error("An error occurred while harvesting a local file:{}. Error is: " + e.getMessage()); } return FileVisitResult.CONTINUE; }
From source file:se.trixon.mapollage.FileVisitor.java
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { if (mExcludePatterns != null) { for (String excludePattern : mExcludePatterns) { if (IOCase.SYSTEM.isCaseSensitive()) { if (StringUtils.contains(dir.toString(), excludePattern)) { return FileVisitResult.SKIP_SUBTREE; }/*from ww w . ja v a 2 s. c om*/ } else { if (StringUtils.containsIgnoreCase(dir.toString(), excludePattern)) { return FileVisitResult.SKIP_SUBTREE; } } } } String[] filePaths = dir.toFile().list(); mOperationListener.onOperationLog(dir.toString()); mOperationListener.onOperationProgress(dir.toString()); if (filePaths != null && filePaths.length > 0) { if (mUseExternalDescription) { Properties p = new Properties(mDefaultDescProperties); try { File file = new File(dir.toFile(), mExternalFileValue); if (file.isFile()) { p.load(new InputStreamReader(new FileInputStream(file), Charset.defaultCharset())); } } catch (IOException ex) { // nvm } mDirToDesc.put(dir.toFile().getAbsolutePath(), p); } for (String fileName : filePaths) { try { TimeUnit.NANOSECONDS.sleep(1); } catch (InterruptedException ex) { mInterrupted = true; return FileVisitResult.TERMINATE; } File file = new File(dir.toFile(), fileName); if (file.isFile() && mPathMatcher.matches(file.toPath().getFileName())) { boolean exclude = false; if (mExcludePatterns != null) { for (String excludePattern : mExcludePatterns) { if (StringUtils.contains(file.getAbsolutePath(), excludePattern)) { exclude = true; break; } } } if (!exclude) { mFiles.add(file); } } } } return FileVisitResult.CONTINUE; }