Java Code Examples for org.apache.maven.plugin.logging.Log#warn()

The following examples show how to use org.apache.maven.plugin.logging.Log#warn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CqUtils.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
public static String getDescription(List<ArtifactModel<?>> models, String descriptionFromPom, Log log) {
    if (descriptionFromPom != null) {
        return descriptionFromPom;
    } else if (models.size() == 1) {
        return models.get(0).getDescription();
    } else {
        final Set<String> uniqueDescriptions = models.stream()
                .map(m -> m.getDescription())
                .collect(Collectors.toCollection(LinkedHashSet::new));
        final String description = uniqueDescriptions
                .stream()
                .collect(Collectors.joining(" "));
        if (uniqueDescriptions.size() > 1) {
            log.warn("Consider adding and explicit <description> if you do not like the concatenated description: "
                    + description);
        }
        return description;
    }
}
 
Example 2
Source File: MavenPluginUtils.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Formats a Roboconf errors and outputs it in the logs.
 * @param error an error
 * @param log the Maven logger
 * @return a string builder with the output
 */
public static StringBuilder formatErrors( Collection<? extends RoboconfError> errors, Log log ) {

	StringBuilder result = new StringBuilder();
	for( Map.Entry<RoboconfError,String> entry : RoboconfErrorHelpers.formatErrors( errors, null, true ).entrySet()) {
		if( entry.getKey().getErrorCode().getLevel() == ErrorLevel.WARNING )
			log.warn( entry.getValue());
		else
			log.error( entry.getValue());

		result.append( entry.getValue());
		result.append( "\n" );
	}

	return result;
}
 
Example 3
Source File: MainInstrumentMojo.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();

    File mainOutputFolder = new File(getProject().getBuild().getOutputDirectory());
    if (!mainOutputFolder.isDirectory()) {
        log.warn("Main folder doesn't exist -- nothing to instrument");
        return;
    }
    
    List<String> classpath;
    try {
        classpath = getProject().getCompileClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Dependency resolution problem", ex);
    }

    log.debug("Processing main output folder ... ");
    instrumentPath(log, classpath, mainOutputFolder);
}
 
Example 4
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void addDependencies(PackageConfig config, Collection<DependencySet> dependencies, JavaArchive jar) {
    Log logger = config.getMojo().getLog();
    for (DependencySet ds : dependencies) {
        ScopeFilter scopeFilter = ServiceUtils.newScopeFilter(ds.getScope());
        ArtifactFilter filter = new ArtifactIncludeFilterTransformer().transform(scopeFilter);
        Set<Artifact> artifacts = ServiceUtils.filterArtifacts(config.getArtifacts(),
            ds.getIncludes(), ds.getExcludes(),
            ds.isUseTransitiveDependencies(), logger, filter);

        for (Artifact artifact : artifacts) {
            File file = artifact.getFile();
            if (file.isFile()) {
                logger.debug("Adding Dependency :" + artifact);
                embedDependency(logger, ds, jar, file);
            } else {
                logger.warn("Cannot embed artifact " + artifact
                    + " - the file does not exist");
            }
        }
    }
}
 
Example 5
Source File: TestInstrumentMojo.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();

    File testOutputFolder = new File(getProject().getBuild().getTestOutputDirectory());
    if (!testOutputFolder.isDirectory()) {
        log.warn("Test folder doesn't exist -- nothing to instrument");
        return;
    }
    
    List<String> classpath;
    try {
        classpath = getProject().getTestClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Dependency resolution problem", ex);
    }
    
    log.debug("Processing test output folder ... ");
    instrumentPath(log, classpath, testOutputFolder);
}
 
