Java Code Examples for org.codehaus.plexus.util.StringUtils#isNotBlank()

The following examples show how to use org.codehaus.plexus.util.StringUtils#isNotBlank() . 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: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Executes git commit -a -m, replacing <code>@{map.key}</code> with
 * <code>map.value</code>.
 * 
 * @param message
 *            Commit message.
 * @param messageProperties
 *            Properties to replace in message.
 * @throws MojoFailureException
 * @throws CommandLineException
 */
protected void gitCommit(String message, Map<String, String> messageProperties)
        throws MojoFailureException, CommandLineException {
    if (StringUtils.isNotBlank(commitMessagePrefix)) {
        message = commitMessagePrefix + message;
    }

    message = replaceProperties(message, messageProperties);

    if (gpgSignCommit) {
        getLog().info("Committing changes. GPG-signed.");

        executeGitCommand("commit", "-a", "-S", "-m", message);
    } else {
        getLog().info("Committing changes.");

        executeGitCommand("commit", "-a", "-m", message);
    }
}
 
Example 2
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Validates plugin configuration. Throws exception if configuration is not
 * valid.
 * 
 * @param params
 *            Configuration parameters to validate.
 * @throws MojoFailureException
 *             If configuration is not valid.
 */
protected void validateConfiguration(String... params)
        throws MojoFailureException {
    if (StringUtils.isNotBlank(argLine)
            && MAVEN_DISALLOWED_PATTERN.matcher(argLine).find()) {
        throw new MojoFailureException(
                "The argLine doesn't match allowed pattern.");
    }
    if (params != null && params.length > 0) {
        for (String p : params) {
            if (StringUtils.isNotBlank(p)
                    && MAVEN_DISALLOWED_PATTERN.matcher(p).find()) {
                throw new MojoFailureException("The '" + p
                        + "' value doesn't match allowed pattern.");
            }
        }
    }
}
 
Example 3
Source File: MavenDependencyScanner.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
private Dependency mapMavenDependencyToLicense(Dependency dependency)
{
    if (StringUtils.isNotBlank(dependency.getLicense()))
    {
        return dependency;
    }

    for (MavenDependency allowedDependency : mavenDependencyService.getMavenDependencies())
    {
        String matchString = allowedDependency.getKey();
        if (dependency.getName().matches(matchString))
        {
            dependency.setLicense(allowedDependency.getLicense());
        }
    }
    return dependency;
}
 
Example 4
Source File: AbstractInvisibleProjectBasedTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
protected IProject importRootFolder(IPath rootPath, String triggerFile) throws Exception {
	if (StringUtils.isNotBlank(triggerFile)) {
		IPath triggerFilePath = rootPath.append(triggerFile);
		Preferences preferences = preferenceManager.getPreferences();
		preferences.setTriggerFiles(Arrays.asList(triggerFilePath));
	}
	final List<IPath> roots = Arrays.asList(rootPath);
	IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			projectsManager.initializeProjects(roots, monitor);
		}
	};
	JavaCore.run(runnable, null, monitor);
	waitForBackgroundJobs();
	String invisibleProjectName = ProjectUtils.getWorkspaceInvisibleProjectName(rootPath);
	return ResourcesPlugin.getWorkspace().getRoot().getProject(invisibleProjectName);
}
 
Example 5
Source File: SystemPropertyStrategy.java    From maven-external-version with Apache License 2.0 5 votes vote down vote up
@Override
public String getVersion( MavenProject mavenProject )
    throws ExternalVersionException
{
    String newVersion = System.getProperty( EXTERNAL_VERSION, mavenProject.getVersion() );
    String qualifier = StringUtils.trim( System.getProperty( EXTERNAL_VERSION_QUALIFIER ) );

    if ( StringUtils.isNotBlank( qualifier ) )
    {
        // TODO: this needs to be cleaned up, the calling method will re-add the -SNAPSHOT if needed, but this is dirty
        newVersion = newVersion.replaceFirst( "-SNAPSHOT", "" ) + "-" + qualifier;
    }

    return newVersion;
}
 
Example 6
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Executes git rebase or git merge --ff-only or git merge --no-ff or git merge.
 * 
 * @param branchName
 *            Branch name to merge.
 * @param rebase
 *            Do rebase.
 * @param noff
 *            Merge with --no-ff.
 * @param ffonly
 *            Merge with --ff-only.
 * @param message
 *            Merge commit message.
 * @param messageProperties
 *            Properties to replace in message.
 * @throws MojoFailureException
 * @throws CommandLineException
 */
