Example usage for org.apache.maven.project MavenProject getResources

List of usage examples for org.apache.maven.project MavenProject getResources

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getResources.

Prototype

public List<Resource> getResources() 

Source Link

Usage

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.writers.rad.RadManifestWriter.java

License:Apache License

/**
 * Search the project for the existing META-INF directory where the manifest should be located.
 *
 * @return the apsolute path to the META-INF directory
 * @throws MojoExecutionException//from   w  ww . jav a 2s .c  o m
 */
protected String getMetaInfBaseDirectory(MavenProject project) throws MojoExecutionException {
    String metaInfBaseDirectory = null;

    if (config.getProject().getPackaging().equals(Constants.PROJECT_PACKAGING_WAR)) {
        // Generating web content settings based on war plug-in warSourceDirectory property
        File warSourceDirectory = new File(IdeUtils.getPluginSetting(config.getProject(),
                JeeUtils.ARTIFACT_MAVEN_WAR_PLUGIN, "warSourceDirectory", //$NON-NLS-1$
                DEFAULT_WEBAPP_RESOURCE_DIR));

        String webContentDir = IdeUtils.toRelativeAndFixSeparator(config.getEclipseProjectDirectory(),
                warSourceDirectory, false);

        metaInfBaseDirectory = config.getProject().getBasedir().getAbsolutePath() + File.separatorChar
                + webContentDir;

        log.debug("Attempting to use: " + metaInfBaseDirectory + " for location of META-INF in war project.");

        File metaInfDirectoryFile = new File(metaInfBaseDirectory + File.separatorChar + META_INF_DIRECTORY);

        if (metaInfDirectoryFile.exists() && !metaInfDirectoryFile.isDirectory()) {
            metaInfBaseDirectory = null;
        }
    }

    if (metaInfBaseDirectory == null) {
        for (Iterator iterator = project.getResources().iterator(); iterator.hasNext();) {
            metaInfBaseDirectory = ((Resource) iterator.next()).getDirectory();

            File metaInfDirectoryFile = new File(
                    metaInfBaseDirectory + File.separatorChar + META_INF_DIRECTORY);

            log.debug("Checking for existence of META-INF directory: " + metaInfDirectoryFile);

            if (metaInfDirectoryFile.exists() && !metaInfDirectoryFile.isDirectory()) {
                metaInfBaseDirectory = null;
            }
        }
    }

    return metaInfBaseDirectory;
}

From source file:com.google.code.play2.plugin.MavenPlay2Builder.java

License:Apache License

