Example usage for org.apache.maven.plugin MojoExecutionException MojoExecutionException

List of usage examples for org.apache.maven.plugin MojoExecutionException MojoExecutionException

Introduction

In this page you can find the example usage for org.apache.maven.plugin MojoExecutionException MojoExecutionException.

Prototype

public MojoExecutionException(String message, Throwable cause) 

Source Link

Document

Construct a new MojoExecutionException exception wrapping an underlying Throwable and providing a message.

Usage

From source file:com.alibaba.maven.plugin.springext.SpringExtExecMojo.java

License:Open Source License

public void execute() throws MojoExecutionException, MojoFailureException {
    try {/* w ww. j av a2 s  .c o  m*/
        ClassLoader cl = createClassLoader();
        String[] args = createArgs();

        if (getLog().isDebugEnabled()) {
            StringBuffer msg = new StringBuffer();

            msg.append("Invoking : ").append(mainClass).append(".main(");

            for (int i = 0; i < args.length; i++) {
                if (i > 0) {
                    msg.append(", ");
                }

                msg.append(args[i]);
            }

            msg.append(")");

            getLog().debug(msg.toString());
        }

        run(cl, mainClass, args);
    } catch (Exception e) {
        throw new MojoExecutionException("Failure: " + e.getClass().getName() + " " + e.getMessage(), e);
    }
}

From source file:com.alibaba.maven.plugin.springext.SpringExtRunnerMojo.java

License:Open Source License

public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*from   ww w  .j  av  a2 s  .  c  o m*/
        getLog().info("Configuring Jetty for project: " + getCurrentProject().getName());

        Server server = createServer();
        Connector connector = createConnector();

        getLog().debug(
                "Setting Connector: " + connector.getClass().getName() + " on port " + connector.getPort());

        server.setConnectors(new Connector[] { connector });
        server.setHandler(createHandler());

        server.start();

        getLog().info("Started Jetty Server");

        server.join();
    } catch (Exception e) {
        throw new MojoExecutionException("Failure: " + e.getClass().getName() + " " + e.getMessage(), e);
    } finally {
        getLog().info("Jetty server exiting.");
    }
}

