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

The following are Jave code examples for showing how to use countMatches() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: CIA   File: ElasticSearchUtilities.java   View Source Code Vote up 6 votes
/**
 * Get a complete ElasticSearch query
 * @param parameters the match parameters that results must have
 * @return the completed query
 */
private static String getCompleteQuery(String parameters){
    StringBuilder builder = new StringBuilder();

    boolean multiField = StringUtils.countMatches(parameters, "}},") > 0 && StringUtils.countMatches(parameters, "\n{\"match\": {\"") > 1;

    // TODO: handle case when there is more than max results
    builder.append("{\"size\": " + MAX_RESULTS + ",");

    // find all
    if (parameters.equals("")){
        builder.append("\n\"query\": {\"match_all\": {}");
        builder.append("}}\n}");
    } else if (!multiField) {
        builder.append("\n\"query\": {\"term\":{");
        builder.append(parameters);
        builder.append("}}\n}");
    } else {
        builder.append("\n\"query\":{\n\"bool\": {\n\"must\": [");
        builder.append(parameters);
        builder.append("]}}\n}");
    }

    return builder.toString();
}
 
Example 2
Project: pnc-repressurized   File: PneumaticCraftUtils.java   View Source Code Vote up 6 votes
public static boolean isEntityValidForFilterUnsafe(String filter, Entity entity) throws IllegalArgumentException {
    if (filter == null) return true;
    if (StringUtils.countMatches(filter, "(") != StringUtils.countMatches(filter, ")"))
        throw new IllegalArgumentException("Not an equal amount of opening and closing braces");
    String[] splits = filter.split("[(),]");
    for (int i = 0; i < splits.length; i++)
        splits[i] = splits[i].trim();
    if (!isEntityValidForName(splits[0], entity)) return false;
    for (int i = 1; i < splits.length; i++) {
        String[] modifier = splits[i].split("=");
        if (modifier.length == 2) {
            if (!isEntityValidForModifier(modifier[0].trim(), modifier[1].trim(), entity)) return false;
        } else {
            throw new IllegalArgumentException("No '=' sign in the modifier.");
        }
    }
    return true;
}
 
Example 3
Project: sierra   File: FastHivdb.java   View Source Code Vote up 6 votes
public Map<DrugClass, Map<Drug, Map<Mutation, Double>>> getDrugClassDrugMutScores() {
	Map<DrugClass, Map<Drug, Map<Mutation, Double>>> result = new EnumMap<>(DrugClass.class);
	for (DrugClass drugClass : gene.getDrugClasses()) {
		result.put(drugClass, new EnumMap<>(Drug.class));
		Map<Drug, Map<Mutation, Double>> drugClassResult = result.get(drugClass);
		for (Drug drug : drugClass.getDrugsForHivdbTesting()) {
			drugClassResult.put(drug, new LinkedHashMap<>());
			Map<Mutation, Double> drugResult = drugClassResult.get(drug);
			Map<String, Double> drugScores = separatedScores.getOrDefault(drug, Collections.emptyMap());
			for (String key : drugScores.keySet()) {
				if (StringUtils.countMatches(key, "+") > 1) {
					continue;
				}
				Mutation mut = triggeredMuts.get(drug).get(key).first();
				drugResult.put(mut, drugScores.get(key));
			}
		}
	}
	return result;
}
 
Example 4
Project: hashsdn-controller   File: StringUtil.java   View Source Code Vote up 6 votes
public static String formatJavaSource(final String input) {
    Iterable<String> split = Splitter.on("\n").trimResults().split(input);

    int basicIndent = 4;
    StringBuilder sb = new StringBuilder();
    int indents = 0, empty = 0;
    for (String line : split) {
        indents -= StringUtils.countMatches(line, "}");
        if (indents < 0) {
            indents = 0;
        }
        if (!line.isEmpty()) {
            sb.append(Strings.repeat(" ", basicIndent * indents));
            sb.append(line);
            sb.append("\n");
            empty = 0;
        } else {
            empty++; // one empty line is allowed
            if (empty < 2) {
                sb.append("\n");
            }
        }
        indents += StringUtils.countMatches(line, "{");
    }
    return ensureEndsWithSingleNewLine(sb.toString());
}
 
