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

The following examples show how to use org.apache.maven.plugin.logging.Log#error() . 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: ArchiveEntryUtils.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void applyPermissionsWithJvm(final File file, final String mode, final Log logger) {
    final FilePermission filePermission = FilePermissionUtils.getFilePermissionFromMode(mode, logger);

    Method method;
    try {
        method = File.class.getMethod("setReadable", new Class[] { Boolean.TYPE, Boolean.TYPE });

        method.invoke(file, new Object[] {filePermission.isReadable(), filePermission.isOwnerOnlyReadable()});

        method = File.class.getMethod("setExecutable", new Class[] { Boolean.TYPE, Boolean.TYPE });
        method.invoke(file, new Object[] {filePermission.isExecutable(), filePermission.isOwnerOnlyExecutable()});

        method = File.class.getMethod("setWritable", new Class[] { Boolean.TYPE, Boolean.TYPE });
        method.invoke(file, new Object[] {filePermission.isWritable(), filePermission.isOwnerOnlyWritable()});
    } catch (final Exception e) {
        logger.error("error calling dynamically file permissions with jvm " + e.getMessage(), e);
        throw new RuntimeException("error calling dynamically file permissions with jvm " + e.getMessage(), e);
    }
}
 
Example 2
Source File: NPM.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to extract the version from a NPM by reading its 'package.json' file.
 *
 * @param npmDirectory the directory in which the NPM is installed
 * @param log          the logger object
 * @return the read version, "0.0.0" if there are not 'package.json' file, {@code null} if this file cannot be
 * read or does not contain the "version" metadata
 */