From source file:com.all4tec.sa.maven.proguard.ProGuardMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    log = getLog();/*ww w .ja  v  a  2  s .co m*/

    if (skip) {
        log.info("Bypass ProGuard processing because \"proguard.skip=true\"");
        return;
    }

    boolean mainIsJar = mavenProject.getPackaging().equals("jar");
    boolean mainIsPom = mavenProject.getPackaging().equals("pom");

    File inJarFile = new File(outputDirectory, injar);
    if (mainIsJar && (!inJarFile.exists())) {
        if (injarNotExistsSkip) {
            log.info("Bypass ProGuard processing because \"injar\" dos not exist");
            return;
        }
        throw new MojoFailureException("Can't find file " + inJarFile);
    }

    if (mainIsPom && (!inJarFile.exists()) && injarNotExistsSkip) {
        log.info("Bypass ProGuard processing because \"injar\" dos not exist");
        return;
    }

    if (!outputDirectory.exists()) {
        if (!outputDirectory.mkdirs()) {
            throw new MojoFailureException("Can't create " + outputDirectory);
        }
    }

    File outJarFile;
    boolean sameArtifact;

    if (attach) {
        outjar = nameNoType(injar);
        if (useArtifactClassifier()) {
            outjar += "-" + attachArtifactClassifier;
        }
        outjar += "." + attachArtifactType;
    }

    if ((outjar != null) && (!outjar.equals(injar))) {
        sameArtifact = false;
        outJarFile = (new File(outputDirectory, outjar)).getAbsoluteFile();
        if (outJarFile.exists()) {
            if (!deleteFileOrDirectory(outJarFile)) {
                throw new MojoFailureException("Can't delete " + outJarFile);
            }
        }
    } else {
        sameArtifact = true;
        outJarFile = inJarFile.getAbsoluteFile();
        File baseFile;
        if (inJarFile.isDirectory()) {
            baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_base");
        } else {
            baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_base.jar");
        }
        if (baseFile.exists()) {
            if (!deleteFileOrDirectory(baseFile)) {
                throw new MojoFailureException("Can't delete " + baseFile);
            }
        }
        if (inJarFile.exists()) {
            if (!inJarFile.renameTo(baseFile)) {
                throw new MojoFailureException("Can't rename " + inJarFile);
            }
        }
        inJarFile = baseFile;
    }

    ArrayList<String> args = new ArrayList<String>();

    if (log.isDebugEnabled()) {
        List dependancy = mavenProject.getCompileArtifacts();
        for (Iterator i = dependancy.iterator(); i.hasNext();) {
            Artifact artifact = (Artifact) i.next();
            log.debug("--- compile artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
                    + artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
        }
        for (Iterator i = mavenProject.getArtifacts().iterator(); i.hasNext();) {
            Artifact artifact = (Artifact) i.next();
            log.debug("--- artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
                    + artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
        }
        for (Iterator i = mavenProject.getDependencies().iterator(); i.hasNext();) {
            Dependency artifact = (Dependency) i.next();
            log.debug("--- dependency " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
                    + artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
        }
    }

    Set inPath = new HashSet();
    boolean hasInclusionLibrary = false;
    if (assembly != null) {
        for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
            Inclusion inc = (Inclusion) iter.next();
            if (!inc.library) {
                File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
                inPath.add(file.toString());
                log.debug("--- ADD injars:" + inc.artifactId);
                StringBuffer filter = new StringBuffer(fileToString(file));
                filter.append("(!META-INF/MANIFEST.MF");
                if (!addMavenDescriptor) {
                    filter.append(",");
                    filter.append("!META-INF/maven/**");
                }
                if (inc.filter != null) {
                    filter.append(",").append(inc.filter);
                }
                filter.append(")");
                args.add("-injars");
                args.add(filter.toString());
            } else {
                hasInclusionLibrary = true;
                log.debug("--- ADD libraryjars:" + inc.artifactId);
                // This may not be CompileArtifacts, maven 2.0.6 bug
                File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
                inPath.add(file.toString());
                args.add("-libraryjars");
                args.add(fileToString(file));
            }
        }
    }

    if ((!mainIsPom) && inJarFile.exists()) {
        args.add("-injars");
        StringBuffer filter = new StringBuffer(fileToString(inJarFile));
        if ((inFilter != null) || (!addMavenDescriptor)) {
            filter.append("(");
            boolean coma = false;

            if (!addMavenDescriptor) {
                coma = true;
                filter.append("!META-INF/maven/**");
            }

            if (inFilter != null) {
                if (coma) {
                    filter.append(",");
                }
                filter.append(inFilter);
            }

            filter.append(")");
        }
        args.add(filter.toString());
    }
    args.add("-outjars");
    args.add(fileToString(outJarFile));

    if (!obfuscate) {
        args.add("-dontobfuscate");
    }

    if (proguardInclude != null) {
        if (proguardInclude.exists()) {
            args.add("-include");
            args.add(fileToString(proguardInclude));
            log.debug("proguardInclude " + proguardInclude);
        } else {
            log.debug("proguardInclude config does not exists " + proguardInclude);
        }
    }

    if (includeDependency) {
        List dependency = this.mavenProject.getCompileArtifacts();
        for (Iterator i = dependency.iterator(); i.hasNext();) {
            Artifact artifact = (Artifact) i.next();
            // dependency filter
            if (isExclusion(artifact)) {
                continue;
            }
            File file = getClasspathElement(artifact, mavenProject);

            if (inPath.contains(file.toString())) {
                log.debug("--- ignore libraryjars since one in injar:" + artifact.getArtifactId());
                continue;
            }
            log.debug("--- ADD libraryjars:" + artifact.getArtifactId());
            args.add("-libraryjars");
            args.add(fileToString(file));
        }
    }

    if (libs != null) {
        for (Iterator i = libs.iterator(); i.hasNext();) {
            Object lib = i.next();
            args.add("-libraryjars");
            args.add(fileNameToString(lib.toString()));
        }
    }

    args.add("-printmapping");
    args.add(fileToString((new File(outputDirectory, "proguard_map.txt").getAbsoluteFile())));

    args.add("-printseeds");
    args.add(fileToString((new File(outputDirectory, "proguard_seeds.txt").getAbsoluteFile())));

    if (log.isDebugEnabled()) {
        args.add("-verbose");
    }

    if (options != null) {
        for (int i = 0; i < options.length; i++) {
            args.add(options[i]);
        }
    }

    // Check if args should be inlined in a proguard configuration file or not. If args total size is more than 32k,
    // process launch will failed
    File vTempFile = null;
    if (writeCommandLineToFile) {
        log.info("Transform command line in file configuration");
        vTempFile = createFileConfiguration(args, mavenProject, outputDirectory);

        // Remove all args, and add just path to Proguard configuration file just created
        args.clear();
        args.add("@" + vTempFile.getAbsolutePath());
        log.info("Configuration file created : " + vTempFile.getAbsolutePath());
    }

    log.info("execute ProGuard " + args.toString());

    proguardMain(getProguardJar(this), args, this);

    if ((assembly != null) && (hasInclusionLibrary)) {

        log.info("creating assembly");

        File baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_result.jar");
        if (baseFile.exists()) {
            if (!baseFile.delete()) {
                throw new MojoFailureException("Can't delete " + baseFile);
            }
        }
        File archiverFile = outJarFile.getAbsoluteFile();
        if (!outJarFile.renameTo(baseFile)) {
            throw new MojoFailureException("Can't rename " + outJarFile);
        }

        MavenArchiver archiver = new MavenArchiver();
        archiver.setArchiver(jarArchiver);
        archiver.setOutputFile(archiverFile);
        archive.setAddMavenDescriptor(addMavenDescriptor);

        try {
            jarArchiver.addArchivedFileSet(baseFile);

            for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
                Inclusion inc = (Inclusion) iter.next();
                if (inc.library) {
                    File file;
                    Artifact artifact = getDependancy(inc, mavenProject);
                    file = getClasspathElement(artifact, mavenProject);
                    if (file.isDirectory()) {
                        getLog().info("merge project: " + artifact.getArtifactId() + " " + file);
                        jarArchiver.addDirectory(file);
                    } else {
                        getLog().info("merge artifact: " + artifact.getArtifactId());
                        jarArchiver.addArchivedFileSet(file);
                    }
                }
            }

            archiver.createArchive(mavenProject, archive);

        } catch (Exception e) {
            throw new MojoExecutionException("Unable to create jar", e);
        }

    }

    if (attach && !sameArtifact) {
        if (useArtifactClassifier()) {
            projectHelper.attachArtifact(mavenProject, attachArtifactType, attachArtifactClassifier,
                    outJarFile);
        } else {
            projectHelper.attachArtifact(mavenProject, attachArtifactType, null, outJarFile);
        }
    }
}