protected void gitMerge(final String branchName, boolean rebase, boolean noff, boolean ffonly, String message,
        Map<String, String> messageProperties)
        throws MojoFailureException, CommandLineException {
    String sign = "";
    if (gpgSignCommit) {
        sign = "-S";
    }
    String msgParam = "";
    String msg = "";
    if (StringUtils.isNotBlank(message)) {
        if (StringUtils.isNotBlank(commitMessagePrefix)) {
            message = commitMessagePrefix + message;
        }

        msgParam = "-m";
        msg = replaceProperties(message, messageProperties);
    }
    if (rebase) {
        getLog().info("Rebasing '" + branchName + "' branch.");
        executeGitCommand("rebase", sign, branchName);
    } else if (ffonly) {
        getLog().info("Merging (--ff-only) '" + branchName + "' branch.");
        executeGitCommand("merge", "--ff-only", sign, branchName);
    } else if (noff) {
        getLog().info("Merging (--no-ff) '" + branchName + "' branch.");
        executeGitCommand("merge", "--no-ff", sign, branchName, msgParam, msg);
    } else {
        getLog().info("Merging '" + branchName + "' branch.");
        executeGitCommand("merge", sign, branchName, msgParam, msg);
    }
}
 
Example 7
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Executes git commands to check for uncommitted changes.
 * 
 * @return <code>true</code> when there are uncommitted changes,
 *         <code>false</code> otherwise.
 * @throws CommandLineException
 * @throws MojoFailureException
 */
private boolean executeGitHasUncommitted() throws MojoFailureException,
        CommandLineException {
    boolean uncommited = false;

    // 1 if there were differences and 0 means no differences

    // git diff --no-ext-diff --ignore-submodules --quiet --exit-code
    final CommandResult diffCommandResult = executeGitCommandExitCode(
            "diff", "--no-ext-diff", "--ignore-submodules", "--quiet",
            "--exit-code");

    String error = null;

    if (diffCommandResult.getExitCode() == SUCCESS_EXIT_CODE) {
        // git diff-index --cached --quiet --ignore-submodules HEAD --
        final CommandResult diffIndexCommandResult = executeGitCommandExitCode(
                "diff-index", "--cached", "--quiet", "--ignore-submodules",
                "HEAD", "--");
        if (diffIndexCommandResult.getExitCode() != SUCCESS_EXIT_CODE) {
            error = diffIndexCommandResult.getError();
            uncommited = true;
        }
    } else {
        error = diffCommandResult.getError();
        uncommited = true;
    }

    if (StringUtils.isNotBlank(error)) {
        throw new MojoFailureException(error);
    }

    return uncommited;
}
 
Example 8
Source File: GitFlowFeatureStartMojo.java    From gitflow-maven-plugin with Apache License 2.0 5 votes vote down vote up
private boolean validateBranchName(String name, String pattern)
        throws MojoFailureException, CommandLineException {
    boolean valid = true;
    if (StringUtils.isNotBlank(name) && validBranchName(name)) {
        if (StringUtils.isNotBlank(pattern) && !name.matches(pattern)) {
            getLog().warn("The name of the branch doesn't match '" + pattern
                    + "'.");
            valid = false;
        }
    } else {
        getLog().warn("The name of the branch is not valid.");
        valid = false;
    }
    return valid;
}
 
Example 9
Source File: AbstractWASMojo.java    From was-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected Set<WebSphereModel> getWebSphereModels() {
  String deployTargets = System.getProperty(Constants.KEY_DEPLOY_TARGETS);

  if (StringUtils.isNotBlank(deployTargets)) {
    if (null != deploymentsPropertyFile && deploymentsPropertyFile.exists()) {
      Map<String, Properties> propertiesMap = PropertiesUtils.loadSectionedProperties(deploymentsPropertyFile, getProjectProperties());
      if (null != propertiesMap && propertiesMap.size() >= 1) {
        getLog().info("Multi targets: " + deployTargets);
        return getWebSphereModels(deployTargets, propertiesMap);
      }
    }

    if (null == deploymentsPropertyFile) {
      getLog().info("Property config file: " + deploymentsPropertyFile + " not configured.");
    }
    if (!deploymentsPropertyFile.exists()) {
      getLog().info("Property config file: " + deploymentsPropertyFile + " doesn't exist.");
    }
    getLog().info("Single target not properly configured.");
    return null;
  } else {
    WebSphereModel model = getWebSphereModel();
    if (!model.isValid()) {
      getLog().info("Single target not properly configured. Missing 'cell' or 'cluster' or 'server' or 'node'");
      return null;
    }
    getLog().info("Single target: " + model.getHost());
    Set<WebSphereModel> models = new HashSet<WebSphereModel>(1);
    models.add(model);
    return models;
  }
}
 
