Search in sources :

Example 11 with DirectoryScanner

use of org.codehaus.plexus.util.DirectoryScanner in project alfresco-maven by Acosix.

the class DuplicateI18nResourcesMojo method getPropertyFileNamesToProcess.

protected List<String> getPropertyFileNamesToProcess() {
    final List<String> propertyFileNames = new ArrayList<>();
    final DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(this.sourceDirectory);
    if (this.includes != null) {
        scanner.setIncludes(this.includes.toArray(new String[0]));
    } else {
        scanner.setIncludes(DEFAULT_INCLUDES.toArray(new String[0]));
    }
    if (this.excludes != null) {
        scanner.setExcludes(this.excludes.toArray(new String[0]));
    }
    scanner.addDefaultExcludes();
    scanner.scan();
    for (final String includedFile : scanner.getIncludedFiles()) {
        propertyFileNames.add(includedFile);
    }
    return propertyFileNames;
}
Also used : DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) ArrayList(java.util.ArrayList)

Example 12 with DirectoryScanner

use of org.codehaus.plexus.util.DirectoryScanner in project providence by morimekta.

the class BaseGenerateSourcesMojo method addDependencyInclude.

private void addDependencyInclude(File workingDir, Set<File> includes, Artifact artifact) throws MojoExecutionException {
    // TODO: Figure out if this is the right way to name the output directories.
    File outputDir = new File(workingDir, artifact.getGroupId().replaceAll("[.]", Strings.escape(File.separator)) + File.separator + artifact.getArtifactId());
    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new MojoExecutionException("Unable to create output dir " + outputDir);
        }
    }
    if (artifact.getFile().isDirectory()) {
        // Otherwise the dependency is a local module, and not packaged.
        // In this case the we need to try to find thrift files in the
        // file tree under that directly.
        DirectoryScanner includeScanner = new DirectoryScanner();
        includeScanner.setBasedir(artifact.getFile());
        // Include basically everything.
        includeScanner.setIncludes(new String[] { "**/*.*" });
        // Skip basic java files. These cannot be used as includes anyway, and
        // is the most common content of the default artifacts.
        includeScanner.setExcludes(new String[] { "**/*.class", "**/*.java", "**/*.properties" });
        includeScanner.scan();
        try {
            for (String filePath : includeScanner.getIncludedFiles()) {
                if (ReflectionUtils.isThriftFile(filePath)) {
                    Path file = Paths.get(project.getBasedir().getAbsolutePath(), filePath);
                    File of = new File(outputDir, new File(filePath).getName());
                    try (FileOutputStream fos = new FileOutputStream(of, false);
                        BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                        Files.copy(file, bos);
                    }
                }
            }
            includes.add(outputDir);
        } catch (IOException e) {
            throw new MojoExecutionException("" + e.getMessage(), e);
        }
    } else {
        try (FileInputStream fis = new FileInputStream(artifact.getFile());
            BufferedInputStream bis = new BufferedInputStream(fis);
            ZipInputStream zis = new ZipInputStream(bis)) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.isDirectory() || !ReflectionUtils.isThriftFile(entry.getName())) {
                    zis.closeEntry();
                    continue;
                }
                File of = new File(outputDir, new File(entry.getName()).getName());
                try (FileOutputStream fos = new FileOutputStream(of, false);
                    BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                    IOUtils.copy(zis, bos);
                }
                zis.closeEntry();
            }
            includes.add(outputDir);
        } catch (IOException e) {
            throw new MojoExecutionException("" + e.getMessage(), e);
        }
    }
}
Also used : Path(java.nio.file.Path) ZipInputStream(java.util.zip.ZipInputStream) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) BufferedInputStream(java.io.BufferedInputStream) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) FileInputStream(java.io.FileInputStream)

Example 13 with DirectoryScanner

use of org.codehaus.plexus.util.DirectoryScanner in project providence by morimekta.