@Override /* Play2Builder */
public boolean build() throws Play2BuildFailure, Play2BuildError/*Play2BuildException*/
{
    Set<String> changedFilePaths = null;
    Map<String, Long> prevChangedFiles = new HashMap<String, Long>();
    synchronized (changedFilesLock) {
        if (!changedFiles.isEmpty()) {
            changedFilePaths = changedFiles.keySet();
            prevChangedFiles = changedFiles;
            changedFiles = new HashMap<String, Long>();
        }//from  ww w  .j  av a2s .  c om
        //TEST - more code inside synchronized block
    }

    if (!forceReloadNextTime && changedFilePaths == null /*&& afterFirstSuccessfulBuild*/ ) {
        return false;
    }

    List<MavenProject> projectsToBuild = projects;
    // - !afterFirstSuccessfulBuild => first build or no previous successful builds, build all modules
    // - currentSourceMaps.isEmpty() => first build, build all modules
    // - projects.size() == 1 => one-module project, just build it
    // - else => not the first build in multimodule-project, calculate modules subset to build
    if (afterFirstSuccessfulBuild
            /*!currentSourceMaps.isEmpty()*//*currentSourceMap != null*/ && projects.size() > 1) {
        projectsToBuild = calculateProjectsToBuild(changedFilePaths);
    }

    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(new Date());
    request.setExecutionListener(new ExecutionEventLogger());
    request.setGoals(goals);

    MavenExecutionResult result = new DefaultMavenExecutionResult();

    MavenSession newSession = new MavenSession(container, session.getRepositorySession(), request, result);
    newSession.setProjects(projectsToBuild);
    newSession.setCurrentProject(session.getCurrentProject());
    newSession.setParallel(session.isParallel());
    newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

    lifecycleExecutor.execute(newSession);

    forceReloadNextTime = result.hasExceptions();

    if (!result.hasExceptions() && !additionalGoals.isEmpty()) {
        request = DefaultMavenExecutionRequest.copy(session.getRequest());
        request.setStartTime(new Date());
        request.setExecutionListener(new ExecutionEventLogger());
        request.setGoals(additionalGoals);

        result = new DefaultMavenExecutionResult();

        newSession = new MavenSession(container, session.getRepositorySession(), request, result);
        List<MavenProject> onlyMe = Arrays.asList(new MavenProject[] { session.getCurrentProject() });
        newSession.setProjects(onlyMe);
        newSession.setCurrentProject(session.getCurrentProject());
        newSession.setParallel(session.isParallel());
        newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

        lifecycleExecutor.execute(newSession);

        forceReloadNextTime = result.hasExceptions();
    }

    if (result.hasExceptions()) {
        synchronized (changedFilesLock) {
            changedFiles.putAll(prevChangedFiles); // restore previously changed paths, required for next rebuild
        }
        Throwable firstException = result.getExceptions().get(0);
        if (firstException.getCause() instanceof MojoFailureException) {
            MojoFailureException mfe = (MojoFailureException) firstException.getCause();
            Throwable mfeCause = mfe.getCause();
            if (mfeCause != null) {
                try {
                    Play2BuildException pbe = null;
                    String causeName = mfeCause.getClass().getName();

                    // sbt-compiler exception
                    if (CompilerException.class.getName().equals(causeName)) {
                        pbe = getSBTCompilerBuildException(mfeCause);
                    } else if (AssetCompilationException.class.getName().equals(causeName)
                            || RoutesCompilationException.class.getName().equals(causeName)
                            || TemplateCompilationException.class.getName().equals(causeName)) {
                        pbe = getPlayBuildException(mfeCause);
                    }

                    if (pbe != null) {
                        throw new Play2BuildFailure(pbe, sourceEncoding);
                    }
                    throw new Play2BuildError("Build failed without reporting any problem!"/*?, ce*/ );
                } catch (Play2BuildFailure e) {
                    throw e;
                } catch (Play2BuildError e) {
                    throw e;
                } catch (Exception e) {
                    throw new Play2BuildError(".... , check Maven console");
                }
            }
        }
        throw new Play2BuildError("The compilation task failed, check Maven console"/*?, firstException*/ );
    }

    // no exceptions
    if (!afterFirstSuccessfulBuild) // this was first successful build
    {
        afterFirstSuccessfulBuild = true;

        if (playWatchService != null) {
            // Monitor all existing, not generated (inside output directory) source and resource roots
            List<File> monitoredDirectories = new ArrayList<File>();
            for (MavenProject p : projects) {
                String targetDirectory = p.getBuild().getDirectory();
                for (String sourceRoot : p.getCompileSourceRoots()) {
                    if (!sourceRoot.startsWith(targetDirectory) && new File(sourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(sourceRoot));
                    }
                }
                for (Resource resource : p.getResources()) {
                    String resourceRoot = resource.getDirectory();
                    if (!resourceRoot.startsWith(targetDirectory) && new File(resourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(resourceRoot));
                    }
                }
            }
            //TODO - remove roots nested inside another roots (is it possible?)

            try {
                watcher = playWatchService.watch(monitoredDirectories, this);
            } catch (FileWatchException e) {
                logger.warn("File watcher initialization failed. Running without hot-reload functionality.", e);
            }
        }
    }

    Map<MavenProject, Map<String, File>> sourceMaps = new HashMap<MavenProject, Map<String, File>>(
            currentSourceMaps);
    for (MavenProject p : projectsToBuild) {
        Map<String, File> sourceMap = new HashMap<String, File>();
        File classesDirectory = new File(p.getBuild().getOutputDirectory());
        String classesDirectoryPath = classesDirectory.getAbsolutePath() + File.separator;
        File analysisCacheFile = defaultAnalysisCacheFile(p);
        Analysis analysis = sbtAnalysisProcessor.readFromFile(analysisCacheFile);
        for (File sourceFile : analysis.getSourceFiles()) {
            Set<File> sourceFileProducts = analysis.getProducts(sourceFile);
            for (File product : sourceFileProducts) {
                String absolutePath = product.getAbsolutePath();
                if (absolutePath.contains("$")) {
                    continue; // skip inner and object classes
                }
                String relativePath = absolutePath.substring(classesDirectoryPath.length());
                //                    String name = product.getName();
                String name = relativePath.substring(0, relativePath.length() - ".class".length());
                /*if (name.indexOf( '$' ) > 0)
                {
                name = name.substring( 0, name.indexOf( '$' ) );
                }*/
                name = name.replace(File.separator, ".");
                //System.out.println(sourceFile.getPath() + " -> " + name);
                sourceMap.put(name, sourceFile);
            }
            /*String[] definitionNames = analysis.getDefinitionNames( sourceFile );
            Set<String> uniqueDefinitionNames = new HashSet<String>(definitionNames.length);
            for (String definitionName: definitionNames)
            {
            if ( !uniqueDefinitionNames.contains( definitionName ) )
            {
                result.put( definitionName, sourceFile );
            //                        System.out.println( "definitionName:'" + definitionName + "', source:'"
            //                                        + sourceFile.getAbsolutePath() + "'" );
                uniqueDefinitionNames.add( definitionName );
            }
            }*/
        }
        sourceMaps.put(p, sourceMap);
    }
    this.currentSourceMaps = sourceMaps;

    boolean reloadRequired = false;
    for (MavenProject p : projectsToBuild) {
        long lastModifiedTime = 0L;
        Set<String> outputFilePaths = new HashSet<String>();
        File outputDirectory = new File(p.getBuild().getOutputDirectory());
        if (outputDirectory.exists() && outputDirectory.isDirectory()) {
            DirectoryScanner classPathScanner = new DirectoryScanner();
            classPathScanner.setBasedir(outputDirectory);
            classPathScanner.setExcludes(new String[] { assetsPrefix + "**" });
            classPathScanner.scan();
            String[] files = classPathScanner.getIncludedFiles();
            for (String fileName : files) {
                File f = new File(outputDirectory, fileName);
                outputFilePaths.add(f.getAbsolutePath());
                long lmf = f.lastModified();
                if (lmf > lastModifiedTime) {
                    lastModifiedTime = lmf;
                }
            }
        }
        if (!reloadRequired && (lastModifiedTime > currentClasspathTimestamps.get(p).longValue()
                || !outputFilePaths.equals(currentClasspathFilePaths.get(p)))) {
            reloadRequired = true;
        }
        currentClasspathTimestamps.put(p, Long.valueOf(lastModifiedTime));
        currentClasspathFilePaths.put(p, outputFilePaths);
    }

    return reloadRequired;
}

