    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.release.plugin;
    018
    019import java.io.File;
    020import java.io.IOException;
    021import java.util.Optional;
    022import java.util.function.Supplier;
    023
    024import org.apache.maven.plugin.MojoExecutionException;
    025import org.apache.maven.plugin.logging.Log;
    026import org.apache.maven.scm.provider.ScmProviderRepository;
    027import org.apache.maven.settings.Server;
    028import org.apache.maven.settings.Settings;
    029import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
    030import org.apache.maven.settings.crypto.SettingsDecrypter;
    031import org.apache.maven.settings.crypto.SettingsDecryptionResult;
    032import org.codehaus.plexus.util.FileUtils;
    033
    034/**
    035 * Shared static functions for all of our Mojos.
    036 *
    037 * @author chtompki
    038 * @since 1.0
    039 */
    040public final class SharedFunctions {
    041
    042    /**
    043     * I want a buffer that is an array with 1024 elements of bytes. We declare
    044     * the constant here for the sake of making the code more readable.
    045     */
    046    public static final int BUFFER_BYTE_SIZE = 1024;
    047
    048    /**
    049     * Copies a {@link File} from the <code>fromFile</code> to the <code>toFile</code> and logs the failure
    050     * using the Maven {@link Log}.
    051     *
    052     * @param log the {@link Log}, the maven logger.
    053     * @param fromFile the {@link File} from which to copy.
    054     * @param toFile the {@link File} to which to copy into.
    055     * @throws MojoExecutionException if an {@link IOException} or {@link NullPointerException} is caught.
    056     */
    057    public static void copyFile(final Log log, final File fromFile, final File toFile) throws MojoExecutionException {
    058        final String format = "Unable to copy file %s tp %s: %s";
    059        requireNonNull(fromFile, () -> String.format(format, fromFile, toFile));
    060        requireNonNull(toFile, () -> String.format(format, fromFile, toFile));
    061        try {
    062            FileUtils.copyFile(fromFile, toFile);
    063        } catch (final IOException e) {
    064            final String message = String.format(format, fromFile, toFile, e.getMessage());
    065            log.error(message);
    066            throw new MojoExecutionException(message, e);
    067        }
    068    }
    069
    070    /**
    071     * Cleans and then initializes an empty directory that is given by the <code>workingDirectory</code>
    072     * parameter.
    073     *
    074     * @param log is the Maven log for output logging, particularly in regards to error management.
    075     * @param workingDirectory is a {@link File} that represents the directory to first attempt to delete then create.
    076     * @throws MojoExecutionException when an {@link IOException} or {@link NullPointerException} is caught for the
    077     *      purpose of bubbling the exception up to Maven properly.
    078     */
    079    public static void initDirectory(final Log log, final File workingDirectory) throws MojoExecutionException {
    080        final String format = "Unable to remove directory %s: %s";
    081        requireNonNull(workingDirectory, () -> String.format(format, workingDirectory));
    082        if (workingDirectory.exists()) {
    083            try {
    084                FileUtils.deleteDirectory(workingDirectory);
    085            } catch (final IOException e) {
    086                final String message = String.format(format, workingDirectory, e.getMessage());
    087                log.error(message);
    088                throw new MojoExecutionException(message, e);
    089            }
    090        }
    091        if (!workingDirectory.exists()) {
    092            workingDirectory.mkdirs();
    093        }
    094    }
    095
    096    /**
    097     * Checks that the specified object reference is not {@code null}. This method is designed primarily for doing parameter validation in methods and
    098     * constructors, as demonstrated below: <blockquote>
    099     *
    100     * <pre>
    101     * public Foo(Bar bar) {
    102     *     this.bar = SharedFunctions.requireNonNull(bar);
    103     * }
    104     * </pre>
    105     *
    106     * </blockquote>
    107     *
    108     * @param obj the object reference to check for nullity
    109     * @param <T> the type of the reference
    110     * @return {@code obj} if not {@code null}
    111     * @throws MojoExecutionException if {@code obj} is {@code null}
    112     */
    113    public static <T> T requireNonNull(final T obj) throws MojoExecutionException {
    114        if (obj == null) {
    115            throw new MojoExecutionException(new NullPointerException());
    116        }
    117        return obj;
    118    }
    119
    120    /**
    121     * Checks that the specified object reference is not {@code null} and throws a customized {@link MojoExecutionException} if it is. This method is designed
    122     * primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below: <blockquote>
    123     *
    124     * <pre>
    125     * public Foo(Bar bar, Baz baz) {
    126     *     this.bar = SharedFunctions.requireNonNull(bar, "bar must not be null");
    127     *     this.baz = SharedFunctions.requireNonNull(baz, "baz must not be null");
    128     * }
    129     * </pre>
    130     *
    131     * </blockquote>
    132     *
    133     * @param obj the object reference to check for nullity
    134     * @param message detail message to be used in the event that a {@code
    135     *                NullPointerException} is thrown
    136     * @param <T> the type of the reference
    137     * @return {@code obj} if not {@code null}
    138     * @throws MojoExecutionException if {@code obj} is {@code null}
    139     */
    140    public static <T> T requireNonNull(final T obj, final String message) throws MojoExecutionException {
    141        if (obj == null) {
    142            throw new MojoExecutionException(new NullPointerException(message));
    143        }
    144        return obj;
    145    }
    146
    147    /**
    148     * Checks that the specified object reference is not {@code null} and throws a customized {@link MojoExecutionException} if it is.
    149     * <p>
    150     * Unlike the method {@link #requireNonNull(Object, String)}, this method allows creation of the message to be deferred until after the null check is made.
    151     * While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the
    152     * message supplier are less than the cost of just creating the string message directly.
    153     * </p>
    154     *
    155     * @param obj the object reference to check for nullity
    156     * @param messageSupplier supplier of the detail message to be used in the event that a {@code NullPointerException} is thrown
    157     * @param <T> the type of the reference
    158     * @return {@code obj} if not {@code null}
    159     * @throws MojoExecutionException if {@code obj} is {@code null}
    160     */
    161    public static <T> T requireNonNull(final T obj, final Supplier<String> messageSupplier) throws MojoExecutionException {
    162        if (obj == null) {
    163            throw new MojoExecutionException(new NullPointerException(messageSupplier.get()));
    164        }
    165        return obj;
    166    }
    167
    168    /**
    169     * Set authentication information on the specified {@link ScmProviderRepository}.
    170     * @param providerRepository target.
    171     * @param distServer temp.
    172     * @param settings temp.
    173     * @param settingsDecrypter temp.
    174     * @param username temp.
    175     * @param password temp.
    176     */
    177    public static void setAuthentication(final ScmProviderRepository providerRepository,
    178                                   final String distServer,
    179                                   final Settings settings,
    180                                   final SettingsDecrypter settingsDecrypter,
    181                                   final String username,
    182                                   final String password) {
    183        final Optional<Server> server =
    184                Optional.ofNullable(distServer).map(settings::getServer).map(DefaultSettingsDecryptionRequest::new)
    185                        .map(settingsDecrypter::decrypt).map(SettingsDecryptionResult::getServer);
    186
    187        providerRepository.setUser(server.map(Server::getUsername).orElse(username));
    188        providerRepository.setPassword(server.map(Server::getPassword).orElse(password));
    189    }
    190
    191    /**
    192     * Making the constructor private because the class only contains static methods.
    193     */
    194    private SharedFunctions() {
    195        // Utility Class
    196    }
    197}