Java Code Examples for org.apache.commons.lang.StringUtils#countMatches()

The following examples show how to use org.apache.commons.lang.StringUtils#countMatches() . 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 want to check out the right sidebar which shows the related API usage.
Example 1
@SuppressWarnings({"null"}) //First parameter is marked as @NonNull and String#replaceAll won't return null
private static String convertToFriendly(String format){
	format = format.replaceAll("%%", "%")
		.replaceAll("%1\\$s", "[player]")
		.replaceAll("%2\\$s", "[message]");
	//Format uses %s instead of %1$s and %2$s
	if (format.contains("%s")){
		if (StringUtils.countMatches(format, "%s") >= 2){
			// Format uses two %s, the order is player, message
			format = format.replaceFirst("%s", "[player]");
			format = format.replaceFirst("%s", "[message]");
		}else{
			// Format mixes %<number>$s and %s
			format = format.replaceFirst("%s", (format.contains("[player]") || format.contains("%1$s") ? "[message]" : "[player]"));
		}
	}
	return format;
}
 
Example 2
/**
 * extract one certificate from series of certificates.
 *
 * @param decodedCertificate series of certificate value in readable format
 * @param ordinal            relating to the order of the certificate in a series of certificate values
 * @return
 */
public static String extractCertificate(String decodedCertificate, int ordinal) {

    String certificateVal;
    int numberOfCertificatesInCertificate = StringUtils.countMatches(decodedCertificate,
            IdentityUtil.PEM_BEGIN_CERTFICATE);
    if (ordinal == numberOfCertificatesInCertificate) {
        certificateVal = decodedCertificate.substring(StringUtils.ordinalIndexOf(decodedCertificate
                , IdentityUtil.PEM_BEGIN_CERTFICATE, ordinal));
    } else {
        certificateVal = decodedCertificate.substring(StringUtils.ordinalIndexOf(
                decodedCertificate, IdentityUtil.PEM_BEGIN_CERTFICATE, ordinal),
                StringUtils.ordinalIndexOf(decodedCertificate,
                        IdentityUtil.PEM_BEGIN_CERTFICATE, ordinal + 1));
    }
    return certificateVal;
}
 
Example 3
/**
 * Validate the username when email username is enabled.
 *
 * @param username Username.
 * @param context Authentication context.
 * @throws InvalidCredentialsException when username is not an email when email username is enabled.
 */
public static void validateUsername(String username, AuthenticationContext context)
        throws InvalidCredentialsException {

    if (IdentityUtil.isEmailUsernameEnabled()) {
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        if (StringUtils.countMatches(tenantAwareUsername, "@") < 1) {
            context.setProperty(CONTEXT_PROP_INVALID_EMAIL_USERNAME, true);
            throw new InvalidCredentialsException("Invalid username. Username has to be an email.");
        }
    }
}
 
Example 4
/**
 * Return the column of the given position.
 * 
 * @param code
 * @param position
 * @return
 */
public static int getColumnOfPosition(final String code, final int position) {
	checkPositionIndex(position, code.length());
	int newLinePosition = code.substring(0, position).lastIndexOf("\n");
	if (newLinePosition == -1) {
		newLinePosition = 0; // Start of file.
	}
	final int tabCount = StringUtils.countMatches(
			code.substring(newLinePosition, position), "\t");
	return position - newLinePosition + (TAB_INDENT_SIZE - 1) * tabCount;
}
 
Example 5
Source Project: micro-integrator   File: SqlBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method to build an executable SQL statement.
 *
 * @param sqlQueryStringBuilder Final sql query string.
 */
private String buildExecutableSQLStatement(StringBuilder sqlQueryStringBuilder) {

    // Check whether any parentheses which are not closed in the SQL statement if so close it.
    int startParenthesesCounts = StringUtils.countMatches(sqlQueryStringBuilder.toString(), START_PARENTHESES);
    int endParenthesesCounts = StringUtils.countMatches(sqlQueryStringBuilder.toString(), CLOSE_PARENTHESES);
    int needToBeCloseParenthesesCount = startParenthesesCounts - endParenthesesCounts;

    if (needToBeCloseParenthesesCount > 0) {
        for (int i = 0; i < needToBeCloseParenthesesCount; i++) {
            sqlQueryStringBuilder.append(CLOSE_PARENTHESES);
        }
    }
    return sqlQueryStringBuilder.toString();
}
 
