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

The following examples show how to use org.apache.commons.lang3.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 check out the related API usage on the sidebar.
Example 1
Source Project: org.hl7.fhir.core   File: ShExGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Emit a ShEx definition for the supplied StructureDefinition
 * @param sd Structure definition to emit
 * @return ShEx definition
 */
private String genShapeDefinition(StructureDefinition sd, boolean isResource) {
  ST resource_decl = tmplt(RESOURCE_DECL_TEMPLATE);
  ST struct_def = tmplt(SHAPE_DEFINITION_TEMPLATE);

  // todo: Figure out why this doesn't identify "Account" as a resource.  getResourceNames() returns "Resource", "Resource"
  // this.context.getResourceNames().contains(sd.getId())
  resource_decl.add("id", sd.getId());
  struct_def.add("resourceDecl", isResource ? resource_decl.render() : "");

  struct_def.add("id", sd.getId());
  List<String> elements = new ArrayList<String>();

  for (ElementDefinition ed : sd.getSnapshot().getElement()) {
    if(StringUtils.countMatches(ed.getPath(), ".") == 1) {
      elements.add(genElementDefinition(sd, ed));
    }
  }
  struct_def.add("elements", StringUtils.join(elements, ",\n\t"));
  return struct_def.render();
}
 
Example 2
Source Project: samantha   File: SeparatedStringSizeExtractor.java    License: MIT License 6 votes vote down vote up
public Map<String, List<Feature>> extract(JsonNode entity, boolean update,
                                          IndexSpace indexSpace) {
    Map<String, List<Feature>> feaMap = new HashMap<>();
    if (entity.has(attrName) || alwaysExtract) {
        List<Feature> features = new ArrayList<>();
        String attr = "";
        if (entity.has(attrName)) {
            attr = entity.get(attrName).asText();
        }
        int size = StringUtils.countMatches(attr, separator) + 1;
        if ("".equals(attr) && !alwaysExtract) {
            size = 0;
        }
        if (maxFeatures != null && size > maxFeatures) {
            size = maxFeatures;
        }
        String key = FeatureExtractorUtilities.composeKey(attrName, "size");
        FeatureExtractorUtilities.getOrSetIndexSpaceToFeaturize(features, update,
                indexSpace, indexName, key, size);
        feaMap.put(feaName, features);
    } else {
        logger.warn("{} is not present in {}", attrName, entity);
    }
    return feaMap;
}
 
Example 3
Source Project: nuls   File: ProgramDescriptors.java    License: MIT License 6 votes vote down vote up
private static String getDesc(String desc) {
    int dimensions = StringUtils.countMatches(desc, "[]");
    desc = desc.replace("[]", "");
    String[] parts = desc.split(" ");
    desc = parts[0];
    String desc1 = Descriptors.DESCRIPTORS.get(desc);
    if (desc1 != null) {
        desc = desc1;
    } else {
        desc1 = ProgramDescriptors.DESCRIPTORS.get(desc);
        if (desc1 != null) {
            desc = desc1;
        }
    }
    for (int i = 0; i < dimensions; i++) {
        desc = "[" + desc;
    }
    return desc;
}
 
Example 4
Source Project: synopsys-detect   File: CpanListParser.java    License: Apache License 2.0 6 votes vote down vote up
public 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 5
public RegexSelector(String regexStr, int group) {
    if (StringUtils.isBlank(regexStr)) {
        throw new IllegalArgumentException("regex must not be empty");
    }
    // Check bracket for regex group. Add default group 1 if there is no group.
    // Only check if there exists the valid left parenthesis, leave regexp validation for Pattern.
    if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
            StringUtils.countMatches(regexStr, "(?:") - StringUtils.countMatches(regexStr, "\\(?:")) {
        regexStr = "(" + regexStr + ")";
    }
    this.regexStr = regexStr;
    try {
        regex = Pattern.compile(regexStr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    } catch (PatternSyntaxException e) {
        throw new IllegalArgumentException("invalid regex", e);
    }
    this.group = group;
}
 