Example 6
Source File: Util.java    From jax-maven-plugin with Apache License 2.0 6 votes vote down vote up
static File createOutputDirectoryIfSpecifiedOrDefault(Log log, String param, List<String> arguments) {
    for (int i = 0; i < arguments.size(); i++) {
        if (isOptionParamSpecifiedAndNotEmpty(arguments, i, param)) {
            String path = arguments.get(i + 1);
            Preconditions.checkNotNull(path, "path for output directory not found, option="+ param);
            File outputDir = new File(path);
            if (!outputDir.exists()) {
                log.info("destination directory (" + param + " option) specified and does not exist, creating: "
                        + outputDir);
                outputDir.mkdirs();
            }
            return outputDir;
        }
    }
    log.warn("destination directory (" + param
            + " option) NOT specified. Generated source will be placed in project root if -keep argument is present.");
    return new File(".");
}
 
Example 7
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 6 votes vote down vote up
@Nonnull
protected File buildDockerInfoJar(@Nonnull Log log) throws MojoExecutionException {
  final File jarFile = getJarFile(buildDirectory, finalName, classifier);

  final MavenArchiver archiver = new MavenArchiver();
  archiver.setArchiver(jarArchiver);
  archiver.setOutputFile(jarFile);

  archive.setForced(forceCreation);

  if (dockerInfoDirectory.exists()) {
    final String prefix = getMetaSubdir();
    archiver.getArchiver().addDirectory(dockerInfoDirectory, prefix);
  } else {
    log.warn("Docker info directory not created - Docker info JAR will be empty");
  }

  try {
    archiver.createArchive(session, project, archive);
  } catch (Exception e) {
    throw new MojoExecutionException("Could not build Docker info JAR", e);
  }

  return jarFile;
}
 
Example 8
Source File: Utils.java    From dsl-compiler-client with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static String parseSettings(String[] value, Log log) throws MojoExecutionException {
	if (value == null || value.length == 0) return null;
	StringBuilder sb = new StringBuilder();
	for (String setting : value) {
		Settings.Option option = settingsOptionFrom(setting);
		if (option == null) {
			if (setting == null || setting.length() == 0 || setting.contains(" ")) {
				throw new MojoExecutionException("Invalid option passed as argument: " + setting);
			}
			if (log.isWarnEnabled()) {
				log.warn("Unrecognizable option: " + setting + ". Will try to pass it anyway.");
			}
		}
		sb.append(setting);
		sb.append(",");
	}
	return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : null;
}
 
