Example usage for org.apache.maven.plugin.logging Log warn

List of usage examples for org.apache.maven.plugin.logging Log warn

Introduction

In this page you can find the example usage for org.apache.maven.plugin.logging Log warn.

Prototype

void warn(Throwable error);

Source Link

Document

Send an exception to the user in the warn error level.
The stack trace for this exception will be output when this error level is enabled.

Usage

From source file:org.apache.marmotta.maven.plugins.repochecker.RepositoryCheckerMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    ClientConnectionManager manager = new PoolingClientConnectionManager();
    final DefaultHttpClient client = new DefaultHttpClient(manager);

    final MatrixPrinter printer;
    if (silent) {
        printer = new SilentMatrixPrinter();
    } else/*  w ww.java  2  s  . co  m*/
        printer = new LogMatrixPrinter(getLog(), 1);

    try {
        final Log log = getLog();
        final List<ArtifactRepository> reps;
        if (repositories != null && repositories.length > 0) {
            @SuppressWarnings("unchecked")
            final LinkedList<ArtifactRepository> _tmp = new LinkedList<ArtifactRepository>(
                    project.getRemoteArtifactRepositories());
            reps = new LinkedList<ArtifactRepository>();

            for (String rid : repositories) {
                ArtifactRepository r = null;
                for (ArtifactRepository ar : _tmp) {
                    if (rid.equals(ar.getId())) {
                        r = ar;
                        break;
                    }
                }
                if (r != null)
                    reps.add(r);
                else
                    log.warn("Could not find artifact repository '" + rid + "'");
            }

            if (reps.size() == 0) {
                log.warn("No artifact repositories provided, skipping.");
                return;
            }
        } else {
            @SuppressWarnings("unchecked")
            final LinkedList<ArtifactRepository> _tmp = new LinkedList<ArtifactRepository>(
                    project.getRemoteArtifactRepositories());
            reps = _tmp;
        }

        printer.printHeader(reps);

        final DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(project, null);
        Set<Artifact> missingArtifacts = checkDepNode(rootNode, reps, 0, client, printer);

        printer.printFooter(reps);

        if (missingArtifacts.size() > 0) {
            log.warn("unresolved dependencies:");
            for (Artifact missing : missingArtifacts) {
                log.warn("  " + missing.getId());
            }
        }
    } catch (DependencyGraphBuilderException e) {
        throw new MojoExecutionException("Cannot build project dependency graph", e);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

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

License:Apache License

/**
 * Wrapper around {@link ArtifactResolver#resolve(Artifact, List, ArtifactRepository)}
 *
 * @param artifactResolver see {@link ArtifactResolver#resolve(Artifact, List, ArtifactRepository)}
 * @param artifact see {@link ArtifactResolver#resolve(Artifact, List, ArtifactRepository)}
 * @param remoteRepos see {@link ArtifactResolver#resolve(Artifact, List, ArtifactRepository)}
 * @param localRepository see {@link ArtifactResolver#resolve(Artifact, List, ArtifactRepository)}
 * @param log Logger/* ww  w  . j  av a 2s .  c  om*/
 * @return the artifact, resolved if possible.
 */
public static Artifact resolveArtifact(ArtifactResolver artifactResolver, Artifact artifact, List remoteRepos,
        ArtifactRepository localRepository, Log log)

{
    try {
        artifactResolver.resolve(artifact, remoteRepos, localRepository);
    } catch (ArtifactNotFoundException e) {
        // ignore, the jar has not been found
    } catch (ArtifactResolutionException e) {
        String message = Messages.getString("IdeUtils.errorresolving",
                new Object[] { artifact.getClassifier(), artifact.getId(), e.getMessage() });

        log.warn(message);
    }

    return artifact;
}

From source file:org.apache.pluto.maven.AssembleMojo.java

License:Apache License

protected void doValidate() throws MojoExecutionException {
    Log log = getLog();

    // Support for the old 'warFiles' mojo parameter.  Apparently
    // the alias for the 'archives' parameter doesn't work properly.
    if (!(warFiles == null || warFiles.isEmpty())) {
        log.warn("'warFiles' parameter is deprecated.  Use 'archives' parameter instead.");
        if (archives == null) {
            archives = new ArrayList();
        }/*from w  ww. j  a  v a 2s .  c om*/
        archives.addAll(warFiles);
    }

    // Warn if the old 'warFilesDestination' mojo parameter is used
    if (warFilesDestination != null) {
        log.warn("'warFilesDestination' parameter is deprecated.  Use 'assemblyOutputDirectory' instead.");
        assemblyOutputDirectory = warFilesDestination;
    }

    // If a list of war files are supplied:
    //   1) webXml, portletXml, and webXmlDestination parameters are ignored
    //   2) verify the files in the List exist.
    //   3) verify the destination is a directory, or create it if it doesn't exist.

    // A list of files was supplied so we ignore other parameters. 
    if (archives != null && !archives.isEmpty()) {
        if (webXml != null) {
            log.debug(
                    "archives parameter and webXml parameter are mutually exclusive.  Ignoring webXml parameter.");
        }
        if (portletXml != null) {
            log.debug(
                    "archives parameter and portletXml parameter are mutually exclusive.  Ignoring portletXml parameter.");
        }
        if (webXmlDestination != null) {
            log.debug(
                    "archives parameter and webXmlDestination parameter are mutually exclusive.  Ignoring webXmlDestination parameter.");
        }

        // verify each file can be found
        for (Iterator i = archives.iterator(); i.hasNext();) {
            File f = new File(i.next().toString());
            if (!f.exists()) {
                log.warn("File " + f.getAbsolutePath() + " does not exist.");
                i.remove();
                continue;
            }
            if (!f.canRead()) {
                log.warn("File " + f.getAbsolutePath() + " exists but cannot be read.");
                i.remove();
                continue;
            }
        }

        // check to see if the warFiles list is now empty
        if (archives.isEmpty()) {
            throw new MojoExecutionException("No war files could be installed due errors.");
        }

        // check to see if the dest dir exists or create it.
        if (!assemblyOutputDirectory.exists()) {
            if (log.isDebugEnabled()) {
                log.debug("Creating destination directory for assembled war files: "
                        + assemblyOutputDirectory.getAbsolutePath());
            }
            try {
                if (!assemblyOutputDirectory.mkdirs()) {
                    throw new MojoExecutionException(
                            "Unable to create destination directory for assembled war files: "
                                    + assemblyOutputDirectory.getAbsolutePath());
                }
            } catch (SecurityException e) {
                throw new MojoExecutionException(
                        "Unable to create destination directory for assembled war files: " + e.getMessage(), e);
            }
        } else {
            if (!assemblyOutputDirectory.isDirectory()) {
                throw new MojoExecutionException("Specified destination for assembled war files "
                        + assemblyOutputDirectory.getAbsolutePath() + " is not a directory!");
            }
            if (!assemblyOutputDirectory.canRead() || !assemblyOutputDirectory.canWrite()) {
                throw new MojoExecutionException(
                        "Unable to read or write to destination directory for assembed war files.  "
                                + "Check permissions on the directory "
                                + assemblyOutputDirectory.getAbsolutePath());
            }
        }

        // A list of archive files was not provided, so use the other parameters instead.

    } else {
        if (webXml == null || !webXml.exists()) {
            throw new MojoExecutionException("Web application descriptor must be a valid web.xml");
        }
        if (portletXml == null || !portletXml.exists()) {
            throw new MojoExecutionException("Portlet descriptor must be a valid portlet.xml");
        }
    }
}

From source file:org.apache.rat.mp.util.ScmIgnoreParser.java

License:Apache License

/**
 * Parses excludes from the given SCM ignore file.
 *
 * @param log       Maven log to show output during RAT runs.
 * @param scmIgnore if <code>null</code> or invalid an empty list of exclusions is returned.
 * @return all exclusions (=non-comment lines) from the SCM ignore file.
 *///from w ww . jav a 2s.  co m
public static List<String> getExcludesFromFile(final Log log, final File scmIgnore) {

    final List<String> exclusionLines = new ArrayList<>();

    if (scmIgnore != null && scmIgnore.exists() && scmIgnore.isFile()) {
        log.info("Parsing exclusions from " + scmIgnore);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(scmIgnore));
            String line;
            while ((line = reader.readLine()) != null) {
                if (!isComment(line)) {
                    exclusionLines.add(line);
                    log.debug("Added " + line);
                }
            }
        } catch (final IOException e) {
            log.warn("Cannot parse " + scmIgnore + " for exclusions. Will skip this file.");
            log.debug("Skip parsing " + scmIgnore + " due to " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
    return exclusionLines;
}

From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java

License:Apache License

public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception {
    boolean isNew = false;

    if (cfg.getProcess() != null || isNew) {
        LOG.info("Stopping Launchpad " + cfg.getId());
        boolean destroy = true;
        final int twoMinutes = 2 * 60 * 1000;
        final File controlPortFile = getControlPortFile(cfg.getDirectory());
        LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists());
        if (controlPortFile.exists()) {
            // reading control port
            int controlPort = -1;
            String secretKey = null;
            LineNumberReader lnr = null;
            String serverName = null;
            try {
                lnr = new LineNumberReader(new FileReader(controlPortFile));
                final String portLine = lnr.readLine();
                final int pos = portLine.indexOf(':');
                controlPort = Integer.parseInt(portLine.substring(pos + 1));
                if (pos > 0) {
                    serverName = portLine.substring(0, pos);
                }// w w  w . ja  v  a 2  s .  c  o m
                secretKey = lnr.readLine();
            } catch (final NumberFormatException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } catch (final IOException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } finally {
                IOUtils.closeQuietly(lnr);
            }

            if (controlPort != -1) {
                final List<String> hosts = new ArrayList<String>();
                if (serverName != null) {
                    hosts.add(serverName);
                }
                hosts.add("localhost");
                hosts.add("127.0.0.1");
                LOG.debug("Found control port " + controlPort);
                int index = 0;
                while (destroy && index < hosts.size()) {
                    final String hostName = hosts.get(index);

                    Socket clientSocket = null;
                    DataOutputStream out = null;
                    BufferedReader in = null;
                    try {
                        LOG.debug("Trying to connect to " + hostName + ":" + controlPort);
                        clientSocket = new Socket();
                        // set a socket timeout
                        clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes);
                        // without that, read() call on the InputStream associated with this Socket is infinite
                        clientSocket.setSoTimeout(twoMinutes);

                        LOG.debug(hostName + ":" + controlPort
                                + " connection estabilished, sending the 'stop' command...");

                        out = new DataOutputStream(clientSocket.getOutputStream());
                        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        if (secretKey != null) {
                            out.writeBytes(secretKey);
                            out.write(' ');
                        }
                        out.writeBytes("stop\n");
                        in.readLine();
                        destroy = false;
                        LOG.debug("'stop' command sent to " + hostName + ":" + controlPort);
                    } catch (final Throwable ignore) {
                        // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions
                        // we ignore this for now
                        LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort
                                + " due to: " + ignore.getMessage());
                    } finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                        IOUtils.closeQuietly(clientSocket);
                    }
                    index++;
                }
            }
        }
        if (cfg.getProcess() != null) {
            final Process process = cfg.getProcess();

            if (!destroy) {
                // as shutdown might block forever, we use a timeout
                final long now = System.currentTimeMillis();
                final long end = now + twoMinutes;

                LOG.debug("Waiting for process to stop...");

                while (isAlive(process) && (System.currentTimeMillis() < end)) {
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
                if (isAlive(process)) {
                    LOG.debug("Process timeout out after 2 minutes");
                    destroy = true;
                } else {
                    LOG.debug("Process stopped");
                }
            }

            if (destroy) {
                LOG.debug("Destroying process...");
                process.destroy();
                LOG.debug("Process destroyed");
            }

            cfg.setProcess(null);
        }
    } else {
        LOG.warn("Launchpad already stopped");
    }
}

