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

The following examples show how to use org.codehaus.plexus.util.StringUtils#isBlank() . 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: DeployUtils.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
public List<Exclusion> parseExclusions(String exclusions) {
    List<Exclusion> result = new ArrayList<>();
    if (StringUtils.isBlank(exclusions)) {
        return result;
    }

    Pattern.compile(";")
            .splitAsStream(exclusions)
            .forEach(s -> {
                        String[] mavenIds = Pattern.compile(":").split(s, 2);
                        if (mavenIds.length == 2) {
                            Exclusion exclusion = new Exclusion();
                            exclusion.setGroupId(mavenIds[0]);
                            exclusion.setArtifactId(mavenIds[1]);
                            result.add(exclusion);
                        }
                    }
            );
    return result;
}
 
Example 2
Source File: RegexPropertySetting.java    From build-helper-maven-plugin with MIT License 6 votes vote down vote up
public void validate()
{
    if ( StringUtils.isBlank( name ) )
    {
        throw new IllegalArgumentException( "name required" );
    }

    if ( StringUtils.isBlank( value ) )
    {
        throw new IllegalArgumentException( "value required" );
    }

    if ( StringUtils.isBlank( regex ) )
    {
        throw new IllegalArgumentException( "regex required" );
    }

    if ( toLowerCase && toUpperCase )
    {
        throw new IllegalArgumentException( "either toUpperCase or toLowerCase can be set, but not both." );
    }
}
 
Example 3
Source File: AbstractScmMojo.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
/**
 * Get info from scm.
 *
 * @param repository
 * @param fileSet
 * @return
 * @throws ScmException
 * @todo this should be rolled into org.apache.maven.scm.provider.ScmProvider and
 *       org.apache.maven.scm.provider.svn.SvnScmProvider
 */
protected InfoScmResult info( ScmRepository repository, ScmFileSet fileSet )
    throws ScmException
{
    CommandParameters commandParameters = new CommandParameters();

    // only for Git, we will make a test for shortRevisionLength parameter
    if ( GitScmProviderRepository.PROTOCOL_GIT.equals( scmManager.getProviderByRepository( repository ).getScmType() )
        && this.shortRevisionLength > 0 )
    {
        getLog().info( "ShortRevision tag detected. The value is '" + this.shortRevisionLength + "'." );
        if ( shortRevisionLength >= 0 && shortRevisionLength < 4 )
        {
            getLog().warn( "shortRevision parameter less then 4. ShortRevisionLength is relaying on 'git rev-parese --short=LENGTH' command, accordingly to Git rev-parse specification the LENGTH value is miminum 4. " );
        }
        commandParameters.setInt( CommandParameter.SCM_SHORT_REVISION_LENGTH, this.shortRevisionLength );
    }

    if ( !StringUtils.isBlank( scmTag ) && !"HEAD".equals( scmTag ) )
    {
        commandParameters.setScmVersion( CommandParameter.SCM_VERSION, new ScmTag( scmTag ) );
    }

    return scmManager.getProviderByRepository( repository ).info( repository.getProviderRepository(), fileSet,
                                                                  commandParameters );
}
 
Example 4
Source File: ThemeMojo.java    From opoopress with Apache License 2.0 6 votes vote down vote up
private void updateThemeConfigurationFile(SiteConfigImpl siteConfig, File themeDir) throws MojoFailureException{
    File config = new File(themeDir, "theme.yml");
    if (!config.exists()) {
        throw new MojoFailureException("Config file '" + config + "' not exists.");
    }

    Locale loc = Locale.getDefault();
    //locale from parameter
    String localeString = locale;
    //locale from site configuration
    if(StringUtils.isBlank(localeString)){
        localeString = siteConfig.get("locale");
    }
    if (StringUtils.isNotEmpty(localeString)) {
        loc = LocaleUtils.toLocale(localeString);
    }

    File localeConfig = new File(themeDir, "theme_" + loc.toString() + ".yml");
    if (localeConfig.exists()) {
        config.renameTo(new File(themeDir, "theme-original.yml"));
        localeConfig.renameTo(config);
    }
}
 
