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

The following examples show how to use org.apache.commons.lang3.StringUtils#isAlphanumeric() . These examples are extracted from open source projects. 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
@Override
public boolean isSupported(final Path workdir, final String name) {
    if(workdir.isRoot()) {
        // Empty argument if not known in validation
        if(StringUtils.isNotBlank(name)) {
            // Bucket names must be a minimum of 6 and a maximum of 50 characters long, and must be globally unique;
            // two different B2 accounts cannot have buckets with the name name. Bucket names can consist of: letters,
            // digits, and "-". Bucket names cannot start with "b2-"; these are reserved for internal Backblaze use.
            if(StringUtils.startsWith(name, "b2-")) {
                return false;
            }
            if(StringUtils.length(name) > 50) {
                return false;
            }
            if(StringUtils.length(name) < 6) {
                return false;
            }
            return StringUtils.isAlphanumeric(StringUtils.removeAll(name, "-"));
        }
    }
    return true;
}
 
Example 2
@Override
public boolean isSupported(final Path workdir, final String name) {
    if(workdir.isRoot()) {
        // Empty argument if not known in validation
        if(StringUtils.isNotBlank(name)) {
            // Container names must be lowercase, between 3-63 characters long and must start with a letter or
            // number. Container names may contain only letters, numbers, and the dash (-) character.
            if(StringUtils.length(name) > 63) {
                return false;
            }
            if(StringUtils.length(name) < 3) {
                return false;
            }
            return StringUtils.isAlphanumeric(StringUtils.removeAll(name, "-"));
        }
    }
    return true;
}
 
Example 3
Source Project: CogStack-Pipeline   File: StringTools.java    License: Apache License 2.0 6 votes vote down vote up
private static String getCompletingString(String string, int begin, int end) {
    while ( begin > 0 && StringUtils.isAlphanumeric(string.substring(begin, begin+1)) ){
        begin -= 1;
    }
    if (begin != 0)
        begin += 1;

    while ( end < string.length() - 1 && StringUtils.isAlphanumeric(string.substring(end, end + 1)) ){
        end += 1;
    }

    String regex = "\\w+(\\(?\\)?\\s+\\w+)*";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(string.substring(begin, end));

    if (matcher.find()) {
        return matcher.group();
    }

    return StringUtils.EMPTY;
}
 
Example 4
Source Project: helix   File: ClusterAccessor.java    License: Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("{clusterId}/statemodeldefs/{statemodel}")
public Response removeClusterStateModelDefinition(@PathParam("clusterId") String clusterId,
    @PathParam("statemodel") String statemodel) {
  //Shall we validate the statemodel string not having special character such as ../ etc?
  if (!StringUtils.isAlphanumeric(statemodel)) {
    return badRequest("Invalid statemodel name!");
  }

  HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
  PropertyKey key = dataAccessor.keyBuilder().stateModelDef(statemodel);
  boolean retcode = true;
  try {
    retcode = dataAccessor.removeProperty(key);
  } catch (Exception e) {
    LOG.error("Failed to remove StateModelDefinition key: {}. Exception: {}.", key, e);
    retcode = false;
  }
  if (!retcode) {
    return badRequest("Failed to remove!");
  }
  return OK();
}
 
Example 5
private boolean isConfigurationHeader(final List<String> lines) {
    if (lines.get(0).contains(" - ")) {
        return true;
    } else {
        return StringUtils.isAlphanumeric(lines.get(0));
    }
}
 
Example 6
Source Project: jdmn   File: DefaultSignavioStringLib.java    License: Apache License 2.0 5 votes vote down vote up
public Boolean isAlphanumeric(String text) {
    if (text == null) {
        return null;
    }

    return StringUtils.isAlphanumeric(text);
}
 
Example 7
protected String escape(final String path) {
    final StringBuilder escaped = new StringBuilder();
    for(char c : path.toCharArray()) {
        if(StringUtils.isAlphanumeric(String.valueOf(c))) {
            escaped.append(c);
        }
        else {
            escaped.append("\\").append(c);
        }
    }
    return escaped.toString();
}
 