Example 6
@Override
public PairObject<IView, ResponseCache> processRequest(IWebMvc owner, IRequestContext requestContext) throws Exception {
    String _mapping = requestContext.getRequestMapping();
    InterceptorRuleMeta _ruleMeta = __interceptorRules.get(_mapping);
    IView _view = null;
    if (_ruleMeta == null) {
        while (StringUtils.countMatches(_mapping, "/") > 1) {
            _mapping = StringUtils.substringBeforeLast(_mapping, "/");
            _ruleMeta = __interceptorRules.get(_mapping);
            if (_ruleMeta != null && _ruleMeta.isMatchAll()) {
                break;
            }
        }
    }
    ResponseCache _responseCache = null;
    if (_ruleMeta != null) {
        _responseCache = _ruleMeta.getResponseCache();
        InterceptContext _context = new InterceptContext(IInterceptor.Direction.BEFORE, owner.getOwner(), null, null, null, _ruleMeta.getContextParams());
        //
        for (Class<? extends IInterceptor> _interceptClass : _ruleMeta.getBeforeIntercepts()) {
            IInterceptor _interceptor = _interceptClass.newInstance();
            if (_interceptClass.isAnnotationPresent(Interceptor.class)) {
                _interceptor = owner.getOwner().getBean(_interceptClass);
            }
            if (_interceptor == null) {
                _interceptor = _interceptClass.newInstance();
            }
            // 执行前置拦截器,若其结果对象不为空则返回并停止执行
            Object _result = _interceptor.intercept(_context);
            if (_result != null) {
                _view = (IView) _result;
                break;
            }
        }
    }
    return new PairObject<IView, ResponseCache>(_view, _responseCache);
}
 
Example 7
Source Project: javadoc.chm   File: Javadoc8Style.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getMethodFullName(String url) {
    String name = StringUtils.substringAfter(url, "#");
    int count = StringUtils.countMatches(name, "-");
    name = StringUtils.replaceOnce(name, "-", "(");
    for (int i = 0; i < count - 2; i++) {
        name = StringUtils.replaceOnce(name, "-", ", ");
    }
    name = StringUtils.replaceOnce(name, "-", ")");
    name = StringUtils.replace(name, ":A", "[]");
    return name;
}
 
Example 8
Source Project: Lottery   File: ContentTxt.java    License: GNU General Public License v2.0 5 votes vote down vote up
public int getTxtCount() {
	String txt = getTxt();
	if (StringUtils.isBlank(txt)) {
		return 1;
	} else {
		return StringUtils.countMatches(txt, PAGE_START) + 1;
	}
}
 
Example 9
Source Project: oxd   File: Tester.java    License: Apache License 2.0 5 votes vote down vote up
public static String getTargetHost(String targetHost) {
    if (StringUtils.countMatches(targetHost, ":") < 2 && "http://localhost".equalsIgnoreCase(targetHost) || "http://127.0.0.1".equalsIgnoreCase(targetHost) ) {
        targetHost = targetHost + ":" + SetUpTest.SUPPORT.getLocalPort();
    }
    if ("localhost".equalsIgnoreCase(targetHost)) {
        targetHost = "http://localhost:" + SetUpTest.SUPPORT.getLocalPort();
    }
    return targetHost;
}
 
Example 10
public String escape(String value) {
  if (null == value) {
    return null;
  }

  String escaped = QueryParserBase.escape(value);

  boolean shouldLeaveDoubleQuotesEscaped = StringUtils.countMatches(value, "\"") % 2 != 0;
  String escapedCharactersRegex = shouldLeaveDoubleQuotesEscaped ? "\\\\([?*])" : "\\\\([?*\"])";

  // unescape supported special characters
  return escaped.replaceAll(escapedCharactersRegex, "$1");
}
 
Example 11
/**
 * Return the column of the given position.
 * 
 * @param code
 * @param position
 * @return
 */
public static int getColumnOfPosition(final String code, final int position) {
	checkPositionIndex(position, code.length());
	int newLinePosition = code.substring(0, position).lastIndexOf("\n");
	if (newLinePosition == -1) {
		newLinePosition = 0; // Start of file.
	}
	final int tabCount = StringUtils.countMatches(
			code.substring(newLinePosition, position), "\t");
	return position - newLinePosition + (TAB_INDENT_SIZE - 1) * tabCount;
}
 
