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

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

Introduction

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

Prototype

void debug(Throwable error);

Source Link

Document

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

Usage

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

License:Apache License

public static void addIdeaDefaults(Log log, boolean useIdeaDefaultExcludes, final Set<String> excludeList) {
    if (useIdeaDefaultExcludes) {
        log.debug("Adding exclusions often needed by projects " + "developed in IDEA...");
        excludeList.addAll(IDEA_DEFAULT_EXCLUDES);
    } else {/*from w  ww  .  ja  v a2s.c o m*/
        log.debug("rat.useIdeaDefaultExcludes set to false. "
                + "Exclusions often needed by projects developed in " + "IDEA will not be added.");
    }
}

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 .  j a  v a 2s.  com*/
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);
                }//from   w w  w .j a  v a  2s.  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.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

/**
 * Build the XAR using the provided archiver.
 *
 * @throws MojoExecutionException//  w  w  w. j ava  2  s . c o m
 */
protected void buildArchive(Archiver archiver) throws ArchiverException, MojoExecutionException {

    Log log = getLog();
    log.debug("Using base directory: " + baseDir);
    archiver.addDirectory(buildOutputDirectory);
    if (includeDependencies) {
        log.debug("Adding dependencies ...");
        addDependencies(archiver);
    }
    if (generateMetadata) {
        log.debug("Generating XAR metadata ...");
        generateMetadata(archiver);
    }
}

From source file:org.apache.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

private void generateMetadata(Archiver archiver) throws ArchiverException, MojoExecutionException {

    Log log = getLog();
    File tmpServicesDir = new File(new File(tmpDirectory, "META-INF"), "services");
    File buildServicesDir = new File(new File(buildOutputDirectory, "META-INF"), "services");
    if (!tmpServicesDir.mkdirs()) {
        throw new MojoExecutionException("Error while creating the directory: " + tmpServicesDir.getPath());
    }/*www. jav a  2 s . com*/

    log.debug("Initializing class scanner ...");
    ClassScanner scanner = new ClassScanner(buildOutputDirectory);
    for (Artifact artifact : filterArtifacts(project.getArtifacts(),
            new ScopeArtifactFilter(Artifact.SCOPE_COMPILE))) {
        scanner.addToClasspath(artifact.getFile());
    }
    List<ServiceLocator> serviceLocators = new ArrayList<ServiceLocator>(serviceClassNames.length);
    for (String serviceClassName : serviceClassNames) {
        // If the user provided its own service file, skip generation
        File file = new File(buildServicesDir, serviceClassName);
        if (file.exists()) {
            log.debug(file + " exists; don't scan for " + serviceClassName + " implementation");
        } else {
            ServiceLocator sl = new ServiceLocator(serviceClassName);
            serviceLocators.add(sl);
            scanner.addVisitor(sl);
        }
    }
    try {
        scanner.scan();
    } catch (ClassScannerException e) {
        throw new MojoExecutionException("Failed to scan classes for services", e);
    }
    for (ServiceLocator sl : serviceLocators) {
        File file = new File(tmpServicesDir, sl.getServiceClassName());
        if (!sl.getImplementations().isEmpty()) {
            String destFileName = "META-INF/services/" + sl.getServiceClassName();
            log.info("Generating " + destFileName);
            try {
                Writer out = new OutputStreamWriter(new FileOutputStream(file));
                try {
                    for (String impl : sl.getImplementations()) {
                        log.debug("  " + impl);
                        out.write(impl);
                        out.write("\n");
                    }
                } finally {
                    out.close();
                }
            } catch (IOException e) {
                throw new MojoExecutionException("Unable to create temporary file " + file, e);
            }
            archiver.addFile(file, destFileName);
        }
    }
}

From source file:org.apache.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

/**
 * Get the set of artifacts that are provided by Synapse at runtime.
 * //from w  w  w.  j a v  a2 s  .  co  m
 * @return
 * @throws MojoExecutionException
 */