From source file:org.apache.tuscany.maven.bundle.plugin.BundleAggregatorMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    try {//  w  w  w .  j a va 2  s. c o  m
        Log log = getLog();
        if (!rootDirectory.isDirectory()) {
            log.warn(rootDirectory + " is not a directory");
            return;
        }
        File[] files = rootDirectory.listFiles();
        aggregateBundles(log, rootDirectory, files, targetBundleFile, bundleName, bundleVersion);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.apache.tuscany.maven.bundle.plugin.BundlesMetaDataBuildMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    Log log = getLog();

    Set<Artifact> artifacts = null;
    if (includeConflictingDepedencies) {
        try {//from w ww .ja va2  s. co m
            artifacts = getDependencyArtifacts(project);
        } catch (Exception e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    } else {
        artifacts = project.getArtifacts();
    }

    try {

        // Create the target directory
        File root;
        if (targetDirectory == null) {
            root = new File(project.getBuild().getDirectory(), "plugins/");
        } else {
            root = targetDirectory;
        }

        if (generateModules) {
            root.mkdirs();
        }

        // Build sets of exclude directories and included/excluded/groupids
        Set<String> excludedFileNames = new HashSet<String>();
        if (excludeDirectories != null) {
            for (File f : excludeDirectories) {
                if (f.isDirectory()) {
                    for (String n : f.list()) {
                        excludedFileNames.add(n);
                    }
                }
            }
        }
        Set<String> includedGroupIds = new HashSet<String>();
        if (includeGroupIds != null) {
            for (String g : includeGroupIds) {
                includedGroupIds.add(g);
            }
        }
        Set<String> excludedGroupIds = new HashSet<String>();
        if (excludeGroupIds != null) {
            for (String g : excludeGroupIds) {
                excludedGroupIds.add(g);
            }
        }

        // Find all the distribution poms
        List<MavenProject> poms = new ArrayList<MavenProject>();

        if (useDistributionName) {
            for (Object o : project.getArtifacts()) {
                Artifact artifact = (Artifact) o;
                if ("pom".equals(artifact.getType()) && artifact.getGroupId().equals(project.getGroupId())
                        && artifact.getArtifactId().startsWith("tuscany-feature-")) {
                    log.info("Dependent distribution: " + artifact);
                    MavenProject pomProject = buildProject(artifact);
                    poms.add(pomProject);
                    // log.info(pomProject.getArtifactMap().toString());
                }
            }
        }

        if (features != null) {
            // find all the features that require processing
            for (Object o : project.getArtifacts()) {
                Artifact artifact = (Artifact) o;
                for (Feature feature : features) {
                    if (artifact.getGroupId().equals(feature.getGroupId())
                            && artifact.getArtifactId().equals(feature.getArtifactId())) {
                        log.info("Feature: " + artifact);
                        MavenProject pomProject = buildProject(artifact);
                        poms.add(pomProject);
                    }
                }
            }

            // force useDistributionName to true so that subsequent generation works
            useDistributionName = true;
        }

        if (extensions != null) {
            // find all the extensions that require processing
            // TODO - putting them in features dir for the time being
            for (Object o : project.getArtifacts()) {
                Artifact artifact = (Artifact) o;
                for (Extension extension : extensions) {
                    if (artifact.getGroupId().equals(extension.getGroupId())
                            && artifact.getArtifactId().equals(extension.getArtifactId())) {
                        log.info("Extension: " + artifact);
                        MavenProject pomProject = buildProject(artifact);
                        poms.add(pomProject);
                    }
                }
            }

            // force useDistributionName to true so that subsequent generation works
            useDistributionName = true;
        }

        // If no features have been specified assume that the current
        // project defines the feature
        if (poms.size() == 0) {
            poms.add(project);
        }

        // Process all the dependency artifacts
        ProjectSet bundleSymbolicNames = new ProjectSet(poms);
        ProjectSet bundleLocations = new ProjectSet(poms);
        ProjectSet jarNames = new ProjectSet(poms);
        ProjectSet serviceProviders = new ProjectSet(poms);

        for (Artifact artifact : artifacts) {

            log.info("Processing artifact: " + artifact);

            // Only consider Compile and Runtime dependencies
            if (!(Artifact.SCOPE_COMPILE.equals(artifact.getScope())
                    || Artifact.SCOPE_RUNTIME.equals(artifact.getScope())
                    || Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                    || (generateTargetPlatform && Artifact.SCOPE_TEST.equals(artifact.getScope())))) {
                log.info("Skipping artifact: " + artifact);
                continue;
            }

            if (artifactTypes == null) {
                artifactTypes = "jar,bundle";
            }
            String types[] = artifactTypes.trim().split("( |\t|\n|\r|\f|,)+");
            Set<String> typeSet = new HashSet<String>(Arrays.asList(types));

            // Only consider JAR and WAR files
            if (!typeSet.contains(artifact.getType())) {
                log.debug("Artifact with unknown type is skipped: " + artifact);
                continue;
            }

            // Exclude artifact if its groupId is excluded or if it's not included
            if (excludedGroupIds.contains(artifact.getGroupId())) {
                log.debug("Artifact groupId is excluded: " + artifact);
                continue;
            }
            if (!includedGroupIds.isEmpty()) {
                if (!includedGroupIds.contains(artifact.getGroupId())) {
                    log.debug("Artifact groupId is not included: " + artifact);
                    continue;
                }
            }

            File artifactFile = artifact.getFile();
            if (!artifactFile.exists()) {
                log.warn("Artifact doesn't exist: " + artifact);
                continue;
            }

            if (log.isDebugEnabled()) {
                log.debug("Processing artifact: " + artifact);
            }

            Manifest customizedMF = findManifest(artifact);

            // Get the bundle name if the artifact is an OSGi bundle
            Manifest mf = null;
            String bundleName = null;
            try {
                mf = BundleUtil.getManifest(artifactFile);
                bundleName = BundleUtil.getBundleSymbolicName(mf);
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }

            if (bundleName != null && customizedMF == null) {

                // Exclude artifact if its file name is excluded
                if (excludedFileNames.contains(artifactFile.getName())) {
                    log.debug("Artifact file is excluded: " + artifact);
                    continue;
                }

                if (generateModules) {
                    // Copy an OSGi bundle as is
                    log.info("Adding OSGi bundle artifact: " + artifact);
                }

                if (!expandThirdPartyBundle || artifact.getGroupId().startsWith("org.apache.tuscany.sca")
                        || artifact.getGroupId().startsWith("org.eclipse")) {
                    if (generateModules) {
                        copyFile(artifactFile, root);
                    }
                    bundleSymbolicNames.add(artifact, bundleName);
                    bundleLocations.add(artifact, artifactFile.getName());
                    jarNames.add(artifact, artifactFile.getName());
                    if (isServiceProvider(mf)) {
                        serviceProviders.add(artifact, bundleName);
                    }
                } else {
                    // Expanding the bundle into a folder

                    setBundleClassPath(mf, artifactFile);

                    int index = artifactFile.getName().lastIndexOf('.');
                    String dirName = artifactFile.getName().substring(0, index);
                    File dir = new File(root, dirName);
                    if (generateModules) {
                        File file = new File(dir, "META-INF");
                        file.mkdirs();
                        file = new File(file, "MANIFEST.MF");

                        FileOutputStream fos = new FileOutputStream(file);
                        write(mf, fos);
                        fos.close();
                        copyFile(artifactFile, dir);
                    }
                    bundleSymbolicNames.add(artifact, bundleName);
                    bundleLocations.add(artifact, dir.getName());
                    jarNames.add(artifact, dirName + "/" + artifactFile.getName());
                    if (isServiceProvider(mf)) {
                        serviceProviders.add(artifact, bundleName);
                    }
                }

            } else if ("war".equals(artifact.getType())) {

                // Exclude artifact if its file name is excluded
                if (excludedFileNames.contains(artifactFile.getName())) {
                    log.debug("Artifact file is excluded: " + artifact);
                    continue;
                }

                if (generateModules) {
                    // Copy a WAR as is
                    log.info("Adding WAR artifact: " + artifact);
                    copyFile(artifactFile, root);
                }
            } else {

                int index = artifactFile.getName().lastIndexOf('.');
                String dirName = artifactFile.getName().substring(0, index);
                File dir = new File(root, dirName);

                // Exclude artifact if its file name is excluded
                if (excludedFileNames.contains(dir.getName())) {
                    log.debug("Artifact file is excluded: " + artifact);
                    continue;
                }

                if (artifactAggregations != null) {
                    boolean aggregated = false;
                    for (ArtifactAggregation group : artifactAggregations) {
                        if (group.matches(artifact)) {
                            group.getArtifacts().add(artifact);
                            aggregated = true;
                            break;
                        }
                    }
                    if (aggregated) {
                        continue;
                    }
                }

                // create manifest directory
                File file = new File(dir, "META-INF");
                if (generateModules) {
                    // Create a bundle directory for a non-OSGi JAR
                    log.info("Adding JAR artifact: " + artifact);

                    file.mkdirs();
                }

                String symbolicName = null;
                if (customizedMF == null) {
                    String version = BundleUtil.osgiVersion(artifact.getVersion());

                    Set<File> jarFiles = new HashSet<File>();
                    jarFiles.add(artifactFile);
                    symbolicName = (artifact.getGroupId() + "." + artifact.getArtifactId());
                    if (generateModules) {
                        mf = BundleUtil.libraryManifest(jarFiles, symbolicName, symbolicName, version, null,
                                this.eclipseBuddyPolicy, this.executionEnvironment);

                        file = new File(file, "MANIFEST.MF");
                        FileOutputStream fos = new FileOutputStream(file);
                        write(mf, fos);
                        fos.close();
                        log.info("Writing generated manifest for: " + artifact + " to " + file);
                    }
                } else {
                    mf = customizedMF;
                    symbolicName = BundleUtil.getBundleSymbolicName(mf);
                    if (symbolicName == null) {
                        throw new MojoExecutionException("Invalid customized MANIFEST.MF for " + artifact);
                    }
                    setBundleClassPath(mf, artifactFile);

                    // re-find the custom MF file and copy it
                    // I can't get the  manifest file from the manifest itself
                    // the Manifest read/write operation seems to be filtering
                    // out some entries that I've added manually????
                    File artifactManifest = null;

                    if (artifactManifests != null) {
                        for (ArtifactManifest m : artifactManifests) {
                            if (m.matches(artifact)) {
                                artifactManifest = m.getManifestFile();
                                break;
                            }
                        }
                    }

                    if (generateModules) {
                        file = new File(file, "MANIFEST.MF");

                        if (artifactManifest != null) {
                            log.info("Copying: " + artifactManifest + " to " + file);
                            copyManifest(artifactManifest, file);
                        } else {
                            FileOutputStream fos = new FileOutputStream(file);
                            write(mf, fos);
                            fos.close();
                            log.info("Writing generated manifest for: " + artifact + " to " + file);
                        }
                    }
                }

                if (generateModules) {
                    copyFile(artifactFile, dir);
                }

                bundleSymbolicNames.add(artifact, symbolicName);
                bundleLocations.add(artifact, dir.getName());
                jarNames.add(artifact, dirName + "/" + artifactFile.getName());
                if (isServiceProvider(mf)) {
                    serviceProviders.add(artifact, symbolicName);
                }
            }
        }

        if (artifactAggregations != null) {
            for (ArtifactAggregation group : artifactAggregations) {
                if (group.getArtifacts().isEmpty()) {
                    continue;
                }
                String symbolicName = group.getSymbolicName();
                String version = group.getVersion();
                File dir = new File(root, symbolicName + "-" + version);
                dir.mkdir();
                Set<File> jarFiles = new HashSet<File>();
                Artifact artifact = null;
                for (Artifact a : group.getArtifacts()) {
                    log.info("Aggragating JAR artifact: " + a);
                    artifact = a;
                    jarFiles.add(a.getFile());
                    copyFile(a.getFile(), dir);
                    jarNames.add(a, symbolicName + "-" + version + "/" + a.getFile().getName());
                }
                Manifest mf = BundleUtil.libraryManifest(jarFiles, symbolicName, symbolicName, version, null,
                        this.eclipseBuddyPolicy, this.executionEnvironment);
                File file = new File(dir, "META-INF");
                file.mkdirs();
                file = new File(file, "MANIFEST.MF");

                FileOutputStream fos = new FileOutputStream(file);
                write(mf, fos);
                fos.close();
                log.info("Written aggregate manifest");
                bundleSymbolicNames.add(artifact, symbolicName);
                bundleLocations.add(artifact, dir.getName());
                if (isServiceProvider(mf)) {
                    serviceProviders.add(artifact, symbolicName);
                }
            }
        }

        if (generateGatewayBundle) {
            generateGatewayBundle(serviceProviders);
        }

        /*
        if (useDistributionName) {
        bundleLocations.nameMap.remove(project.getArtifactId());
        jarNames.nameMap.remove(project.getArtifactId());
        bundleSymbolicNames.nameMap.remove(project.getArtifactId());
        }
        */

        // Generate a PDE target
        if (generateTargetPlatform) {
            generatePDETarget(bundleSymbolicNames, root, log);
        }

        // Generate a plugin.xml referencing the PDE target
        if (generatePlugin) {
            File pluginxml = new File(project.getBasedir(), "plugin.xml");
            FileOutputStream pluginXMLFile = new FileOutputStream(pluginxml);
            writePluginXML(new PrintStream(pluginXMLFile));
            pluginXMLFile.close();
        }

        if (generateConfig) {
            generateEquinoxConfig(bundleLocations, root, log);
        }

        if (generateManifestJar) {
            generateManifestJar(jarNames, root, log);
            generateEquinoxLauncherManifestJar(jarNames, root, log);
        }

        if (generateAntScript) {
            generateANTPath(jarNames, root, log);
        }

        if (generateWhichJars) {
            generateWhichJars(jarNames, root, log);
        }

        if (generateAggregatedBundle) {
            generateAggregatedBundles(bundleLocations, root, log);
        }

    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.apache.tuscany.maven.bundle.plugin.ModuleBundlesBuildMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    Log log = getLog();

    Set<Artifact> artifacts = null;
    if (includeConflictingDepedencies) {
        try {/*from  w  w  w. j  a  v a  2  s .c o  m*/
            artifacts = getDependencyArtifacts(project);
        } catch (Exception e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    } else {
        artifacts = project.getArtifacts();
    }

    try {

        // Create the target directory
        File root;
        if (targetDirectory == null) {
            root = new File(project.getBuild().getDirectory(), "plugins/");
        } else {
            root = targetDirectory;
        }
        root.mkdirs();

        // Build sets of exclude directories and included/excluded/groupids
        Set<String> excludedFileNames = new HashSet<String>();
        if (excludeDirectories != null) {
            for (File f : excludeDirectories) {
                if (f.isDirectory()) {
                    for (String n : f.list()) {
                        excludedFileNames.add(n);
                    }
                }
            }
        }
        Set<String> includedGroupIds = new HashSet<String>();
        if (includeGroupIds != null) {
            for (String g : includeGroupIds) {
                includedGroupIds.add(g);
            }
        }
        Set<String> excludedGroupIds = new HashSet<String>();
        if (excludeGroupIds != null) {
            for (String g : excludeGroupIds) {
                excludedGroupIds.add(g);
            }
        }

        // Find all the distribution poms
        List<MavenProject> poms = new ArrayList<MavenProject>();
        poms.add(project);
        if (useDistributionName) {
            for (Object o : project.getArtifacts()) {
                Artifact artifact = (Artifact) o;
                if ("pom".equals(artifact.getType()) && artifact.getGroupId().equals(project.getGroupId())
                        && artifact.getArtifactId().startsWith("tuscany-feature-")) {
                    log.info("Dependent distribution: " + artifact);
                    MavenProject pomProject = buildProject(artifact);
                    poms.add(pomProject);
                    // log.info(pomProject.getArtifactMap().toString());
                }
            }
        }

        // Process all the dependency artifacts
        ProjectSet bundleSymbolicNames = new ProjectSet(poms);
        ProjectSet bundleLocations = new ProjectSet(poms);
        ProjectSet jarNames = new ProjectSet(poms);
        ProjectSet serviceProviders = new ProjectSet(poms);

        for (Artifact artifact : artifacts) {

            // Only consider Compile and Runtime dependencies
            if (!(Artifact.SCOPE_COMPILE.equals(artifact.getScope())
                    || Artifact.SCOPE_RUNTIME.equals(artifact.getScope())
                    || Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                    || (generateTargetPlatform && Artifact.SCOPE_TEST.equals(artifact.getScope())))) {
                log.info("Skipping artifact: " + artifact);
                continue;
            }

            if (artifactTypes == null) {
                artifactTypes = "jar,bundle";
            }
            String types[] = artifactTypes.trim().split("( |\t|\n|\r|\f|,)+");
            Set<String> typeSet = new HashSet<String>(Arrays.asList(types));

            // Only consider JAR and WAR files
            if (!typeSet.contains(artifact.getType())) {
                log.debug("Artifact with unknown type is skipped: " + artifact);
                continue;
            }

            // Exclude artifact if its groupId is excluded or if it's not included
            if (excludedGroupIds.contains(artifact.getGroupId())) {
                log.debug("Artifact groupId is excluded: " + artifact);
                continue;
            }
            if (!includedGroupIds.isEmpty()) {
                if (!includedGroupIds.contains(artifact.getGroupId())) {
                    log.debug("Artifact groupId is not included: " + artifact);
                    continue;
                }
            }

            File artifactFile = artifact.getFile();
            if (!artifactFile.exists()) {
                log.warn("Artifact doesn't exist: " + artifact);
                continue;
            }

            if (log.isDebugEnabled()) {
                log.debug("Processing artifact: " + artifact);
            }

            Manifest customizedMF = findManifest(artifact);

            // Get the bundle name if the artifact is an OSGi bundle
            Manifest mf = null;
            String bundleName = null;
            try {
                mf = BundleUtil.getManifest(artifactFile);
                bundleName = BundleUtil.getBundleSymbolicName(mf);
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }

            if (bundleName != null && customizedMF == null) {

                // Exclude artifact if its file name is excluded
                if (excludedFileNames.contains(artifactFile.getName())) {
                    log.debug("Artifact file is excluded: " + artifact);
                    continue;
                }

                // Copy an OSGi bundle as is
                log.info("Adding OSGi bundle artifact: " + artifact);

                if (!expandThirdPartyBundle || artifact.getGroupId().startsWith("org.apache.tuscany.sca")
                        || artifact.getGroupId().startsWith("org.eclipse")) {
                    copyFile(artifactFile, root);
                    bundleSymbolicNames.add(artifact, bundleName);
                    bundleLocations.add(artifact, artifactFile.getName());
                    jarNames.add(artifact, artifactFile.getName());
                    if (isServiceProvider(mf)) {
                        serviceProviders.add(artifact, bundleName);
                    }
                } else {
                    // Expanding the bundle into a folder

                    setBundleClassPath(mf, artifactFile);

                    int index = artifactFile.getName().lastIndexOf('.');
                    String dirName = artifactFile.getName().substring(0, index);
                    File dir = new File(root, dirName);

                    File file = new File(dir, "META-INF");
                    file.mkdirs();
                    file = new File(file, "MANIFEST.MF");

                    FileOutputStream fos = new FileOutputStream(file);
                    write(mf, fos);
                    fos.close();
                    copyFile(artifactFile, dir);
                    bundleSymbolicNames.add(artifact, bundleName);
                    bundleLocations.add(artifact, dir.getName());
                    jarNames.add(artifact, dirName + "/" + artifactFile.getName());
                    if (isServiceProvider(mf)) {
                        serviceProviders.add(artifact, bundleName);
                    }
                }

            } else if ("war".equals(artifact.getType())) {

                // Exclude artifact if its file name is excluded
                if (excludedFileNames.contains(artifactFile.getName())) {
                    log.debug("Artifact file is excluded: " + artifact);
                    continue;
                }

                // Copy a WAR as is
                log.info("Adding WAR artifact: " + artifact);
                copyFile(artifactFile, root);

            } else {

                int index = artifactFile.getName().lastIndexOf('.');
                String dirName = artifactFile.getName().substring(0, index);
                File dir = new File(root, dirName);

                // Exclude artifact if its file name is excluded
                if (excludedFileNames.contains(dir.getName())) {
                    log.debug("Artifact file is excluded: " + artifact);
                    continue;
                }

                if (artifactAggregations != null) {
                    boolean aggregated = false;
                    for (ArtifactAggregation group : artifactAggregations) {
                        if (group.matches(artifact)) {
                            group.getArtifacts().add(artifact);
                            aggregated = true;
                            break;
                        }
                    }
                    if (aggregated) {
                        continue;
                    }
                }

                // Create a bundle directory for a non-OSGi JAR
                log.info("Adding JAR artifact: " + artifact);

                // create manifest directory
                File file = new File(dir, "META-INF");
                file.mkdirs();

                String symbolicName = null;
                if (customizedMF == null) {
                    String version = BundleUtil.osgiVersion(artifact.getVersion());

                    Set<File> jarFiles = new HashSet<File>();
                    jarFiles.add(artifactFile);
                    symbolicName = (artifact.getGroupId() + "." + artifact.getArtifactId());
                    mf = BundleUtil.libraryManifest(jarFiles, symbolicName, symbolicName, version, null,
                            this.eclipseBuddyPolicy, this.executionEnvironment);

                    file = new File(file, "MANIFEST.MF");
                    FileOutputStream fos = new FileOutputStream(file);
                    write(mf, fos);
                    fos.close();
                    log.info("Writing generated manifest for: " + artifact + " to " + file);
                } else {
                    mf = customizedMF;
                    symbolicName = BundleUtil.getBundleSymbolicName(mf);
                    if (symbolicName == null) {
                        throw new MojoExecutionException("Invalid customized MANIFEST.MF for " + artifact);
                    }
                    setBundleClassPath(mf, artifactFile);

                    // re-find the custom MF file and copy it
                    // I can't get the  manifest file from the manifest itself
                    // the Manifest read/write operation seems to be filtering
                    // out some entries that I've added manually????
                    File artifactManifest = null;

                    if (artifactManifests != null) {
                        for (ArtifactManifest m : artifactManifests) {
                            if (m.matches(artifact)) {
                                artifactManifest = m.getManifestFile();
                                break;
                            }
                        }
                    }

                    file = new File(file, "MANIFEST.MF");

                    if (artifactManifest != null) {
                        log.info("Copying: " + artifactManifest + " to " + file);
                        copyManifest(artifactManifest, file);
                    } else {
                        FileOutputStream fos = new FileOutputStream(file);
                        write(mf, fos);
                        fos.close();
                        log.info("Writing generated manifest for: " + artifact + " to " + file);
                    }
                }

                copyFile(artifactFile, dir);
                bundleSymbolicNames.add(artifact, symbolicName);
                bundleLocations.add(artifact, dir.getName());
                jarNames.add(artifact, dirName + "/" + artifactFile.getName());
                if (isServiceProvider(mf)) {
                    serviceProviders.add(artifact, symbolicName);
                }
            }
        }

        if (artifactAggregations != null) {
            for (ArtifactAggregation group : artifactAggregations) {
                if (group.getArtifacts().isEmpty()) {
                    continue;
                }
                String symbolicName = group.getSymbolicName();
                String version = group.getVersion();
                File dir = new File(root, symbolicName + "-" + version);
                dir.mkdir();
                Set<File> jarFiles = new HashSet<File>();
                Artifact artifact = null;
                for (Artifact a : group.getArtifacts()) {
                    log.info("Aggragating JAR artifact: " + a);
                    artifact = a;
                    jarFiles.add(a.getFile());
                    copyFile(a.getFile(), dir);
                    jarNames.add(a, symbolicName + "-" + version + "/" + a.getFile().getName());
                }
                Manifest mf = BundleUtil.libraryManifest(jarFiles, symbolicName, symbolicName, version, null,
                        this.eclipseBuddyPolicy, this.executionEnvironment);
                File file = new File(dir, "META-INF");
                file.mkdirs();
                file = new File(file, "MANIFEST.MF");

                FileOutputStream fos = new FileOutputStream(file);
                write(mf, fos);
                fos.close();
                log.info("Written aggregate manifest");
                bundleSymbolicNames.add(artifact, symbolicName);
                bundleLocations.add(artifact, dir.getName());
                if (isServiceProvider(mf)) {
                    serviceProviders.add(artifact, symbolicName);
                }
            }
        }

        if (generateGatewayBundle) {
            generateGatewayBundle(serviceProviders);
        }

        /*
        if (useDistributionName) {
        bundleLocations.nameMap.remove(project.getArtifactId());
        jarNames.nameMap.remove(project.getArtifactId());
        bundleSymbolicNames.nameMap.remove(project.getArtifactId());
        }
        */

        // Generate a PDE target
        if (generateTargetPlatform) {
            generatePDETarget(bundleSymbolicNames, root, log);
        }

        // Generate a plugin.xml referencing the PDE target
        if (generatePlugin) {
            File pluginxml = new File(project.getBasedir(), "plugin.xml");
            FileOutputStream pluginXMLFile = new FileOutputStream(pluginxml);
            writePluginXML(new PrintStream(pluginXMLFile));
            pluginXMLFile.close();
        }

        if (generateConfig) {
            generateEquinoxConfig(bundleLocations, root, log);
        }

        if (generateManifestJar) {
            generateManifestJar(jarNames, root, log);
            generateEquinoxLauncherManifestJar(jarNames, root, log);
        }

        if (generateAntScript) {
            generateANTPath(jarNames, root, log);
        }

        if (generateAggregatedBundle) {
            generateAggregatedBundles(bundleLocations, root, log);
        }

    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.apache.tuscany.maven.bundle.plugin.ThirdPartyBundleBuildMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    Log log = getLog();

    String projectGroupId = project.getGroupId();
    Set<File> jarFiles = new HashSet<File>();
    for (Object o : project.getArtifacts()) {
        Artifact artifact = (Artifact) o;

        if (!(Artifact.SCOPE_COMPILE.equals(artifact.getScope())
                || Artifact.SCOPE_RUNTIME.equals(artifact.getScope()))) {
            if (log.isDebugEnabled()) {
                log.debug("Skipping artifact: " + artifact);
            }/*from   w ww . j a va2  s  .  c om*/
            continue;
        }
        if (!"jar".equals(artifact.getType())) {
            continue;
        }
        if (projectGroupId.equals(artifact.getGroupId())) {
            continue;
        }

        if (log.isDebugEnabled()) {
            log.debug("Artifact: " + artifact);
        }
        String bundleName = null;
        try {
            bundleName = BundleUtil.getBundleSymbolicName(artifact.getFile());
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
        if (bundleName == null || true) {
            if (artifact.getFile().exists()) {
                log.info("Adding third party jar: " + artifact);
                jarFiles.add(artifact.getFile());
            } else {
                log.warn("Third party jar not found: " + artifact);
            }
        }
    }

    try {
        String version = BundleUtil.osgiVersion(project.getVersion());

        Manifest mf = BundleUtil.libraryManifest(jarFiles, project.getName(), symbolicName, version, "lib");
        File file = new File(project.getBasedir(), "META-INF");
        file.mkdir();
        file = new File(file, "MANIFEST.MF");
        if (log.isDebugEnabled()) {
            log.debug("Generating " + file);
        }

        FileOutputStream fos = new FileOutputStream(file);
        write(mf, fos);
        fos.close();

        File lib = new File(project.getBasedir(), "lib");
        if (lib.isDirectory()) {
            for (File c : lib.listFiles()) {
                c.delete();
            }
        }
        lib.mkdir();
        byte[] buf = new byte[4096];
        for (File jar : jarFiles) {
            File jarFile = new File(lib, jar.getName());
            if (log.isDebugEnabled()) {
                log.debug("Copying " + jar + " to " + jarFile);
            }
            FileInputStream in = new FileInputStream(jar);
            FileOutputStream out = new FileOutputStream(jarFile);
            for (;;) {
                int len = in.read(buf);
                if (len > 0) {
                    out.write(buf, 0, len);
                } else {
                    break;
                }
            }
            in.close();
            out.close();
        }
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.boretti.drools.integration.drools5.DroolsClassProcessor.java

License:Open Source License

public static void postProcess(Log log, File inputDirectory, String extension, File reportDirectory,
        String reportFile, String[] includes, String[] excludes) throws MojoExecutionException {
    DroolsGoalExecutionLogs dgel = new DroolsGoalExecutionLogs();
    DirectoryScanner scanner = new DirectoryScanner();
    if (!inputDirectory.exists()) {
        log.warn("Skipping not existing directory " + inputDirectory);
        return;//from  w  ww .  ja  v  a  2s.c o m
    }
    scanner.setBasedir(inputDirectory);
    if (includes == null || includes.length == 0) {
        scanner.setIncludes(new String[] { "**/*" + extension, "*" + extension });
    } else {
        log.info("Included files are " + Arrays.toString(includes));
        scanner.setIncludes(includes);
    }
    if (excludes != null && excludes.length != 0) {
        log.info("Excluded files are " + Arrays.toString(excludes));
        scanner.setExcludes(excludes);
    }
    log.info("Files must ends with " + extension + " to be processed");
    scanner.scan();
    for (String file : scanner.getIncludedFiles()) {
        if (!file.endsWith(extension))
            continue;
        File sfile = new File(inputDirectory, file);
        DroolsClassProcessor.ClassProcessor(log, sfile, dgel);
    }
    try {
        dgel.writeMeToFile(new File(reportDirectory, reportFile));
    } catch (IOException e) {
        log.error("Unable to write report :" + e.getMessage(), e);
        throw new MojoExecutionException("" + e.getMessage(), e);
    } catch (JAXBException e) {
        log.error("Unable to write report :" + e.getMessage(), e);
        throw new MojoExecutionException("" + e.getMessage(), e);
    }
}