Example 5
Project: rskj   File: IpUtils.java   View Source Code Vote up 6 votes
public static InetSocketAddress parseAddress(String address) {
    if(StringUtils.isBlank(address)) {
        return null;
    }
    
    Matcher matcher = ipv6Pattern.matcher(address);
    if(matcher.matches()) {
        return parseMatch(matcher);
    }

    matcher = ipv4Pattern.matcher(address);
    if(StringUtils.countMatches(address, ":") == 1 && matcher.matches()) {
        return parseMatch(matcher);
    }

    logger.debug("Invalid address: {}. For ipv6 use de convention [address]:port. For ipv4 address:port", address);
    return null;
}
 
Example 6
Project: Wechat-Group   File: ToStringUtils.java   View Source Code Vote up 6 votes
/**
 * 用于产生去掉空值属性并以换行符分割各属性键值的toString字符串
 * @param obj
 */
public static String toSimpleString(Object obj) {
  String toStringResult = ToStringBuilder.reflectionToString(obj, THE_STYLE);
  String[] split = toStringResult.split(SimpleMultiLineToStringStyle.LINE_SEPARATOR);
  StringBuilder result = new StringBuilder();
  for (String string : split) {
    if (string.endsWith(SimpleMultiLineToStringStyle.NULL_TEXT)) {
      continue;
    }

    result.append(string + SimpleMultiLineToStringStyle.LINE_SEPARATOR);
  }

  if (result.length() == 0) {
    return "";
  }

  //如果没有非空的属性,就输出 <all null properties>
  if (StringUtils.countMatches(result, SimpleMultiLineToStringStyle.LINE_SEPARATOR) == 2) {
    return result.toString().split(SimpleMultiLineToStringStyle.LINE_SEPARATOR)[0]
      + "<all null values>]";
  }

  return result.deleteCharAt(result.length() - 1).toString();
}
 
Example 7
Project: Android_watch_magpie   File: LogicTupleEvent.java   View Source Code Vote up 6 votes
public List<String> getArguments() {
    List<String> arguments = new ArrayList<>();
    int elements = StringUtils.countMatches(logicRepresentation, ",");

    if (elements == 0) {
        arguments.add(getSubstring("(", ")"));
    } else if (elements == 1) {
        arguments.add(getSubstring("(", ","));
        arguments.add(getSubstring(",", ")"));
    } else if (elements > 1) {
        arguments.add(getSubstring("(", ","));
        String restString = getSubstring(",", ")");
        String[] restArray = StringUtils.split(restString, ",");
        for (String aRestArray : restArray) {
            arguments.add(aRestArray);
        }
    }
    return arguments;
}
 
Example 8
Project: RManager   File: CoreUtil.java   View Source Code Vote up 6 votes
public static String toCustom(String format, Duration time) {
    long millis = time.toMillis();
    long seconds = time.getSeconds();
    long minutes = time.toMinutes();
    long hours = time.toHours();
    long days = time.toDays();

    String ms = String.valueOf(millis - (seconds * 1000));
    String s = String.valueOf(seconds - (minutes * 60));
    String m = String.valueOf(minutes - (hours * 60));
    String h = String.valueOf(hours - (days * 24));
    String d = String.valueOf(days);

    if (format.contains("s")) {
        int msCount = StringUtils.countMatches(format, 's');
        ms = ms.substring(0, msCount - 1);
    }

    return format.replace("%D", d).replace("%H", h).replace("%M", m).replace("%S", s).replaceAll("%+s*", ms);
}
 