the class BaseGenerateSourcesMojo method executeInternal.

boolean executeInternal(IncludeExcludeFileSelector includeDirs, File outputDir, IncludeExcludeFileSelector inputSelector, String defaultInputIncludes, boolean testCompile) throws MojoExecutionException, MojoFailureException {
    Set<File> inputFiles = ProvidenceInput.getInputFiles(project, inputSelector, defaultInputIncludes, print_debug, getLog());
    if (inputFiles.isEmpty()) {
        return false;
    }
    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new MojoExecutionException("Unable to create target directory " + outputDir);
        }
    }
    TreeSet<File> includes = new TreeSet<>();
    File workingDir = new File(buildDir, testCompile ? "providence-test" : "providence");
    File[] deleteFiles = workingDir.listFiles();
    if (!workingDir.exists()) {
        if (!workingDir.mkdirs()) {
            throw new MojoExecutionException("Unable to create working directory " + workingDir);
        }
    } else if (deleteFiles != null) {
        StreamSupport.<File>stream(Spliterators.spliterator(deleteFiles, Spliterator.DISTINCT | Spliterator.IMMUTABLE), false).forEach(File::delete);
    }
    Set<Artifact> resolvedArtifacts = new HashSet<>();
    for (Dependency dep : dependencies) {
        if (testCompile || !TEST.equalsIgnoreCase(dep.getScope())) {
            resolveDependency(dep, includes, workingDir, resolvedArtifacts);
        }
    }
    if (includeDirs != null) {
        DirectoryScanner includeScanner = new DirectoryScanner();
        includeScanner.setIncludes(includeDirs.getIncludes());
        if (includeDirs.getExcludes() != null) {
            includeScanner.setExcludes(includeDirs.getExcludes());
        }
        includeScanner.setBasedir(project.getBasedir());
        includeScanner.scan();
        for (String dir : includeScanner.getIncludedDirectories()) {
            includes.add(new File(project.getBasedir(), dir));
        }
        for (String dir : includeScanner.getExcludedDirectories()) {
            includes.remove(new File(project.getBasedir(), dir));
        }
    }
    FileManager fileManager = new FileManager(outputDir);
    ProgramParser parser = new ThriftProgramParser(require_field_id, require_enum_value, allow_language_reserved_names);
    TypeLoader loader = new TypeLoader(includes, parser);
    if (print_debug) {
        inputFiles.stream().filter(Objects::nonNull).map(file -> {
            try {
                return file.getAbsoluteFile().getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }).sorted().forEach(f -> getLog().info("Compiling: " + f));
    }
    JavaOptions javaOptions = new JavaOptions();
    javaOptions.android = android;
    javaOptions.jackson = jackson;
    javaOptions.rw_binary = rw_binary;
    javaOptions.hazelcast_portable = hazelcast_portable;
    javaOptions.generated_annotation_version = generated_annotation_version;
    javaOptions.public_constructors = public_constructors;
    GeneratorOptions generatorOptions = new GeneratorOptions();
    generatorOptions.generator_program_name = "providence-maven-plugin";
    generatorOptions.program_version = getVersionString();
    GeneratorFactory factory = new JavaGeneratorFactory();
    Generator generator = new JavaGenerator(fileManager, generatorOptions, javaOptions);
    Path base = project.getBasedir().toPath().toAbsolutePath();
    if (project.getParent() != null && project.getParent().getBasedir() != null) {
        // Only replace with parent if parent is a parent directory of this.
        Path parentBase = project.getParent().getBasedir().toPath().toAbsolutePath();
        if (base.toString().startsWith(parentBase.toString())) {
            base = parentBase;
        }
    }
    for (File in : inputFiles) {
        ProgramTypeRegistry registry;
        try {
            registry = loader.load(in);
        } catch (SerializerException e) {
            // ParseException is a SerializerException. And serialize exceptions can come from
            // failing to make sense of constant definitions.
            getLog().error("    ============ >> PROVIDENCE << ============");
            getLog().error("");
            Arrays.stream(e.asString().split("\r?\n")).forEach(l -> getLog().error(l));
            getLog().error("");
            getLog().error("    ============ << PROVIDENCE >> ============");
            throw new MojoFailureException("Failed to parse thrift file: " + in.getName(), e);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read thrift file: " + in.getName(), e);
        }
        try {
            if (skipIfMissingNamespace && registry.getProgram().getNamespaceForLanguage(factory.generatorName()) == null) {
                getLog().warn("Skipping (no " + factory.generatorName() + " namespace) " + base.relativize(in.toPath()));
                continue;
            }
            generator.generate(registry);
        } catch (GeneratorException e) {
            throw new MojoFailureException("Failed to generate program: " + registry.getProgram().getProgramName(), e);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to write program file: " + registry.getProgram().getProgramName(), e);
        }
    }
    try {
        generator.generateGlobal(loader.getProgramRegistry(), inputFiles);
    } catch (GeneratorException e) {
        throw new MojoFailureException("Failed to generate global", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write global file", e);
    }
    return compileOutput;
}
Also used : Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) ArtifactResolutionRequest(org.apache.maven.artifact.resolver.ArtifactResolutionRequest) Spliterators(java.util.Spliterators) Parameter(org.apache.maven.plugins.annotations.Parameter) IncludeExcludeFileSelector(org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector) MavenProject(org.apache.maven.project.MavenProject) Strings(net.morimekta.util.Strings) Artifact(org.apache.maven.artifact.Artifact) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) GeneratorException(net.morimekta.providence.generator.GeneratorException) Set(java.util.Set) JavaGeneratorFactory(net.morimekta.providence.generator.format.java.JavaGeneratorFactory) ArtifactResolver(org.apache.maven.artifact.resolver.ArtifactResolver) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) FileManager(net.morimekta.providence.generator.util.FileManager) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) Spliterator(java.util.Spliterator) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) AbstractMojo(org.apache.maven.plugin.AbstractMojo) ZipInputStream(java.util.zip.ZipInputStream) Generator(net.morimekta.providence.generator.Generator) Dependency(org.apache.maven.model.Dependency) Component(org.apache.maven.plugins.annotations.Component) ProvidenceInput(net.morimekta.providence.maven.util.ProvidenceInput) ProgramParser(net.morimekta.providence.reflect.parser.ProgramParser) ArtifactResolutionResult(org.apache.maven.artifact.resolver.ArtifactResolutionResult) TreeSet(java.util.TreeSet) BufferedOutputStream(java.io.BufferedOutputStream) HashSet(java.util.HashSet) ArtifactRepository(org.apache.maven.artifact.repository.ArtifactRepository) ProvidenceDependency(net.morimekta.providence.maven.util.ProvidenceDependency) StreamSupport(java.util.stream.StreamSupport) IOUtils(net.morimekta.util.io.IOUtils) Properties(java.util.Properties) JavaOptions(net.morimekta.providence.generator.format.java.JavaOptions) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) File(java.io.File) ReflectionUtils(net.morimekta.providence.reflect.util.ReflectionUtils) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Paths(java.nio.file.Paths) RepositorySystem(org.apache.maven.repository.RepositorySystem) JavaGenerator(net.morimekta.providence.generator.format.java.JavaGenerator) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) SerializerException(net.morimekta.providence.serializer.SerializerException) TypeLoader(net.morimekta.providence.reflect.TypeLoader) InputStream(java.io.InputStream) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) ProgramParser(net.morimekta.providence.reflect.parser.ProgramParser) TypeLoader(net.morimekta.providence.reflect.TypeLoader) JavaGenerator(net.morimekta.providence.generator.format.java.JavaGenerator) JavaGeneratorFactory(net.morimekta.providence.generator.format.java.JavaGeneratorFactory) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) TreeSet(java.util.TreeSet) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) GeneratorException(net.morimekta.providence.generator.GeneratorException) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) HashSet(java.util.HashSet) Path(java.nio.file.Path) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Dependency(org.apache.maven.model.Dependency) ProvidenceDependency(net.morimekta.providence.maven.util.ProvidenceDependency) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) SerializerException(net.morimekta.providence.serializer.SerializerException) Artifact(org.apache.maven.artifact.Artifact) FileManager(net.morimekta.providence.generator.util.FileManager) JavaGeneratorFactory(net.morimekta.providence.generator.format.java.JavaGeneratorFactory) GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) JavaOptions(net.morimekta.providence.generator.format.java.JavaOptions) File(java.io.File) Generator(net.morimekta.providence.generator.Generator) JavaGenerator(net.morimekta.providence.generator.format.java.JavaGenerator)