Example 8
Source Project: cyberduck   File: Archive.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Escape blank
 *
 * @param path Filename
 * @return Escaped whitespace in path
 */
protected String escape(final String path) {
    final StringBuilder escaped = new StringBuilder();
    for(char c : path.toCharArray()) {
        if(StringUtils.isAlphanumeric(String.valueOf(c))
                || c == Path.DELIMITER) {
            escaped.append(c);
        }
        else {
            escaped.append("\\").append(c);
        }
    }
    return escaped.toString();
}
 
Example 9
/**
 * If this is a user site, return an id based on the user EID, otherwise
 * just return the site id.
 * 
 * @param site
 *        The site.
 * @return The effective site id.
 */
public String getSiteEffectiveId(Site site)
{
	if (SiteService.isUserSite(site.getId()))
	{
		try
		{
			String userId = SiteService.getSiteUserId(site.getId());
			String eid = UserDirectoryService.getUserEid(userId);
			// SAK-31889: if your EID has special chars, much easier to just use your uid
			if (StringUtils.isAlphanumeric(eid)) {
				return SiteService.getUserSiteId(eid);
			}
		}
		catch (UserNotDefinedException e)
		{
			log.warn("getSiteEffectiveId: user eid not found for user site: "
					+ site.getId());
		}
	}
	else
	{
		String displayId = portal.getSiteNeighbourhoodService().lookupSiteAlias(site.getReference(), null);
		if (displayId != null)
		{
			return displayId;
		}
	}

	return site.getId();
}
 
Example 10
@Override
public ValidationResult initialize(RuntimeContainer runtimeContainer, ComponentProperties properties) {
    // init
    AzureStorageContainerProperties componentProperties = (AzureStorageContainerProperties) properties;

    this.containerName = componentProperties.container.getValue();

    // validate
    ValidationResult validationResult = super.initialize(runtimeContainer, properties);
    if (validationResult.getStatus() == ValidationResult.Result.ERROR) {
        return validationResult;
    }

    String errorMessage = "";
    // not empty
    if (StringUtils.isEmpty(containerName)) {
        errorMessage = messages.getMessage("error.ContainerEmpty");
    }
    // valid characters 0-9 a-z and -
    else if (!StringUtils.isAlphanumeric(containerName.replaceAll("-", ""))) {

        errorMessage = messages.getMessage("error.IncorrectName");
    }
    // all lowercase
    else if (!StringUtils.isAllLowerCase(containerName.replaceAll("(-|\\d)", ""))) {
        errorMessage = messages.getMessage("error.UppercaseName");
    }
    // length range : 3-63
    else if ((containerName.length() < 3) || (containerName.length() > 63)) {
        errorMessage = messages.getMessage("error.LengthError");
    }

    if (errorMessage.isEmpty()) {
        return ValidationResult.OK;
    } else {
        return new ValidationResult(ValidationResult.Result.ERROR, errorMessage);
    }
}
 
Example 11
/**
 * If this is a user site, return an id based on the user EID, otherwise
 * just return the site id.
 * 
 * @param site
 *        The site.
 * @return The effective site id.
 */
public String getSiteEffectiveId(Site site)
{
	if (SiteService.isUserSite(site.getId()))
	{
		try
		{
			String userId = SiteService.getSiteUserId(site.getId());
			String eid = UserDirectoryService.getUserEid(userId);
			// SAK-31889: if your EID has special chars, much easier to just use your uid
			if (StringUtils.isAlphanumeric(eid)) {
				return SiteService.getUserSiteId(eid);
			}
		}
		catch (UserNotDefinedException e)
		{
			log.warn("getSiteEffectiveId: user eid not found for user site: "
					+ site.getId());
		}
	}
	else
	{
		String displayId = portal.getSiteNeighbourhoodService().lookupSiteAlias(site.getReference(), null);
		if (displayId != null)
		{
			return displayId;
		}
	}

	return site.getId();
}
 