From source file:com.google.code.play2.plugin.MavenPlay2Builder.java

License:Apache License

private MavenProject findProjectFor(String filePath) {
    MavenProject result = null;/*from  w  w w  .ja  v  a 2 s . c  o m*/
    search: for (MavenProject p : projects) {
        for (String sourceRoot : p.getCompileSourceRoots()) {
            if (filePath.startsWith(sourceRoot)) {
                result = p;
                break search;
            }
        }
        for (Resource resource : p.getResources()) {
            if (filePath.startsWith(resource.getDirectory())) {
                result = p;
                break search;
            }
        }
    }
    return result;
}

From source file:com.sixdegreeshq.sitenav.GeneratorMojo.java

License:Apache License

/**
 * got from/*from ww w . j a va 2  s  . c  o  m*/
 * https://github.com/querydsl/querydsl/blob/master/querydsl-maven-plugin/src/main/java/com/querydsl/maven/AbstractExporterMojo.java
 *
 */
@SuppressWarnings("unchecked")
private ClassLoader getProjectClassLoader(MavenProject project)
        throws DependencyResolutionRequiredException, MalformedURLException {
    List<String> classpathElements;
    if (testing) {
        classpathElements = project.getTestClasspathElements();
        for (Resource testResource : project.getTestResources()) {
            classpathElements.add(testResource.getDirectory());
        }

    } else {
        classpathElements = project.getCompileClasspathElements();
    }

    for (Resource testResource : project.getResources()) {
        classpathElements.add(testResource.getDirectory());
    }

    List<URL> urls = new ArrayList<URL>(classpathElements.size());
    for (String element : classpathElements) {
        File file = new File(element);
        if (file.exists()) {
            urls.add(file.toURI().toURL());
        }
    }
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
}