Example 6
Source Project: ghidra   File: JavaSourceFile.java    License: Apache License 2.0 5 votes vote down vote up
public void removeJavaStatement(int lineNumber) {
	JavaSourceLine startLine = getStatementStartForLine(lineNumber);
	if (startLine.getText().trim().endsWith(";")) {
		startLine.delete(); // statement is all on one line, nothing more to do
		return;
	}

	List<JavaSourceLine> linesToClear = new ArrayList<>(
		getRemainingLinesForStatement(startLine, startLine.getLineNumber() + 1));
	linesToClear.add(0, startLine);

	int size = linesToClear.size();
	for (int i = 0; i < size - 1; i++) {
		linesToClear.get(i).delete();
	}

	// do the last line special
	JavaSourceLine lastLine = linesToClear.get(size - 1);
	String text = lastLine.getText();
	int count = StringUtils.countMatches(text, ';');
	if (count == 1) {
		// normal line
		lastLine.delete();
		return;
	}

	// remove all text up to the first semicolon
	text = text.substring(text.indexOf(";") + 1);
	lastLine.setText(text);
}
 
Example 7
private HashMap<String, Double> getEntropy(String target, String snippet, HashMap<String, Double> entropies,
		Boolean normalization, int tokens) throws IOException {
	int tot = tokens;
	double np;
	double count = StringUtils.countMatches(snippet, target);
	double p = count / (double) tot;
	np = 1 - p;
	double ent = -p * (Math.log(p) / Math.log(2)) - np * (Math.log(np) / Math.log(2));
	if (normalization) {
		entropies.put(target, ent);
	} else {
		entropies.put(target.toLowerCase(Locale.ENGLISH), weightRange(ent)); 
	}
	return entropies;
}
 
Example 8
/**
 * Detect the application context and the first nested path
 * Strategy used to test some Path Traversal issues
 * 
 * Ex: http://www.example.org/myapp/assets/test.jsf
 *
 * returns /myapp/assets/
 */
public static String getApplicationContextAndNestedPath(URL url) {

    String path = url.getPath();
    int i = path.lastIndexOf('/');
    String context = path.substring(0, i + 1);

    return (StringUtils.countMatches(context, "/") == 3) ? context : "";
}
 
Example 9
Source Project: quarkus   File: QuarkusCommandHandlers.java    License: Apache License 2.0 5 votes vote down vote up
static List<AppArtifactCoords> computeCoordsFromQuery(final QuarkusCommandInvocation invocation,
        final Set<String> extensionsQuery) {
    final ArrayList<AppArtifactCoords> builder = new ArrayList<>();
    for (String query : extensionsQuery) {
        final int countColons = StringUtils.countMatches(query, ":");
        if (countColons == 1) {
            builder.add(toCoords(AppArtifactKey.fromString(query), null));
        } else if (countColons > 1) {
            builder.add(AppArtifactCoords.fromString(query));
        } else {
            SelectionResult result = select(query, invocation.getPlatformDescriptor().getExtensions(), false);
            if (result.matches()) {
                final Set<AppArtifactCoords> withStrippedVersion = result.getExtensions().stream().map(Extensions::toCoords)
                        .map(Extensions::stripVersion).collect(Collectors.toSet());
                // We strip the version because those extensions are managed
                builder.addAll(withStrippedVersion);
            } else {
                StringBuilder sb = new StringBuilder();
                // We have 3 cases, we can still have a single candidate, but the match is on label
                // or we have several candidates, or none
                Set<Extension> candidates = result.getExtensions();
                if (candidates.isEmpty()) {
                    // No matches at all.
                    invocation.log().info(nok("Cannot find a dependency matching '" + query + "', maybe a typo?"));
                    return null;
                } else {
                    sb.append(nok("Multiple extensions matching '")).append(query).append("'");
                    result.getExtensions()
                            .forEach(extension -> sb.append(System.lineSeparator()).append("     * ")
                                    .append(extension.managementKey()));
                    sb.append(System.lineSeparator())
                            .append("     Be more specific e.g using the exact name or the full GAV.");
                    invocation.log().info(sb.toString());
                    return null;
                }
            }
        }
    }
    return builder;
}
 
Example 10
@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 11
Source Project: find   File: ResultsITCase.java    License: MIT License 5 votes vote down vote up
@Test
@ResolvedBug("FIND-93")
public void testNoResults() {
    final ListView results = findService.search("thissearchwillalmostcertainlyreturnnoresults");

    new WebDriverWait(getDriver(), 60L).withMessage("No results message should appear")
        .until(ExpectedConditions.textToBePresentInElement(results.resultsDiv(), "No results found"));

    findPage.scrollToBottom();

    final int occurrences = StringUtils.countMatches(results.resultsDiv().getText(), "results found");
    verifyThat("Only one message showing at the bottom of search results", occurrences, is(1));
}
 