Example 12
Source Project: windup   File: DotWriter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getDotSafeName(String inName)
{
    String name = null;
    if (StringUtils.isAlphanumeric(inName))
    {
        name = inName;
    }
    else
    {
        name = "\"" + inName + "\"";
    }

    return name;
}
 
Example 13
Source Project: pepper-metrics   File: HttpUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean checkSegment(String s) {
	return NumberUtils.isDigits(s) || !StringUtils.isAlphanumeric(s);
}
 
Example 14
@Override
public void handleCommand(Entity entity, String message, String[] args) {
    // :givebadge Alex NL1

    // should refuse to give badges that belong to ranks
    if (entity.getType() != EntityType.PLAYER) {
        return;
    }

    Player player = (Player) entity;

    if (player.getRoomUser().getRoom() == null) {
        return;
    }

    Player targetUser = PlayerManager.getInstance().getPlayerByName(args[0]);

    if (targetUser == null) {
        player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Could not find user: " + args[0]));
        return;
    }

    if (args.length == 1) {
        player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Badge code not provided"));
        return;
    }

    String badge = args[1];

    if (badge.length() != 3) {
        player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Badge codes have a length of three characters."));
        return;
    }

    // Badge should be alphanumeric
    if (!StringUtils.isAlphanumeric(badge)) {
        player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Badge code provided not alphanumeric."));
        return;
    }

    // Check if characters are uppercase
    for (int i=0; i < badge.length(); i++) {
        if (!Character.isUpperCase(badge.charAt(i)) && !Character.isDigit(badge.charAt(i))) {
            player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Badge code should be uppercase."));
            return;
        }
    }

    PlayerDetails targetDetails = targetUser.getDetails();
    List<String> badges = targetDetails.getBadges();

    // Check if user already owns badge
    if (badges.contains(badge)) {
        player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "User " + targetDetails.getName() + " already owns this badge."));
        return;
    }

    List<String> rankBadges = BadgeDao.getAllRankBadges();

    // Check if badge code is a rank badge
    if (rankBadges.contains(badge)) {
        player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "This badge belongs to a certain rank. If you would like to give " + targetDetails.getName() + " this badge, increase their rank."));
        return;
    }

    // Add badge
    badges.add(badge);
    targetDetails.setBadges(badges);

    // Set current badge to newly given
    targetDetails.setCurrentBadge(badge);

    // Set badge to active for display
    targetDetails.setShowBadge(true);

    // Send badges to user
    targetUser.send(new AVAILABLE_BADGES(targetDetails));

    Room targetRoom = targetUser.getRoomUser().getRoom();

    // Let other room users know something changed if targetUser is inside a room
    if (targetRoom != null) {
        targetRoom.send(new USER_BADGE(targetUser.getRoomUser().getInstanceId(), targetDetails));
        targetRoom.send(new FIGURE_CHANGE(targetUser.getRoomUser().getInstanceId(), targetDetails));
    }

    // Persist changes
    BadgeDao.saveCurrentBadge(targetDetails);
    BadgeDao.addBadge(targetDetails.getId(), badge);

    player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Badge " + badge + " added to user " + targetDetails.getName()));
}
 