Example 12
private static void validateMapping(String typeETK, String typeEhbox, String typeRecipe, int actualMapSize) throws TechnicalConnectorException {
   TechnicalConnectorExceptionValues errorValue;
   if (typeETK != null && typeEhbox != null && actualMapSize <= 3) {
      if (StringUtils.countMatches(typeETK, "-") > 1 || StringUtils.countMatches(typeEhbox, "-") > 1 || StringUtils.countMatches(typeRecipe, "-") > 1) {
         errorValue = TechnicalConnectorExceptionValues.INVALID_MAPPING;
         LOG.debug("\t## " + MessageFormat.format(errorValue.getMessage(), "maximum one '-' is allowed."));
         throw new TechnicalConnectorException(errorValue, new Object[]{"maximum one '-' is allowed."});
      }
   } else {
      errorValue = TechnicalConnectorExceptionValues.INVALID_MAPPING;
      LOG.debug("\t## " + MessageFormat.format(errorValue.getMessage(), "mapping doesn't contains key for ETKDEPOT or EHBOX."));
      throw new TechnicalConnectorException(errorValue, new Object[]{"mapping doesn't contains key for ETKDEPOT or EHBOX or RECIPE."});
   }
}
 
Example 13
Source Project: oxd   File: SetUpTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void setupSwaggerSuite(String host, String opHost, String redirectUrls) {
    try {
        if (StringUtils.countMatches(host, ":") < 2 && "http://localhost".equalsIgnoreCase(host) || "http://127.0.0.1".equalsIgnoreCase(host) ) {
            host = host + ":" + SetUpTest.SUPPORT.getLocalPort();
        }
        io.swagger.client.api.SetUpTest.beforeSuite(host, opHost, redirectUrls); // manual swagger tests setup
        io.swagger.client.api.SetUpTest.setTokenProtectionEnabled(SUPPORT.getConfiguration().getProtectCommandsWithAccessToken());
    } catch (Throwable e) {
        LOG.error("Failed to setup swagger suite.");
    }
}
 
Example 14
Source Project: JWT4B   File: PostBody.java    License: GNU General Public License v3.0 5 votes vote down vote up
public KeyValuePair getJWTFromPostBody() {
	int from = 0;
	int index = body.indexOf("&") == -1 ? body.length() : body.indexOf("&");
	int parameterCount = StringUtils.countMatches(body, "&") + 1;

	List<KeyValuePair> postParameterList = new ArrayList<KeyValuePair>();
	for (int i = 0; i < parameterCount; i++) {
		String parameter = body.substring(from, index);
		parameter = parameter.replace("&", "");

		String[] parameterSplit = parameter.split(Pattern.quote("="));
		if (parameterSplit.length > 1) {
			String name = parameterSplit[0];
			String value = parameterSplit[1];
			postParameterList.add(new KeyValuePair(name, value));
			from = index;
			index = body.indexOf("&", index + 1);
			if (index == -1) {
				index = body.length();
			}
		}
	}
	for (String keyword : Config.tokenKeywords) {
		for (KeyValuePair postParameter : postParameterList) {
			if (keyword.equals(postParameter.getName())
					&& TokenCheck.isValidJWT(postParameter.getValue())) {
				return postParameter;
			}
		}
	}
	return null;
}
 
Example 15
Source Project: iaf   File: SvnUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getLogReport(String urlString) throws DomBuilderException, XPathExpressionException, ConfigurationException, SenderException, TimeOutException, IOException {
	String head = getHeadHtml(urlString);
	String etag = XmlUtils.evaluateXPathNodeSetFirstElement(head,
			"headers/header[lower-case(@name)='etag']");
	if (etag != null) {
		if (StringUtils.countMatches(etag, "\"") >= 2) {
			String s = StringUtils.substringAfter(etag, "\"");
			String s2 = StringUtils.substringBefore(s, "\"");
			String s3 = StringUtils.substringBefore(s2, "/");
			String s4 = StringUtils.substringAfter(s2, "/");
			return getReportHtml(urlString, s3, s4);
		}
	}
	return null;
}
 
