Java Code Examples for org.apache.commons.lang3.StringUtils#containsWhitespace()

The following examples show how to use org.apache.commons.lang3.StringUtils#containsWhitespace() . 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: RepositoryHookSettingsValidator.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Validates form data in repository triggers tab
 *
 * @param settings - to be validated.
 * @param errors - callback for reporting validation errors.
 * @throws IOException if JSON parsing error occurs
 */
private void validaterepositoryTriggersTab(final Settings settings, final SettingsValidationErrors errors) throws IOException {
    final String repositoryTriggersJson = settings.getString(Field.REPOSITORY_TRIGGERS_JSON, StringUtils.EMPTY);
    final ObjectMapper mapper = new ObjectMapper();
    final Map<String, Trigger> triggerMap = mapper.readValue(repositoryTriggersJson, mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Trigger.class));
    for (final Map.Entry<String, Trigger> triggerEntry : triggerMap.entrySet()) {
        final Trigger trigger = triggerEntry.getValue();
        if (StringUtils.isBlank(trigger.getTarget())) {
            errors.addFieldError(triggerEntry.getKey(), this.i18n.getText("error.string.empty"));
        } else if (StringUtils.containsWhitespace(trigger.getTarget())) {
            errors.addFieldError(triggerEntry.getKey(), this.i18n.getText("error.string.contains.whitespace"));
        }
        try {
            final Pattern pattern = Pattern.compile(triggerEntry.getValue().getRegex(), Pattern.CASE_INSENSITIVE);
            final Matcher matcher = pattern.matcher(BRANCH_TEST_STRING);
            if (matcher.groupCount() != 1) {
                errors.addFieldError(triggerEntry.getKey(), this.i18n.getText("error.regex.needs.capturing"));
            }
        } catch (final PatternSyntaxException e) {
            errors.addFieldError(triggerEntry.getKey(), e.getLocalizedMessage());
        }
    }
}
 
Example 2
Source File: AWSDynamoUtils.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the table settings (read and write capacities).
 * @param appid name of the {@link com.erudika.para.core.App}
 * @param readCapacity read capacity
 * @param writeCapacity write capacity
 * @return true if updated
 */
public static boolean updateTable(String appid, long readCapacity, long writeCapacity) {
	if (StringUtils.isBlank(appid) || StringUtils.containsWhitespace(appid)) {
		return false;
	}
	String table = getTableNameForAppid(appid);
	try {
		// AWS throws an exception if the new read/write capacity values are the same as the current ones
		getClient().updateTable(b -> b.tableName(table).
				provisionedThroughput(b1 -> b1.readCapacityUnits(readCapacity).writeCapacityUnits(writeCapacity)));
		return true;
	} catch (Exception e) {
		logger.error("Could not update table '{}' - table is not active or no change to capacity: {}",
				table, e.getMessage());
	}
	return false;
}
 
Example 3
Source File: CommandUtils.java    From JavaPackager with GNU General Public License v3.0 5 votes vote down vote up
private static void createArguments(Commandline command, Object... arguments) {
	for (Object argument : arguments) {
		
		if (argument == null)
			continue;
		
		if (argument.getClass().isArray()) {
			createArguments(command, (Object[])argument);
			continue;
		}
		
		if (argument instanceof File) {
			
			File argFile = (File) argument;
			if (argFile.getName().contains("*")) {
				argument = org.codehaus.plexus.util.StringUtils.quoteAndEscape(argFile.getParentFile().getAbsolutePath(), '\"') + File.separator + argFile.getName();
			} else {
				argument = ((File) argument).getAbsolutePath();
			}
			
		}

		String arg = argument.toString().trim(); 
		if (!arg.contains("\"") && StringUtils.containsWhitespace(arg)) {
			arg = org.codehaus.plexus.util.StringUtils.quoteAndEscape(arg, '\"');
		}
		command.createArg().setValue(arg);

	}
}
 
Example 4
Source File: PasswordValidator.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
private boolean validateNoSpaces() {
   if (StringUtils.containsWhitespace(firstPass.getText().toString())) {
      setError(firstPassLayout, firstPass, R.string.account_registration_password_contains_space_error_msg);
      return false;
   }

   return true;
}
 
Example 5
Source File: Matchers.java    From freeacs with MIT License 5 votes vote down vote up
public static Matcher<String> hasNoSpace() {
    return new BaseMatcher<String>() {
        @Override
        public boolean matches(final Object item) {
            return !StringUtils.containsWhitespace(item.toString());
        }
        @Override
        public void describeTo(final Description description) {
            description.appendText("Should not contain space");
        }
    };
}
 
Example 6
Source File: SolrUtil.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public static String escapeForStandardTokenizer(String search) {
  if (search == null) {
    return null;
  }
  String newSearch = escapeQueryChars(search.trim());
  if (StringUtils.containsWhitespace(newSearch)) {
    newSearch = "\"" + newSearch + "\"";
  }

  return newSearch;
}
 
