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:com.edugility.jpa.maven.plugin.ListEntityClassnamesMojo.java

License:Open Source License

/**
 * Executes this mojo./*  w  ww . ja  va2s  . com*/
 *
 * @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 w w  . j  a v a2s.  co 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.edugility.liquibase.maven.AssembleChangeLogMojo.java

License:Open Source License

/**
 * Given an {@link Iterable} of {@link Artifact}s, and given a
 * non-{@code null}, non-empty return value from the {@link
 * #getChangeLogResourceNames()} method, this method returns a
 * {@link Collection} of {@link URL}s representing changelog
 * {@linkplain ClassLoader#getResources(String) resources found}
 * among the supplied {@link Artifact}s.
 *
 * @param artifacts an {@link Iterable} of {@link Artifact}s; may be
 * {@code null}/*from  w ww .j a va  2  s .  c  om*/
 *
 * @return a {@link Collection} of {@link URL}s representing
 * changelog resources found among the supplied {@link Artifact}s
 *
 * @exception IOException if an input/output error occurs such as
 * the kind that might be thrown by the {@link
 * ClassLoader#getResources(String)} method
 *
 * @see #getChangeLogResourceNames()
 *
 * @see ClassLoader#getResources(String)
 */
public Collection<? extends URL> getChangeLogResources(final Iterable<? extends Artifact> artifacts)
        throws IOException {
    final Log log = this.getLog();
    Collection<URL> returnValue = null;
    final ClassLoader loader = this.toClassLoader(artifacts);
    if (loader != null) {
        final Iterable<String> changeLogResourceNames = this.getChangeLogResourceNames();
        if (log != null && log.isDebugEnabled()) {
            log.debug(String.format("Change log resource names: %s", changeLogResourceNames));
        }
        if (changeLogResourceNames == null) {
            throw new IllegalStateException("this.getChangeLogResourceNames()",
                    new NullPointerException("this.getChangeLogResourceNames()"));
        }
        returnValue = new ArrayList<URL>();
        for (final String name : changeLogResourceNames) {
            if (name != null) {
                final Enumeration<URL> urls = loader.getResources(name);
                if (urls != null) {
                    returnValue.addAll(Collections.list(urls));
                }
            }
        }
    }
    if (returnValue == null) {
        returnValue = Collections.emptySet();
    }
    return returnValue;
}

From source file:com.edugility.liquibase.maven.AssembleChangeLogMojo.java

License:Open Source License

/**
 * Executes this {@link AssembleChangeLogMojo} by calling the {@link
 * #assembleChangeLog()} method./*from   ww w. ja  v a2s. com*/
 *
 * @exception MojoFailureException if an error occurs; under normal
 * circumstances this goal will not fail so this method does not
 * throw {@link MojoExecutionException}
 *
 * @exception TemplateSyntaxError if the supplied {@code template}
 * contained syntax errors
 *
 * @exception TemplateRuntimeError if there was a problem merging
 * the supplied {@link Collection} of {@link URL}s with the compiled
 * version of the supplied {@code template}
 *
 * @see #assembleChangeLog()
 */
@Override
public void execute() throws MojoFailureException {
    final Log log = this.getLog();
    if (this.getSkip()) {
        if (log != null && log.isDebugEnabled()) {
            log.debug("Skipping execution by request");
        }
    } else {
        try {
            this.assembleChangeLog();
        } catch (final RuntimeException e) {
            throw e;
        } catch (final IOException e) {
            throw new MojoFailureException("Failure assembling changelog", e);
        } catch (final ArtifactResolutionException e) {
            throw new MojoFailureException("Failure assembling changelog", e);
        } catch (final DependencyGraphBuilderException e) {
            throw new MojoFailureException("Failure assembling changelog", e);
        }
    }
}

From source file:com.edugility.liquibase.maven.AssembleChangeLogMojo.java

License:Open Source License

/**
 * Assembles a <a href="http://www.liquibase.org/">Liquibase</a> <a
 * href="http://www.liquibase.org/documentation/databasechangelog.html">changelog</a>
 * from changelog fragments {@linkplain #getChangeLogResources()
 * found in topological dependency order among the dependencies} of
 * the {@linkplain #getProject() current project}.
 *
 * <p>This method:</p>/*  w  w w . j  a  v a2 s  .co m*/
 *
 * <ul>
 *
 * <li>{@linkplain #getChangeLogTemplateResource() Verifies that
 * there is a template} that exists either in the {@linkplain
 * #getProject() project} or (more commonly) in this plugin</li>
 *
 * <li>Verifies that the template can be read and has contents</li>
 *
 * <li>{@linkplain
 * Artifacts#getArtifactsInTopologicalOrder(MavenProject,
 * DependencyGraphBuilder, ArtifactFilter, ArtifactResolver,
 * ArtifactRepository) Retrieves and resolves the project's
 * dependencies and sorts them in topological order} from the
 * artifact with the least dependencies to {@linkplain #getProject()
 * the current project} (which by definition has the most
 * dependencies)</li>
 *
 * <li>Builds a {@link ClassLoader} that can "see" the {@linkplain
 * Artifact#getFile() <code>File</code>s associated with those
 * <code>Artifact</code>s} and uses it to {@linkplain
 * ClassLoader#getResources(String) find} the {@linkplain
 * #getChangeLogResourceNames() specified changelog resources}</li>
 * 
 * <li>Passes a {@link Collection} of {@link URL}s representing (in
 * most cases) {@code file:} or {@code jar:} {@link URL}s through
 * the {@linkplain TemplateRuntime MVEL template engine}, thus
 * merging the template and the {@link URL}s into an aggregating
 * changelog</li>
 *
 * <li>{@linkplain #write(String, Collection, File) Writes} the
 * resulting changelog to the destination denoted by the {@link
 * #getOutputFile() outputFile} parameter</li>
 * 
 * </ul>
 *
 * @exception ArtifactResolutionException if there was a problem
 * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest)
 * resolving} a given {@link Artifact} representing a dependency
 *
 * @exception DependencyGraphBuilderException if there was a problem
 * with dependency resolution
 *
 * @exception IOException if there was a problem with input or
 * output
 *
 * @see #getChangeLogTemplateResource()
 *
 * @see #getChangeLogResources()
 *
 * @see #getOutputFile()
 *
 * @see #write(String, Collection, File)
 */
public final void assembleChangeLog()
        throws ArtifactResolutionException, DependencyGraphBuilderException, IOException {
    final Log log = this.getLog();
    final URL changeLogTemplateResource = this.getChangeLogTemplateResource();
    if (log != null && log.isDebugEnabled()) {
        log.debug(String.format("Change log template resource: %s", changeLogTemplateResource));
    }
    if (changeLogTemplateResource != null) {
        final String templateContents = this.readTemplate(changeLogTemplateResource);
        if (log != null && log.isDebugEnabled()) {
            log.debug(String.format("Change log template contents: %s", templateContents));
        }
        if (templateContents != null) {
            final Collection<? extends URL> urls = this.getChangeLogResources();
            if (log != null && log.isDebugEnabled()) {
                log.debug(String.format("Change log resources: %s", urls));
            }
            if (urls != null && !urls.isEmpty()) {
                final File outputFile = this.getOutputFile();
                if (log != null && log.isDebugEnabled()) {
                    log.debug(String.format("Output file: %s", outputFile));
                }
                if (outputFile != null) {
                    this.write(templateContents, urls, outputFile);
                }
            }
        }
    }
}

From source file:com.edugility.liquibase.maven.AssembleChangeLogMojo.java

License:Open Source License

/**
 * Writes appropriate representations of the supplied {@link URL}s
 * as interpreted and merged into the supplied {@code template}
 * contents to the {@link File} represented by the {@code
 * outputFile} parameter value.//from ww  w.  j  a  v a2  s .c  o  m
 *
 * @param template an <a href="http://mvel.codehaus.org/">MVEL</a>
 * template; may be {@code null} in which case no action will be
 * taken
 *
 * @param urls a {@link Collection} of {@link URL}s representing
 * existing changelog fragment resources, sorted in topological
 * dependency order; may be {@code null} in which case no action
 * will be taken
 *
 * @param outputFile a {@link File} representing the full path to
 * the location where an aggregate changelog should be written; may
 * be {@code null} in which case no action will be taken; not
 * validated in any way by this method
 *
 * @exception IOException if there was a problem writing to the supplied {@link File}
 *
 * @exception TemplateSyntaxError if the supplied {@code template}
 * contained syntax errors
 *
 * @exception TemplateRuntimeError if there was a problem merging
 * the supplied {@link Collection} of {@link URL}s with the compiled
 * version of the supplied {@code template}
 *
 * @see #getOutputFile()
 *
 * @see #getChangeLogResources()
 *
 * @see #getChangeLogResourceNames()
 */
public void write(final String template, final Collection<? extends URL> urls, final File outputFile)
        throws IOException {
    if (template != null && urls != null && !urls.isEmpty() && outputFile != null) {
        final CompiledTemplate compiledTemplate = TemplateCompiler.compileTemplate(template);
        assert compiledTemplate != null;
        final Map<Object, Object> variables = new HashMap<Object, Object>();
        variables.put("databaseChangeLogXsdVersion", this.getDatabaseChangeLogXsdVersion());
        variables.put("changeLogParameters", this.getChangeLogParameters());
        variables.put("resources", urls);
        String encoding = this.getChangeLogCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }
        final Log log = this.getLog();
        if (log != null && log.isDebugEnabled()) {
            log.debug(String.format("Writing change log to %s using character encoding %s", outputFile,
                    encoding));
        }
        final Writer writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile), encoding));
        try {
            TemplateRuntime.execute(compiledTemplate, this, new MapVariableResolverFactory(variables),
                    null /* no TemplateRegistry */, new TemplateOutputWriter(writer));
        } finally {
            try {
                writer.flush();
            } catch (final IOException ignore) {
                // ignore on purpose
            }
            try {
                writer.close();
            } catch (final IOException ignore) {
                // ignore on purpose
            }
        }
    }
}

