use of java.nio.file.FileVisitor in project buck by facebook.
the class WorkspaceGenerator method writeWorkspace.
public Path writeWorkspace() throws IOException {
DocumentBuilder docBuilder;
Transformer transformer;
try {
docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
transformer = TransformerFactory.newInstance().newTransformer();
} catch (ParserConfigurationException | TransformerConfigurationException e) {
throw new RuntimeException(e);
}
DOMImplementation domImplementation = docBuilder.getDOMImplementation();
final Document doc = domImplementation.createDocument(/* namespaceURI */
null, "Workspace", /* docType */
null);
doc.setXmlVersion("1.0");
Element rootElem = doc.getDocumentElement();
rootElem.setAttribute("version", "1.0");
final Stack<Element> groups = new Stack<>();
groups.push(rootElem);
FileVisitor<Map.Entry<String, WorkspaceNode>> visitor = new FileVisitor<Map.Entry<String, WorkspaceNode>>() {
@Override
public FileVisitResult preVisitDirectory(Map.Entry<String, WorkspaceNode> dir, BasicFileAttributes attrs) throws IOException {
Preconditions.checkArgument(dir.getValue() instanceof WorkspaceGroup);
Element element = doc.createElement("Group");
element.setAttribute("location", "container:");
element.setAttribute("name", dir.getKey());
groups.peek().appendChild(element);
groups.push(element);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Map.Entry<String, WorkspaceNode> file, BasicFileAttributes attrs) throws IOException {
Preconditions.checkArgument(file.getValue() instanceof WorkspaceFileRef);
WorkspaceFileRef fileRef = (WorkspaceFileRef) file.getValue();
Element element = doc.createElement("FileRef");
element.setAttribute("location", "container:" + MorePaths.relativize(MorePaths.normalize(outputDirectory), fileRef.getPath()).toString());
groups.peek().appendChild(element);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Map.Entry<String, WorkspaceNode> file, IOException exc) throws IOException {
return FileVisitResult.TERMINATE;
}
@Override
public FileVisitResult postVisitDirectory(Map.Entry<String, WorkspaceNode> dir, IOException exc) throws IOException {
groups.pop();
return FileVisitResult.CONTINUE;
}
};
walkNodeTree(visitor);
Path projectWorkspaceDir = getWorkspaceDir();
projectFilesystem.mkdirs(projectWorkspaceDir);
Path serializedWorkspace = projectWorkspaceDir.resolve("contents.xcworkspacedata");
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(outputStream);
transformer.transform(source, result);
String contentsToWrite = outputStream.toString();
if (MoreProjectFilesystems.fileContentsDiffer(new ByteArrayInputStream(contentsToWrite.getBytes(Charsets.UTF_8)), serializedWorkspace, projectFilesystem)) {
projectFilesystem.writeContentsToPath(contentsToWrite, serializedWorkspace);
}
} catch (TransformerException e) {
throw new RuntimeException(e);
}
Path xcshareddata = projectWorkspaceDir.resolve("xcshareddata");
projectFilesystem.mkdirs(xcshareddata);
Path workspaceSettingsPath = xcshareddata.resolve("WorkspaceSettings.xcsettings");
String workspaceSettings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"" + " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" + "<plist version=\"1.0\">\n" + "<dict>\n" + "\t<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>\n" + "\t<false/>\n" + "</dict>\n" + "</plist>";
projectFilesystem.writeContentsToPath(workspaceSettings, workspaceSettingsPath);
return projectWorkspaceDir;
}
use of java.nio.file.FileVisitor in project elasticsearch by elastic.
the class ExceptionSerializationTests method testExceptionRegistration.
public void testExceptionRegistration() throws ClassNotFoundException, IOException, URISyntaxException {
final Set<Class<?>> notRegistered = new HashSet<>();
final Set<Class<?>> hasDedicatedWrite = new HashSet<>();
final Set<Class<?>> registered = new HashSet<>();
final String path = "/org/elasticsearch";
final Path startPath = PathUtils.get(ElasticsearchException.class.getProtectionDomain().getCodeSource().getLocation().toURI()).resolve("org").resolve("elasticsearch");
final Set<? extends Class<?>> ignore = Sets.newHashSet(CancellableThreadsTests.CustomException.class, org.elasticsearch.rest.BytesRestResponseTests.WithHeadersException.class, AbstractClientHeadersTestCase.InternalException.class);
FileVisitor<Path> visitor = new FileVisitor<Path>() {
private Path pkgPrefix = PathUtils.get(path).getParent();
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path next = pkgPrefix.resolve(dir.getFileName());
if (ignore.contains(next)) {
return FileVisitResult.SKIP_SUBTREE;
}
pkgPrefix = next;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
checkFile(file.getFileName().toString());
return FileVisitResult.CONTINUE;
}
private void checkFile(String filename) {
if (filename.endsWith(".class") == false) {
return;
}
try {
checkClass(loadClass(filename));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private void checkClass(Class<?> clazz) {
if (ignore.contains(clazz) || isAbstract(clazz.getModifiers()) || isInterface(clazz.getModifiers())) {
return;
}
if (isEsException(clazz) == false) {
return;
}
if (ElasticsearchException.isRegistered(clazz.asSubclass(Throwable.class), Version.CURRENT) == false && ElasticsearchException.class.equals(clazz.getEnclosingClass()) == false) {
notRegistered.add(clazz);
} else if (ElasticsearchException.isRegistered(clazz.asSubclass(Throwable.class), Version.CURRENT)) {
registered.add(clazz);
try {
if (clazz.getMethod("writeTo", StreamOutput.class) != null) {
hasDedicatedWrite.add(clazz);
}
} catch (Exception e) {
// fair enough
}
}
}
private boolean isEsException(Class<?> clazz) {
return ElasticsearchException.class.isAssignableFrom(clazz);
}
private Class<?> loadClass(String filename) throws ClassNotFoundException {
StringBuilder pkg = new StringBuilder();
for (Path p : pkgPrefix) {
pkg.append(p.getFileName().toString()).append(".");
}
pkg.append(filename.substring(0, filename.length() - 6));
return getClass().getClassLoader().loadClass(pkg.toString());
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
pkgPrefix = pkgPrefix.getParent();
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(startPath, visitor);
final Path testStartPath = PathUtils.get(ExceptionSerializationTests.class.getResource(path).toURI());
Files.walkFileTree(testStartPath, visitor);
assertTrue(notRegistered.remove(TestException.class));
assertTrue(notRegistered.remove(UnknownHeaderException.class));
assertTrue("Classes subclassing ElasticsearchException must be registered \n" + notRegistered.toString(), notRegistered.isEmpty());
// check
assertTrue(registered.removeAll(ElasticsearchException.getRegisteredKeys()));
assertEquals(registered.toString(), 0, registered.size());
}
use of java.nio.file.FileVisitor in project buck by facebook.
the class ProjectFilesystem method walkRelativeFileTree.
/**
* Walks a project-root relative file tree with a visitor and visit options.
*/
public void walkRelativeFileTree(Path pathRelativeToProjectRoot, EnumSet<FileVisitOption> visitOptions, final FileVisitor<Path> fileVisitor) throws IOException {
FileVisitor<Path> relativizingVisitor = new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return fileVisitor.preVisitDirectory(relativize(dir), attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
return fileVisitor.visitFile(relativize(file), attrs);
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return fileVisitor.visitFileFailed(relativize(file), exc);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return fileVisitor.postVisitDirectory(relativize(dir), exc);
}
};
Path rootPath = getPathForRelativePath(pathRelativeToProjectRoot);
walkFileTree(rootPath, visitOptions, relativizingVisitor);
}
use of java.nio.file.FileVisitor in project midpoint by Evolveum.
the class SchemaDistMojo method execute.
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("SchemaDist plugin started");
try {
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();
if (catalogPath != null) {
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);
}
} else {
getLog().debug("Catalog search disabled for " + artifact);
}
}
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");
}
Aggregations