public static String getVersionFromNPM(File npmDirectory, Log log) {
    File packageFile = new File(npmDirectory, PACKAGE_JSON);
    if (!packageFile.isFile()) {
        return "0.0.0";
    }

    FileReader reader = null;
    try {
        reader = new FileReader(packageFile);  //NOSONAR
        JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
        return (String) json.get("version");
    } catch (IOException | ParseException e) {
        log.error("Cannot extract version from " + packageFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return null;
}
 
Example 3
Source File: ExtensionDescriptorMojo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void collectMissing(Log log, int depth, List<AppArtifactKey> missing) {
    final StringBuilder buf = new StringBuilder();
    if (included) {
        buf.append('+');
    } else {
        buf.append('-');
        missing.add(gact);
    }
    buf.append(' ');
    for (int i = 0; i < depth; ++i) {
        buf.append("    ");
    }
    buf.append(gact);
    log.error(buf.toString());
    for (Node child : children) {
        child.collectMissing(log, depth + 1, missing);
    }
}
 
Example 4
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 5
Source File: BaseMojo.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
static void printBigErrorMessageAndThrow(Log log, String terseMessage, List<String> linesToLog) throws MojoExecutionException {
    log.error("");
    log.error("");
    log.error("");
    log.error("************************************");
    log.error("Could not execute the release plugin");
    log.error("************************************");
    log.error("");
    log.error("");
    for (String line : linesToLog) {
        log.error(line);
    }
    log.error("");
    log.error("");
    throw new MojoExecutionException(terseMessage);
}
 
Example 6
Source File: LocalGitRepo.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
public boolean revertChanges(Log log, List<File> changedFiles) throws MojoExecutionException {
    if (hasReverted) {
        return true;
    }
    boolean hasErrors = false;
    File workTree = workingDir();
    for (File changedFile : changedFiles) {
        try {
            String pathRelativeToWorkingTree = Repository.stripWorkDir(workTree, changedFile);
            git.checkout().addPath(pathRelativeToWorkingTree).call();
        } catch (Exception e) {
            hasErrors = true;
            log.error("Unable to revert changes to " + changedFile + " - you may need to manually revert this file. Error was: " + e.getMessage());
        }
    }
    hasReverted = true;
    return !hasErrors;
}
 
Example 7
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 8
Source File: NPM.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the NPM registry location.
 *
 * @param node           the node manager
 * @param log            the logger
 * @param npmRegistryUrl the registry url
 */
public static void configureRegistry(NodeManager node, Log log, String npmRegistryUrl) {
    try {
        node.factory().getNpmRunner(node.proxy()).execute("config set registry " + npmRegistryUrl);
    } catch (TaskRunnerException e) {
        log.error("Error during the configuration of NPM registry with the url " + npmRegistryUrl + " - check log", e);
    }
}
 
Example 9
Source File: AwsAutoScalingDeployUtils.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public List<Ec2Instance> getInstancesForAutoScalingGroup(Log log, AutoScalingGroup autoScalingGroup) throws MojoFailureException {
    log.info("retrieving list of instanceId's for auto scaling group with id : " + activeConfiguration.getAutoScalingGroupId());

    activeConfiguration.getHosts().clear();

    log.debug("describing instances in auto scaling group");

    if (autoScalingGroup.getInstances().isEmpty()) {
        return new ArrayList<>();
    }

    Map<String, Instance> instanceMap = autoScalingGroup.getInstances().stream().collect(Collectors.toMap(Instance::getInstanceId, Function.identity()));

    try {
        DescribeInstancesResult instancesResult = awsEc2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(autoScalingGroup.getInstances().stream().map(Instance::getInstanceId).collect(Collectors.toList())));
        List<Ec2Instance> ec2Instances = instancesResult.getReservations().stream().flatMap(r -> r.getInstances().stream()).map(this::toEc2Instance).collect(Collectors.toList());
        log.debug("describing elb status");
        autoScalingGroup.getLoadBalancerNames().forEach(elb -> this.updateInstancesStateOnLoadBalancer(elb, ec2Instances));
        ec2Instances.forEach(i -> i.updateAsState(AwsState.map(instanceMap.get(i.getInstanceId()).getLifecycleState())));
        ec2Instances.sort((o1, o2) -> {

            int sComp = o1.getAsState().compareTo(o2.getAsState());

            if (sComp != 0) {
                return sComp;
            } else {
                return o1.getElbState().compareTo(o2.getElbState());
            }
        });
        if (activeConfiguration.isIgnoreInStandby()) {
            return ec2Instances.stream().filter(i -> i.getAsState() != AwsState.STANDBY).collect(Collectors.toList());
        }
        return ec2Instances;
    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
        throw new MojoFailureException(e.getMessage());
    }

}
 
Example 10
Source File: Ec2Instance.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public boolean isReachable(boolean usePrivate, int port, Log log) {
    if (usePrivate ? privateIp == null : publicIp == null) {
        log.error("Instance has no IP, probably still booting");
        return false;
    }
    return InstanceUtils.isReachable(usePrivate ? privateIp : publicIp, port, instanceId, log);
}
 
Example 11
Source File: DockerBuildInformation.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void updateGitInformation(Log log) {
  try {
    final Repository repo = new Git().getRepo();
    if (repo != null) {
      this.repo   = repo.getConfig().getString("remote", "origin", "url");
      final ObjectId head = repo.resolve("HEAD");
      if (head != null && !isNullOrEmpty(head.getName())) {
        this.commit = head.getName();
      }
    }
  } catch (IOException e) {
    log.error("Failed to read Git information", e);
  }
}
 
Example 12
Source File: MavenLogHandler.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new MavenLogHandler which adapts a {@link Handler} to emit log messages onto a Maven Log.
 *
 * @param log                       The Maven Log to emit log messages to.
 * @param prefix                    An optional prefix used to prefix any log message.
 * @param encoding                  The encoding which should be used.
 * @param acceptedLogRecordPrefixes A non-null list of prefixes holding LogRecord logger names for
 *                                  permitted/accepted LogRecords.
 */
public MavenLogHandler(final Log log,
                       final String prefix,
                       final String encoding,
                       final String[] acceptedLogRecordPrefixes) {

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

    // Assign internal state
    this.log = log;
    this.prefix = prefix.isEmpty() ? "" : "[" + prefix + "]: ";

    setFormatter(new SimpleFormatter());
    setLevel(getJavaUtilLoggingLevelFor(log));
    try {
        setEncoding(encoding);
    } catch (UnsupportedEncodingException e) {
        log.error("Could not use encoding '" + encoding + "'", e);
    }

    if (acceptedLogRecordPrefixes != null && acceptedLogRecordPrefixes.length > 0) {
        setFilter(getLoggingFilter(acceptedLogRecordPrefixes));
    }
}
 
Example 13
Source File: AbiCheck.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static boolean matchingClasses(String className, JavaClassSignature expected,
    JavaClassSignature actual, Log log) {
  boolean match = true;
  if (!expected.superClass.equals(actual.superClass)) {
    match = false;
    log.error(String
        .format("Class %s: Expected superclass %s, found %s", className, expected.superClass,
            actual.superClass));
  }
  if (!SetMatcher.compare(expected.interfaces, actual.interfaces,
      item -> true,
      item -> log.error(String.format("Class %s: Missing interface %s", className, item)),
      item -> log.error(String.format("Class %s: Extra interface %s", className, item)))) {
    match = false;
  }
  if (!SetMatcher
      .compare(new HashSet<>(expected.attributes), new HashSet<>(actual.attributes),
          item -> true,
          item -> log.error(String.format("Class %s: Missing attribute %s", className, item)),
          item -> log.error(String.format("Class %s: Extra attribute %s", className, item)))) {
    match = false;
  }
  if (!SetMatcher.compare(expected.methods, actual.methods,
      item -> true,
      item -> log.error(String.format("Class %s: Missing method %s", className, item)),
      item -> log.error(String.format("Class %s: Extra method %s", className, item)))) {
    match = false;
  }
  if (!SetMatcher.compare(expected.fields, actual.fields,
      item -> true,
      item -> log.error(String.format("Class %s: Missing field %s", className, item)),
      item -> log.error(String.format("Class %s: Extra field %s", className, item)))) {
    match = false;
  }
  return match;
}
 
Example 14
Source File: AbstractRepo.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
public int execute(@Nullable String customCommand, @Nonnull final Log logger, @Nonnull final File cvsFolder, @Nonnull @MustNotContainNull final String... args) {
  final List<String> cli = new ArrayList<>();
  cli.add(GetUtils.findFirstNonNull(customCommand, this.command));
  cli.addAll(Arrays.asList(args));

  if (logger.isDebugEnabled()) {
    logger.debug("Executing repo command : " + cli);
  }

  final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
  final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

  final ProcessExecutor executor = new ProcessExecutor(cli);

  int result = -1;

  try {
    final ProcessResult processResult = executor.directory(cvsFolder).redirectError(errorStream).redirectOutput(outStream).executeNoTimeout();
    result = processResult.getExitValue();

    if (logger.isDebugEnabled()) {
      logger.debug("Exec.out.........................................");
      logger.debug(new String(errorStream.toByteArray(), Charset.defaultCharset()));
      logger.debug(".................................................");
    }

    if (result != 0) {
      logger.error(new String(errorStream.toByteArray(), Charset.defaultCharset()));
    }

  } catch (IOException | InterruptedException | InvalidExitValueException ex) {
    if (ex instanceof InterruptedException) {
      Thread.currentThread().interrupt();
    }
    logger.error("Unexpected error", ex);
  }

  return result;
}
 
Example 15
Source File: BuildMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
private static void requireValidDockerFilePath(@Nonnull Log log,
                                               @Nonnull Path contextDirectory,
                                               @Nullable Path dockerfile)
    throws MojoFailureException {

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

  if (dockerfile == null
          && !Files.exists(contextDirectory.resolve("Dockerfile"))
          && !Files.exists(contextDirectory.resolve("dockerfile"))) {
    // user did not override the default value
    log.error("Missing Dockerfile in context directory: " + contextDirectory);
    throw new MojoFailureException("Missing Dockerfile in context directory: "
        + contextDirectory);
  }

  if (dockerfile != null) {
    if (!Files.exists(dockerfile)) {
      log.error("Missing Dockerfile at " + dockerfile);
      throw new MojoFailureException("Missing Dockerfile at " + dockerfile);
    }
    if (!dockerfile.startsWith(contextDirectory)) {
      log.error("Dockerfile " + dockerfile + " is not a child of the context directory: "
          + contextDirectory);
      throw new MojoFailureException("Dockerfile " + dockerfile
          + " is not a child of the context directory: " + contextDirectory);
    }
  }
}
 
Example 16
Source File: WebJars.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file.
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(Log log, File file) {
    if (file == null) {
        return false;
    }
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        try (JarFile jar = new JarFile(file)) {

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(matcher.group(1) + "-" + matcher.group(2));
                }
            }
        } catch (IOException e) {
            log.error("Cannot check if the file " + file.getName()
                + " is a webjar, cannot open it", e);
            return false;
        }

        for (String lib : found) {
            log.info("Web Library found in " + file.getName() + " : " + lib);
        }

        return !found.isEmpty();
    }

    return false;
}
 