Example 5
Source File: CpanListParser.java    From hub-detect with Apache License 2.0 6 votes vote down vote up
Map<String, String> createNameVersionMap(final List<String> listText) {
    final Map<String, String> nameVersionMap = new HashMap<>();

    for (final String line : listText) {
        if (StringUtils.isBlank(line)) {
            continue;
        }

        if (StringUtils.countMatches(line, "\t") != 1 || line.trim().contains(" ")) {
            continue;
        }

        try {
            final String[] module = line.trim().split("\t");
            final String name = module[0].trim();
            final String version = module[1].trim();
            nameVersionMap.put(name, version);
        } catch (final IndexOutOfBoundsException indexOutOfBoundsException) {
            logger.debug(String.format("Failed to handle the following line:%s", line));
        }
    }

    return nameVersionMap;
}
 
Example 6
Source File: MavenDependencyScanner.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
private static void licenseMatcher(Map<Pattern, String> licenseMap, Dependency dependency, License license)
{
    String licenseName = license.getName();
    if (StringUtils.isBlank(licenseName))
    {
        LOGGER.info("Dependency '{}' has no license set.", dependency.getName());
        return;
    }

    for (Entry<Pattern, String> entry : licenseMap.entrySet())
    {
        if (entry.getKey().matcher(licenseName).matches())
        {
            dependency.setLicense(entry.getValue());
            return;
        }
    }

    LOGGER.info("No licenses found for '{}'", licenseName);
}
 
Example 7
Source File: MySQLMessageQueueStorage.java    From hermes with Apache License 2.0 5 votes vote down vote up
private boolean matchesFilter(String topic, MessagePriority dataObj, String filterString) {
	if (StringUtils.isBlank(filterString)) {
		return true;
	}
	ByteBuf byteBuf = Unpooled.wrappedBuffer(dataObj.getAttributes());
	try {
		return m_filter.isMatch(topic, filterString, getAppProperties(byteBuf));
	} catch (Exception e) {
		log.error("Can not find filter for: {}" + filterString);
		return false;
	}
}
 
Example 8
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes command line executables.
 * 
 */
private void initExecutables() {
    if (StringUtils.isBlank(cmdMvn.getExecutable())) {
        if (StringUtils.isBlank(mvnExecutable)) {
            mvnExecutable = "mvn";
        }
        cmdMvn.setExecutable(mvnExecutable);
    }
    if (StringUtils.isBlank(cmdGit.getExecutable())) {
        if (StringUtils.isBlank(gitExecutable)) {
            gitExecutable = "git";
        }
        cmdGit.setExecutable(gitExecutable);
    }
}
 
Example 9
Source File: RequirePropertyDiverges.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the property is not null or empty string
 *
 * @param propValue value of the property from the project.
 * @throws EnforcerRuleException
 */
void checkPropValueNotBlank( Object propValue ) throws EnforcerRuleException
{

    if ( propValue == null || StringUtils.isBlank( propValue.toString() ) )
    {
        throw new EnforcerRuleException( String.format(
                "Property '%s' is required for this build and not defined in hierarchy at all.", property ) );
    }
}
 
Example 10
Source File: ValidateLicenses.java    From sonarqube-licensecheck with Apache License 2.0 5 votes vote down vote up
public Set<Dependency> validateLicenses(Set<Dependency> dependencies, SensorContext context)
{
    for (Dependency dependency : dependencies)
    {
        if (StringUtils.isBlank(dependency.getLicense()))
        {
            licenseNotFoundIssue(context, dependency);
        }
        else
        {
            checkForLicenses(context, dependency);
        }
    }
    return dependencies;
}
 