Example 7
Source File: AWSDynamoUtils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a table in AWS DynamoDB.
 * @param appid name of the {@link com.erudika.para.core.App}
 * @param readCapacity read capacity
 * @param writeCapacity write capacity
 * @return true if created
 */
public static boolean createTable(String appid, long readCapacity, long writeCapacity) {
	if (StringUtils.isBlank(appid)) {
		return false;
	} else if (StringUtils.containsWhitespace(appid)) {
		logger.warn("DynamoDB table name contains whitespace. The name '{}' is invalid.", appid);
		return false;
	} else if (existsTable(appid)) {
		logger.warn("DynamoDB table '{}' already exists.", appid);
		return false;
	}
	try {
		String table = getTableNameForAppid(appid);
		CreateTableResponse tbl = getClient().createTable(b -> b.tableName(table).
				sseSpecification(b2 -> b2.enabled(ENCRYPTION_AT_REST_ENABLED)).
				provisionedThroughput(b4 -> b4.readCapacityUnits(readCapacity).writeCapacityUnits(writeCapacity)).
				keySchema(KeySchemaElement.builder().attributeName(Config._KEY).keyType(KeyType.HASH).build()).
				attributeDefinitions(AttributeDefinition.builder().
						attributeName(Config._KEY).attributeType(ScalarAttributeType.S).build()));

		logger.info("Waiting for DynamoDB table to become ACTIVE...");
		waitForActive(table);
		// NOT IMPLEMENTED in SDK v2:
		// String status = tbl.waitForActive().getTableStatus();
		logger.info("Created DynamoDB table '{}', status {}.", table, tbl.tableDescription().tableStatus());
	} catch (Exception e) {
		logger.error(null, e);
		return false;
	}
	return true;
}
 
Example 8
Source File: AWSDynamoUtils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a table in AWS DynamoDB which will be shared between apps.
 * @param readCapacity read capacity
 * @param writeCapacity write capacity
 * @return true if created
 */
public static boolean createSharedTable(long readCapacity, long writeCapacity) {
	if (StringUtils.isBlank(SHARED_TABLE) || StringUtils.containsWhitespace(SHARED_TABLE) ||
			existsTable(SHARED_TABLE)) {
		return false;
	}
	String table = getTableNameForAppid(SHARED_TABLE);
	try {
		GlobalSecondaryIndex secIndex = GlobalSecondaryIndex.builder().
				indexName(getSharedIndexName()).
				provisionedThroughput(b -> b.readCapacityUnits(1L).writeCapacityUnits(1L)).
				projection(Projection.builder().projectionType(ProjectionType.ALL).build()).
				keySchema(KeySchemaElement.builder().attributeName(Config._APPID).keyType(KeyType.HASH).build(),
						KeySchemaElement.builder().attributeName(Config._ID).keyType(KeyType.RANGE).build()).build();

		AttributeDefinition[] attributes = new AttributeDefinition[] {
			AttributeDefinition.builder().attributeName(Config._KEY).attributeType(ScalarAttributeType.S).build(),
			AttributeDefinition.builder().attributeName(Config._APPID).attributeType(ScalarAttributeType.S).build(),
			AttributeDefinition.builder().attributeName(Config._ID).attributeType(ScalarAttributeType.S).build()
		};

		CreateTableResponse tbl = getClient().createTable(b -> b.tableName(table).
				keySchema(KeySchemaElement.builder().attributeName(Config._KEY).keyType(KeyType.HASH).build()).
				sseSpecification(b2 -> b2.enabled(ENCRYPTION_AT_REST_ENABLED)).
				attributeDefinitions(attributes).
				globalSecondaryIndexes(secIndex).
				provisionedThroughput(b6 -> b6.readCapacityUnits(readCapacity).writeCapacityUnits(writeCapacity)));
		logger.info("Waiting for DynamoDB table to become ACTIVE...");
		waitForActive(table);
		logger.info("Created shared table '{}', status {}.", table, tbl.tableDescription().tableStatus());
	} catch (Exception e) {
		logger.error(null, e);
		return false;
	}
	return true;
}
 
Example 9
Source File: EventNameManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates and returns a short name based on the given display name.<br>
 * The generated short name will be returned only if it was not already used.<br>
 * The input parameter will be clean from "evil" characters such as punctuation and accents
 *
 * 1) if the {@code displayName} is a one-word name, then no further calculation will be done and it will be returned as it is, to lower case
 * 2) the {@code displayName} will be split by word and transformed to lower case. If the total length is less than 15, then it will be joined using "-" and returned
 * 3) the first letter of each word will be taken, excluding numbers
 * 4) a random code will be returned
 *
 * @param displayName
 * @return
 */
public String generateShortName(String displayName) {
    Validate.isTrue(StringUtils.isNotBlank(displayName));
    String cleanDisplayName = StringUtils.stripAccents(StringUtils.normalizeSpace(displayName)).toLowerCase(Locale.ENGLISH).replaceAll(FIND_EVIL_CHARACTERS, "-");
    if(!StringUtils.containsWhitespace(cleanDisplayName) && isUnique(cleanDisplayName)) {
        return cleanDisplayName;
    }
    Optional<String> dashedName = getDashedName(cleanDisplayName);
    if(dashedName.isPresent()) {
        return dashedName.get();
    }
    Optional<String> croppedName = getCroppedName(cleanDisplayName);
    return croppedName.orElseGet(this::generateRandomName);
}
 