Example 15
@Override
public FieldMap parse( String fields )
{
    List<String> prefixList = Lists.newArrayList();
    FieldMap fieldMap = new FieldMap();

    StringBuilder builder = new StringBuilder();

    String[] fieldSplit = fields.split( "" );

    for ( int i = 0; i < fieldSplit.length; i++ )
    {
        String c = fieldSplit[i];

        // if we reach a field transformer, parse it out here (necessary to allow for () to be used to handle transformer parameters)
        if ( (c.equals( ":" ) && fieldSplit[i + 1].equals( ":" )) || c.equals( "~" ) || c.equals( "|" ) )
        {
            boolean insideParameters = false;

            for ( ; i < fieldSplit.length; i++ )
            {
                c = fieldSplit[i];

                if ( StringUtils.isAlphanumeric( c ) || c.equals( ":" ) || c.equals( "~" ) || c.equals( "|" ) )
                {
                    builder.append( c );
                }
                else if ( c.equals( "(" ) ) // start parameter
                {
                    insideParameters = true;
                    builder.append( c );
                }
                else if ( insideParameters && c.equals( ";" ) ) // allow parameter separator
                {
                    builder.append( c );
                }
                else if ( (insideParameters && c.equals( ")" )) ) // end
                {
                    builder.append( c );
                    break;
                }
                else if ( c.equals( "," ) || ( c.equals( "[" ) && !insideParameters ) ) // rewind and break
                {
                    i--;
                    break;
                }
            }
        }
        else if ( c.equals( "," ) )
        {
            putInMap( fieldMap, joinedWithPrefix( builder, prefixList ) );
            builder = new StringBuilder();
        }
        else if ( c.equals( "[" ) || c.equals( "(" ) )
        {
            prefixList.add( builder.toString() );
            builder = new StringBuilder();
        }
        else if ( c.equals( "]" ) || c.equals( ")" ) )
        {
            if ( !builder.toString().isEmpty() )
            {
                putInMap( fieldMap, joinedWithPrefix( builder, prefixList ) );
            }

            prefixList.remove( prefixList.size() - 1 );
            builder = new StringBuilder();
        }
        else if ( StringUtils.isAlphanumeric( c ) || c.equals( "*" ) || c.equals( ":" ) || c.equals( ";" ) || c.equals( "~" ) || c.equals( "!" )
            || c.equals( "|" ) || c.equals( "{" ) || c.equals( "}" ) )
        {
            builder.append( c );
        }
    }

    if ( !builder.toString().isEmpty() )
    {
        putInMap( fieldMap, joinedWithPrefix( builder, prefixList ) );
    }

    return fieldMap;
}
 
Example 16
/**
 * Indicates whether the given query parameter is valid.
 */
public static boolean isValidQueryParam( String param )
{
    return StringUtils.isAlphanumeric( param );
}
 
Example 17
Source Project: webanno   File: FeatureDetailForm.java    License: Apache License 2.0 4 votes vote down vote up
private void actionSave(AjaxRequestTarget aTarget, Form<?> aForm)
{
    AnnotationFeature feature = getModelObject();
    String name = feature.getUiName();
    name = name.replaceAll("\\W", "");
    // Check if feature name is not from the restricted names list
    if (WebAnnoConst.RESTRICTED_FEATURE_NAMES.contains(name)) {
        error("'" + feature.getUiName().toLowerCase() + " (" + name + ")'"
                + " is a reserved feature name. Please use a different name "
                + "for the feature.");
        return;
    }
    if (RELATION_TYPE.equals(getModelObject().getLayer().getType())
            && (name.equals(WebAnnoConst.FEAT_REL_SOURCE)
                    || name.equals(WebAnnoConst.FEAT_REL_TARGET) || name.equals(FIRST)
                    || name.equals(NEXT))) {
        error("'" + feature.getUiName().toLowerCase() + " (" + name + ")'"
                + " is a reserved feature name on relation layers. . Please "
                + "use a different name for the feature.");
        return;
    }
    // Checking if feature name doesn't start with a number or underscore
    // And only uses alphanumeric characters
    if (StringUtils.isNumeric(name.substring(0, 1))
            || name.substring(0, 1).equals("_")
            || !StringUtils.isAlphanumeric(name.replace("_", ""))) {
        error("Feature names must start with a letter and consist only of "
                + "letters, digits, or underscores.");
        return;
    }
    if (isNull(feature.getId())) {
        feature.setLayer(getModelObject().getLayer());
        feature.setProject(getModelObject().getLayer().getProject());

        if (annotationService.existsFeature(feature.getName(),
                feature.getLayer())) {
            error("This feature is already added for this layer!");
            return;
        }

        if (annotationService.existsFeature(name, feature.getLayer())) {
            error("This feature already exists!");
            return;
        }
        feature.setName(name);

        FeatureSupport<?> fs = featureSupportRegistry
                .getFeatureSupport(featureType.getModelObject().getFeatureSupportId());

        // Let the feature support finalize the configuration of the feature
        fs.configureFeature(feature);

    }

    // Save feature
    annotationService.createFeature(feature);

    // Clear currently selected feature / feature details
    setModelObject(null);
    
    success("Settings for feature [" + feature.getUiName() + "] saved.");
    aTarget.addChildren(getPage(), IFeedback.class);
    
    aTarget.add(findParent(ProjectLayersPanel.class).get(MID_FEATURE_DETAIL_FORM));
    aTarget.add(findParent(ProjectLayersPanel.class).get(MID_FEATURE_SELECTION_FORM));

    // Trigger LayerConfigurationChangedEvent
    applicationEventPublisherHolder.get().publishEvent(
            new LayerConfigurationChangedEvent(this, feature.getProject()));
}
 