Example 11
Source File: BazelExternalIdGenerator.java    From hub-detect with Apache License 2.0 5 votes vote down vote up
private Optional<String[]> executeDependencyListQuery(final BazelExternalIdExtractionFullRule xPathRule, final List<String> dependencyListQueryArgs) {
    ExecutableOutput targetDependenciesQueryResults = null;
    try {
        targetDependenciesQueryResults = executableRunner.executeQuietly(workspaceDir, bazelExe, dependencyListQueryArgs);
    } catch (ExecutableRunnerException e) {
        logger.debug(String.format("Error executing bazel with args: %s: %s", dependencyListQueryArgs, e.getMessage()));
        exceptionsGenerated.put(xPathRule, e);
        return Optional.empty();
    }
    final int targetDependenciesQueryReturnCode = targetDependenciesQueryResults.getReturnCode();
    if (targetDependenciesQueryReturnCode != 0) {
        String msg = String.format("Error executing bazel with args: %s: Return code: %d; stderr: %s", dependencyListQueryArgs,
            targetDependenciesQueryReturnCode,
            targetDependenciesQueryResults.getErrorOutput());
        logger.debug(msg);
        exceptionsGenerated.put(xPathRule, new IntegrationException(msg));
        return Optional.empty();
    }
    final String targetDependenciesQueryOutput = targetDependenciesQueryResults.getStandardOutput();
    logger.debug(String.format("Bazel targetDependenciesQuery returned %d; output: %s", targetDependenciesQueryReturnCode, targetDependenciesQueryOutput));
    if (StringUtils.isBlank(targetDependenciesQueryOutput)) {
        logger.debug("Bazel targetDependenciesQuery found no dependencies");
        return Optional.empty();
    }
    final String[] rawDependencies = targetDependenciesQueryOutput.split("\\s+");
    return Optional.of(rawDependencies);
}
 
Example 12
Source File: MdPageGeneratorMojo.java    From markdown-page-generator-plugin with MIT License 5 votes vote down vote up
private String getInputEncoding() {
    if (StringUtils.isBlank(inputEncoding)) {
        return Charset.defaultCharset().name();
    } else {
        return inputEncoding;
    }
}
 
Example 13
Source File: MavenGoal.java    From butterfly with MIT License 5 votes vote down vote up
@Override
public String getDescription() {
    String description = DESCRIPTION + Arrays.toString(goals);
    if (!StringUtils.isBlank(getRelativePath())) {
        description += " against pom file " + getRelativePath();
    }
    return description;
}
 
Example 14
Source File: MdPageGeneratorMojo.java    From markdown-page-generator-plugin with MIT License 5 votes vote down vote up
private String getOutputEncoding() {
    if (StringUtils.isBlank(outputEncoding)) {
        return Charset.defaultCharset().name();
    } else {
        return outputEncoding;
    }
}
 
Example 15
Source File: InitMojo.java    From helm-maven-plugin with MIT License 4 votes vote down vote up
protected void downloadAndUnpackHelm() throws MojoExecutionException {

		Path directory = Paths.get(getHelmExecutableDirectory());
		if (Files.exists(directory.resolve(SystemUtils.IS_OS_WINDOWS ? "helm.exe" : "helm"))) {
			getLog().info("Found helm executable, skip init.");
			return;
		}

		String url = getHelmDownloadUrl();
		if (StringUtils.isBlank(url)) {
			String os = getOperatingSystem();
			String architecture = getArchitecture();
			String extension = getExtension();
			url = String.format("https://get.helm.sh/helm-v%s-%s-%s.%s", getHelmVersion(), os, architecture, extension);
		}

		getLog().debug("Downloading Helm: " + url);
		boolean found = false;
		try (InputStream dis = new URL(url).openStream();
			 InputStream cis = createCompressorInputStream(dis);
			 ArchiveInputStream is = createArchiverInputStream(cis)) {

			// create directory if not present
			Files.createDirectories(directory);

			// get helm executable entry
			ArchiveEntry entry = null;
			while ((entry = is.getNextEntry()) != null) {

				String name = entry.getName();
				if (entry.isDirectory() || (!name.endsWith("helm.exe") && !name.endsWith("helm"))) {
					getLog().debug("Skip archive entry with name: " + name);
					continue;
				}

				getLog().debug("Use archive entry with name: " + name);
				Path helm = directory.resolve(name.endsWith(".exe") ? "helm.exe" : "helm");
				try (FileOutputStream output = new FileOutputStream(helm.toFile())) {
					IOUtils.copy(is, output);
				}

				addExecPermission(helm);

				found = true;
				break;
			}

		} catch (IOException e) {
			throw new MojoExecutionException("Unable to download and extract helm executable.", e);
		} 

		if (!found) {
			throw new MojoExecutionException("Unable to find helm executable in tar file.");
		}
	}
 