Example 16
@Override
protected void checkLiterals(Tree tree, List<LiteralTree> literals) {
	
	StringBuilder query =new StringBuilder();
	for (LiteralTree literal:literals){
		query.append(literal.value());
	}

	boolean isQueryWhereComplient = false;
	String queryString = query.toString().toUpperCase();
	if (queryString.trim().contains("WHERE")) {
		String whereClause = queryString.substring(queryString.indexOf("WHERE"));
		whereClause = CheckUtils.removeQuotedContent(whereClause);
		whereClause = whereClause.replace(" ", "");

		if (whereClause.contains("GROUPBY")) {
			whereClause = whereClause.substring(0, whereClause.indexOf("GROUPBY"));
		} else if (whereClause.contains("ORDERBY")) {
			whereClause = whereClause.substring(0, whereClause.indexOf("ORDERBY"));
		}

		if (StringUtils.countMatches(whereClause, "=") != StringUtils.countMatches(whereClause, "?")) {
			isQueryWhereComplient = false;
		} else {
			isQueryWhereComplient = true;
		}

	} else {
		isQueryWhereComplient = true;
	}
	if (!isQueryWhereComplient){
		addIssue(tree, MESSAGE);
	}

	
}
 
Example 17
/**
 * get extracted certificate values from decodedCertificate
 *
 * @param decodedCertificate decoded series of certificate value.
 * @return list of decoded certificate values.
 */
private static List<String> getExtractedCertificateValues(String decodedCertificate) {

    int numOfCertificates = StringUtils.countMatches(decodedCertificate, IdentityUtil.PEM_BEGIN_CERTFICATE);
    List<String> extractedCertificateValues = new ArrayList<>();
    for (int i = 1; i <= numOfCertificates; i++) {
        extractedCertificateValues.add(IdentityApplicationManagementUtil.extractCertificate
                (decodedCertificate, i));
    }
    return extractedCertificateValues;
}
 
Example 18
/**
 * Return the column of the given position.
 * 
 * @param code
 * @param position
 * @return
 */
public static int getColumnOfPosition(final String code, final int position) {
	checkPositionIndex(position, code.length());
	int newLinePosition = code.substring(0, position).lastIndexOf("\n");
	if (newLinePosition == -1) {
		newLinePosition = 0; // Start of file.
	}
	final int tabCount = StringUtils.countMatches(
			code.substring(newLinePosition, position), "\t");
	return position - newLinePosition + (TAB_INDENT_SIZE - 1) * tabCount;
}
 
Example 19
/**
 * {@inheritDoc}
 */
@Override
public void evaluatePropertyExpression(View view, Map<String, Object> evaluationParameters,
        UifDictionaryBean expressionConfigurable, String propertyName, boolean removeExpression) {

    Map<String, String> propertyExpressions = expressionConfigurable.getPropertyExpressions();
    if ((propertyExpressions == null) || !propertyExpressions.containsKey(propertyName)) {
        return;
    }

    String expression = propertyExpressions.get(propertyName);

    // If the property name is a default value which grabs a new sequence number don't evaluate the expression
    // since a new sequence number has already been retrieved.
    if (StringUtils.equals(propertyName, UifConstants.ComponentProperties.DEFAULT_VALUE) &&
            StringUtils.contains(expression, UifConstants.SEQUENCE_PREFIX)) {
        return;
    }

    // check whether expression should be evaluated or property should retain the expression
    if (CopyUtils.fieldHasAnnotation(expressionConfigurable.getClass(), propertyName, KeepExpression.class)) {
        // set expression as property value to be handled by the component
        ObjectPropertyUtils.setPropertyValue(expressionConfigurable, propertyName, expression);
        return;
    }

    Object propertyValue = null;

    // replace binding prefixes (lp, dp, fp) in expression before evaluation
    String adjustedExpression = replaceBindingPrefixes(view, expressionConfigurable, expression);

    // determine whether the expression is a string template, or evaluates to another object type
    if (StringUtils.startsWith(adjustedExpression, UifConstants.EL_PLACEHOLDER_PREFIX) && StringUtils.endsWith(
            adjustedExpression, UifConstants.EL_PLACEHOLDER_SUFFIX) && (StringUtils.countMatches(adjustedExpression,
            UifConstants.EL_PLACEHOLDER_PREFIX) == 1)) {
        propertyValue = evaluateExpression(evaluationParameters, adjustedExpression);
    } else {
        // treat as string template
        propertyValue = evaluateExpressionTemplate(evaluationParameters, adjustedExpression);
    }

    // if property name has the special indicator then we need to add the expression result to the property
    // value instead of replace
    if (StringUtils.endsWith(propertyName, ExpressionEvaluator.EMBEDDED_PROPERTY_NAME_ADD_INDICATOR)) {
        StringUtils.removeEnd(propertyName, ExpressionEvaluator.EMBEDDED_PROPERTY_NAME_ADD_INDICATOR);

        Collection collectionValue = ObjectPropertyUtils.getPropertyValue(expressionConfigurable, propertyName);
        if (collectionValue == null) {
            throw new RuntimeException("Property name: " + propertyName
                    + " with collection type was not initialized. Cannot add expression result");
        }
        collectionValue.add(propertyValue);
    } else {
        ObjectPropertyUtils.setPropertyValue(expressionConfigurable, propertyName, propertyValue);
    }

    if (removeExpression) {
        propertyExpressions.remove(propertyName);
    }
}
 