Example 9
Project: phrase-java   File: TagProcessor.java   View Source Code Vote up 5 votes
private void findTagContent() {
	int startTags = StringUtils.countMatches(target, tag.getStartTag());
	int endTags = StringUtils.countMatches(target, tag.getEndTag());
	//make sure the amount of start and end tags are equal
	if(startTags == endTags) {
		String[] results = StringUtils.substringsBetween(target.toString(), tag.getStartTag().toString(), tag.getEndTag().toString());
		for(String result : results) {
			tagResult.addResult(result);
			logger.log("Found Tag: %s", result);
		}
	} else {
		//TODO: throw exception or something
		logger.log("Tag counts don't match. Found %s start tags and %s end tags!", startTags, endTags);
	}
}
 
Example 10
Project: momo-2   File: Macro.java   View Source Code Vote up 5 votes
/**
 * Resolve macro name and contents from a create statement
 * This works to involve quotations around a spaced macro name
 * @param s The parameters of a create statement - The contents past the $macro create bit
 * @return Two index array: [0] is the macro name, [1] is the contents
 * Prerequisite: s.split() must have length of >= 2
 */
private static String[] resolveMacroNameAndContents(String s) {
	String[] toReturn = new String[2];
	if(s.contains("\"") && StringUtils.countMatches(s, "\"") > 1) {
		int secondIndexOfQuotes = s.indexOf("\"", s.indexOf("\"") + 1);
		toReturn[0] = s.substring(s.indexOf("\"") + 1, secondIndexOfQuotes);
		toReturn[1] = s.substring(secondIndexOfQuotes + 2);
	} else {
		toReturn[0] = s.split(" ")[0];
		toReturn[1] = Util.getCommandContents(s);
	}
	return toReturn;
}
 
Example 11
Project: phonk   File: EditorFragment.java   View Source Code Vote up 5 votes
/**
 * Get current cursor line
 */
public int getCurrentCursorLine(Editable editable) {
    int selectionStartPos = Selection.getSelectionStart(editable);

    // no selection
    if (selectionStartPos < 0) return -1;

    String preSelectionStartText = editable.toString().substring(0, selectionStartPos);
    return StringUtils.countMatches(preSelectionStartText, "\n");
}
 
Example 12
Project: careconnect-reference-implementation   File: SNOMEDUKMockValidationSupport.java   View Source Code Vote up 5 votes
@Override
public StructureDefinition fetchStructureDefinition(FhirContext theContext, String theUrl) {
  String url = theUrl;
  if (url.startsWith(URL_PREFIX_STRUCTURE_DEFINITION)) {
    // no change
  } else if (url.indexOf('/') == -1) {
    url = URL_PREFIX_STRUCTURE_DEFINITION + url;
  } else if (StringUtils.countMatches(url, '/') == 1) {
    url = URL_PREFIX_STRUCTURE_DEFINITION_BASE + url;
  }
  return provideStructureDefinitionMap(theContext).get(url);
}
 
Example 13
Project: strqlbuilder   File: Chunk.java   View Source Code Vote up 5 votes
protected String extractParams(String str, Object... values) {
int args = values == null ? 0 : values.length;
if (args == 0) {
    return str;
}
if (StringUtils.isBlank(str)) {
    return str;
}
if (args != StringUtils.countMatches(str, ":")) {
    throw new ParseSqlException("El número de parámetros no coincide en el predicado " + str);
}
ConditionValues cv = ConditionValuesParser.getInstance(str, values).parse();
str = cv.getCondition();
values = cv.getValues();

Matcher m = Pattern.compile(":([^\\s\\)]+)").matcher(str);
int i = 0;
while (m.find()) {
    String paramName = m.group(1);
    Object value = values[i++];
    if (value instanceof StrQLBuilder) {
	sqls.add(new Parameter<StrQLBuilder>(paramName, (StrQLBuilder) value));
	continue;
    }
    if (value != null && value.getClass().isArray()) {
	value = StrQLUtils.arrayToList(value); // convert array to list
    }
    params.add(new Parameter<Object>(paramName, value));
}
return str;
   }
 
Example 14
Project: wavemaker-app-build-tools   File: PageMinFileUpdator.java   View Source Code Vote up 4 votes
private static void validatePageMinFile(String string, String subString) {
    if (StringUtils.countMatches(string, subString) != 1) {
        throw new WMRuntimeException("Page resource update not supported");
    }
}
 