Example 18
/**
 * Return where clause expression for non-String
 * {@code entityPath.fieldName} by transforming it to text before check its
 * value.
 * <p/>
 * Expr:
 * {@code entityPath.fieldName.as(String.class) like ('%' + searchStr + '%')}
 * <p/>
 * Like operation is case insensitive.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the value to find, may be null
 * @param enumClass Enumeration type. Needed to enumeration values
 * @return BooleanExpression
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> BooleanExpression createEnumExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr,
        Class<? extends Enum> enumClass) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    // Filter string to search than cannot be a identifier
    if (!StringUtils.isAlphanumeric(StringUtils.lowerCase(searchStr))) {
        return null;
    }

    // TODO i18n of enum name

    // normalize search string
    searchStr = StringUtils.trim(searchStr).toLowerCase();

    // locate enums matching by name
    Set matching = new HashSet();

    Enum<?> enumValue;
    String enumStr;

    for (Field enumField : enumClass.getDeclaredFields()) {
        if (enumField.isEnumConstant()) {
            enumStr = enumField.getName();
            enumValue = Enum.valueOf(enumClass, enumStr);

            // Check enum name contains string to search
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
                continue;
            }

            // Check using toString
            enumStr = enumValue.toString();
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
            }
        }
    }
    if (matching.isEmpty()) {
        return null;
    }

    // create a enum in matching condition
    BooleanExpression expression = entityPath.get(fieldName).in(matching);
    return expression;
}
 
Example 19
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> BooleanExpression createEnumExpression(
        PathBuilder<T> entityPath, String fieldName, String searchStr,
        Class<? extends Enum> enumClass) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }
    // Filter string to search than cannot be a identifier
    if (!StringUtils.isAlphanumeric(StringUtils.lowerCase(searchStr))) {
        return null;
    }

    // TODO i18n of enum name

    // normalize search string
    searchStr = StringUtils.trim(searchStr).toLowerCase();

    // locate enums matching by name
    Set matching = new HashSet();

    Enum<?> enumValue;
    String enumStr;

    for (Field enumField : enumClass.getDeclaredFields()) {
        if (enumField.isEnumConstant()) {
            enumStr = enumField.getName();
            enumValue = Enum.valueOf(enumClass, enumStr);

            // Check enum name contains string to search
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
                continue;
            }

            // Check using toString
            enumStr = enumValue.toString();
            if (enumStr.toLowerCase().contains(searchStr)) {
                // Add to matching enum
                matching.add(enumValue);
            }
        }
    }
    if (matching.isEmpty()) {
        return null;
    }

    // create a enum in matching condition
    BooleanExpression expression = entityPath.get(fieldName).in(matching);
    return expression;
}