From source file:com.edugility.liquibase.maven.AssembleChangeLogMojo.java

License:Open Source License

/**
 * Given a {@link URL} to a changelog template, fully reads that
 * template into memory and returns it, uninterpolated, as a {@link
 * String}./*from   w  w  w .  j  a  v  a 2 s. c  o m*/
 *
 * <p>This method may return {@code null}.</p>
 *
 * @param changeLogTemplateResource a {@link URL} to an <a
 * href="http://mvel.codehaus.org/">MVEL<a> template; must not be
 * {@code null}
 *
 * @return the contents of the template, uninterpolated, or {@code
 * null}
 *
 * @exception IOException if an input/output error occurs
 *
 * @see #getTemplateCharacterEncoding()
 */
private final String readTemplate(final URL changeLogTemplateResource) throws IOException {
    final Log log = this.getLog();
    if (changeLogTemplateResource == null) {
        throw new IllegalArgumentException("changeLogTemplateResource",
                new NullPointerException("changeLogTemplateResource"));
    }
    String returnValue = null;
    final InputStream rawStream = changeLogTemplateResource.openStream();
    if (rawStream != null) {
        BufferedReader reader = null;
        String templateCharacterEncoding = this.getTemplateCharacterEncoding();
        if (templateCharacterEncoding == null) {
            templateCharacterEncoding = "UTF-8";
        }
        if (log != null && log.isDebugEnabled()) {
            log.debug(String.format("Reading change log template from %s using character encoding %s",
                    changeLogTemplateResource, templateCharacterEncoding));
        }
        try {
            reader = new BufferedReader(new InputStreamReader(rawStream, templateCharacterEncoding));
            String line = null;
            final StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append(LS);
            }
            returnValue = sb.toString();
        } finally {
            try {
                rawStream.close();
            } catch (final IOException nothingWeCanDo) {

            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException nothingWeCanDo) {

                }
            }
        }
    } else if (log != null && log.isDebugEnabled()) {
        log.debug(String.format("Opening change log template %s results in a null InputStream.",
                changeLogTemplateResource));
    }
    return returnValue;
}