From source file:com.totsp.mavenplugin.gwt.util.BuildClasspathUtil.java

License:Open Source License

/**
 * Get resources for specific scope./*from w  ww. ja  va2s  . c  om*/
 * 
 * @param project
 * @param scope
 * @return
 */
@SuppressWarnings("unchecked")
private static List<Resource> getResources(final MavenProject project, final DependencyScope scope) {
    if (DependencyScope.COMPILE.equals(scope)) {
        return project.getResources();
    } else if (DependencyScope.TEST.equals(scope)) {
        return project.getTestResources();
    } else {
        throw new RuntimeException("Not allowed scope " + scope);
    }
}

From source file:org.apache.felix.bundleplugin.BundlePlugin.java

License:Apache License

private static String getMavenResourcePaths(MavenProject project) {
    final String basePath = project.getBasedir().getAbsolutePath();

    Set pathSet = new LinkedHashSet();
    for (Iterator i = project.getResources().iterator(); i.hasNext();) {
        org.apache.maven.model.Resource resource = (org.apache.maven.model.Resource) i.next();

        final String sourcePath = resource.getDirectory();
        final String targetPath = resource.getTargetPath();

        // ignore empty or non-local resources
        if (new File(sourcePath).exists() && ((targetPath == null) || (targetPath.indexOf("..") < 0))) {
            DirectoryScanner scanner = new DirectoryScanner();

            scanner.setBasedir(resource.getDirectory());
            if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) {
                scanner.setIncludes((String[]) resource.getIncludes().toArray(EMPTY_STRING_ARRAY));
            } else {
                scanner.setIncludes(DEFAULT_INCLUDES);
            }//from  w  ww  .jav  a2  s  .  c  o  m

            if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) {
                scanner.setExcludes((String[]) resource.getExcludes().toArray(EMPTY_STRING_ARRAY));
            }

            scanner.addDefaultExcludes();
            scanner.scan();

            List includedFiles = Arrays.asList(scanner.getIncludedFiles());

            for (Iterator j = includedFiles.iterator(); j.hasNext();) {
                String name = (String) j.next();
                String path = sourcePath + '/' + name;

                // make relative to project
                if (path.startsWith(basePath)) {
                    if (path.length() == basePath.length()) {
                        path = ".";
                    } else {
                        path = path.substring(basePath.length() + 1);
                    }
                }

                // replace windows backslash with a slash
                // this is a workaround for a problem with bnd 0.0.189
                if (File.separatorChar != '/') {
                    name = name.replace(File.separatorChar, '/');
                    path = path.replace(File.separatorChar, '/');
                }

                // copy to correct place
                path = name + '=' + path;
                if (targetPath != null) {
                    path = targetPath + '/' + path;
                }

                // use Bnd filtering?
                if (resource.isFiltering()) {
                    path = '{' + path + '}';
                }

                pathSet.add(path);
            }
        }
    }

    StringBuffer resourcePaths = new StringBuffer();
    for (Iterator i = pathSet.iterator(); i.hasNext();) {
        resourcePaths.append(i.next());
        if (i.hasNext()) {
            resourcePaths.append(',');
        }
    }

    return resourcePaths.toString();
}

From source file:org.apache.myfaces.trinidadbuild.plugin.jdeveloper.JDeveloperMojo.java

License:Apache License