Example 17
Source File: WebJars.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file.
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(Log log, File file) {
    if (file == null) {
        return false;
    }
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        try (JarFile jar = new JarFile(file)) {

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            search(found, jar);
        } catch (IOException e) {
            log.error("Cannot check if the file " + file.getName()
                + " is a webjar, cannot open it", e);
            return false;
        }

        for (String lib : found) {
            log.info("Web Library found in " + file.getName() + " : " + lib);
        }

        return !found.isEmpty();
    }

    return false;
}
 
Example 18
Source File: IDLReader.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void init(
        Document iddDoc,
        Document extensionDoc,
        final String service,
        String packageName,
        final String basedir,
        final String genSrcDir,
        final Log log,
        final String outputDir,
        boolean client,
        boolean server)
        throws Exception {

    try {
        output = new File(basedir, genSrcDir);
        if (outputDir != null) {
            iDDOutputDir = new File(basedir+"/"+outputDir);
            if (!iDDOutputDir.exists()) {
                if (!iDDOutputDir.mkdirs()) {
                    throw new IllegalArgumentException("IDD Output Directory "+iDDOutputDir+" could not be created");
                }
            }
            if (!iDDOutputDir.isDirectory() || (!iDDOutputDir.canWrite())) {
                throw new IllegalArgumentException("IDD Output Directory "+iDDOutputDir+" is not a directory or cannot be written to.");
            }
        }
        config = new Configuration();
        config.setClassForTemplateLoading(IDLReader.class, "/templates");

        config.setStrictSyntaxMode(true);
        this.log = log;
        this.packageName = packageName;
        this.service = service;
        this.client = client;
        this.server = server || !client; // server must be true if client if false.

        dataModel = NodeModel.wrap(iddDoc.cloneNode(true));

        if (extensionDoc != null) {
            NodeModel extensionModel = NodeModel.wrap(extensionDoc);
            mergeExtensionsIntoDocument(getRootNode(dataModel),
                    getRootNode(extensionModel));
            removeUndefinedOperations(getRootNode(dataModel),
                    getRootNode(extensionModel));
        }
        if(log.isDebugEnabled()) {
            log.debug(serialize());
        }
    } catch (final Exception e) {
        log.error("Failed to initialise FTL", e);
        throw e;
    }
}
 