Example 9
Source File: LogUtil.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
public static void logDeployResult(Log log, String result) {
    if (result == null || result.isEmpty()) {
        return;
    }
    DeployResult deployResult;
    try {
        deployResult = new ObjectMapper().readValue(result, DeployResult.class);
        log.info("List of successfully deployed applications");
        deployResult.getSuccess().forEach(log::info);
        if (!deployResult.getError().isEmpty()) {
            log.error("List of applications that failed to deploy");
            deployResult.getError().forEach((key, entry) -> log.error(key + " -> " + entry));
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        log.warn("Unable to parse deploy result -> " + result);
    }
}
 
Example 10
Source File: AbstractFilter.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final void initialize(final Log log) {

    // Check sanity
    Validate.notNull(log, "log");

    // Assign internal state
    this.log = log;

    if (delayedLogMessages.size() > 0) {
        for (DelayedLogMessage current : delayedLogMessages) {
            if (current.logLevel.equalsIgnoreCase("warn") && log.isWarnEnabled()) {
                log.warn(current.message);
            } else if (current.logLevel.equals("info") && log.isInfoEnabled()) {
                log.info(current.message);
            } else if (log.isDebugEnabled()) {
                log.debug(current.message);
            }
        }

        delayedLogMessages.clear();
    }

    // Delegate
    onInitialize();
}
 
Example 11
Source File: ReleaseMojo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
private static void revertChanges(Log log, LocalGitRepo repo, List<File> changedFiles, boolean throwIfError) throws MojoExecutionException {
    if (!repo.revertChanges(log, changedFiles)) {
        String message = "Could not revert changes - working directory is no longer clean. Please revert changes manually";
        if (throwIfError) {
            throw new MojoExecutionException(message);
        } else {
            log.warn(message);
        }
    }
}
 
Example 12
Source File: BaseMojo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
protected final void configureJsch(final Log log) {
	if (!disableSshAgent) {
		if (serverId != null) {
			final Server server = settings.getServer(serverId);
			if (server != null) {
				privateKey = privateKey == null ? server.getPrivateKey() : privateKey;
				passphrase = passphrase == null ? server.getPassphrase() : passphrase;
			} else {
				log.warn(format("No server configuration in Maven settings found with id %s", serverId));
			}
		}

		JschConfigSessionFactory.setInstance(new SshAgentSessionFactory(log, knownHosts, privateKey, passphrase));
	}
}
 
Example 13
Source File: BaseMojo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
protected CredentialsProvider getCredentialsProvider(final Log log) throws ValidationException {
    if (serverId != null) {
        Server server = settings.getServer(serverId);
        if (server == null) {
            log.warn(format("No server configuration in Maven settings found with id %s", serverId));
        }
        if (server.getUsername() != null && server.getPassword() != null) {
            return new UsernamePasswordCredentialsProvider(server.getUsername(), server.getPassword());
        }
    }
    return null;
}
 
Example 14
Source File: SpringBootUtil.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
/**
 * Get the Spring Boot Uber JAR in its expected location, validating the JAR
 * contents and handling spring-boot-maven-plugin classifier configuration as
 * well. If the JAR was not found in its expected location, then return null.
 * 
 * @param outputDirectory
 * @param project
 * @param log
 * @return the JAR File if it was found, false otherwise
 */
public static File getSpringBootUberJAR(MavenProject project, Log log) {

    File fatArchive = getSpringBootUberJARLocation(project, log);

    if (io.openliberty.tools.common.plugins.util.SpringBootUtil.isSpringBootUberJar(fatArchive)) {
        log.info("Found Spring Boot Uber JAR: " + fatArchive.getAbsolutePath());
        return fatArchive;
    }

    log.warn("Spring Boot Uber JAR was not found in expected location: " + fatArchive.getAbsolutePath());
    return null;
}
 
Example 15
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void embedFileSet(Log log, MavenProject project, FileSet fs, JavaArchive jar) {
    File directory = new File(fs.getDirectory());
    if (!directory.isAbsolute()) {
        directory = new File(project.getBasedir(), fs.getDirectory());
    }

    if (!directory.isDirectory()) {
        log.warn("File set root directory (" + directory.getAbsolutePath() + ") does not exist " +
            "- skipping");
        return;
    }

    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(directory);
    if (fs.getOutputDirectory() == null) {
        fs.setOutputDirectory("/");
    } else if (!fs.getOutputDirectory().startsWith("/")) {
        fs.setOutputDirectory("/" + fs.getOutputDirectory());
    }
    List<String> excludes = fs.getExcludes();
    if (fs.isUseDefaultExcludes()) {
        excludes.addAll(FileUtils.getDefaultExcludesAsList());
    }
    if (!excludes.isEmpty()) {
        scanner.setExcludes(excludes.toArray(new String[0]));
    }
    if (!fs.getIncludes().isEmpty()) {
        scanner.setIncludes(fs.getIncludes().toArray(new String[0]));
    }
    scanner.scan();
    String[] files = scanner.getIncludedFiles();
    for (String path : files) {
        File file = new File(directory, path);
        log.debug("Adding " + fs.getOutputDirectory() + path + " to the archive");
        jar.addAsResource(file, fs.getOutputDirectory() + path);
    }
}
 
Example 16
Source File: WebJars.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static File getOutput(Log log, File out, boolean stripVersion, String path) {
    if (stripVersion) {
        Matcher matcher = WEBJAR_INTERNAL_PATH_REGEX.matcher(path);
        if (matcher.matches()) {
            return new File(out, matcher.group(1) + "/" + matcher.group(3));
        } else {
            log.warn(path + " does not match the regex - did not strip the version for this file");
        }
    }
    return new File(out, path);
}
 
Example 17
Source File: Utils.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static void pushImage(final DockerClient docker, final String imageName,
                             final List<String> imageTags, final Log log,
                             final DockerBuildInformation buildInfo,
                             final int retryPushCount, final int retryPushTimeout,
                             final boolean skipPush)
        throws MojoExecutionException, DockerException, InterruptedException {

  if (skipPush) {
    log.info("Skipping docker push");
    return;
  }

  int attempt = 0;
  do {
    final AnsiProgressHandler ansiProgressHandler = new AnsiProgressHandler();
    final DigestExtractingProgressHandler handler = new DigestExtractingProgressHandler(
            ansiProgressHandler);

    try {
      log.info("Pushing " + imageName);
      docker.push(imageName, handler);

      if (imageTags != null) {
        final String imageNameNoTag = getImageNameWithNoTag(imageName);
        for (final String imageTag : imageTags) {
          final String imageNameAndTag = imageNameNoTag + ":" + imageTag;
          log.info("Pushing " + imageNameAndTag);
          docker.push(imageNameAndTag, new AnsiProgressHandler());
        }
      }

      // A concurrent push raises a generic DockerException and not
      // the more logical ImagePushFailedException. Hence the rather
      // wide catch clause.
    } catch (DockerException e) {
      if (attempt < retryPushCount) {
        log.warn(String.format(PUSH_FAIL_WARN_TEMPLATE, imageName, retryPushTimeout / 1000,
            attempt + 1, retryPushCount));
        sleep(retryPushTimeout);
        continue;
      } else {
        throw e;
      }
    }
    if (buildInfo != null) {
      final String imageNameWithoutTag = parseImageName(imageName)[0];
      buildInfo.setDigest(imageNameWithoutTag + "@" + handler.digest());
    }
    break;
  } while (attempt++ <= retryPushCount);
}
 
Example 18
Source File: XsdGeneratorHelper.java    From jaxb2-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Inserts XML documentation annotations into all generated XSD files found
 * within the supplied outputDir.
 *
 * @param log       A Maven Log.
 * @param outputDir The outputDir, where generated XSD files are found.
 * @param docs      The SearchableDocumentation for the source files within the compilation unit.
 * @param renderer  The JavaDocRenderer used to convert JavaDoc annotations into XML documentation annotations.
 * @return The number of processed XSDs.
 */
public static int insertJavaDocAsAnnotations(final Log log,
                                             final String encoding,
                                             final File outputDir,
                                             final SearchableDocumentation docs,
                                             final JavaDocRenderer renderer) {

    // Check sanity
    Validate.notNull(docs, "docs");
    Validate.notNull(log, "log");
    Validate.notNull(outputDir, "outputDir");
    Validate.isTrue(outputDir.isDirectory(), "'outputDir' must be a Directory.");
    Validate.notNull(renderer, "renderer");

    int processedXSDs = 0;
    final List<File> foundFiles = new ArrayList<File>();
    addRecursively(foundFiles, RECURSIVE_XSD_FILTER, outputDir);

    if (foundFiles.size() > 0) {

        // Create the processors.
        final XsdAnnotationProcessor classProcessor = new XsdAnnotationProcessor(docs, renderer);
        final XsdEnumerationAnnotationProcessor enumProcessor
                = new XsdEnumerationAnnotationProcessor(docs, renderer);

        for (File current : foundFiles) {

            // Create an XSD document from the current File.
            final Document generatedSchemaFileDocument = parseXmlToDocument(current);

            // Replace all namespace prefixes within the provided document.
            process(generatedSchemaFileDocument.getFirstChild(), true, classProcessor);
            processedXSDs++;

            // Overwrite the vanilla file.
            savePrettyPrintedDocument(generatedSchemaFileDocument, current, encoding);
        }

    } else {
        if (log.isWarnEnabled()) {
            log.warn("Found no generated 'vanilla' XSD files to process under ["
                    + FileSystemUtilities.getCanonicalPath(outputDir) + "]. Aborting processing.");
        }
    }

    // All done.
    return processedXSDs;
}
 
Example 19
Source File: RequireEncoding.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
public void execute( EnforcerRuleHelper helper )
    throws EnforcerRuleException
{
    try
    {
        if ( StringUtils.isBlank( encoding ) )
        {
            encoding = (String) helper.evaluate( "${project.build.sourceEncoding}" );
        }
        Log log = helper.getLog();

        Set< String > acceptedEncodings = new HashSet< String >( Arrays.asList( encoding ) );
        if ( encoding.equals( StandardCharsets.US_ASCII.name() ) )
        {
            log.warn( "Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1" );
        }

        if ( acceptAsciiSubset && ( encoding.equals( StandardCharsets.ISO_8859_1.name() ) || encoding.equals( StandardCharsets.UTF_8.name() ) ) )
        {
            acceptedEncodings.add( StandardCharsets.US_ASCII.name() );
        }

        String basedir = (String) helper.evaluate( "${basedir}" );
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir( basedir );
        if ( StringUtils.isNotBlank( includes ) )
        {
            ds.setIncludes( includes.split( "[,\\|]" ) );
        }
        if ( StringUtils.isNotBlank( excludes ) )
        {
            ds.setExcludes( excludes.split( "[,\\|]" ) );
        }
        if ( useDefaultExcludes )
        {
            ds.addDefaultExcludes();
        }
        ds.scan();
        StringBuilder filesInMsg = new StringBuilder();
        for ( String file : ds.getIncludedFiles() )
        {
            String fileEncoding = getEncoding( encoding, new File( basedir, file ), log );
            if ( log.isDebugEnabled() )
            {
                log.debug( file + "==>" + fileEncoding );
            }
            if ( fileEncoding != null && !acceptedEncodings.contains( fileEncoding ) )
            {
                filesInMsg.append( file );
                filesInMsg.append( "==>" );
                filesInMsg.append( fileEncoding );
                filesInMsg.append( "\n" );
                if ( failFast )
                {
                    throw new EnforcerRuleException( filesInMsg.toString() );
                }
            }
        }
        if ( filesInMsg.length() > 0 )
        {
            throw new EnforcerRuleException( "Files not encoded in " + encoding + ":\n" + filesInMsg );
        }
    }
    catch ( IOException ex )
    {
        throw new EnforcerRuleException( "Reading Files", ex );
    }
    catch ( ExpressionEvaluationException e )
    {
        throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e );
    }
}
 