Example 12
private boolean isJwtBearerToken(String token) {
    return StringUtils.countMatches(token, ".") == 2 && (token.startsWith("Bearer") || token.startsWith("bearer"));
}
 
Example 13
Source Project: reasonml-idea-plugin   File: ORProjectManager.java    License: MIT License 4 votes vote down vote up
private static int fileSeparatorCount(@NotNull VirtualFile file) {
    return StringUtils.countMatches(file.getPath(), '/');
}
 
Example 14
@Override
public List<Float> getDosageAsFloats(IPrescription prescription){
	ArrayList<Float> list = new ArrayList<>();
	ArrayList<Float> sub_list = new ArrayList<>();
	float num = 0;
	String dosis = prescription.getDosageInstruction();
	if (dosis != null) {
		// Match stuff like '1/2', '7/8', '~1,2'
		// System.out.println(dosis.matches(special_num_at_start));
		if (dosis.matches(special_num_at_start)) {
			list.add(getNum(dosis.replace("~", "")));
		} else if (dosis.matches("[0-9½¼]+([xX][0-9]+(/[0-9]+)?|)")) { //$NON-NLS-1$
			String[] dose = dosis.split("[xX]"); //$NON-NLS-1$
			float count = getNum(dose[0]);
			if (dose.length > 1)
				num = getNum(dose[1]) * count;
			else
				num = getNum(dose[0]);
			list.add(num);
		} else {
			sub_list = getDosageAsFloats(dosis, "-");
			if (StringUtils.countMatches(dosis, "-") > 1 && sub_list.size() > 0) {
				return sub_list;
			}
			sub_list = getDosageAsFloats(dosis, "/");
			if (StringUtils.countMatches(dosis, "/") > 1 && sub_list.size() > 0) {
				return sub_list;
			}
			if (dosis.indexOf('-') != -1 || dosis.indexOf('/') != -1) {
				String[] dos = dosis.split("[- /]"); //$NON-NLS-1$
				if (dos.length > 2) {
					for (String d : dos) {
						boolean hasDigit = d.matches("^[~/.]*[½¼0-9].*");
						if (d.indexOf(' ') != -1)
							list.add(getNum(d.substring(0, d.indexOf(' '))));
						else if (d.length() > 0 && hasDigit)
							list.add(getNum(d));
						if (list.size() >= 4)
							return list;
					}
				} else if (dos.length > 1) {
					list.add(getNum(dos[1]));
				} else {
					// nothing to add
				}
			}
		}
	}
	return list;
}
 
Example 15
public static String relativeToAbsolute(String currentPath, String relativePath) {
    //begin with /
    if (relativePath.startsWith(File.separator)) {
        return relativePath;
    }

    String path = currentPath;
    File f = new File(currentPath);
    if (f.isFile()) {
        path = FilenameUtils.getPath(currentPath);
    }


    //begin with . means current path
    if (!relativePath.startsWith("..")) {
        if (relativePath.startsWith(".")) {
            return joinWithFilename(relativePath.substring(1), currentPath);
        } else {
            return joinWithFilename(relativePath, currentPath);
        }
    }

    //begin with .. means back path
    int count = StringUtils.countMatches(relativePath, "..");
    if (path.endsWith(File.separator)) {
        path = path.substring(0, path.length() - 1);
    }

    int idx = StringUtils.lastIndexOf(relativePath, "..");
    String realpath = relativePath.substring(idx + 1);

    String[] paths = StringUtils.split(path, File.separatorChar);
    int basepathCount = paths.length - count;
    if (0 > basepathCount) throw new RuntimeException("parent folder is so short.");
    if (0 == basepathCount) return realpath;
    String[] basePaths = new String[basepathCount];
    for (int i = 0; i < basepathCount; i++) {
        basePaths[i] = paths[i];
    }

    String basepath = StringUtils.join(basePaths, File.separator);
    return joinWithFilename(realpath, basepath);
}
 