private void generateProject() throws IOException, MojoExecutionException {
    if (!"pom".equals(project.getPackaging())) {
        File projectFile = getJProjectFile(project);

        // Get Project Properties to tell Mojo whether or not to add
        // library refs and taglibs to the project.
        Properties props = project.getProperties();
        String addLibs = (String) props.get(_PROPERTY_ADD_LIBRARY);
        String addTagLibs = (String) props.get(_PROPERTY_ADD_TAGLIBS);

        final boolean webProject = this.isWebProject();

        _addLibraries = (addLibs == null) ? true : (new Boolean(addLibs)).booleanValue();
        _addLibraries = _addLibraries & webProject;

        _addTagLibs = (addTagLibs == null) ? true : (new Boolean(addTagLibs)).booleanValue();
        _addTagLibs = _addTagLibs && webProject;

        // TODO: read configuration for war:war goal
        File webappDir = new File(project.getBasedir(), "src/main/webapp");
        // TODO: read configuration for compiler:complie goal
        File outputDir = new File(project.getBuild().getDirectory(), "classes");

        MavenProject executionProject = project.getExecutionProject();
        List compileSourceRoots = executionProject.getCompileSourceRoots();
        if (sourceRoots != null) {
            for (int i = 0; i < sourceRoots.length; i++) {
                compileSourceRoots.add(sourceRoots[i].getAbsolutePath());
            }/* w  w  w.  j a  v  a2s  .co  m*/
        }

        List compileResourceRoots = executionProject.getResources();
        if (resourceRoots != null) {
            for (int i = 0; i < resourceRoots.length; i++) {
                Resource resource = new Resource();
                resource.setDirectory(resourceRoots[i].getAbsolutePath());
                compileResourceRoots.add(resource);
            }
        }

        getLog().info("Generating JDeveloper " + release + " Project " + project.getArtifactId());

        Set pluginArtifacts = new LinkedHashSet();
        pluginArtifacts.addAll(project.getPluginArtifacts());

        // Note: include "compile", "provided", "system" and "runtime"
        // scopes
        Set compileArtifacts = new LinkedHashSet();
        compileArtifacts.addAll(project.getCompileArtifacts());
        compileArtifacts.addAll(project.getRuntimeArtifacts());

        // Note: separate "runtime" vs. "compile" dependencies in
        // JDeveloper?
        generateProject(projectFile, project.getArtifactId(), project.getPackaging(), project.getDependencies(),
                new ArrayList(compileArtifacts), compileSourceRoots, compileResourceRoots,
                Collections.singletonList(webappDir.getPath()), outputDir);
    }
}

From source file:org.apache.myfaces.trinidadbuild.plugin.jdeveloper.JDeveloperMojo.java

License:Apache License