Example 15
Project: aceql-http   File: PreparedStatementRunner.java   View Source Code Vote up 4 votes
/**
    * Executes a SQL prepared statement for an update.
    * 
    * @return the return code of the prepared statement
    * 
    * @throws SQLException
    *             if a SQL Exception is raised
    */
   public int executeUpdate() throws SQLException {
prepStatement = connection.prepareStatement(sql);

int numberOfIntMarks = StringUtils.countMatches(sql, "?");
int numberOfParams = params.size();

if (numberOfIntMarks != numberOfParams) {
    throw new SQLException(
	    "sql statement numbers of \"?\" do no match number of parameters: "
		    + numberOfIntMarks + " and " + numberOfParams);
}

for (int i = 0; i < params.size(); i++) {
    int j = i + 1;
    prepStatement.setObject(j, params.get(i));
}

int rc = -1;

String sqlLower = sql.toLowerCase();

if (sqlLower.startsWith(SELECT)) {
    throw new SQLException("sql string is not an update: " + sql);
}

if (sqlLower.startsWith(UPDATE) || sqlLower.startsWith(DELETE)) {
    if (sqlLower.indexOf(" " + WHERE + " ") == 0) {
	throw new SQLException(
		"update and delete are not permitted without a WHERE clause: "
			+ sql);
    }
}

if (sqlLower.startsWith(UPDATE) || sqlLower.startsWith(DELETE)
	|| sqlLower.startsWith(INSERT)) {
    rc = prepStatement.executeUpdate();
} else {
    throw new SQLException(
	    "Statement is not INSERT / UPDATE / DELETE: " + sql);
}

debug(this.toString());
return rc;
   }
 
Example 16
Project: beaker-notebook-archive   File: JavaEvaluator.java   View Source Code Vote up 4 votes
public void append(String string) {
  this.delegate.append(string);
  this.linesCount += StringUtils.countMatches(string, LINE_BREAK);
}
 
Example 17
Project: Saber-Bot   File: MessageGenerator.java   View Source Code Vote up 4 votes
/**
 * Generates the body content of the discord message for events using the
 * "full" display style
 * @param se the ScheduleEntry Object represented by the display
 * @return the body content as a string
 */
private static String generateBodyFull(ScheduleEntry se)
{
    String msg = "";

    // create the upper code block containing the event start/end/shouldRepeat/expire info
    String timeLine = genTimeLine(se);
    String repeatLine = "> " + se.getRecurrence().toString(false) + "\n";
    if(se.getExpire() != null)
    {   // expire information on separate line
        repeatLine += "> expires " + se.getExpire().getMonth().getDisplayName(TextStyle.SHORT, Locale.ENGLISH) +
                " " + se.getExpire().getDayOfMonth() + ", " + se.getExpire().getYear() + "\n";
    }
    else if(se.getRecurrence().getCount() != null)
    {   // remaining event occurrences on separate line
        repeatLine += "> occurs " + se.getRecurrence().countRemaining(se.getStart()) + " more times\n";
    }
    msg += "```Markdown\n\n" + timeLine + repeatLine +
            (se.getLocation()==null ? "":"<Location: "+se.getLocation()+">\n")+"```\n";

    // insert each comment line with a gap line
    for( String comment : se.getComments() )
    {
        // don't break the maximum length of messages
        if(msg.length() > 1800) break;

        // code blocks in comments must be closed
        int code = StringUtils.countMatches("```", comment);
        if((code%2) == 1) msg += ParsingUtilities.parseMessageFormat(comment, se, false) + " ```" + "\n";
        else msg += ParsingUtilities.parseMessageFormat(comment, se, false) + "\n\n";
    }

    // generate the lower code block
    String zoneLine = "[" + se.getStart().getZone().getDisplayName(TextStyle.FULL, Locale.ENGLISH) + "]" +
            MessageGenerator.genTimer(se.getStart(), se.getEnd()) + "\n";

    // if rsvp is enabled, show the number of rsvp
    if(Main.getScheduleManager().isRSVPEnabled(se.getChannelId()))
    {
        String rsvpLine = "- ";
        Map<String, String> options = Main.getScheduleManager().getRSVPOptions(se.getChannelId());
        for(String key : options.keySet()) // I iterate over the keys rather than the values to keep a order consistent with reactions
        {
            String type = options.get(key);
            rsvpLine += "<" + type + " " + se.getRsvpMembersOfType(type).size() +
                    (se.getRsvpLimit(type)>=0 ? "/"+se.getRsvpLimit(type)+"> " : "> ");
        }
        if(se.getDeadline() != null)
        {
            rsvpLine += "\n+ RSVP closes " + se.getDeadline().getMonth().getDisplayName(TextStyle.SHORT, Locale.ENGLISH) +
                " " + se.getDeadline().getDayOfMonth() + ", " + se.getDeadline().getYear() + ".";
        }
        msg += "```Markdown\n\n" + zoneLine + rsvpLine + "```";
    }
    else
    {
        msg += "```Markdown\n\n" + zoneLine + "```";
    }
    return msg;
}
 