From source file:com.edugility.liquibase.maven.AssembleChangeLogMojo.java

License:Open Source License

/**
 * Creates and returns a new {@link ClassLoader} whose classpath
 * encompasses reachable changelog resources found among the
 * supplied {@link Artifact}s.// ww w .ja v  a 2  s  .co m
 *
 * <p>This method may return {@code null}.</p>
 *
 * @param artifacts an {@link Iterable} of {@link Artifact}s, some
 * of whose members may house changelog fragments; may be {@code
 * null} in which case {@code null} will be returned
 *
 * @return an appropriate {@link ClassLoader}, or {@code null}
 *
 * @exception MalformedURLException if during classpath assembly a
 * bad {@link URL} was encountered
 *
 * @see #toURLs(Artifact)
 */
private final ClassLoader toClassLoader(final Iterable<? extends Artifact> artifacts)
        throws MalformedURLException {
    final Log log = this.getLog();
    ClassLoader loader = null;
    if (artifacts != null) {
        final Collection<URL> urls = new ArrayList<URL>();
        for (final Artifact artifact : artifacts) {
            final Collection<? extends URL> classpathElements = this.toURLs(artifact);
            if (classpathElements != null && !classpathElements.isEmpty()) {
                urls.addAll(classpathElements);
            }
        }
        if (!urls.isEmpty()) {
            if (log != null && log.isDebugEnabled()) {
                log.debug(String.format("Creating URLClassLoader with the following classpath: %s", urls));
            }
            loader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
                    Thread.currentThread().getContextClassLoader());
        }
    }
    return loader;
}

