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.agilejava.docbkx.maven.AbstractTransformerMojo.java

License:Apache License

/**
 * Creates an instance of an XPath expression for picking the title from a document.
 *
 * @return An XPath expression to pick the title from a document.
 * @throws MojoExecutionException If the XPath expression cannot be parsed.
 *///w  w  w. jav  a 2s  .  co m
protected XPath createTitleXPath() throws MojoExecutionException {
    try {
        StringBuffer builder = new StringBuffer();
        builder.append(
                "(article/title|article/articleinfo/title|book/title|book/bookinfo/title)[position()=1]");
        return new DOMXPath(builder.toString());
    } catch (JaxenException je) {
        throw new MojoExecutionException("Failed to parse XPath.", je);
    }
}

From source file:com.agilejava.docbkx.maven.AbstractTransformerMojo.java

License:Apache License

/**
 * Configures and executes the given ant tasks, mainly preprocess and postprocess defined in the pom configuration.
 *
 * @param antTasks The tasks to execute//from  w  w  w.  ja  v a  2  s. co m
 * @param mavenProject The current maven project
 * @throws MojoExecutionException If something wrong occurs while executing the ant tasks.
 */
protected void executeTasks(Target antTasks, MavenProject mavenProject) throws MojoExecutionException {
    try {
        ExpressionEvaluator exprEvaluator = (ExpressionEvaluator) antTasks.getProject()
                .getReference("maven.expressionEvaluator");
        Project antProject = antTasks.getProject();
        PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(antProject);
        propertyHelper.setNext(new AntPropertyHelper(exprEvaluator, getLog()));
        DefaultLogger antLogger = new DefaultLogger();
        antLogger.setOutputPrintStream(System.out);
        antLogger.setErrorPrintStream(System.err);
        antLogger.setMessageOutputLevel(2);
        antProject.addBuildListener(antLogger);
        antProject.setBaseDir(mavenProject.getBasedir());
        Path p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getArtifacts().iterator(), File.pathSeparator));
        antProject.addReference("maven.dependency.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.compile.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getRuntimeClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.runtime.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(mavenProject.getTestClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.test.classpath", p);
        List artifacts = getArtifacts();
        List list = new ArrayList(artifacts.size());
        File file;
        for (Iterator i = artifacts.iterator(); i.hasNext(); list.add(file.getPath())) {
            Artifact a = (Artifact) i.next();
            file = a.getFile();
            if (file == null)
                throw new DependencyResolutionRequiredException(a);
        }

        p = new Path(antProject);
        p.setPath(StringUtils.join(list.iterator(), File.pathSeparator));
        antProject.addReference("maven.plugin.classpath", p);
        getLog().info("Executing tasks");
        antTasks.execute();
        getLog().info("Executed tasks");
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing ant tasks", e);
    }
}

From source file:com.agilejava.docbkx.maven.AbstractWebhelpMojo.java

License:Apache License

/**
 * DOCUMENT ME!/*from ww  w . j  a v  a2s  .c  om*/
 *
 * @throws MojoExecutionException DOCUMENT ME!
 */