Example 10
Source File: MavenDependencyScanner.java    From sonarqube-licensecheck with Apache License 2.0 5 votes vote down vote up
private Function<Dependency, Dependency> loadLicenseFromPom(Map<Pattern, String> licenseMap, MavenSettings settings)
{
    return (Dependency dependency) ->
    {
        if (StringUtils.isNotBlank(dependency.getLicense())
            || dependency.getPomPath() == null)
        {
            return dependency;
        }

        return loadLicense(licenseMap, settings, dependency);
    };
}
 
Example 11
Source File: PomModel.java    From raptor with Apache License 2.0 4 votes vote down vote up
public String getGroupId() {
    return StringUtils.isNotBlank(groupId) ? groupId : DEFAULT_GROUP_ID;
}
 
Example 12
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 13
Source File: AntTaskUtils.java    From was-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static void execute(WebSphereModel model, PlexusConfiguration target, MavenProject project,
                           MavenProjectHelper projectHelper, List<Artifact> pluginArtifact, Log logger)
    throws IOException, MojoExecutionException {
  // The fileName should probably use the plugin executionId instead of the targetName
  boolean useDefaultTargetName = false;
  String antTargetName = target.getAttribute("name");
  if (null == antTargetName) {
    antTargetName = DEFAULT_ANT_TARGET_NAME;
    useDefaultTargetName = true;
  }
  StringBuilder fileName = new StringBuilder(50);
  fileName.append("build");
  if (StringUtils.isNotBlank(model.getHost())) {
    fileName.append("-").append(model.getHost());
  }
  if (StringUtils.isNotBlank(model.getApplicationName())) {
    fileName.append("-").append(model.getApplicationName());
  }
  fileName.append("-").append(antTargetName).append("-").append(CommandUtils.getTimestampString()).append(".xml");
  File buildFile = getBuildFile(project, fileName.toString());

  if (model.isVerbose()) {
    logger.info("ant fileName: " + fileName);
  }

  if (buildFile.exists()) {
    logger.info("[SKIPPED] already executed");
    return;
  }

  StringWriter writer = new StringWriter();
  AntXmlPlexusConfigurationWriter xmlWriter = new AntXmlPlexusConfigurationWriter();
  xmlWriter.write(target, writer);

  StringBuffer antXML = writer.getBuffer();

  if (useDefaultTargetName) {
    stringReplace(antXML, "<target", "<target name=\"" + antTargetName + "\"");
  }

  final String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
  antXML.insert(0, xmlHeader);
  final String projectOpen = "<project name=\"" + Constants.PLUGIN_ID + "\" default=\"" + antTargetName + "\">\n";
  int index = antXML.indexOf("<target");
  antXML.insert(index, projectOpen);

  final String projectClose = "\n</project>";
  antXML.append(projectClose);

  buildFile.getParentFile().mkdirs();
  FileUtils.fileWrite(buildFile.getAbsolutePath(), "UTF-8", antXML.toString());

  Project antProject = generateAntProject(model, buildFile, project, projectHelper, pluginArtifact, logger);
  antProject.executeTarget(antTargetName);
}
 