From source file:com.all4tec.sa.maven.proguard.ProGuardMojo.java

License:Apache License

/**
 * Create a temporary file and fill it with Proguard configuration.
 * //from  w ww .  ja  va 2s . c  om
 * @param pArgsList List of args to push in Proguard configuration file
 * @param pMavenProject current project
 * @exception MojoExecutionException Exception throw if problem occurs on file creation
 */
private static File createFileConfiguration(List<String> pArgsList, MavenProject pMavenProject,
        File pOutputDirectory) throws MojoExecutionException {
    File vTempFile = null;

    try {
        String vFileName = pMavenProject.getName() + "arguments-inlining.proguardconf";

        vTempFile = new File(pOutputDirectory.getAbsolutePath(), vFileName);

        Writer vWriter = new BufferedWriter(new FileWriter(vTempFile));

        // Get iterator
        Iterator<String> vArgsIterator = pArgsList.iterator();

        // Iterate and add each line with a space behind
        while (vArgsIterator.hasNext()) {
            String vNextArg = vArgsIterator.next();
            vWriter.write(vNextArg + " ");
        }

        IOUtils.closeQuietly(vWriter);

    } catch (IOException pException) {
        throw new MojoExecutionException("Unable to create proguard configuration file ", pException);
    }

    return vTempFile;
}

From source file:com.amazonaws.generator.scala.GeneratorMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException {
    try {/* ww  w .j a v a 2s . c  o m*/
        generateClient();
    } catch (Exception e) {
        throw new MojoExecutionException("Generation failed", e);
    }

    project.addCompileSourceRoot(baseDir.getPath());
}