Example 16
/**
 * Returns the element's calculated height taking relevant CSS into account, but <b>not</b> the element's child
 * elements.
 *
 * @return the element's calculated height taking relevant CSS into account, but <b>not</b> the element's child
 *         elements
 */
private int getEmptyHeight() {
    if (height2_ != null) {
        return height2_.intValue();
    }

    final DomNode node = getElement().getDomNodeOrDie();
    if (!node.mayBeDisplayed()) {
        height2_ = Integer.valueOf(0);
        return 0;
    }

    if (NONE.equals(getDisplay())) {
        height2_ = Integer.valueOf(0);
        return 0;
    }

    final Element elem = getElement();
    final int windowHeight = elem.getWindow().getWebWindow().getInnerHeight();

    if (elem instanceof HTMLBodyElement) {
        height2_ = windowHeight;
        return windowHeight;
    }

    final boolean explicitHeightSpecified = !super.getHeight().isEmpty();

    int defaultHeight;
    if (node instanceof HtmlDivision && StringUtils.isBlank(node.getTextContent())) {
        defaultHeight = 0;
    }
    else if (elem.getFirstChild() == null) {
        if (node instanceof HtmlRadioButtonInput || node instanceof HtmlCheckBoxInput) {
            defaultHeight = 13;
        }
        else if (node instanceof HtmlButton) {
            defaultHeight = 20;
        }
        else if (node instanceof HtmlInput && !(node instanceof HtmlHiddenInput)) {
            final BrowserVersion browser = getBrowserVersion();
            if (browser.hasFeature(JS_CLIENTHIGHT_INPUT_17)) {
                defaultHeight = 17;
            }
            else if (browser.hasFeature(JS_CLIENTHIGHT_INPUT_21)) {
                defaultHeight = 21;
            }
            else {
                defaultHeight = 20;
            }
        }
        else if (node instanceof HtmlSelect) {
            defaultHeight = 20;
        }
        else if (node instanceof HtmlTextArea) {
            defaultHeight = 49;
        }
        else if (node instanceof HtmlInlineFrame) {
            defaultHeight = 154;
        }
        else {
            defaultHeight = 0;
        }
    }
    else {
        defaultHeight = getBrowserVersion().getFontHeight(getFontSize());
        if (node instanceof HtmlDivision) {
            defaultHeight *= StringUtils.countMatches(node.asText(), '\n') + 1;
        }
    }

    final int defaultWindowHeight = elem instanceof HTMLCanvasElement ? 150 : windowHeight;

    int height = pixelValue(elem, new CssValue(defaultHeight, defaultWindowHeight) {
        @Override public String get(final ComputedCSSStyleDeclaration style) {
            final Element element = style.getElement();
            if (element instanceof HTMLBodyElement) {
                return String.valueOf(element.getWindow().getWebWindow().getInnerHeight());
            }
            return style.getStyleAttribute(HEIGHT, true);
        }
    });

    if (height == 0 && !explicitHeightSpecified) {
        height = defaultHeight;
    }

    height2_ = Integer.valueOf(height);
    return height;
}
 
Example 17
@JsonProperty( value = "level", access = JsonProperty.Access.READ_ONLY )
@JacksonXmlProperty( localName = "level", isAttribute = true )
public int getLevel()
{
    return StringUtils.countMatches( path, PATH_SEP );
}
 
Example 18
Source Project: tutorials   File: CountCharsExampleUnitTest.java    License: MIT License 4 votes vote down vote up
@Test
public void givenString_whenUsingStringUtils_thenCountChars() throws InterruptedException {
    int count = StringUtils.countMatches("elephant", "e");
    assertEquals(2, count);
}
 
Example 19
private int countLines(String val) {
    return StringUtils.countMatches(val, "\n");
}
 
Example 20
Source Project: components   File: DependenciesReader.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Checks whether dependency is correct and required. Required dependencies are: compile, runtime, provided Also
 * dependency should be fully described. It should contain gav, classifier and scope (totally 5 fields, thus 4 ":"
 * separators between fields)
 * 
 * @param dependencyLine line from dependencies.txt file describing component dependencies
 * @return true, if dependency is required; false - otherwise
 */
private boolean isRequiredDependency(String dependencyLine) {
    boolean result = (StringUtils.countMatches(dependencyLine, ":") > 3) && !dependencyLine.endsWith("test")
            && !dependencyLine.endsWith("system");
    return result;
}