Example 14
Source File: EclipselinkModelGenMojo.java    From eclipselink-maven-plugin with Apache License 2.0 4 votes vote down vote up
private List<String> buildCompilerOptions(String processor, String compileClassPath)
{
    final Map<String, String> compilerOpts = new LinkedHashMap<String, String>();
    compilerOpts.put("cp", compileClassPath);
    compilerOpts.put("proc:only", null);
    compilerOpts.put("processor", processor);

    if (this.noWarn)
    {
        compilerOpts.put("nowarn", null);
    }

    if (this.verbose)
    {
        compilerOpts.put("verbose", null);
    }

    if (!StringUtils.isEmpty(encoding))
    {
        compilerOpts.put("encoding", encoding);
    }

    info("Output directory: " + this.generatedSourcesDirectory.getAbsolutePath());
    if (!this.generatedSourcesDirectory.exists())
    {
        this.generatedSourcesDirectory.mkdirs();
    }
    compilerOpts.put("d", this.generatedSourcesDirectory.getAbsolutePath());

    try
    {
        compilerOpts.put("sourcepath", source.getCanonicalPath());
    }
    catch (IOException e)
    {
        throw new RuntimeException(e.getMessage(), e);
    }

    final List<String> opts = new ArrayList<String>(compilerOpts.size() * 2);
    for (Map.Entry<String, String> compilerOption : compilerOpts.entrySet())
    {
        opts.add("-" + compilerOption.getKey());
        String value = compilerOption.getValue();
        if (StringUtils.isNotBlank(value))
        {
            opts.add(value);
        }
    }
    return opts;
}
 
Example 15
Source File: PodlockParser.java    From hub-detect with Apache License 2.0 4 votes vote down vote up
private Optional<String> parseRawPodName(final String podText) {
    if (StringUtils.isNotBlank(podText)) {
        return Optional.of(podText.split(" ")[0].trim());
    }
    return Optional.empty();
}
 
Example 16
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Executes command line.
 * 
 * @param cmd
 *            Command line.
 * @param failOnError
 *            Whether to throw exception on NOT success exit code.
 * @param argStr
 *            Command line arguments as a string.
 * @param args
 *            Command line arguments.
 * @return {@link CommandResult} instance holding command exit code, output
 *         and error if any.
 * @throws CommandLineException
 * @throws MojoFailureException
 *             If <code>failOnError</code> is <code>true</code> and command
 *             exit code is NOT equals to 0.
 */
private CommandResult executeCommand(final Commandline cmd,
        final boolean failOnError, final String argStr,
        final String... args) throws CommandLineException,
        MojoFailureException {
    // initialize executables
    initExecutables();

    if (getLog().isDebugEnabled()) {
        getLog().debug(
                cmd.getExecutable() + " " + StringUtils.join(args, " ")
                        + (argStr == null ? "" : " " + argStr));
    }

    cmd.clearArgs();
    cmd.addArguments(args);

    if (StringUtils.isNotBlank(argStr)) {
        cmd.createArg().setLine(argStr);
    }

    final StringBufferStreamConsumer out = new StringBufferStreamConsumer(
            verbose);

    final CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();

    // execute
    final int exitCode = CommandLineUtils.executeCommandLine(cmd, out, err);

    String errorStr = err.getOutput();
    String outStr = out.getOutput();

    if (failOnError && exitCode != SUCCESS_EXIT_CODE) {
        // not all commands print errors to error stream
        if (StringUtils.isBlank(errorStr) && StringUtils.isNotBlank(outStr)) {
            errorStr = outStr;
        }

        throw new MojoFailureException(errorStr);
    }

    return new CommandResult(exitCode, outStr, errorStr);
}
 
Example 17
Source File: PomModel.java    From raptor with Apache License 2.0 4 votes vote down vote up
public String getVersion() {
    return StringUtils.isNotBlank(version) ? version : DEFAULT_VERSION;
}
 
Example 18
Source File: PomModel.java    From raptor with Apache License 2.0 4 votes vote down vote up
public String getArtifactId() {
    return StringUtils.isNotBlank(artifactId) ? artifactId : DEFAULT_ARTIFACT_ID;
}
 
Example 19
Source File: Utils.java    From deadcode4j with Apache License 2.0 2 votes vote down vote up
/**
 * Indicates if a <code>String</code> is neither <code>null</code>, empty, nor consists of whitespace only.
 *
 * @since 2.2.0
 */
public static boolean isNotBlank(@Nullable String string) {
    // we simply delegate this - but we have it in one place
    return StringUtils.isNotBlank(string);
}
 
Example 20
Source File: GitFlowVersionInfo.java    From gitflow-maven-plugin with Apache License 2.0 2 votes vote down vote up
/**
 * Validates version.
 * 
 * @param version
 *            Version to validate.
 * @return <code>true</code> when version is valid, <code>false</code>
 *         otherwise.
 */
public static boolean isValidVersion(final String version) {
    return StringUtils.isNotBlank(version)
            && (ALTERNATE_PATTERN.matcher(version).matches() || STANDARD_PATTERN
                    .matcher(version).matches());
}