Example 14 with DirectoryScanner

use of org.codehaus.plexus.util.DirectoryScanner in project tycho by eclipse.

the class IncludeValidationHelper method checkIncludesExist.

private void checkIncludesExist(String buildPropertiesKey, List<String> includePatterns, MavenProject project, boolean strict, String... ignoredIncludes) throws MojoExecutionException {
    File baseDir = project.getBasedir();
    List<String> nonMatchingIncludes = new ArrayList<>();
    List<String> ignoreList = Arrays.asList(ignoredIncludes);
    if (includePatterns == null || includePatterns.isEmpty()) {
        String message = new File(baseDir, "build.properties").getAbsolutePath() + ": " + buildPropertiesKey + " value(s) must be specified.";
        if (strict) {
            throw new MojoExecutionException(message);
        } else {
            log.warn(message);
        }
    }
    for (String includePattern : includePatterns) {
        if (ignoreList.contains(includePattern)) {
            continue;
        }
        if (new File(baseDir, includePattern).exists()) {
            continue;
        }
        // it does not exist as a file nor dir. Try if it matches any files as ant pattern
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setIncludes(new String[] { includePattern });
        scanner.setBasedir(baseDir);
        scanner.scan();
        if (scanner.getIncludedFiles().length == 0) {
            nonMatchingIncludes.add(includePattern);
        }
    }
    if (nonMatchingIncludes.size() > 0) {
        String message = new File(baseDir, "build.properties").getAbsolutePath() + ": " + buildPropertiesKey + " value(s) " + nonMatchingIncludes + " do not match any files.";
        if (strict) {
            throw new MojoExecutionException(message);
        } else {
            log.warn(message);
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) ArrayList(java.util.ArrayList) File(java.io.File)

Example 15 with DirectoryScanner

use of org.codehaus.plexus.util.DirectoryScanner in project tycho by eclipse.

the class ProductExportMojo method copyDirectory.

private void copyDirectory(File source, File target, String excludes) throws IOException {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(source);
    ds.setExcludes(new String[] { excludes });
    ds.scan();
    for (String relPath : ds.getIncludedFiles()) {
        File targetFile = new File(target, relPath);
        targetFile.getParentFile().mkdirs();
        FileUtils.copyFile(new File(source, relPath), targetFile);
    }
}
Also used : DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Aggregations

DirectoryScanner (org.codehaus.plexus.util.DirectoryScanner)46 File (java.io.File)31 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)12 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)7 FileInputStream (java.io.FileInputStream)4 FileOutputStream (java.io.FileOutputStream)4 InputStream (java.io.InputStream)4 Path (java.nio.file.Path)4 LinkedHashSet (java.util.LinkedHashSet)4 HashSet (java.util.HashSet)3 BufferedInputStream (java.io.BufferedInputStream)2 BufferedOutputStream (java.io.BufferedOutputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 OutputStream (java.io.OutputStream)2 UncheckedIOException (java.io.UncheckedIOException)2 Arrays (java.util.Arrays)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Properties (java.util.Properties)2