Example 20
Source Project: hop   File: Const.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Split the given string using the given delimiter and enclosure strings.
 * <p>
 * The delimiter and enclosures are not regular expressions (regexes); rather they are literal strings that will be
 * quoted so as not to be treated like regexes.
 * <p>
 * This method expects that the data contains an even number of enclosure strings in the input; otherwise the results
 * are undefined
 *
 * @param stringToSplit   the String to split
 * @param delimiter       the delimiter string
 * @param enclosure       the enclosure string
 * @param removeEnclosure removes enclosure from split result
 * @return an array of strings split on the delimiter (ignoring those in enclosures), or null if the string to split
 * is null.
 */
public static String[] splitString( String stringToSplit, String delimiter, String enclosure, boolean removeEnclosure ) {

  ArrayList<String> splitList = null;

  // Handle "bad input" cases
  if ( stringToSplit == null ) {
    return null;
  }
  if ( delimiter == null ) {
    return ( new String[] { stringToSplit } );
  }

  // Split the string on the delimiter, we'll build the "real" results from the partial results
  String[] delimiterSplit = stringToSplit.split( Pattern.quote( delimiter ) );

  // At this point, if the enclosure is null or empty, we will return the delimiter split
  if ( Utils.isEmpty( enclosure ) ) {
    return delimiterSplit;
  }

  // Keep track of partial splits and concatenate them into a legit split
  StringBuilder concatSplit = null;

  if ( delimiterSplit != null && delimiterSplit.length > 0 ) {

    // We'll have at least one result so create the result list object
    splitList = new ArrayList<>();

    // Proceed through the partial splits, concatenating if the splits are within the enclosure
    for ( String currentSplit : delimiterSplit ) {
      if ( !currentSplit.contains( enclosure ) ) {

        // If we are currently concatenating a split, we are inside an enclosure. Since this
        // split doesn't contain an enclosure, we can concatenate it (with a delimiter in front).
        // If we're not concatenating, the split is fine so add it to the result list.
        if ( concatSplit != null ) {
          concatSplit.append( delimiter );
          concatSplit.append( currentSplit );
        } else {
          splitList.add( currentSplit );
        }
      } else {
        // Find number of enclosures in the split, and whether that number is odd or even.
        int numEnclosures = StringUtils.countMatches( currentSplit, enclosure );
        boolean oddNumberOfEnclosures = ( numEnclosures % 2 != 0 );
        boolean addSplit = false;

        // This split contains an enclosure, so either start or finish concatenating
        if ( concatSplit == null ) {
          concatSplit = new StringBuilder( currentSplit ); // start concatenation
          addSplit = !oddNumberOfEnclosures;
        } else {
          // Check to make sure a new enclosure hasn't started within this split. This method expects
          // that there are no non-delimiter characters between a delimiter and a starting enclosure.

          // At this point in the code, the split shouldn't start with the enclosure, so add a delimiter
          concatSplit.append( delimiter );

          // Add the current split to the concatenated split
          concatSplit.append( currentSplit );

          // If the number of enclosures is odd, the enclosure is closed so add the split to the list
          // and reset the "concatSplit" buffer. Otherwise continue
          addSplit = oddNumberOfEnclosures;
        }
        if ( addSplit ) {
          String splitResult = concatSplit.toString();
          //remove enclosure from resulting split
          if ( removeEnclosure ) {
            splitResult = removeEnclosure( splitResult, enclosure );
          }

          splitList.add( splitResult );
          concatSplit = null;
          addSplit = false;
        }
      }
    }
  }

  // Return list as array
  return splitList.toArray( new String[ splitList.size() ] );
}