Example 19
Source File: ProcessRunner.java    From botsing with Apache License 2.0 4 votes vote down vote up
private static boolean executeProcess(File workDir, Log log, long timeout, String... command)
		throws InterruptedException, IOException {
	Process process = null;

	if (log.isDebugEnabled()) {
		log.debug("Going to execute command: " + String.join(" ", command));
	}

	try {
		ProcessBuilder builder = new ProcessBuilder(command);

		builder.directory(workDir.getAbsoluteFile());
		builder.redirectErrorStream(true);

		process = builder.start();
		handleProcessOutput(process, log);

		boolean exitResult = process.waitFor(timeout, TimeUnit.SECONDS);

		// process did not complete before timeout, kill it
		if (!exitResult) {
			log.error("Process terminated because it took more than " + timeout + "s to complete");
			throw new InterruptedException();
		}

		// Get process exitcode
		int exitCode = process.waitFor();

		if (exitCode != 0) {
			// process terminated abnormally
			log.error("Error executing process");
			return false;

		} else {
			// process terminated normally
			log.debug("Process terminated");
		}

	} catch (InterruptedException e) {
		if (process != null) {

			try {
				// be sure streamers are closed, otherwise process might
				// hang on Windows
				process.getOutputStream().close();
				process.getInputStream().close();
				process.getErrorStream().close();

			} catch (Exception t) {
				log.error("Failed to close process stream: " + t.toString());
			}

			process.destroy();

		}
		return false;

	}

	return true;
}