Example 18
Project: spring2ts   File: JavaTypescriptTypeMapping.java   View Source Code Vote up 4 votes
private boolean checkRightNumberOfParenthesis(String group) {
    return StringUtils.countMatches(group, '<') == StringUtils.countMatches(group, '>');
}
 
Example 19
Project: Slide-RSS   File: SpoilerRobotoTextView.java   View Source Code Vote up 4 votes
private void setEmoteSpans(SpannableStringBuilder builder) {
    for (URLSpan span : builder.getSpans(0, builder.length(), URLSpan.class)) {
            setLargeLinks(builder, span);
        File emoteDir = new File(Environment.getExternalStorageDirectory(), "RedditEmotes");
        File emoteFile = new File(emoteDir, span.getURL().replace("/", "").replaceAll("-.*", "")
                + ".png"); //BPM uses "-" to add dynamics for emotes in browser. Fall back to original here if exists.
        boolean startsWithSlash = span.getURL().startsWith("/");
        boolean hasOnlyOneSlash = StringUtils.countMatches(span.getURL(), "/") == 1;

        if (emoteDir.exists() && startsWithSlash && hasOnlyOneSlash && emoteFile.exists()) {
            //We've got an emote match
            int start = builder.getSpanStart(span);
            int end = builder.getSpanEnd(span);
            CharSequence textCovers = builder.subSequence(start, end);

            //Make sure bitmap loaded works well with screen density.
            BitmapFactory.Options options = new BitmapFactory.Options();
            DisplayMetrics metrics = new DisplayMetrics();
            ((WindowManager) getContext().getSystemService(
                    Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
            options.inDensity = 240;
            options.inScreenDensity = metrics.densityDpi;
            options.inScaled = true;

            //Since emotes are not directly attached to included text, add extra character to attach image to.
            builder.removeSpan(span);
            if (builder.subSequence(start, end).charAt(0) != '.') {
                builder.insert(start, ".");
            }
            Bitmap emoteBitmap = BitmapFactory.decodeFile(emoteFile.getAbsolutePath(), options);
            builder.setSpan(new ImageSpan(getContext(), emoteBitmap), start, start + 1,
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            //Check if url span has length. If it does, it's a spoiler/caption
            if (textCovers.length() > 1) {
                builder.setSpan(new URLSpan("/sp"), start + 1, end + 1,
                        Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                builder.setSpan(new StyleSpan(Typeface.ITALIC), start + 1, end + 1,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            builder.append("\n"); //Newline to fix text wrapping issues
        }
    }
}
 
Example 20
Project: sierra   File: Mutation.java   View Source Code Vote up 4 votes
public boolean isUnsequenced() {
	// "NNN", "NN-", "NNG" should be considered as unsequenced region
	return !isInsertion &&
		StringUtils.countMatches(triplet.replace('-', 'N'),	"N") > 1;
}