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

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

Introduction

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

Prototype

boolean isDebugEnabled();

Source Link

Usage

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

License:Open Source License

public static PackageBuilder getPackageBuilder(Log logger, MavenProject project) throws MojoExecutionException {
    if (logger.isDebugEnabled())
        logger.debug("starting creation of package builder");
    ClassLoader loader = DroolsHelper.class.getClassLoader();
    List<?> classpathFiles = null;
    try {/*w w w.j ava  2 s .  c o m*/
        classpathFiles = project.getRuntimeClasspathElements();
    } catch (Exception e) {
        throw new MojoExecutionException("Error during build " + e.getMessage(), e);
    }
    URL[] urls = new URL[classpathFiles.size()];

    for (int i = 0; i < classpathFiles.size(); ++i) {
        try {
            urls[i] = new File((String) classpathFiles.get(i)).toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Error during build " + e.getMessage(), e);
        }
    }

    URLClassLoader ucl = new URLClassLoader(urls, loader);

    PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
    conf.setClassLoader(ucl);
    return new PackageBuilder(conf);
}

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

License:Open Source License

public static boolean compileSourceFile(Log logger, MavenProject project, File src, File dest, boolean xml,
        DroolsGoalExecutionLogs dgel) throws MojoExecutionException {
    if (logger.isDebugEnabled())
        logger.debug("starting compilation of source file " + src);
    PackageBuilder builder = getPackageBuilder(logger, project);
    try {/*  w ww  .  j  a v a 2 s. c om*/
        InputStreamReader instream = new InputStreamReader(new FileInputStream(src));
        if (xml)
            builder.addPackageFromXml(instream);
        else
            builder.addPackageFromDrl(instream);
        if (!validationError(logger, builder.getErrors(), src))
            return false;
        dest.getParentFile().mkdirs();
        Package dpackage = builder.getPackage();
        ObjectOutputStream outstream = new ObjectOutputStream(new FileOutputStream(dest));
        outstream.writeObject(dpackage);
        if (outstream != null)
            outstream.close();
        dgel.getLogs().add(new DroolsGoalExecutionLog(src.getAbsolutePath(), "compile",
                "Compiling file " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()));
        return true;
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException("Error because of file not found " + e.getMessage(), e);
    } catch (DroolsParserException e) {
        if (!validationError(logger, builder.getErrors(), src))
            return false;
        throw new MojoExecutionException("Error because of unexpected drools error " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error because of IO Error " + e.getMessage(), e);
    }
}

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

License:Open Source License

public static boolean validateSourceFile(Log logger, MavenProject project, File src, boolean xml,
        DroolsGoalExecutionLogs dgel) throws MojoExecutionException {
    if (logger.isDebugEnabled())
        logger.debug("starting validation of source file " + src);
    PackageBuilder builder = getPackageBuilder(logger, project);
    try {/*  w w  w  . ja v a 2 s  .c o m*/
        InputStreamReader instream = new InputStreamReader(new FileInputStream(src));
        if (xml)
            builder.addPackageFromXml(instream);
        else
            builder.addPackageFromDrl(instream);
        dgel.getLogs().add(new DroolsGoalExecutionLog(src.getAbsolutePath(), "validate",
                "Validate file " + src.getAbsolutePath()));
        return validationError(logger, builder.getErrors(), src);
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException("Error because of file not found " + e.getMessage(), e);
    } catch (DroolsParserException e) {
        if (!validationError(logger, builder.getErrors(), src))
            return false;
        throw new MojoExecutionException("Error because of unexpected drools error " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error because of IO Error " + e.getMessage(), e);
    }
}

From source file:org.bytedeco.javacpp.tools.BuildMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {
    final Log log = getLog();
    try {//ww  w  .  java  2 s .com
        if (log.isDebugEnabled()) {
            log.debug("classPath: " + classPath);
            log.debug("classPaths: " + Arrays.deepToString(classPaths));
            log.debug("includePath: " + includePath);
            log.debug("includePaths: " + Arrays.deepToString(includePaths));
            log.debug("linkPath: " + linkPath);
            log.debug("linkPaths: " + Arrays.deepToString(linkPaths));
            log.debug("preloadPath: " + preloadPath);
            log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths));
            log.debug("outputDirectory: " + outputDirectory);
            log.debug("outputName: " + outputName);
            log.debug("compile: " + compile);
            log.debug("deleteJniFiles: " + deleteJniFiles);
            log.debug("header: " + header);
            log.debug("copyLibs: " + copyLibs);
            log.debug("jarPrefix: " + jarPrefix);
            log.debug("properties: " + properties);
            log.debug("propertyFile: " + propertyFile);
            log.debug("propertyKeysAndValues: " + propertyKeysAndValues);
            log.debug("classOrPackageName: " + classOrPackageName);
            log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames));
            log.debug("environmentVariables: " + environmentVariables);
            log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions));
            log.debug("skip: " + skip);
        }

        if (skip) {
            log.info("Skipping execution of JavaCPP Builder");
            return;
        }

        classPaths = merge(classPaths, classPath);
        classOrPackageNames = merge(classOrPackageNames, classOrPackageName);

        Logger logger = new Logger() {
            @Override
            public void debug(String s) {
                log.debug(s);
            }

            @Override
            public void info(String s) {
                log.info(s);
            }

            @Override
            public void warn(String s) {
                log.warn(s);
            }

            @Override
            public void error(String s) {
                log.error(s);
            }
        };
        Builder builder = new Builder(logger).classPaths(classPaths).outputDirectory(outputDirectory)
                .outputName(outputName).compile(compile).deleteJniFiles(deleteJniFiles).header(header)
                .copyLibs(copyLibs).jarPrefix(jarPrefix).properties(properties).propertyFile(propertyFile)
                .properties(propertyKeysAndValues).classesOrPackages(classOrPackageNames)
                .environmentVariables(environmentVariables).compilerOptions(compilerOptions);
        Properties properties = builder.properties;
        log.info("Detected platform \"" + Loader.getPlatform() + "\"");
        log.info("Building for platform \"" + properties.get("platform") + "\"");
        String separator = properties.getProperty("platform.path.separator");
        for (String s : merge(includePaths, includePath)) {
            String v = properties.getProperty("platform.includepath", "");
            properties.setProperty("platform.includepath",
                    v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
        }
        for (String s : merge(linkPaths, linkPath)) {
            String v = properties.getProperty("platform.linkpath", "");
            properties.setProperty("platform.linkpath",
                    v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
        }
        for (String s : merge(preloadPaths, preloadPath)) {
            String v = properties.getProperty("platform.preloadpath", "");
            properties.setProperty("platform.preloadpath",
                    v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
        }
        Properties projectProperties = project.getProperties();
        for (String key : properties.stringPropertyNames()) {
            projectProperties.setProperty("javacpp." + key, properties.getProperty(key));
        }
        File[] outputFiles = builder.build();
        if (log.isDebugEnabled()) {
            log.debug("outputFiles: " + Arrays.deepToString(outputFiles));
        }
    } catch (IOException | ClassNotFoundException | NoClassDefFoundError | InterruptedException
            | ParserException e) {
        log.error("Failed to execute JavaCPP Builder: " + e.getMessage());
        throw new MojoExecutionException("Failed to execute JavaCPP Builder", e);
    }
}

From source file:org.codehaus.mojo.apt.AptUtils.java

License:Open Source License

public static boolean invokeForked(Log log, File workingDirectory, String executable, String meminitial,
        String maxmemory, List<String> args) throws MojoExecutionException {
    // create command

    Commandline cli = new Commandline();

    cli.setWorkingDirectory(workingDirectory.getAbsolutePath());
    log.debug("Using working directory " + cli.getWorkingDirectory());

    cli.setExecutable(executable);/*w w w.j  a v a  2  s .c o  m*/

    if (StringUtils.isNotEmpty(meminitial)) {
        cli.createArg().setValue("-J-Xms" + meminitial);
    }

    if (StringUtils.isNotEmpty(maxmemory)) {
        cli.createArg().setValue("-J-Xmx" + maxmemory);
    }

    // create arguments file

    File argsFile;

    try {
        argsFile = createArgsFile(args);

        String argsPath = argsFile.getCanonicalPath().replace(File.separatorChar, '/');
        cli.createArg().setValue("@" + argsPath);
    } catch (IOException exception) {
        throw new MojoExecutionException("Error creating arguments file", exception);
    }

    log.debug("Using argument file:");
    LogUtils.log(log, LogUtils.LEVEL_DEBUG, argsFile, "  ");

    // invoke apt

    if (log.isDebugEnabled()) {
        log.debug("Invoking apt with command " + cli);
    }

    StringStreamConsumer out = new StringStreamConsumer();
    StringStreamConsumer err = new StringStreamConsumer();

    int result;

    try {
        result = CommandLineUtils.executeCommandLine(cli, out, err);
    } catch (CommandLineException exception) {
        throw new MojoExecutionException("Error while executing the apt compiler", exception);
    }

    // log output

    LogUtils.log(log, LogUtils.LEVEL_INFO, new StringReader(out.getOutput()));
    LogUtils.log(log, LogUtils.LEVEL_WARN, new StringReader(err.getOutput()));

    // log result

    log.debug("Apt returned " + result);

    return (result == 0);
}

From source file:org.codehaus.mojo.apt.LogUtils.java

License:Open Source License

public static boolean isEnabled(Log log, int level) {
    boolean enabled;

    if (level == LEVEL_DEBUG) {
        enabled = log.isDebugEnabled();
    } else if (level == LEVEL_INFO) {
        enabled = log.isInfoEnabled();//from   www.j  av  a 2s  .c om
    } else if (level == LEVEL_WARN) {
        enabled = log.isWarnEnabled();
    } else if (level == LEVEL_ERROR) {
        enabled = log.isErrorEnabled();
    } else {
        throw new IllegalArgumentException("Unknown log level: " + level);
    }

    return enabled;
}

From source file:org.codehaus.mojo.cobertura.integration.LogLevel.java

License:Apache License

/**
 * Simple conversion method extracting the LogLevel matching the level
 * assigned to the supplied Log.// w w  w. j a  va 2s  . c  om
 *
 * @param mavenLog The non-null Log instance.
 * @return The LogLevel matching the existing level of the supplied mavenLog.
 */
public static LogLevel getMatchingLevel(final Log mavenLog) {

    // Check sanity
    Validate.notNull(mavenLog, "Cannot handle null mavenLog argument.");

    LogLevel toReturn;
    if (mavenLog.isDebugEnabled()) {
        toReturn = LogLevel.DEBUG;
    } else if (mavenLog.isInfoEnabled()) {
        toReturn = LogLevel.INFO;
    } else if (mavenLog.isWarnEnabled()) {
        toReturn = LogLevel.WARNING;
    } else {
        toReturn = LogLevel.ERROR;
    }

    // All done.
    return toReturn;
}

From source file:org.codehaus.mojo.jaxb2.AbstractJaxbMojo.java

License:Apache License

/**
 * {@inheritDoc}//  w  w w  .j  av  a 2 s .c om
 */
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {

    // 0) Get the log and its relevant level
    final Log log = getLog();
    final boolean isDebugEnabled = log.isDebugEnabled();
    final boolean isInfoEnabled = log.isInfoEnabled();

    // 1) Should we skip execution?
    if (shouldExecutionBeSkipped()) {

        if (isDebugEnabled) {
            log.debug("Skipping execution, as instructed.");
        }
        return;
    }

    // 2) Printout relevant version information.
    if (isDebugEnabled) {
        logPluginAndJaxbDependencyInfo();
    }

    // 3) Are generated files stale?
    if (isReGenerationRequired()) {

        if (performExecution()) {

            // As instructed by the performExecution() method, update
            // the timestamp of the stale File.
            updateStaleFileTimestamp();

            // Hack to support M2E
            buildContext.refresh(getOutputDirectory());

        } else if (isInfoEnabled) {
            log.info("Not updating staleFile timestamp as instructed.");
        }
    } else if (isInfoEnabled) {
        log.info("No changes detected in schema or binding files - skipping JAXB generation.");
    }

    // 4) If the output directories exist, add them to the MavenProject's source directories
    if (getOutputDirectory().exists() && getOutputDirectory().isDirectory()) {

        final String canonicalPathToOutputDirectory = FileSystemUtilities
                .getCanonicalPath(getOutputDirectory());

        if (log.isDebugEnabled()) {
            log.debug("Adding existing JAXB outputDirectory [" + canonicalPathToOutputDirectory
                    + "] to Maven's sources.");
        }

        // Add the output Directory.
        getProject().addCompileSourceRoot(canonicalPathToOutputDirectory);
    }
}

From source file:org.codehaus.mojo.jaxb2.helpers.SchemagenHelper.java

License:Apache License

/**
 * Replaces all namespaces within generated schema files, as instructed by the configured Schema instances.
 *
 * @param resolverMap                The map relating generated schema file name to
 *                                   SimpleNamespaceResolver instances.
 * @param configuredTransformSchemas The Schema instances read from the configuration of this plugin.
 * @param mavenLog                   The active Log.
 * @param schemaDirectory            The directory where all generated schema files reside.
 * @throws MojoExecutionException If the namespace replacement could not be done.
 *///from   w w w .  j  a va 2s. c  o  m
public static void replaceNamespacePrefixes(final Map<String, SimpleNamespaceResolver> resolverMap,
        final List<TransformSchema> configuredTransformSchemas, final Log mavenLog, final File schemaDirectory)
        throws MojoExecutionException {
    if (mavenLog.isDebugEnabled()) {
        mavenLog.debug("Got resolverMap.keySet() [generated filenames]: " + resolverMap.keySet());
    }

    for (SimpleNamespaceResolver currentResolver : resolverMap.values()) {

        File generatedSchemaFile = new File(schemaDirectory, currentResolver.getSourceFilename());
        Document generatedSchemaFileDocument = null;

        for (TransformSchema currentTransformSchema : configuredTransformSchemas) {

            // Should we alter the namespace prefix as instructed by the current schema?
            final String newPrefix = currentTransformSchema.getToPrefix();
            final String currentUri = currentTransformSchema.getUri();

            if (StringUtils.isNotEmpty(newPrefix)) {

                // Find the old/current prefix of the namespace for the current schema uri.
                final String oldPrefix = currentResolver.getNamespaceURI2PrefixMap().get(currentUri);

                if (StringUtils.isNotEmpty(oldPrefix)) {

                    // Can we perform the prefix substitution?
                    validatePrefixSubstitutionIsPossible(oldPrefix, newPrefix, currentResolver);

                    if (mavenLog.isDebugEnabled()) {
                        mavenLog.debug("Subtituting namespace prefix [" + oldPrefix + "] with [" + newPrefix
                                + "] in file [" + currentResolver.getSourceFilename() + "].");
                    }

                    // Get the Document of the current schema file.
                    if (generatedSchemaFileDocument == null) {
                        generatedSchemaFileDocument = parseXmlToDocument(generatedSchemaFile);
                    }

                    // Replace all namespace prefixes within the provided document.
                    process(generatedSchemaFileDocument.getFirstChild(), true,
                            new ChangeNamespacePrefixProcessor(oldPrefix, newPrefix));
                }
            }
        }

        if (generatedSchemaFileDocument != null) {
            // Overwrite the generatedSchemaFile with the content of the generatedSchemaFileDocument.
            mavenLog.debug("Overwriting file [" + currentResolver.getSourceFilename() + "] with content ["
                    + getHumanReadableXml(generatedSchemaFileDocument) + "]");
            savePrettyPrintedDocument(generatedSchemaFileDocument, generatedSchemaFile);
        } else {
            mavenLog.debug("No namespace prefix changes to generated schema file ["
                    + generatedSchemaFile.getName() + "]");
        }
    }
}

From source file:org.codehaus.mojo.jaxb2.helpers.SchemagenHelper.java

License:Apache License

/**
 * Updates all schemaLocation attributes within the generated schema files to match the 'file'
 * properties within the Schemas read from the plugin configuration. After that, the files are
 * physically renamed./*w w w. j  a  va 2s  .co m*/
 *
 * @param resolverMap                The map relating generated schema file name to
 *                                   SimpleNamespaceResolver instances.
 * @param configuredTransformSchemas The Schema instances read from the configuration of this plugin.
 * @param mavenLog                   The active Log.
 * @param schemaDirectory            The directory where all generated schema files reside.
 */
public static void renameGeneratedSchemaFiles(final Map<String, SimpleNamespaceResolver> resolverMap,
        final List<TransformSchema> configuredTransformSchemas, final Log mavenLog,
        final File schemaDirectory) {
    // Create the map relating namespace URI to desired filenames.
    Map<String, String> namespaceUriToDesiredFilenameMap = new TreeMap<String, String>();
    for (TransformSchema current : configuredTransformSchemas) {
        if (StringUtils.isNotEmpty(current.getToFile())) {
            namespaceUriToDesiredFilenameMap.put(current.getUri(), current.getToFile());
        }
    }

    // Replace the schemaLocation values to correspond to the new filenames
    for (SimpleNamespaceResolver currentResolver : resolverMap.values()) {
        File generatedSchemaFile = new File(schemaDirectory, currentResolver.getSourceFilename());
        Document generatedSchemaFileDocument = parseXmlToDocument(generatedSchemaFile);

        // Replace all namespace prefixes within the provided document.
        process(generatedSchemaFileDocument.getFirstChild(), true,
                new ChangeFilenameProcessor(namespaceUriToDesiredFilenameMap));

        // Overwrite the generatedSchemaFile with the content of the generatedSchemaFileDocument.
        if (mavenLog.isDebugEnabled()) {
            mavenLog.debug("Changed schemaLocation entries within [" + currentResolver.getSourceFilename()
                    + "]. " + "Result: [" + getHumanReadableXml(generatedSchemaFileDocument) + "]");
        }
        savePrettyPrintedDocument(generatedSchemaFileDocument, generatedSchemaFile);
    }

    // Now, rename the actual files.
    for (SimpleNamespaceResolver currentResolver : resolverMap.values()) {
        final String newFilename = namespaceUriToDesiredFilenameMap.get(currentResolver.getLocalNamespaceURI());
        final File originalFile = new File(schemaDirectory, currentResolver.getSourceFilename());

        if (StringUtils.isNotEmpty(newFilename)) {
            File renamedFile = FileUtils.resolveFile(schemaDirectory, newFilename);
            String renameResult = (originalFile.renameTo(renamedFile) ? "Success " : "Failure ");

            if (mavenLog.isDebugEnabled()) {
                String suffix = "renaming [" + originalFile.getAbsolutePath() + "] to [" + renamedFile + "]";
                mavenLog.debug(renameResult + suffix);
            }
        }
    }
}