Example 16
Source File: ArchiveLinker.java    From maven-native with MIT License 4 votes vote down vote up
@Override
protected Commandline createLinkerCommandLine( List<File> objectFiles, LinkerConfiguration config )
{
    Commandline cl = new Commandline();

    cl.setWorkingDirectory( config.getWorkingDirectory().getPath() );

    String executable = EXECUTABLE;

    if ( !StringUtils.isBlank( config.getExecutable() ) )
    {
        executable = config.getExecutable();
    }

    cl.setExecutable( executable );

    for ( int i = 0; i < config.getStartOptions().length; ++i )
    {
        cl.createArg().setValue( config.getStartOptions()[i] );
    }

    // the next 2 are for completeness, the start options should be good enough
    for ( int i = 0; i < config.getMiddleOptions().length; ++i )
    {
        cl.createArg().setValue( config.getMiddleOptions()[i] );
    }

    for ( int i = 0; i < config.getEndOptions().length; ++i )
    {
        cl.createArg().setValue( config.getEndOptions()[i] );
    }

    cl.createArg().setFile( config.getOutputFile() );

    for ( int i = 0; i < objectFiles.size(); ++i )
    {
        File objFile = objectFiles.get( i );

        cl.createArg().setValue( objFile.getPath() );
    }

    return cl;

}
 
Example 17
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 18
Source File: SetMojo.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private static String fixNullOrEmpty( String value, String defaultValue )
{
    return StringUtils.isBlank( value ) ? defaultValue : value;
}
 
Example 19
Source File: GitFlowReleaseStartMojo.java    From gitflow-maven-plugin with Apache License 2.0 4 votes vote down vote up
private String getReleaseVersion() throws MojoFailureException, VersionParseException, CommandLineException {
    // get current project version from pom
    final String currentVersion = getCurrentProjectVersion();

    String defaultVersion = null;
    if (tychoBuild) {
        defaultVersion = currentVersion;
    } else {
        // get default release version
        defaultVersion = new GitFlowVersionInfo(currentVersion)
                .getReleaseVersionString();
    }

    if (defaultVersion == null) {
        throw new MojoFailureException(
                "Cannot get default project version.");
    }

    String version = null;
    if (settings.isInteractiveMode()) {
        try {
            while (version == null) {
                version = prompter.prompt("What is release version? ["
                        + defaultVersion + "]");

                if (!"".equals(version)
                        && (!GitFlowVersionInfo.isValidVersion(version) || !validBranchName(version))) {
                    getLog().info("The version is not valid.");
                    version = null;
                }
            }
        } catch (PrompterException e) {
            throw new MojoFailureException("release-start", e);
        }
    } else {
        version = releaseVersion;
    }

    if (StringUtils.isBlank(version)) {
        getLog().info("Version is blank. Using default version.");
        version = defaultVersion;
    }

    return version;
}
 
Example 20
Source File: GitFlowHotfixFinishMojo.java    From gitflow-maven-plugin with Apache License 2.0 4 votes vote down vote up
private String promptBranchName() throws MojoFailureException, CommandLineException {
    // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/*
    String hotfixBranches = gitFindBranches(gitFlowConfig.getHotfixBranchPrefix(), false);

    // find hotfix support branches
    if (!gitFlowConfig.getHotfixBranchPrefix().endsWith("/")) {
        String supportHotfixBranches = gitFindBranches(gitFlowConfig.getHotfixBranchPrefix() + "*/*", false);
        hotfixBranches = hotfixBranches + supportHotfixBranches;
    }

    if (StringUtils.isBlank(hotfixBranches)) {
        throw new MojoFailureException("There are no hotfix branches.");
    }

    String[] branches = hotfixBranches.split("\\r?\\n");

    List<String> numberedList = new ArrayList<String>();
    StringBuilder str = new StringBuilder("Hotfix branches:").append(LS);
    for (int i = 0; i < branches.length; i++) {
        str.append((i + 1) + ". " + branches[i] + LS);
        numberedList.add(String.valueOf(i + 1));
    }
    str.append("Choose hotfix branch to finish");

    String hotfixNumber = null;
    try {
        while (StringUtils.isBlank(hotfixNumber)) {
            hotfixNumber = prompter.prompt(str.toString(), numberedList);
        }
    } catch (PrompterException e) {
        throw new MojoFailureException("hotfix-finish", e);
    }

    String hotfixBranchName = null;
    if (hotfixNumber != null) {
        int num = Integer.parseInt(hotfixNumber);
        hotfixBranchName = branches[num - 1];
    }

    return hotfixBranchName;
}