private Set<Artifact> getSynapseRuntimeArtifacts() throws MojoExecutionException {
    Log log = getLog();
    log.debug("Looking for synapse-core artifact in XAR project dependencies ...");
    Artifact synapseCore = null;
    for (Iterator<?> it = project.getDependencyArtifacts().iterator(); it.hasNext();) {
        Artifact artifact = (Artifact) it.next();
        if (artifact.getGroupId().equals("org.apache.synapse")
                && artifact.getArtifactId().equals("synapse-core")) {
            synapseCore = artifact;
            break;
        }
    }
    if (synapseCore == null) {
        throw new MojoExecutionException("Could not locate dependency on synapse-core");
    }

    log.debug("Loading project data for " + synapseCore + " ...");
    MavenProject synapseCoreProject;
    try {
        synapseCoreProject = projectBuilder.buildFromRepository(synapseCore, remoteArtifactRepositories,
                localRepository);
    } catch (ProjectBuildingException e) {
        throw new MojoExecutionException("Unable to retrieve project information for " + synapseCore, e);
    }
    Set<Artifact> synapseRuntimeDeps;
    try {
        synapseRuntimeDeps = synapseCoreProject.createArtifacts(artifactFactory, Artifact.SCOPE_RUNTIME,
                new TypeArtifactFilter("jar"));
    } catch (InvalidDependencyVersionException e) {
        throw new MojoExecutionException("Unable to get project dependencies for " + synapseCore, e);
    }
    log.debug("Direct runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    log.debug("Resolving transitive dependencies for " + synapseCore + " ...");
    try {
        synapseRuntimeDeps = artifactCollector.collect(synapseRuntimeDeps, synapseCoreProject.getArtifact(),
                synapseCoreProject.getManagedVersionMap(), localRepository, remoteArtifactRepositories,
                artifactMetadataSource, null, Collections.singletonList(new DebugResolutionListener(logger)))
                .getArtifacts();
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve transitive dependencies for " + synapseCore);
    }
    log.debug("All runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    return synapseRuntimeDeps;
}

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

License:Apache License

public static void aggregateBundles(Log log, File root, File[] files, File targetBundleFile, String bundleName,
        String bundleVersion) throws Exception {
    targetBundleFile.getParentFile().mkdirs();
    Set<File> jarFiles = new HashSet<File>();
    List<Manifest> manifests = new ArrayList<Manifest>();
    for (File child : files) {
        try {// w w w  .ja v a2s.  com
            Manifest manifest = null;
            if (child.isDirectory()) {
                File mf = new File(child, "META-INF/MANIFEST.MF");
                if (mf.isFile()) {
                    FileInputStream is = new FileInputStream(mf);
                    manifest = new Manifest(is);
                    is.close();
                    if (manifest != null) {
                        String classpath = manifest.getMainAttributes().getValue("Bundle-ClassPath");
                        if (classpath != null) {
                            for (HeaderClause clause : HeaderParser.parse(classpath)) {
                                if (clause.getValue().equals(".")) {
                                    continue;
                                } else {
                                    jarFiles.add(new File(child, clause.getValue()));
                                }
                            }
                        } else {
                            // 
                        }
                    }
                }
            } else if (child.getName().endsWith(".jar")) {
                JarFile jar = new JarFile(child);
                manifest = jar.getManifest();
                jar.close();
                if (manifest != null) {
                    String id = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                    if (id != null && (id.startsWith("org.eclipse.")
                            || id.startsWith("org.apache.tuscany.sca.gateway"))) {
                        manifest = null;
                    } else {
                        jarFiles.add(child);
                    }
                }
            }
            if (manifest == null) {
                continue;
            }

            log.debug("Bundle file: " + child);
            manifests.add(manifest);
        } catch (Exception e) {
            throw e;
        }
    }
    Manifest merged = new Manifest();
    Attributes attributes = merged.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0");
    attributes.putValue("Bundle-ManifestVersion", "2");
    attributes.putValue("Bundle-License", "http://www.apache.org/licenses/LICENSE-2.0.txt");
    attributes.putValue("Bundle-DocURL", "http://www.apache.org/");
    attributes.putValue("Bundle-RequiredExecutionEnvironment", "J2SE-1.5,JavaSE-1.6");
    attributes.putValue("Bundle-Vendor", "The Apache Software Foundation");
    attributes.putValue("Bundle-Version", bundleVersion);
    attributes.putValue("Bundle-SymbolicName", bundleName);
    attributes.putValue("SCA-Version", "1.1");
    attributes.putValue("Bundle-Name", bundleName);
    // attributes.putValue("Bundle-ActivationPolicy", "lazy");
    for (Manifest mf : manifests) {
        for (Map.Entry<Object, Object> e : mf.getMainAttributes().entrySet()) {
            Attributes.Name key = (Attributes.Name) e.getKey();
            String name = key.toString();
            String oldValue = attributes.getValue(name);
            String value = (String) e.getValue();
            if (name.equals("Export-Package") || name.equals("Import-Package") || name.equals("Require-Bundle")
                    || name.equals("DynamicImport-Package") || name.equals("Bundle-ClassPath")
                    || name.equals("Private-Package") || name.equals("Bundle-Description")) {
                attributes.putValue(name, merge(oldValue, value));
            } else if (name.equals(BUNDLE_ACTIVATOR)) {
                oldValue = attributes.getValue(BUNDLE_ACTIVATOR_LIST);
                attributes.putValue(BUNDLE_ACTIVATOR_LIST, merge(oldValue, value));
            } else if (name.equals("Main-Class") || name.startsWith("Eclipse-") || name.startsWith("Bundle-")) {
                // Ignore
            } else {
                // Ignore
                // attributes.putValue(name, value);
            }
        }
    }
    log.info("Generating " + targetBundleFile);
    attributes.putValue(BUNDLE_ACTIVATOR, AggregatedBundleActivator.class.getName());
    String bundleClassPath = attributes.getValue(BUNDLE_CLASSPATH);
    bundleClassPath = merge(bundleClassPath, ".");
    for (File f : jarFiles) {
        bundleClassPath = merge(bundleClassPath, f.getName());
    }
    attributes.putValue(BUNDLE_CLASSPATH, bundleClassPath);

    FileOutputStream fos = new FileOutputStream(targetBundleFile);
    JarOutputStream bundle = new JarOutputStream(fos, merged);

    for (File file : jarFiles) {
        log.info("Adding " + file);
        addEntry(bundle, file.getName(), file);
    }

    String classFile = AggregatedBundleActivator.class.getName().replace(".", "/") + ".class";
    InputStream classStream = BundleAggregatorMojo.class.getClassLoader().getResourceAsStream(classFile);
    addEntry(bundle, classFile, classStream);
    bundle.close();
}

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 w  w  .  j a v a2  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;
        }

        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.BundlesMetaDataBuildMojo.java

License:Apache License

private Set<Artifact> getDependencyArtifacts(MavenProject project)
        throws DependencyTreeBuilderException, ArtifactResolutionException, ArtifactNotFoundException {
    Log log = getLog();
    Set<Artifact> artifacts = new HashSet<Artifact>();
    ArtifactFilter artifactFilter = createResolvingArtifactFilter(Artifact.SCOPE_RUNTIME);

    // TODO: note that filter does not get applied due to MNG-3236

    DependencyNode rootNode = dependencyTreeBuilder.buildDependencyTree(project, local, factory,
            artifactMetadataSource, artifactFilter, artifactCollector);
    CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
    rootNode.accept(visitor);/*ww w . j a  va  2  s  .  c o m*/

    // Add included artifacts
    for (Object node : visitor.getNodes()) {
        DependencyNode depNode = (DependencyNode) node;
        int state = depNode.getState();
        if (state == DependencyNode.INCLUDED) {
            Artifact artifact = depNode.getArtifact();
            // Exclude the project artifact to avoid offline resolution failure
            if (!artifact.equals(project.getArtifact())) {
                resolver.resolve(artifact, remoteRepos, local);
                artifacts.add(artifact);
            }
        }
    }
    // Scan for newer versions that are omitted
    for (Object node : visitor.getNodes()) {
        DependencyNode depNode = (DependencyNode) node;
        int state = depNode.getState();
        if (state == DependencyNode.OMITTED_FOR_CONFLICT) {
            Artifact artifact = depNode.getArtifact();
            resolver.resolve(artifact, remoteRepos, local);
            if (state == DependencyNode.OMITTED_FOR_CONFLICT) {
                Artifact related = depNode.getRelatedArtifact();
                if (log.isDebugEnabled()) {
                    log.debug("Dependency node: " + depNode);
                }
                // Compare the version
                ArtifactVersion v1 = new DefaultArtifactVersion(artifact.getVersion());
                ArtifactVersion v2 = new DefaultArtifactVersion(related.getVersion());
                if (v1.compareTo(v2) > 0) {
                    // Only add newer version if it is omitted for conflict
                    if (artifacts.add(artifact)) {
                        log.info("Dependency node added: " + depNode);
                    }
                }
            }
        }
    }
    return artifacts;
}

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 .jav a2 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);
    }

}