From source file:com.github.genthaler.credentials.SetAllMojo.java

License:Apache License

/**
 * Execute the mojo./* www . ja v a 2s .  c  o  m*/
 * 
 * @throws MojoExecutionException
 */
@Override
public void execute() throws MojoExecutionException {
    Log log = getLog();
    boolean debugEnabled = log.isDebugEnabled();

    for (Server server : this.settings.getServers()) {
        String settingsKey = server.getId();
        String username = server.getUsername();
        String password = server.getPassword();

        String usernameProperty = settingsKey + "." + DEFAULT_USERNAME_PROPERTY_SUFFIX;

        String passwordProperty = settingsKey + "." + DEFAULT_PASSWORD_PROPERTY_SUFFIX;

        if (!project.getProperties().containsKey(usernameProperty))
            project.getProperties().setProperty(usernameProperty, username);
        if (!project.getProperties().containsKey(passwordProperty))
            project.getProperties().setProperty(passwordProperty, password);

        if (useSystemProperties) {
            if (System.getProperty(usernameProperty) == null)
                System.setProperty(usernameProperty, username);
            if (System.getProperty(passwordProperty) == null)
                System.setProperty(passwordProperty, password);
        }

        if (debugEnabled)
            log.debug(String.format("username property '%s' is '%s'", usernameProperty, username));

        if (debugEnabled)
            log.debug(String.format("password property '%s' is '%s'", passwordProperty, password));
    }
}

From source file:com.github.genthaler.credentials.SetMojo.java

License:Apache License

/**
 * Execute the mojo./*from   w w  w  .  j a  v a  2s  . c  o m*/
 * 
 * @throws MojoExecutionException
 */
@Override
public void execute() throws MojoExecutionException {
    Log log = getLog();
    boolean debugEnabled = log.isDebugEnabled();

    if (null == usernameProperty) {
        if (null == settingsKey)
            throw new MojoExecutionException("At least one of settingsKey and usernameProperty must be set");
        usernameProperty = settingsKey + "." + DEFAULT_USERNAME_PROPERTY_SUFFIX;
    }

    if (debugEnabled)
        log.debug(String.format("usernameProperty is %s", usernameProperty));

    if (null == passwordProperty) {
        if (null == settingsKey)
            throw new MojoExecutionException("At least one of settingsKey and passwordProperty must be set");
        passwordProperty = settingsKey + "." + DEFAULT_PASSWORD_PROPERTY_SUFFIX;
    }

    if (debugEnabled)
        log.debug(String.format("passwordProperty is %s", passwordProperty));

    String username = coalesce(System.getProperty(usernameProperty),
            project.getProperties().getProperty(usernameProperty));

    if (debugEnabled)
        log.debug(String.format("username so far is %s", username));

    String password = coalesce(System.getProperty(passwordProperty),
            project.getProperties().getProperty(passwordProperty));

    if (debugEnabled)
        log.debug(String.format("password so far is %s", password));

    // Only lookup credentials if they're not already set.
    if (null == username || null == password) {
        if (null == settingsKey) {
            throw new MojoExecutionException(String.format(
                    "If %s/%s properties not set manually, then the settings key must be specified, either at the command line or in the pom.xml",
                    usernameProperty, passwordProperty));
        }

        Server server = this.settings.getServer(this.settingsKey);

        if (null == server) {
            throw new MojoExecutionException(String.format(
                    "You have specified a settingsKey property value of %s, there must be a server entry with id %s in your settings.xml",
                    settingsKey, settingsKey));
        } else {
            if (null == username)
                username = server.getUsername();

            if (null == password) {
                password = server.getPassword();

                try {
                    password = securityDispatcher.decrypt(password);
                } catch (SecDispatcherException e) {
                    // Don't care if we can't decrypt, either it wasn't
                    // encrypted in the first place, and/or it'll just fail
                    // on the target system.
                    getLog().warn(e);
                }
            }
        }
    }

    if (null == username)
        username = "";
    if (null == password)
        password = "";

    project.getProperties().setProperty(usernameProperty, username);
    project.getProperties().setProperty(passwordProperty, password);

    if (useSystemProperties) {
        System.setProperty(usernameProperty, username);
        System.setProperty(passwordProperty, password);
    }

    if (debugEnabled)
        log.debug(String.format("username property '%s' is '%s'", usernameProperty, username));

    if (debugEnabled)
        log.debug(String.format("password property '%s' is '%s'", passwordProperty, password));
}