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

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

Introduction

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

Prototype

boolean isWarnEnabled();

Source Link

Usage

From source file:apparat.embedding.maven.MavenLogAdapter.java

License:Open Source License

/**
 * Maps the level of a given Maven log to a corresponding
 * Apparat log level.//from  w w  w . j  a  v a 2  s .  c o m
 *
 * @param log The current Maven log.
 * @return The corresponding Apparat log level.
 */
public static LogLevel mapLevelOf(final org.apache.maven.plugin.logging.Log log) {
    //
    // We return an instance of a Scala case object here.
    //

    if (log.isDebugEnabled()) {
        return Debug$.MODULE$;
    } else if (log.isInfoEnabled()) {
        return Info$.MODULE$;
    } else if (log.isWarnEnabled()) {
        return Warning$.MODULE$;
    } else if (log.isErrorEnabled()) {
        return Error$.MODULE$;
    } else {
        return Off$.MODULE$;
    }
}

From source file:com.edugility.jpa.maven.plugin.ListEntityClassnamesMojo.java

License:Open Source License

/**
 * Returns a {@link Set} of {@link URL}s that represents the test
 * classpath./*from  ww w .j ava  2  s .  c  om*/
 *
 * <p>This uses the {@linkplain #getProject() associated
 * <tt>MavenProject</tt>} to {@linkplain
 * MavenProject#getTestClasspathElements() supply the information}.
 * If that {@link MavenProject} is {@code null}, then an {@linkplain
 * Collection#isEmpty() empty} {@linkplain
 * Collections#unmodifiableSet(Set) unmodifiable <tt>Set</tt>} is
 * returned.</p>
 *
 * <p>{@link String}-to-{@link URL} conversion is accomplished like
 * this:</p>
 *
 * <ul>
 *
 * <li>The {@link MavenProject#getTestClasspathElements()} method
 * returns an untyped {@link List}.  There is no contractual
 * guarantee about the type of its contents.  Each element is
 * therefore treated as an {@link Object}.</li>
 *
 * <li>If the element is non-{@code null}, then its {@link
 * Object#toString()} method is invoked.  The resulting {@link
 * String} is used to {@linkplain File#File(String) construct a
 * <tt>File</tt>}.</li>
 *
 * <li>The resulting {@link File}'s {@link File#toURI()} method is
 * invoked and the {@linkplain URI result}'s {@link URI#toURL()}
 * method is invoked.  The return value is added to the {@link Set}
 * that will be returned.</li>
 *
 * </ul>
 *
 * <p>This method never returns {@code null}.</p>
 *
 * @return a {@link Set} of {@link URL}s representing the test
 * classpath, never {@code null}.  The {@link Set}'s iteration order
 * is guaranteed to be equal to that of the iteration order of the
 * return value of the {@link
 * MavenProject#getTestClasspathElements()} method.
 *
 * @exception DependencyResolutionRequiredException if the {@link
 * MavenProject#getTestClasspathElements()} method throws a {@link
 * DependencyResolutionRequiredException}
 */
private final Set<URL> getTestClasspathURLs() throws DependencyResolutionRequiredException {
    final Set<URL> urls;

    final Log log = this.getLog();
    assert log != null;

    final MavenProject project = this.getProject();
    final List<?> classpathElements;
    if (project == null) {
        classpathElements = null;
    } else {
        classpathElements = project.getTestClasspathElements();
    }

    if (classpathElements == null || classpathElements.isEmpty()) {
        if (log.isWarnEnabled()) {
            log.warn(String
                    .format("The test classpath contained no elements. Consequently no Entities were found."));
        }
        urls = Collections.emptySet();
    } else {
        final Set<URL> mutableUrls = new LinkedHashSet<URL>(classpathElements.size());
        for (final Object o : classpathElements) {
            if (o != null) {
                final File file = new File(o.toString());
                if (file.canRead()) {
                    try {
                        mutableUrls.add(file.toURI().toURL());
                    } catch (final MalformedURLException wontHappen) {
                        throw (InternalError) new InternalError(String.format(
                                "While attempting to convert a file, %s, into a URL, a MalformedURLException was encountered.",
                                file)).initCause(wontHappen);
                    }
                } else if (log.isWarnEnabled()) {
                    log.warn(String.format("The test classpath element %s could not be read.", file));
                }
            }
        }
        if (mutableUrls.isEmpty()) {
            urls = Collections.emptySet();
        } else {
            urls = Collections.unmodifiableSet(mutableUrls);
        }
    }
    if (log.isWarnEnabled() && urls.isEmpty()) {
        log.warn(String.format("No URLs were found from the test classpath (%s).", classpathElements));
    }
    return urls;
}

From source file:com.edugility.jpa.maven.plugin.ListEntityClassnamesMojo.java

License:Open Source License

/**
 * Executes this mojo./* w  w w.j  a  v  a 2  s.  co m*/
 *
 * @exception MojoExecutionException if this mojo could not be executed
 *
 * @exception MojoFailureException if the build should fail
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    final Log log = this.getLog();
    if (log == null) {
        throw new MojoExecutionException("this.getLog() == null");
    }

    try {
        this.initialize();
    } catch (final DependencyResolutionRequiredException kaboom) {
        throw new MojoExecutionException(String.format(
                "Dependencies of the current Maven project could not be downloaded during initialization of the jpa-maven-plugin."),
                kaboom);
    } catch (final NotWritableDirectoryException kaboom) {
        throw new MojoExecutionException(String.format(
                "The output directory path, %s, exists and is a directory, but the current user, %s, cannot write to it.",
                kaboom.getFile(), System.getProperty("user.name")), kaboom);
    } catch (final NotWritableFileException kaboom) {
        throw new MojoExecutionException(String.format(
                "The outputFile specified, %s, is a regular file, but cannot be written to by Maven running as user %s.  The outputFile parameter must designate either an existing, writable file or a non-existent file.",
                outputFile, System.getProperty("user.name")), kaboom);
    } catch (final NotNormalFileException kaboom) {
        throw new MojoExecutionException(String.format(
                "The outputFile specified, %s, is not a directory, but is also not a normal file.  The outputFile parameter must deisgnate either an existing, writable, normal file or a non-existent file.",
                outputFile), kaboom);
    } catch (final NotDirectoryException kaboom) {
        throw new MojoExecutionException(String.format(
                "The output directory path, %s, exists but is not a directory.", kaboom.getFile()), kaboom);
    } catch (final PathCreationFailedException kaboom) {
        throw new MojoExecutionException(
                String.format("Some portion of the output directory path, %s, could not be created.",
                        kaboom.getFile()),
                kaboom);
    } catch (final FileException other) {
        throw new MojoExecutionException("An unexpected FileException occurred during initialization.", other);
    }

    // Scan the test classpath for Entity, MappedSuperclass, IdClass,
    // Embeddable, etc. annotations.
    final AnnotationDB db;
    AnnotationDB tempDb = null;
    try {
        tempDb = this.scan();
    } catch (final IOException kaboom) {
        throw new MojoExecutionException(
                "Execution failed because an IOException was encountered during URL scanning.", kaboom);
    } finally {
        db = tempDb;
        tempDb = null;
    }
    assert db != null;

    if (log.isDebugEnabled()) {
        log.debug("Annotation index:");
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        db.outputAnnotationIndex(pw);
        log.debug(sw.toString());
        try {
            sw.close();
        } catch (final IOException ignored) {
            // ignored on purpose
        }
        pw.close();
    }

    final Properties properties = new Properties();

    // Having scanned the classpaths, get the "index", which is a Map
    // of classnames indexed by annotation classnames.
    final Map<String, Set<String>> ai = db.getAnnotationIndex();
    if (ai == null) {
        if (log.isWarnEnabled()) {
            log.warn("After scanning for Entities, a null annotation index was returned by the AnnotationDB.");
        }
    } else if (ai.isEmpty()) {
        if (log.isWarnEnabled()) {
            log.warn("After scanning for Entities, no annotated Entities were found.");
        }
    } else {

        final Map<String, Set<String>> propertyNameIndex = new HashMap<String, Set<String>>();

        // For each of the annotations we are interested in, do some
        // work on the classes that sport those annotations.
        for (final String jpaAnnotation : JPA_ANNOTATIONS) {

            // Find all classnames annotated with that annotation
            // (e.g. @Entity, @MappedSuperclass, etc.).
            final Set<String> annotatedClassNames = ai.get(jpaAnnotation);

            if (annotatedClassNames != null && !annotatedClassNames.isEmpty()) {

                for (final String annotatedClassName : annotatedClassNames) {
                    assert annotatedClassName != null;

                    // For every classname we find, see which property name it
                    // is going to be assigned to.  For example, we might be
                    // configured so that com.foobar.* get assigned to the
                    // foobarClassnames property.
                    final String propertyName = this.determinePropertyName(annotatedClassName);
                    assert propertyName != null;

                    Set<String> relevantClassNames = propertyNameIndex.get(propertyName);
                    if (relevantClassNames == null) {
                        relevantClassNames = new TreeSet<String>();
                        propertyNameIndex.put(propertyName, relevantClassNames);
                    }
                    assert relevantClassNames != null;

                    // Add the annotated class to the set of other annotated
                    // classnames stored under that property.
                    relevantClassNames.add(annotatedClassName);

                }
            }
        }

        final Set<Entry<String, Set<String>>> entrySet = propertyNameIndex.entrySet();
        assert entrySet != null;

        if (!entrySet.isEmpty()) {

            final String firstItemPrefix = this.getFirstItemPrefix();
            final String prefix = this.getPrefix();
            final String suffix = this.getSuffix();
            final String lastItemSuffix = this.getLastItemSuffix();

            for (final Entry<String, Set<String>> entry : entrySet) {
                assert entry != null;

                // For every entry indexing a set of classes under a property
                // name, stringify the set of classnames into a single
                // StringBuilder.  Index that stringified set under the
                // property name.  This Properties will be the contents of our file.

                final StringBuilder sb = new StringBuilder();

                final String propertyName = entry.getKey();
                assert propertyName != null;

                final Set<String> classNames = entry.getValue();
                assert classNames != null;
                assert !classNames.isEmpty();

                final Iterator<String> classNamesIterator = classNames.iterator();
                assert classNamesIterator != null;
                assert classNamesIterator.hasNext();

                while (classNamesIterator.hasNext()) {
                    sb.append(this.decorate(classNamesIterator.next(),
                            sb.length() <= 0 ? firstItemPrefix : prefix,
                            classNamesIterator.hasNext() ? suffix : lastItemSuffix));
                }

                properties.setProperty(propertyName, sb.toString());

            }
        }

    }

    if (log.isDebugEnabled()) {
        final Enumeration<?> propertyNames = properties.propertyNames();
        if (propertyNames != null) {
            while (propertyNames.hasMoreElements()) {
                final Object nextElement = propertyNames.nextElement();
                if (nextElement != null) {
                    final String key = nextElement.toString();
                    assert key != null;
                    final String value = properties.getProperty(key);
                    log.debug(String.format("%s = %s", key, value));
                }
            }
        }
    }

    final MavenProject project = this.getProject();
    if (project != null) {
        final Properties projectProperties = project.getProperties();
        if (projectProperties != null) {
            @SuppressWarnings("unchecked")
            final Enumeration<String> propertyNames = (Enumeration<String>) properties.propertyNames();
            if (propertyNames != null && propertyNames.hasMoreElements()) {
                while (propertyNames.hasMoreElements()) {
                    final String propertyName = propertyNames.nextElement();
                    if (propertyName != null) {
                        projectProperties.setProperty(propertyName, properties.getProperty(propertyName));
                    }
                }
            }
        }
    }

    if (this.getUseOutputFile()) {
        final File outputFile = this.getOutputFile();
        if (outputFile != null) {
            assert outputFile.exists() ? outputFile.isFile() : true;
            assert outputFile.getParentFile() != null;
            assert outputFile.getParentFile().isDirectory();
            assert outputFile.getParentFile().canWrite();
            assert !outputFile.exists() ? outputFile.getParentFile().canWrite() : true;

            // Prepare to write.  Get the character encoding, accounting for
            // possible null return values from an overridden getEncoding()
            // method.
            String encoding = this.getEncoding();
            if (encoding == null) {
                encoding = "";
            } else {
                encoding = encoding.trim();
            }
            if (encoding.isEmpty()) {
                encoding = "UTF8";
            }

            // Set up the Writer to point to the outputFile and have the
            // Properties store itself there.
            Writer writer = null;
            try {
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), encoding));
                properties.store(writer, "Generated by " + this.getClass().getName());
                writer.flush();
            } catch (final IOException kaboom) {
                throw new MojoExecutionException(String.format(
                        "While attempting to write to the outputFile parameter (%s), an IOException was encountered.",
                        outputFile), kaboom);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (final IOException ignore) {
                        // ignored on purpose
                    }
                }
            }
        }
    }
}

