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

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

Introduction

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

Prototype

void error(Throwable error);

Source Link

Document

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

Usage

From source file:net.sf.junite2.JUnitEEMojo.java

License:Apache License

public void execute() throws MojoExecutionException {

    JUnitEETest jeetest = new JUnitEETest();

    jeetest.setRunall(runAll);/*  ww  w  . j av  a 2 s  . co  m*/

    File f = outputDirectory;

    if (!f.exists()) {
        f.mkdirs();
    }

    File touch = new File(f, outfile);

    jeetest.setOutfile(touch.getAbsolutePath());

    FormatterElement xmlformat = new FormatterElement();

    xmlformat.setType("xml");

    jeetest.addFormatter(xmlformat);

    FormatterElement txtformat = new FormatterElement();

    txtformat.setType("plain");

    jeetest.addFormatter(txtformat);

    try {
        execute(jeetest);

    } catch (MojoExecutionException me) {
        throw me;

    } catch (Exception e) {
        e.printStackTrace();
        Log log = getLog();
        log.error(e);
        throw new MojoExecutionException(e.getMessage());

    }

}

From source file:net.sf.junite2.JUnitEEMojo.java

License:Apache License

protected void execute(JUnitEETest test) throws Exception {
    StringBuffer arguments = new StringBuffer();
    boolean done;
    String sessionCookie;//from w  ww .j  a  v a2 s. c om
    URL requestUrl;
    URLConnection con;
    Log log = getLog();

    arguments.append(url).append("?output=xml");

    if (threaded) {
        log.debug("Threaded mode");
        arguments.append("&thread=true");
    }

    if (test.getResource() != null) {
        arguments.append("&resource=").append(test.getResource());
    }
    if (test.getRunall()) {
        arguments.append("&all=true");
    } else if (test.getName() != null) {
        arguments.append("&suite=").append(URLEncoder.encode(test.getName()));
    } else {
        throw new Exception("You must specify the test name or runall attribute");
    }
    if (!test.getFiltertrace()) {
        arguments.append("&filterTrace=false");
    }

    log.debug("url is " + arguments.toString());

    InputStream in = null;
    requestUrl = new URL(arguments.toString());

    try {

        con = requestUrl.openConnection();
        sessionCookie = con.getHeaderField("Set-Cookie");
        log.debug("Session cookie : " + sessionCookie);

        if (sessionCookie != null) {
            int index = sessionCookie.indexOf(';');
            if (index != -1) {
                sessionCookie = sessionCookie.substring(0, index);
            }
        }
        in = con.getInputStream();
        done = parseResult(in, test);
    } catch (MojoExecutionException me) {
        throw me;
    } catch (Exception e) {

        throw new Exception("Error accessing url " + requestUrl.toString(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }

    try {
        while (!done) {
            try {
                log.debug("Sleeping ... ");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // continue work
            }
            //log("Get xml again using URL " + requestUrl, Project.MSG_DEBUG);
            con = requestUrl.openConnection();
            if (sessionCookie != null) {
                con.setRequestProperty("Cookie", sessionCookie);
            }
            in = con.getInputStream();
            try {
                done = parseResult(in, test);

            } catch (MojoExecutionException me) {
                throw me;
            } catch (Throwable thr) {
                log.debug(thr);
                throw new MojoExecutionException(thr.getMessage());
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }

    } catch (Exception e) {
        log.error("Failed to execute test: " + e.getMessage());
        throw new Exception(e);
    }
}

From source file:net.sf.junite2.JUnitEEMojo.java

License:Apache License

private boolean parseResult(InputStream in, JUnitEETest test) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Log log = getLog();

    Document document;//from w  w  w . ja  v  a  2  s  .com
    byte[] buffer = readInput(in);

    try {
        document = builder.parse(new ByteArrayInputStream(buffer));
    } catch (SAXException e) {
        log.error("Invalid xml:\n " + new String(buffer));

        throw new Exception("Unable to parse test result (no valid xml).");
    }

    Element root = document.getDocumentElement();
    if (root.getAttributeNode("unfinished") != null) {
        log.debug(String.valueOf(root.getAttributeNode("unfinished")));
        return false;
    }
    root.normalize();

    NodeList testcases = root.getElementsByTagName("testsuite");
    Vector resultFormatters = createFormatters(test);

    log.debug("Found " + testcases.getLength() + " testsuites");

    if (testcases.getLength() <= 0) {
        log.debug("No testsuites found " + new String(buffer));
        throw new MojoExecutionException("No testsuites found!");
    }

    int failure_count = 0;
    int error_count = 0;

    for (int i = 0; i < testcases.getLength(); i++) {
        Node node = testcases.item(i);
        NamedNodeMap attributes = node.getAttributes();
        String testClass = attributes.getNamedItem("name").getNodeValue();
        String testPkg = attributes.getNamedItem("package").getNodeValue();
        int errors = Integer.parseInt(attributes.getNamedItem("errors").getNodeValue());
        int failures = Integer.parseInt(attributes.getNamedItem("failures").getNodeValue());
        String testName;

        if (testPkg != null && testPkg.length() != 0) {
            testName = testPkg + "." + testClass;
        } else {
            testName = testClass;
        }
        Enumeration enumeration = resultFormatters.elements();

        while (enumeration.hasMoreElements()) {
            JUnitEEResultFormatter formatter = (JUnitEEResultFormatter) enumeration.nextElement();
            log.debug("Calling formatter " + formatter + " for node " + node);
            formatter.format(node);
            formatter.flush();
        }

        if (errors != 0) {
            error_count += errors;

        }
        if (failures != 0) {
            failure_count += failures;
        }

    }

    NodeList errorMessages = root.getElementsByTagName("errorMessage");

    for (int i = 0; i < errorMessages.getLength(); i++) {
        Node message = errorMessages.item(i);
        log.debug(message.getFirstChild().getNodeValue());
    }
    if (errorMessages.getLength() != 0) {
        throw new MojoExecutionException("Test execution failed.");
    }

    if (error_count > 0)
        throw new MojoExecutionException(error_count + " errors occured");

    if (failure_count > 0)
        throw new MojoExecutionException(failure_count + " failures occured");

    return true;
}

From source file:net.sourceforge.mavenhippo.FileManager.java

License:Apache License

private void createSourceRootFolder(File sourceRoot, Log log) throws FileManagerException {
    if (sourceRoot.mkdirs()) {
        log.info("sourceRoot folder was created at \"" + sourceRoot.getAbsolutePath() + "\"");
    } else {/*from   w  w w . j a  v a 2 s .c om*/
        log.error("Could not create the source root file. It is probably caused by lack of permissions.");
        throw new FileManagerException("Could not create the source root.");
    }
}

From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java

License:Apache License

/**
 * Gets the template locations./* w  w w  . j  a va2s .c  o m*/
 *
 * @return the template locations
 */
private Iterator<Entry<String, String>> getTemplateLocations() {
    final Log log = this.getLog();
    List<Resource> resList = this.resources;

    if (resList.isEmpty()) {
        log.info("No resource element was specified, using short configuration.");
        // If no resources specified, create a resource based on the other
        // parameters and defaults
        final Resource resource = new Resource();
        resource.source = new FileSet();

        if (this.sassSourceDirectory != null) {
            log.debug("Setting source directory: " + this.sassSourceDirectory.toString());
            resource.source.setDirectory(this.sassSourceDirectory.toString());
        } else {
            log.error("\"" + this.sassSourceDirectory + "\" is not a directory.");
            resource.source.setDirectory("./src/main/sass");
        }
        if (this.includes != null) {
            log.debug("Setting includes: " + Arrays.toString(this.includes));
            resource.source.setIncludes(Arrays.asList(this.includes));
        }
        if (this.excludes != null) {
            log.debug("Setting excludes: " + Arrays.toString(this.excludes));
            resource.source.setExcludes(Arrays.asList(this.excludes));
        }
        resource.relativeOutputDirectory = this.relativeOutputDirectory;
        resource.destination = this.destination;
        resList = ImmutableList.of(resource);
    }

    final List<Entry<String, String>> locations = new ArrayList<Entry<String, String>>();
    for (final Resource source : resList) {
        for (final Entry<String, String> entry : source.getDirectoriesAndDestinations(log).entrySet()) {
            log.info("Queueing Sass template for compile: " + entry.getKey() + " => " + entry.getValue());
            locations.add(entry);
        }
    }
    return locations.iterator();
}

From source file:nl.geodienstencentrum.maven.plugin.sass.report.SCSSLintMojo.java

License:Apache License

/**
 * Execute the lint script.//from www.ja v  a  2s  .c  om
 *
 * @see org.apache.maven.plugin.Mojo#execute()
 * @throws MojoExecutionException when the execution of the plugin
 *         errored
 * @throws MojoFailureException when the Sass compilation fails
 *
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.isSkip()) {
        return;
    }
    final Log log = this.getLog();

    // create directory
    this.outputFile.getParentFile().mkdirs();

    log.info("Linting Sass sources in: " + this.getSassSourceDirectory());

    final StringBuilder sassScript = new StringBuilder();
    this.buildBasicSassScript(sassScript);

    log.debug("scss-lint ruby script:\n" + sassScript);

    System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe");
    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby");
    ScriptContext context = jruby.getContext();

    ArrayList<String> argv = new ArrayList<>();
    argv.add("--format=Checkstyle");
    argv.add("-o" + this.outputFile);
    // argv.add("--config " + get config from some params,);
    argv.addAll(this.getSourceDirs());
    // this.getSassSourceDirectory().getPath()
    context.setAttribute(ScriptEngine.ARGV, argv.toArray(new String[argv.size()]), ScriptContext.GLOBAL_SCOPE);
    try {
        log.info("Reporting scss lint in: " + this.outputFile.getAbsolutePath());
        ExitCode result = ExitCode
                .getExitCode(Ints.checkedCast((Long) jruby.eval(sassScript.toString(), context)));
        log.debug("scss-lint result: " + result.toString());
        switch (result) {
        case CODE_0:
            log.info(result.msg());
            break;
        case CODE_1:
            log.warn(result.msg());
            break;
        case CODE_2:
            log.error(result.toString());
            if (this.failOnError) {
                throw new MojoFailureException(result.toString());
            }
        case CODE_64:
            // fall through
        case CODE_66:
            // fall through
        case CODE_70:
            // fall through
        case CODE_78:
            // fall through
        default:
            log.error(result.toString());
            throw new MojoExecutionException(result.toString());
        }
    } catch (final ScriptException e) {
        throw new MojoExecutionException("Failed to execute scss-lint Ruby script:\n" + sassScript, e);
    }
}

From source file:nl.geodienstencentrum.maven.plugin.sass.Resource.java

License:Apache License

/**
 * Gets the source directories and target destinations.
 *
 * @param log//from  w w  w.ja  v  a  2 s  .  com
 *            the maven logging instance to use for messages
 * @return the directories and destinations, may be an empty map if the
 *            source does not exist.
 */
public Map<String, String> getDirectoriesAndDestinations(final Log log) {
    final File sourceDirectory = new File(this.source.getDirectory());
    final Map<String, String> result = new LinkedHashMap<>();

    if (!sourceDirectory.exists()) {
        log.error("Specified sourcedirectory (" + sourceDirectory + ") does not exist.");
        return result;
    }

    // Scan for directories
    final DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(sourceDirectory);
    scanner.setIncludes(this.source.getIncludes().toArray(new String[this.source.getIncludes().size()]));
    scanner.setExcludes(this.source.getExcludes().toArray(new String[this.source.getExcludes().size()]));

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

    result.put(FilenameUtils.separatorsToUnix(sourceDirectory.toString()),
            FilenameUtils.separatorsToUnix(this.destination.toString()));

    for (final String included : scanner.getIncludedDirectories()) {
        if (!included.isEmpty()) {
            final String subdir = StringUtils.difference(sourceDirectory.toString(), included);

            final File sourceDir = new File(sourceDirectory, included);

            File destDir = new File(this.destination, subdir);
            if (this.relativeOutputDirectory != null && !this.relativeOutputDirectory.isEmpty()) {
                destDir = new File(destDir, this.relativeOutputDirectory);
            }

            result.put(FilenameUtils.separatorsToUnix(sourceDir.toString()),
                    FilenameUtils.separatorsToUnix(destDir.toString()));
        }
    }

    return result;
}

From source file:org.acmsl.dockerfile.maven.DockerfileMojo.java

License:Open Source License

/**
 * Executes Dockerfile Maven Plugin.//  w w w .j a v a2  s.  c  o  m
 * @param log the Maven log.
 * @param version the Dockerfile Maven Plugin version.
 * @throws MojoExecutionException if the process fails.
 */
protected void execute(@NotNull final Log log, final String version) throws MojoExecutionException {
    boolean running = false;

    @Nullable
    final File outputDirPath = getOutputDir();

    if (outputDirPath != null) {
        //initialize directories
        @NotNull
        final File outputDir = outputDirPath.getAbsoluteFile();

        if ((!outputDir.exists()) && (!outputDir.mkdirs())) {
            log.warn("Cannot create output folder: " + outputDir);
        }

        log.info("Running Dockerfile Maven Plugin " + version);

        running = true;
    } else {
        log.error("outputDir is null");
    }

    if (!running) {
        log.error("NOT running Dockerfile Maven Plugin " + version);
        throw new MojoExecutionException("Dockerfile Maven Plugin could not start");
    }
}

From source file:org.acmsl.queryj.tools.maven.AntProjectAdapter.java

License:Open Source License

/**
 * See {@link Project#log(String)}.//w w w. j  av  a2 s . c  om
 * @param message the message.
 * @param msgLevel either {@link Project#MSG_ERR}, {@link Project#MSG_WARN},
 * {@link Project#MSG_INFO}, {@link Project#MSG_VERBOSE}, or {@link Project#MSG_DEBUG}.
 * @param log the {@link Log} instance.
 */
protected void log(@NotNull final String message, final int msgLevel, @NotNull final Log log) {
    switch (msgLevel) {
    case MSG_ERR:
        log.error(message);
        break;
    case MSG_WARN:
        log.warn(message);
        break;
    case MSG_VERBOSE:
    case MSG_DEBUG:
        log.debug(message);
        break;
    default:
        log.info(message);
        break;
    }
}

From source file:org.acmsl.queryj.tools.maven.AntProjectAdapter.java

License:Open Source License

/**
 * See {@link Project#log(Task, String, int)}.
 * @param task the task.//from  w  ww. j a  va 2s  . c o m
 * @param message the message.
 * @param msgLevel either {@link Project#MSG_ERR}, {@link Project#MSG_WARN},
 * {@link Project#MSG_INFO}, {@link Project#MSG_VERBOSE}, or {@link Project#MSG_DEBUG}.
 * @param log the {@link Log} instance.
 */
protected void log(@NotNull final Task task, @NotNull final String message, final int msgLevel,
        @NotNull final Log log) {
    @NotNull
    final String t_strMessage = "[" + task.getTaskName() + "] " + message;

    switch (msgLevel) {
    case MSG_ERR:
        log.error(t_strMessage);
        break;
    case MSG_WARN:
        log.warn(t_strMessage);
        break;
    case MSG_VERBOSE:
    case MSG_DEBUG:
        log.debug(t_strMessage);
        break;
    default:
        log.info(t_strMessage);
        break;
    }
}