protected void copyTemplate() throws MojoExecutionException {
    try {
        if (templateDirectory == null) {
            getLog().debug("Copying template from docbook xsl release");

            this.copyCommonFromXslRelease();
            this.copySearchFromXslRelease();

        } else {
            getLog().debug("Copying template from custom directory: " + templateDirectory.getAbsolutePath());
            FileUtils.copyResourcesRecursively(templateDirectory.toURL(), targetBaseDir);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to copy template", e);
    }
}

From source file:com.agilejava.docbkx.maven.AbstractWebhelpMojo.java

License:Apache License

protected void copyCommonFromXslRelease() throws MojoExecutionException {
    try {// w  w w  .j av a2  s  .  c o m
        URL url = this.getClass().getClassLoader().getResource("docbook/webhelp/template/common");
        FileUtils.copyResourcesRecursively(url, new File(targetBaseDir, "common"));
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to copy common template from XSL release", e);
    }
}

From source file:com.agilejava.docbkx.maven.AbstractWebhelpMojo.java

License:Apache License

protected void copySearchFromXslRelease() throws MojoExecutionException {
    try {/*from w  w  w  .j a va  2  s.c om*/
        this.copyOneSearchItemFromXslRelease("nwSearchFnt.js");
        this.copyOneSearchItemFromXslRelease("stemmers/" + "en_stemmer.js");
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to copy search template from XSL release", e);
    }
}

From source file:com.agilejava.maven.docbkx.GeneratorMojo.java

License:Apache License

/**
 * Generate the source code of the plugin supporting the {@link #type}.
 *
 * @throws MojoExecutionException//from  www  . ja  v  a2s . c o  m
 *             If we fail to generate the source code.
 */
private void generateSourceCode() throws MojoExecutionException {
    File sourcesDir = new File(targetDirectory, getPackageName().replace('.', '/'));

    try {
        FileUtils.forceMkdir(sourcesDir);
    } catch (IOException ioe) {
        throw new MojoExecutionException("Can't create directory for sources.", ioe);
    }

    ClassLoader loader = this.getClass().getClassLoader();
    InputStream in = loader.getResourceAsStream("plugins.stg");
    Reader reader = new InputStreamReader(in, Charset.forName(encoding));
    StringTemplateGroup group = new StringTemplateGroup(reader);
    StringTemplate template = group.getInstanceOf("plugin");
    File targetFile = new File(sourcesDir, getClassName() + ".java");
    Specification specification = null;

    try {
        specification = createSpecification();
        getLog().info("Number of parameters: " + specification.getParameters().size());
        template.setAttribute("spec", specification);
        FileUtils.writeStringToFile(targetFile, template.toString(), encoding);
    } catch (IOException ioe) {
        if (specification == null) {
            throw new MojoExecutionException("Failed to read parameters.", ioe);
        } else {
            throw new MojoExecutionException("Failed to create " + targetFile + ".", ioe);
        }
    }

    project.addCompileSourceRoot(targetDirectory.getAbsolutePath());
}

From source file:com.agilejava.maven.docbkx.GeneratorMojo.java

License:Apache License

/**
 * Returns a String version of the URL pointing the specific file in the
 * distribution. (Note that the filename passed in is expected to leave out
 * the version specific directory name. It will be included by this
 * operation.)/*from  w ww.j  a v a2 s.  co m*/
 *
 * @param filename
 *            The filename for which we need a URL.
 * @return A URL pointing to the specific filename.
 * @throws MojoExecutionException
 *             If we can't create a URL from the filename passed in.
 */
private String createURL(String filename) throws MojoExecutionException {
    try {
        StringBuilder builder = new StringBuilder();
        builder.append("jar:");
        builder.append(distribution.toURL().toExternalForm());
        builder.append("!/");
        builder.append(sourceRootDirectory);
        builder.append(filename);

        return builder.toString();
    } catch (MalformedURLException mue) {
        throw new MojoExecutionException("Failed to construct URL for " + filename + ".", mue);
    }
}

From source file:com.agilejava.maven.docbkx.GeneratorMojo.java

License:Apache License

/**
 * Returns a {@link Collection} of all parameter names defined in the
 * stylesheet or in one of the stylesheets imported or included in the
 * stylesheet./* w  w  w  .  j  a v a 2  s . co m*/
 *
 * @param url
 *            The location of the stylesheet to analyze.
 * @return A {@link Collection} of all parameter names found in the
 *         stylesheet pinpointed by the <code>url</code> argument.
 *
 * @throws MojoExecutionException
 *             If the operation fails to detect parameter names.
 */
private Collection getParameterNames(String url) throws MojoExecutionException {
    ByteArrayOutputStream out = null;

    try {
        Transformer transformer = createParamListTransformer();
        Source source = new StreamSource(url);
        out = new ByteArrayOutputStream();

        Result result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        if (out.size() != 0) {
            // at least one param has been found, because the split with return an empty string if there is no data
            String[] paramNames = new String(out.toByteArray()).split("\n");
            return new HashSet(Arrays.asList(paramNames));
        } else {
            // else no param found
            return new HashSet();
        }
    } catch (IOException ioe) {
        // Impossible, but let's satisfy PMD and FindBugs
        getLog().warn("Failed to flush ByteArrayOutputStream.");
    } catch (TransformerConfigurationException tce) {
        throw new MojoExecutionException("Failed to create Transformer for retrieving parameter names", tce);
    } catch (TransformerException te) {
        throw new MojoExecutionException("Failed to apply Transformer for retrieving parameter names.", te);
    } finally {
        IOUtils.closeQuietly(out);
    }

    return Collections.EMPTY_SET;
}

From source file:com.akathist.maven.plugins.launch4j.Launch4jMojo.java

License:Open Source License

public void execute() throws MojoExecutionException {
    if (getLog().isDebugEnabled())
        printState();//from  w  ww  .j  a  v  a2  s .  co  m

    Config c = new Config();

    c.setHeaderType(headerType);
    c.setOutfile(outfile);
    c.setJar(getJar());
    c.setDontWrapJar(dontWrapJar);
    c.setErrTitle(errTitle);
    c.setDownloadUrl(downloadUrl);
    c.setSupportUrl(supportUrl);
    c.setCmdLine(cmdLine);
    c.setChdir(chdir);
    c.setPriority(priority);
    c.setStayAlive(stayAlive);
    c.setManifest(manifest);
    c.setIcon(icon);
    c.setHeaderObjects(objs);
    c.setLibs(libs);
    c.setVariables(vars);

    if (classPath != null) {
        c.setClassPath(classPath.toL4j(dependencies));
    }
    if (jre != null) {
        c.setJre(jre.toL4j());
    }
    if (singleInstance != null) {
        c.setSingleInstance(singleInstance.toL4j());
    }
    if (splash != null) {
        c.setSplash(splash.toL4j());
    }
    if (versionInfo != null) {
        c.setVersionInfo(versionInfo.toL4j());
    }
    if (messages != null) {
        c.setMessages(messages.toL4j());
    }

    ConfigPersister.getInstance().setAntConfig(c, getBaseDir());
    File workdir = setupBuildEnvironment();
    Builder b = new Builder(new MavenLog(getLog()), workdir);

    try {
        b.build();
    } catch (BuilderException e) {
        getLog().error(e);
        throw new MojoExecutionException("Failed to build the executable; please verify your configuration.",
                e);
    }
}

From source file:com.akathist.maven.plugins.launch4j.Launch4jMojo.java

License:Open Source License

/**
 * Unzips the given artifact in-place and returns the newly-unzipped top-level directory.
 * Writes a marker file to prevent unzipping more than once.
 *//*  w  w  w  . ja v  a2s.  com*/
private File unpackWorkDir(Artifact a) throws MojoExecutionException {
    String version = a.getVersion();
    File platJar = a.getFile();
    File dest = platJar.getParentFile();
    File marker = new File(dest, platJar.getName() + ".unpacked");

    // If the artifact is a SNAPSHOT, then a.getVersion() will report the long timestamp,
    // but getFile() will be 1.1-SNAPSHOT.
    // Since getFile() doesn't use the timestamp, all timestamps wind up in the same place.
    // Therefore we need to expand the jar every time, if the marker file is stale.
    if (marker.exists() && marker.lastModified() > platJar.lastModified()) {
        // if (marker.exists() && marker.platJar.getName().indexOf("SNAPSHOT") == -1) {
        getLog().info("Platform-specific work directory already exists: " + dest.getAbsolutePath());
    } else {
        JarFile jf = null;
        try {
            // trying to use plexus-archiver here is a miserable waste of time:
            jf = new JarFile(platJar);
            Enumeration en = jf.entries();
            while (en.hasMoreElements()) {
                JarEntry je = (JarEntry) en.nextElement();
                File outFile = new File(dest, je.getName());
                File parent = outFile.getParentFile();
                if (parent != null)
                    parent.mkdirs();
                if (je.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    InputStream in = jf.getInputStream(je);
                    byte[] buf = new byte[1024];
                    int len;
                    FileOutputStream fout = null;
                    try {
                        fout = new FileOutputStream(outFile);
                        while ((len = in.read(buf)) >= 0) {
                            fout.write(buf, 0, len);
                        }
                        fout.close();
                        fout = null;
                    } finally {
                        if (fout != null) {
                            try {
                                fout.close();
                            } catch (IOException e2) {
                            } // ignore
                        }
                    }
                    outFile.setLastModified(je.getTime());
                }
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Error unarchiving " + platJar, e);
        } finally {
            try {
                if (jf != null)
                    jf.close();
            } catch (IOException e) {
            } // ignore
        }

        try {
            marker.createNewFile();
            marker.setLastModified(new Date().getTime());
        } catch (IOException e) {
            getLog().warn("Trouble creating marker file " + marker, e);
        }
    }

    String n = platJar.getName();
    File workdir = new File(dest, n.substring(0, n.length() - 4));
    setPermissions(workdir);
    return workdir;
}