From source file:com.edugility.jpa.maven.plugin.ListEntityClassnamesMojo.java

License:Open Source License

/**
 * Returns the appropriate property name given a {@linkplain Class#getName() class name}.
 *
 * <p>If the supplied {@code className} is {@code null} or consists
 * solely of {@linkplain Character#isWhitespace(char) whitespace},
 * then the {@linkplain #getDefaultPropertyName() default property
 * name} is returned.<p>//from   w ww. j  a va2 s.  c  o  m
 *
 * <p>Otherwise, a property name is 
 */
public String determinePropertyName(String className) {
    String propertyName = this.getDefaultPropertyName();
    if (className != null) {
        className = className.trim();
        if (!className.isEmpty()) {
            final Log log = this.getLog();
            assert log != null;

            // Find the class' package name.  Extract "com.foobar" from
            // "com.foobar.Foo".
            final int index = Math.max(0, className.lastIndexOf('.'));
            String packageName = className.substring(0, index);
            assert packageName != null;
            if (log.isDebugEnabled()) {
                log.debug("Package: " + packageName);
            }

            final Map<String, String> propertyNames = this.getPropertyNames();
            if (propertyNames == null) {
                if (log.isWarnEnabled()) {
                    log.warn(String.format(
                            "Property names were never initialized; assigning default property name (%s) to class name %s.",
                            propertyName, className));
                }
            } else if (propertyNames.isEmpty()) {
                if (log.isWarnEnabled()) {
                    log.warn(String.format(
                            "Property names were initialized to the empty set; assigning default property name (%s) to class name %s.",
                            propertyName, className));
                }
            } else {
                propertyName = propertyNames.get(packageName);
                while (propertyName == null && packageName != null && !packageName.isEmpty()) {
                    final int dotIndex = Math.max(0, packageName.lastIndexOf('.'));
                    packageName = packageName.substring(0, dotIndex);
                    if (log.isDebugEnabled()) {
                        log.debug("Package: " + packageName);
                    }
                    propertyName = propertyNames.get(packageName);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("propertyName: " + propertyName);
            }
        }
    }
    if (propertyName == null) {
        propertyName = DEFAULT_DEFAULT_PROPERTY_NAME;
    }
    return propertyName;
}

From source file:com.github.jrh3k5.flume.mojo.plugin.plexus.MojoLogger.java

License:Apache License

/**
 * Determine a {@link Logger} level based on the configuration of the given
 * {@link Log}./*from ww  w  . j ava2s  . c  o  m*/
 * 
 * @param log
 *            The {@link Log} to determine the logger level.
 * @return A {@link Logger} level corresponding to the log level in the
 *         given {@link Log}.
 */
private static int determineThreshold(Log log) {
    if (log.isDebugEnabled()) {
        return Logger.LEVEL_DEBUG;
    } else if (log.isInfoEnabled()) {
        return Logger.LEVEL_INFO;
    } else if (log.isWarnEnabled()) {
        return Logger.LEVEL_WARN;
    } else if (log.isErrorEnabled()) {
        return Logger.LEVEL_ERROR;
    } else {
        return Logger.LEVEL_DISABLED;
    }
}

From source file:com.redhat.rcm.maven.plugin.buildmetadata.common.MojoUtils.java

License:Apache License

/**
 * Logs and creates the given exception.
 *
 * @param log the logger to use./*w ww  .  j  a v a 2 s.  c o  m*/
 * @param e the original exception to throw.
 * @param message the message to log and add to the mojo exception.
 * @return the exception that wraps the given exception.
 */
public static MojoExecutionException createException(final Log log, final Throwable e, final String message) {
    if (log.isWarnEnabled()) {
        log.warn(message, e);
    }

    return new MojoExecutionException(message, e);
}

From source file:com.sri.vt.majic.util.clean.Cleaner.java

License:Apache License

/**
 * Creates a new cleaner./*  ww  w  .j  a v  a2s. c o m*/
 * 
 * @param log The logger to use, may be <code>null</code> to disable logging.
 * @param verbose Whether to perform verbose logging.
 */
public Cleaner(final Log log, boolean verbose) {
    logDebug = (log == null || !log.isDebugEnabled()) ? null : new Logger() {
        public void log(CharSequence message) {
            log.debug(message);
        }
    };

    logInfo = (log == null || !log.isInfoEnabled()) ? null : new Logger() {
        public void log(CharSequence message) {
            log.info(message);
        }
    };

    logWarn = (log == null || !log.isWarnEnabled()) ? null : new Logger() {
        public void log(CharSequence message) {
            log.warn(message);
        }
    };

    logVerbose = verbose ? logInfo : logDebug;
}

From source file:de.smartics.maven.plugin.buildmetadata.common.MojoUtils.java

License:Apache License

/**
 * Logs and creates the given exception.
 *
 * @param log the logger to use.//from w  ww  .  jav  a  2  s. c  o  m
 * @param exception the original exception to throw.
 * @param message the message to log and add to the mojo exception.
 * @return the exception that wraps the given exception.
 */
public static MojoExecutionException createException(final Log log, final Throwable exception,
        final String message) {
    if (log.isWarnEnabled()) {
        log.warn(message, exception);
    }

    return new MojoExecutionException(message, exception);
}

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

License:Open Source License

/**
 * Checks whether the debug level is enabled.
 * @param mavenLog the underlying {@link Log}.
 * @return {@code true} in such case.//  w w  w .  jav  a 2  s. c  o m
 */
protected boolean isWarnEnabled(@NotNull final Log mavenLog) {
    return mavenLog.isWarnEnabled();
}

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();// w w  w. ja va  2s.com
    } else if (level == LEVEL_INFO) {
        enabled = log.isInfoEnabled();
    } 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;
}