From source file:com.anite.maven.plugin.hivedoc.HivedocReport.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    try {/*w w  w  .j a  va  2 s. c o  m*/
        // Construct the registry and output the XML File 
        ModuleDescriptorProvider provider = new XmlModuleDescriptorProvider(
                new DefaultClassResolver(getClassLoader()));

        Dom4JRegistrySerializer serializer = new Dom4JRegistrySerializer();
        serializer.addModuleDescriptorProvider(provider);

        Document result = serializer.createRegistryDocument();

        // Run the XSL over it to generate Hivedoc
        File outputFolder = new File(project.getReporting().getOutputDirectory() + "/hivedoc");
        outputFolder.mkdirs();
        File outputFile = new File(outputFolder, "index.html");
        DocumentSource registryDocument = new DocumentSource(result);
        Source xsltFile = new StreamSource(this.getClass().getClassLoader().getResourceAsStream(XSLT_FILE));
        Result output = new StreamResult(new FileOutputStream(outputFile));

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer trans = transformerFactory.newTransformer(xsltFile);
        trans.setParameter("base.dir", outputFolder.getAbsolutePath());

        trans.transform(registryDocument, output);

        // Copy the resources to the output folder
        copyResouceDir("private.png", outputFolder);
        copyResouceDir("public.png", outputFolder);
        copyResouceDir("hivemind.css", outputFolder);

    } catch (MalformedURLException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    } catch (DependencyResolutionRequiredException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    } catch (FileNotFoundException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    } catch (TransformerConfigurationException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    } catch (TransformerException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    } catch (ClassCastException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    } catch (IOException e) {
        this.getLog().error(e);
        throw new MojoExecutionException("", e);
    }
}

From source file:com.anthemengineering.mojo.infer.InferMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {
    if (inferDir == null) {
        inferDir = new File(System.getProperty(USER_DIR), DEFAULT_MAVEN_BUILD_DIR_NAME).getAbsolutePath();
    }/*ww  w.j  av a  2 s . c o  m*/

    if (inferPath != null && !INFER_CMD_NAME.equals(inferPath)) {
        getLog().info(String.format("Infer path set to: %s", inferPath));
    }
    // check if infer is on the PATH and if not, then download it.
    if (inferPath == null && download) {
        inferPath = downloadInfer(new File(inferDir, INFER_DOWNLOAD_DIRETORY_NAME));
    } else if (inferPath == null) {
        inferPath = inferCommand;
    }

    try {
        // get source directory, if it doesn't exist then we're done
        final File sourceDir = new File(project.getBuild().getSourceDirectory());

        if (!sourceDir.exists()) {
            return;
        }

        final File inferOutputDir = getInferOutputDir();

        final SimpleSourceInclusionScanner scanner = new SimpleSourceInclusionScanner(
                Collections.singleton("**/*.java"), Collections.<String>emptySet());
        scanner.addSourceMapping(new SuffixMapping(JAVA_SRC_EXTENSION, Collections.<String>emptySet()));
        final Collection<File> sourceFiles = scanner.getIncludedSources(sourceDir, null);

        final int numSourceFiles = sourceFiles.size();
        fileCount += numSourceFiles;

        final String classpath = getRuntimeAndCompileClasspath();

        completeInferExecutions(classpath, inferOutputDir, sourceFiles, numSourceFiles);

        reportResults(inferOutputDir, numSourceFiles);
    } catch (final DependencyResolutionRequiredException e) {
        getLog().error(e);
        throw new MojoExecutionException("Unable to get required dependencies to perform Infer check!", e);
    } catch (final InclusionScanException e) {
        getLog().error(e);
        throw new MojoExecutionException("Failed to get sources! Cannot complete Infer check", e);
    }
}

From source file:com.anthemengineering.mojo.infer.InferMojo.java

License:Apache License

/**
 * Gets/Creates the directory where Infer output will be written.
 *
 * @return the directory where Infer output will be written
 * @throws MojoExecutionException if the Infer output directory cannot be created
 *//*from   ww  w .  j av  a2 s .c om*/
private File getInferOutputDir() throws MojoExecutionException {
    // infer output to build dir of project maven was run from
    final File outputDir = new File(inferDir, INFER_OUTPUT_DIRECTORY_NAME);
    try {
        FileUtils.forceMkdir(outputDir);
    } catch (final IOException e) {
        getLog().error(e);
        throw new MojoExecutionException("Exception occurred trying to generate output directory for Infer!",
                e);
    }

    return outputDir;
}

From source file:com.anthemengineering.mojo.infer.InferMojo.java

License:Apache License