Example 10
Source File: LoggingRequestValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private boolean isValidPath(String path) {
    try {
        Paths.get(path);
    } catch (InvalidPathException ex) {
        return false;
    }
    return !StringUtils.containsWhitespace(path);
}
 
Example 11
Source File: StructuredExample.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public NamespaceBuilder setName(String namespaceName) {

				if (namespaceName != null) {
					if (namespaceName.contains("|") || namespaceName.contains(":") || StringUtils.containsWhitespace(namespaceName)) {
						throw new ExampleFormatException("The namespace name cannot contain whitespace, '|' or ':'! Namespace passed in was: " + namespaceName);
					}
				}

				this.namespaceName = namespaceName;
				return this;
			}
 
Example 12
Source File: StructuredExample.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public NamespaceBuilder addFeature(String feature, Float value) {
	if (StringUtils.isBlank(feature)) throw new ExampleFormatException("The feature name must be provided!");

	if (feature.contains("|") || feature.contains(":") || StringUtils.containsWhitespace(feature))
		throw new ExampleFormatException("The feature name cannot contain whitespace, '|' or ':'! Feature name passed in was: " + feature);

	if (features == null) features = new ArrayList<StructuredExample.Namespace.Feature>();
	features.add(new Feature(feature, value));
	return this;
}
 
Example 13
Source File: CheckImproperRolesNamesRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 *            ************* Following are the Rule Parameters********* <br>
 * <br>
 * 
 *            ruleKey : check-for-improper-roles-name <br>
 * <br>
 * 
 *            threadsafe : if true , rule will be executed on multiple
 *            threads <br>
 * <br>
 * 
 *            severity : Enter the value of severity <br>
 * <br>
 * 
 *            ruleCategory : Enter the value of category <br>
 * <br>
 * 
 * @param resourceAttributes
 *            this is a resource in context which needs to be scanned this
 *            is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam,
        Map<String, String> resourceAttributes) {

    logger.debug("========CheckImproperRolesNamesRule started=========");
    Annotation annotation = null;
    String resourceId = null;

    String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
    String category = ruleParam.get(PacmanRuleConstants.CATEGORY);

    MDC.put("executionId", ruleParam.get("executionId"));
    MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID));

    List<LinkedHashMap<String, Object>> issueList = new ArrayList<>();
    LinkedHashMap<String, Object> issue = new LinkedHashMap<>();

    if (!PacmanUtils.doesAllHaveValue(severity, category)) {
        logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
        throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
    }

    if (resourceAttributes != null) {
        resourceId = resourceAttributes.get(PacmanSdkConstants.RESOURCE_ID);
        if (StringUtils.containsWhitespace(resourceId)) {
            annotation = Annotation.buildAnnotation(ruleParam,
                    Annotation.Type.ISSUE);
            annotation.put(PacmanSdkConstants.DESCRIPTION,
                    "Improper roles name found !!");
            annotation.put(PacmanRuleConstants.SEVERITY, severity);
            annotation.put(PacmanRuleConstants.CATEGORY, category);

            issue.put(PacmanRuleConstants.VIOLATION_REASON,
                    " Role name with space found");
            issueList.add(issue);
            annotation.put("issueDetails", issueList.toString());
            logger.debug(
                    "========CheckImproperRolesNamesRule with annotation : {} =========",
                    annotation);
            return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,
                    PacmanRuleConstants.FAILURE_MESSAGE, annotation);
        }
    }
    logger.debug("========CheckImproperRolesNamesRule ended=========");
    return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,
            PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 14
Source File: CheckImproperAccountNamesRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam 
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * ruleKey : check-for-improper-account-name <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========CheckImproperAccountNamesRule started=========");
	Annotation annotation = null;
	String resourceId = null;
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	
	MDC.put("executionId", ruleParam.get("executionId")); 
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID));
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(severity,category)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		resourceId = resourceAttributes.get(PacmanSdkConstants.RESOURCE_ID);
		if(StringUtils.containsWhitespace(resourceId)){
		logger.info(resourceId, "=========_resourceId");
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Improper account name found !!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "Account name with space found");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			
			logger.debug("========CheckImproperAccountNamesRule ended with an annotation : {}=========", annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
	}
		}
	logger.debug("========CheckImproperAccountNamesRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 15
Source File: JvmUtil.java    From recheck with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String toArg( final Object key, final Object val ) {
	return toArg( key ) + "=" + (StringUtils.containsWhitespace( val.toString() ) ? "\"" + val + "\"" : val);
}
 
Example 16
Source File: PathToJar.java    From beakerx with Apache License 2.0 4 votes vote down vote up
private void checkNotWhitespaces(String path) {
  if (StringUtils.containsWhitespace(path)) {
    throw new RuntimeException("Can not create path with whitespace.");
  }
}