Search in sources :

Example 1 with FileVisitor

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;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Element(org.w3c.dom.Element) DOMImplementation(org.w3c.dom.DOMImplementation) Document(org.w3c.dom.Document) FileVisitor(java.nio.file.FileVisitor) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) TransformerException(javax.xml.transform.TransformerException) Path(java.nio.file.Path) StreamResult(javax.xml.transform.stream.StreamResult) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stack(java.util.Stack) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) SortedMap(java.util.SortedMap)

Example 2 with FileVisitor

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());
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IllegalShardRoutingStateException(org.elasticsearch.cluster.routing.IllegalShardRoutingStateException) ActionTransportException(org.elasticsearch.transport.ActionTransportException) SearchContextMissingException(org.elasticsearch.search.SearchContextMissingException) SnapshotException(org.elasticsearch.snapshots.SnapshotException) AccessDeniedException(java.nio.file.AccessDeniedException) SearchException(org.elasticsearch.search.SearchException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) RecoverFilesRecoveryException(org.elasticsearch.indices.recovery.RecoverFilesRecoveryException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) NotDirectoryException(java.nio.file.NotDirectoryException) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) IOException(java.io.IOException) IndexTemplateMissingException(org.elasticsearch.indices.IndexTemplateMissingException) NoSuchFileException(java.nio.file.NoSuchFileException) FailedNodeException(org.elasticsearch.action.FailedNodeException) SearchParseException(org.elasticsearch.search.SearchParseException) URISyntaxException(java.net.URISyntaxException) AliasesNotFoundException(org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException) RecoveryEngineException(org.elasticsearch.index.engine.RecoveryEngineException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) TimestampParsingException(org.elasticsearch.action.TimestampParsingException) RoutingMissingException(org.elasticsearch.action.RoutingMissingException) RepositoryException(org.elasticsearch.repositories.RepositoryException) AlreadyExpiredException(org.elasticsearch.index.AlreadyExpiredException) InvalidIndexTemplateException(org.elasticsearch.indices.InvalidIndexTemplateException) QueryShardException(org.elasticsearch.index.query.QueryShardException) FileSystemException(java.nio.file.FileSystemException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) ActionNotFoundTransportException(org.elasticsearch.transport.ActionNotFoundTransportException) ParsingException(org.elasticsearch.common.ParsingException) FileSystemLoopException(java.nio.file.FileSystemLoopException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) AtomicMoveNotSupportedException(java.nio.file.AtomicMoveNotSupportedException) AbstractClientHeadersTestCase(org.elasticsearch.client.AbstractClientHeadersTestCase) FileVisitor(java.nio.file.FileVisitor) CancellableThreadsTests(org.elasticsearch.common.util.CancellableThreadsTests) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet)

Example 3 with FileVisitor

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);
}
Also used : Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) FileVisitor(java.nio.file.FileVisitor) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 4 with FileVisitor

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");
}
Also used : Path(java.nio.file.Path) MalformedURLException(java.net.MalformedURLException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) CatalogManager(org.apache.xml.resolver.CatalogManager) Artifact(org.apache.maven.artifact.Artifact) Catalog(org.apache.xml.resolver.Catalog) InvalidVersionSpecificationException(org.apache.maven.artifact.versioning.InvalidVersionSpecificationException) FileVisitor(java.nio.file.FileVisitor) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

FileVisitor (java.nio.file.FileVisitor)4 Path (java.nio.file.Path)4 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)4 IOException (java.io.IOException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 EOFException (java.io.EOFException)1 FileNotFoundException (java.io.FileNotFoundException)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1 AccessDeniedException (java.nio.file.AccessDeniedException)1 AtomicMoveNotSupportedException (java.nio.file.AtomicMoveNotSupportedException)1 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)1 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)1 FileSystemException (java.nio.file.FileSystemException)1 FileSystemLoopException (java.nio.file.FileSystemLoopException)1 NoSuchFileException (java.nio.file.NoSuchFileException)1 NotDirectoryException (java.nio.file.NotDirectoryException)1 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)1 HashSet (java.util.HashSet)1