/**
 * Executes infer once for each source file and writes the output to {@code inferOutputDir}.
 *
 * @param classpath classpath used as an argument to the javac command given to Infer.
 * @param inferOutputDir directory where Infer will write its output
 * @param sourceFiles collection of files for Infer to analyze
 * @param numSourceFiles number of source files to analyze; used to make sure every Infer execution finishes
 * before moving on.//from   w  w  w.j a v a  2 s.  c  o  m
 */
private void completeInferExecutions(final String classpath, final File inferOutputDir,
        Collection<File> sourceFiles, int numSourceFiles) throws MojoExecutionException {
    // temporary directory for storing .class files created by {@code javac}; placed in build directory
    final File buildTmpDir = new File(project.getBuild().getDirectory(), JAVAC_OUTPUT_DIRECTORY_NAME);
    try {
        FileUtils.forceMkdir(buildTmpDir);
    } catch (final IOException e) {
        final String errMsg = String.format("Unable to make temp directory %s!", buildTmpDir.getAbsolutePath());
        getLog().error(errMsg, e);
        throw new MojoExecutionException(errMsg, e);
    }
    buildTmpDir.deleteOnExit();

    // used to wait for all processes running infer to complete
    final CountDownLatch doneSignal = new CountDownLatch(numSourceFiles);

    // TODO: optionally allow debugging info? Output directory?

    // TODO: a better way to do this may be to determine if there is an entry point that takes a set of source
    //  files and the classpath and use this. @See mvn, inferj and inferlib in the infer repository.

    ExecutorService pool = null;
    try {
        pool = Executors.newFixedThreadPool(4);

        for (final File sourceFile : sourceFiles) {
            final Runnable r = new Runnable() {
                @Override
                public void run() {
                    Process proc = null;

                    try {
                        // infer
                        final List<String> command = new ArrayList<String>();
                        command.add(inferPath);
                        command.add("-i");
                        command.add("-o");
                        command.add(inferOutputDir.getAbsolutePath());

                        command.add("--");

                        // javac
                        command.add("javac");
                        command.add(sourceFile.getAbsolutePath());
                        command.add("-d");
                        command.add(buildTmpDir.getAbsolutePath());
                        command.add("-classpath");
                        command.add(classpath);

                        final ProcessBuilder builder = new ProcessBuilder(command);
                        builder.environment().putAll(System.getenv());

                        if (consoleOut) {
                            builder.redirectErrorStream(true);
                            proc = builder.start();

                            InputStreamReader isr = null;
                            BufferedReader br = null;
                            InputStream pis = null;

                            try {
                                pis = proc.getInputStream();

                                isr = new InputStreamReader(pis);
                                br = new BufferedReader(isr);
                                String line = null;
                                while ((line = br.readLine()) != null) {
                                    getLog().info(line);
                                }
                            } catch (final IOException e) {
                                getLog().error(String.format("Error writing process output for file: %s.",
                                        sourceFile.getAbsolutePath()), e);
                            } finally {
                                if (isr != null) {
                                    isr.close();
                                }

                                if (br != null) {
                                    br.close();
                                }

                                if (pis != null) {
                                    pis.close();
                                }
                            }
                        } else {
                            // no logging.
                            proc = builder.start();
                        }

                        // NOTE: most/all executions end in failure during analysis, however,
                        // supported java bugs are still reported
                        proc.waitFor();
                    } catch (final IOException e) {
                        getLog().error(
                                "Exception occurred while trying to perform Infer execution; output not complete"
                                        + "",
                                e);
                    } catch (final InterruptedException e) {
                        getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e);
                    } finally {
                        try {
                            // currently they all fail, although java bugs are still reported
                            if (proc != null && proc.exitValue() != 0) {
                                FAILED_CHECKS.put(sourceFile, proc.exitValue());
                            }
                        } catch (final Exception e) {
                            FAILED_CHECKS.put(sourceFile, -1);
                        }
                        doneSignal.countDown();
                    }
                }
            };

            pool.submit(r);
        }
    } finally {
        if (pool != null) {
            pool.shutdown();
        }
    }
    try {
        doneSignal.await();
    } catch (final InterruptedException e) {
        getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e);
    }
}

From source file:com.antwerkz.sofia.SofiaMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();//  ww  w  . j  ava 2s .  c  o  m
    }
    try {
        generate();
        project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}