private void copyTagLibraries(File projectDir, List dependencies, List artifacts) throws IOException {

    File targetDir = new File(projectDir, "src/main/webapp/WEB-INF");

    for (Iterator i = dependencies.iterator(); i.hasNext();) {
        Dependency dependency = (Dependency) i.next();
        MavenProject dependentProject = findDependentProject(dependency.getManagementKey());

        if (dependentProject != null) {
            List resourceRoots = dependentProject.getResources();

            for (Iterator j = resourceRoots.iterator(); j.hasNext();) {
                Resource resource = (Resource) j.next();
                String resourceRoot = resource.getDirectory();
                File resourceDirectory = new File(resourceRoot);

                if (resourceDirectory.exists()) {
                    DirectoryScanner scanner = new DirectoryScanner();
                    scanner.setBasedir(resourceRoot);
                    scanner.addDefaultExcludes();
                    scanner.setIncludes(new String[] { "META-INF/*.tld" });
                    scanner.scan();//from w w  w.ja v  a  2s .c o  m

                    String[] tldFiles = scanner.getIncludedFiles();
                    for (int k = 0; k < tldFiles.length; k++) {
                        File sourceFile = new File(resourceDirectory, tldFiles[k]);
                        File targetFile = new File(targetDir, sourceFile.getName());

                        if (targetFile.exists())
                            targetFile.delete();

                        FileUtils.copyFile(sourceFile, targetFile);
                    }
                }
            }
        }
    }

    Map sourceMap = new TreeMap();

    for (Iterator i = artifacts.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();
        if (!isDependentProject(artifact.getDependencyConflictId()) && "jar".equals(artifact.getType())) {
            File file = artifact.getFile();
            JarFile jarFile = new JarFile(file);
            Enumeration jarEntries = jarFile.entries();
            while (jarEntries.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
                String name = jarEntry.getName();
                if (name.startsWith("META-INF/") && name.endsWith(".tld")) {
                    List taglibs = (List) sourceMap.get(name);
                    if (taglibs == null) {
                        taglibs = new ArrayList();
                        sourceMap.put(name, taglibs);
                    }
                    taglibs.add(file);
                }
            }
        }
    }

    for (Iterator i = sourceMap.entrySet().iterator(); i.hasNext();) {
        Map.Entry e = (Map.Entry) i.next();
        List taglibs = (List) e.getValue();
        String name = (String) e.getKey();

        for (Iterator ti = taglibs.iterator(); ti.hasNext();) {
            File file = (File) ti.next();
            File sourceFile = new File(name);
            StringBuffer buff = new StringBuffer(sourceFile.getName());
            if (taglibs.size() > 1) {
                String jarName = file.getName().substring(0, file.getName().length() - ".jar".length());
                buff.insert(buff.length() - ".tld".length(), "-" + jarName);
            }

            URL jarURL = file.toURL();
            URL sourceURL = new URL("jar:" + jarURL.toExternalForm() + "!/" + name);
            File targetFile = new File(targetDir, buff.toString());

            if (targetFile.exists())
                targetFile.delete();
            FileUtils.copyURLToFile(sourceURL, targetFile);
            targetFile.setReadOnly();
        }
    }
}

From source file:org.apache.usergrid.chop.plugin.Utils.java

License:Apache License

/**
 * Copies all found resource files, including test resources to the <code>targetFolder</code>.
 * <p>/* w  w w.j  ava 2  s  .  co  m*/
 * Resource files to be copied are filtered or included according to the configurations inside
 * <code>project</code>'s pom.xml file.
 *
 * @param project       project whose resource files to be copied
 * @param targetFolder  matching resource files are stored in this directory
 * @return
 */
public static boolean copyResourcesTo(MavenProject project, String targetFolder) {
    File targetFolderFile = new File(targetFolder);
    String includes;
    String excludes;
    List allResources = project.getResources();
    allResources.addAll(project.getTestResources());

    // If there is no resource folder under project, mvn chop:runner goal should fail
    if (!hasResourceFolders(project)) {
        return false;
    } else {
        LOG.info("Copying resource files to runner.jar");

        for (Object res : allResources) {
            if (!(res instanceof Resource)) {
                continue;
            }
            Resource resource = (Resource) res;
            try {
                File baseDir = new File(resource.getDirectory());
                includes = resource.getIncludes().toString().replace("[", "").replace("]", "").replace(" ", "");
                excludes = resource.getExcludes().toString().replace("[", "").replace("]", "").replace(" ", "");

                List<String> resFiles = FileUtils.getFileNames(baseDir, includes, excludes, true, true);
                for (String resFile : resFiles) {
                    File resourceFile = new File(resFile);
                    LOG.info("Copying {} to {}", resourceFile.getName(), targetFolder);
                    FileUtils.copyFileToDirectory(resourceFile, targetFolderFile);
                }
            } catch (IOException e) {
                LOG.info("Error while trying to copy resource files.", e);
            } catch (IllegalStateException e) {
                String path = resource.getDirectory();
                path = path.substring(0, path.lastIndexOf("/"));
                LOG.info("There is no resource folder under {} folder.", path);
            }
        }
        return true;
    }
}

From source file:org.apache.usergrid.chop.plugin.Utils.java

License:Apache License

/**
 * Returns true if there is at least one resource folder inside the project.
 *
 * @param project/*from  ww  w . j  ava2s  .co  m*/
 * @return
 */
public static boolean hasResourceFolders(MavenProject project) {
    List<Resource> resources = project.getResources();
    for (Resource res : resources) {
        if (FileUtils.fileExists(res.getDirectory())) {
            return true;
        }
    }
    return false;
}