Example 20
Source File: BuildMojo.java    From dockerfile-maven with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DockerClient dockerClient)
    throws MojoExecutionException, MojoFailureException {
  final Log log = getLog();

  if (skipBuild) {
    log.info("Skipping execution because 'dockerfile.build.skip' is set");
    return;
  }

  log.info("dockerfile: " + dockerfile);
  log.info("contextDirectory: " + contextDirectory);

  Path dockerfilePath = null;
  if (dockerfile != null) {
    dockerfilePath = dockerfile.toPath();
  }
  final String imageId = buildImage(
      dockerClient, log, verbose, contextDirectory.toPath(), dockerfilePath, repository, tag, 
      pullNewerImage, noCache, buildArgs, cacheFrom, squash);

  if (imageId == null) {
    log.warn("Docker build was successful, but no image was built");
  } else {
    log.info(MessageFormat.format("Detected build of image with id {0}", imageId));
    writeMetadata(Metadata.IMAGE_ID, imageId);
  }

  // Do this after the build so that other goals don't use the tag if it doesn't exist
  if (repository != null) {
    writeImageInfo(repository, tag);
  }

  writeMetadata(log);

  if (repository == null) {
    log.info(MessageFormat.format("Successfully built {0}", imageId));
  } else {
    log.info(MessageFormat.format("Successfully built {0}", formatImageName(repository, tag)));
  }
}