List of usage examples for org.apache.commons.lang StringUtils countMatches
public static int countMatches(String str, String sub)
Counts how many times the substring appears in the larger String.
From source file:org.b3log.latke.servlet.handler.RouteHandler.java
/** * Adds the specified context handler meta * * @param contextHandlerMeta the specified context handler meta */// w w w .j av a2 s.c o m public static void addContextHandlerMeta(final ContextHandlerMeta contextHandlerMeta) { final Method invokeHolder = contextHandlerMeta.getInvokeHolder(); final Class<?> returnType = invokeHolder.getReturnType(); final String methodName = invokeHolder.getDeclaringClass().getName() + "#" + invokeHolder.getName(); if (!void.class.equals(returnType)) { LOGGER.error("Handler method [" + methodName + "] must return void"); System.exit(-1); } final Class<?>[] exceptionTypes = invokeHolder.getExceptionTypes(); if (0 < exceptionTypes.length) { LOGGER.error("Handler method [" + methodName + "] can not throw exceptions"); System.exit(-1); } final Class<?>[] parameterTypes = invokeHolder.getParameterTypes(); if (1 != parameterTypes.length) { LOGGER.error("Handler method [" + methodName + "] must have one parameter with type [RequestContext]"); System.exit(-1); } final Class<?> parameterType = parameterTypes[0]; if (!RequestContext.class.equals(parameterType)) { LOGGER.error("Handler method [" + methodName + "] must have one parameter with type [RequestContext]"); System.exit(-1); } final HttpMethod[] httpMethods = contextHandlerMeta.getHttpMethods(); for (int i = 0; i < httpMethods.length; i++) { final String httpMethod = httpMethods[i].name(); final String[] uriTemplates = contextHandlerMeta.getUriTemplates(); for (int j = 0; j < uriTemplates.length; j++) { final String uriTemplate = uriTemplates[j]; final String key = httpMethod + "." + uriTemplate; final int segs = StringUtils.countMatches(uriTemplate, "/"); if (!StringUtils.contains(uriTemplate, "{")) { switch (segs) { case 1: ONE_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); break; case 2: TWO_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); break; case 3: THREE_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); break; default: FOUR_MORE_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); } } else { // URI templates contain path vars switch (segs) { case 1: switch (httpMethod) { case "GET": ONE_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": ONE_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": ONE_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": ONE_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: ONE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } break; case 2: switch (httpMethod) { case "GET": TWO_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": TWO_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": TWO_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": TWO_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: TWO_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } break; case 3: switch (httpMethod) { case "GET": THREE_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": THREE_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": THREE_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": THREE_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: THREE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } break; default: switch (httpMethod) { case "GET": FOUR_MORE_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": FOUR_MORE_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": FOUR_MORE_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": FOUR_MORE_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: FOUR_MORE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } } } } } LOGGER.log(Level.DEBUG, "Added a processor method [" + methodName + "]"); }
From source file:org.betaconceptframework.astroboa.engine.jcr.util.JcrNodeUtils.java
public static String getYearMonthDayPathForContentObjectNode(Node contentObjectNode) throws RepositoryException { if (contentObjectNode == null || contentObjectNode.getParent() == null) { return ""; }/* w w w.j a va2s . c o m*/ //In releases prior to 3 (2.x.x) content object nodes were stored //under path contentTypeFolder/year/month/day //where as from release 3 and onwards content object nodes are stored under path //contentTypeFolder/year/month/day/hour/minute //This method takes under consideration both structures for compatibility reasons //Find content object type folder Node contentObjectTypeFolderNode = contentObjectNode.getParent(); //Try to find contentObjectTypeFolder node while (contentObjectTypeFolderNode != null && !contentObjectTypeFolderNode.isNodeType(CmsBuiltInItem.GenericContentTypeFolder.getJcrName())) { contentObjectTypeFolderNode = contentObjectTypeFolderNode.getParent(); } if (contentObjectTypeFolderNode == null) { return ""; } String contentObjectNodeParentPath = contentObjectNode.getParent().getPath(); String contentObjectTypeFolderPath = contentObjectTypeFolderNode.getPath(); String path = StringUtils.difference(contentObjectTypeFolderPath + "/", contentObjectNodeParentPath); logger.debug("CO Parent Path {} \n Type Folder Path {}\n Difference {}", new Object[] { contentObjectNodeParentPath, contentObjectTypeFolderPath, path }); //Path has either the format year/month/day or year/month/day/hour/minute int count = StringUtils.countMatches(path, "/"); if (count == 2) { return path; } else { //Must return the first two path = StringUtils.substringBeforeLast(path, "/"); return StringUtils.substringBeforeLast(path, "/"); } }
From source file:org.broadinstitute.gatk.utils.commandline.ListAppenderUnitTest.java
@Test public void testListAppender() { LOGGER.removeAllAppenders();/*from w w w. ja v a 2s. c o m*/ final ListAppender listAppender = new ListAppender( new PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN), EVENTS_TO_KEEP, Level.WARN); LOGGER.addAppender(listAppender); for (int i = 0; i < EVENTS; i++) { LOGGER.warn(i + MSG_TO_LOG); LOGGER.info(i + MSG_TOO_LONG); } final String listAppenderString = listAppender.toString(); listAppender.write(); Assert.assertEquals(StringUtils.countMatches(listAppenderString, MSG_TO_LOG), EVENTS_TO_KEEP); Assert.assertFalse(listAppenderString.contains(MSG_TOO_LONG)); Assert.assertTrue(listAppenderString.contains(Integer.toString(EVENTS_TO_KEEP))); Assert.assertTrue(listAppenderString.contains(listAppender.logLevelToKeep.toString())); Assert.assertEquals(listAppender.numLoggingEvents, EVENTS); }
From source file:org.broadinstitute.gatk.utils.commandline.ListAppenderUnitTest.java
@Test public void testListAppenderNoWarnMsgs() { LOGGER.removeAllAppenders();/*from www. j a v a 2s. c o m*/ final ListAppender listAppender = new ListAppender( new PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN), EVENTS_TO_KEEP, Level.WARN); LOGGER.addAppender(listAppender); for (int i = 0; i < EVENTS; i++) { LOGGER.info(i + MSG_TOO_LONG); } final String listAppenderString = listAppender.toString(); Assert.assertEquals(StringUtils.countMatches(listAppenderString, MSG_TO_LOG), 0); Assert.assertFalse(listAppenderString.contains(MSG_TOO_LONG)); Assert.assertFalse(listAppenderString.contains(Integer.toString(EVENTS_TO_KEEP))); Assert.assertTrue(listAppenderString.contains(listAppender.logLevelToKeep.toString().toLowerCase())); Assert.assertEquals(listAppender.numLoggingEvents, 0); }
From source file:org.broadinstitute.gatk.utils.fasta.CachingIndexedFastaSequenceFileUnitTest.java
@Test(enabled = true) public void testIupacChanges() throws FileNotFoundException, InterruptedException { final String testFasta = privateTestDir + "iupacFASTA.fasta"; final CachingIndexedFastaSequenceFile iupacPreserving = new CachingIndexedFastaSequenceFile( new File(testFasta), false, true); final CachingIndexedFastaSequenceFile makeNs = new CachingIndexedFastaSequenceFile(new File(testFasta)); int preservingNs = 0; int changingNs = 0; for (SAMSequenceRecord contig : iupacPreserving.getSequenceDictionary().getSequences()) { final String sPreserving = fetchBaseString(iupacPreserving, contig.getSequenceName(), 0, 15000); preservingNs += StringUtils.countMatches(sPreserving, "N"); final String sChanging = fetchBaseString(makeNs, contig.getSequenceName(), 0, 15000); changingNs += StringUtils.countMatches(sChanging, "N"); }// w w w .j av a 2 s .c o m Assert.assertEquals(changingNs, preservingNs + 4); }
From source file:org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFileUnitTest.java
@Test(enabled = true) public void testIupacChanges() throws FileNotFoundException, InterruptedException { final String testFasta = privateTestDir + "iupacFASTA.fasta"; final CachingIndexedFastaSequenceFile iupacPreserving = new CachingIndexedFastaSequenceFile( new File(testFasta), CachingIndexedFastaSequenceFile.DEFAULT_CACHE_SIZE, false, true); final CachingIndexedFastaSequenceFile makeNs = new CachingIndexedFastaSequenceFile(new File(testFasta)); int preservingNs = 0; int changingNs = 0; for (SAMSequenceRecord contig : iupacPreserving.getSequenceDictionary().getSequences()) { final String sPreserving = fetchBaseString(iupacPreserving, contig.getSequenceName(), 0, 15000); preservingNs += StringUtils.countMatches(sPreserving, "N"); final String sChanging = fetchBaseString(makeNs, contig.getSequenceName(), 0, 15000); changingNs += StringUtils.countMatches(sChanging, "N"); }//from w ww .j a v a 2 s.c o m Assert.assertEquals(changingNs, preservingNs + 4); }
From source file:org.cesecore.certificates.ca.X509CA.java
/** * Constructs the SubjectAlternativeName extension that will end up on the generated certificate. * // www.j a v a 2 s.c om * If the DNS values in the subjectAlternativeName extension contain parentheses to specify labels that should be redacted, the parentheses are removed and another extension * containing the number of redacted labels is added. * * @param subAltNameExt * @param publishToCT * @return An extension generator containing the SubjectAlternativeName extension and an extension holding the number of redacted labels if the certificate is to be published * to a CTLog * @throws IOException */ private ExtensionsGenerator getSubjectAltNameExtensionForCert(Extension subAltNameExt, boolean publishToCT) throws IOException { String subAltName = CertTools.getAltNameStringFromExtension(subAltNameExt); List<String> dnsValues = CertTools.getPartsFromDN(subAltName, CertTools.DNS); int[] nrOfRecactedLables = new int[dnsValues.size()]; boolean sanEdited = false; int i = 0; for (String dns : dnsValues) { if (StringUtils.contains(dns, "(") && StringUtils.contains(dns, ")")) { // if it contains parts that should be redacted // Remove the parentheses from the SubjectAltName that will end up on the certificate String certBuilderDNSValue = StringUtils.remove(dns, '('); certBuilderDNSValue = StringUtils.remove(certBuilderDNSValue, ')'); subAltName = StringUtils.replace(subAltName, dns, certBuilderDNSValue); sanEdited = true; if (publishToCT) { String redactedLable = StringUtils.substring(dns, StringUtils.indexOf(dns, "("), StringUtils.lastIndexOf(dns, ")") + 1); // tex. (top.secret).domain.se => redactedLable = (top.secret) aka. including the parentheses nrOfRecactedLables[i] = StringUtils.countMatches(redactedLable, ".") + 1; } } i++; } ExtensionsGenerator gen = new ExtensionsGenerator(); gen.addExtension(Extension.subjectAlternativeName, subAltNameExt.isCritical(), CertTools.getGeneralNamesFromAltName(subAltName)); // If there actually are redacted parts, add the extension containing the number of redacted lables to the certificate if (publishToCT && sanEdited) { ASN1EncodableVector v = new ASN1EncodableVector(); for (int val : nrOfRecactedLables) { v.add(new ASN1Integer(val)); } ASN1Encodable seq = new DERSequence(v); gen.addExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6"), false, seq); } return gen; }
From source file:org.commonjava.maven.ext.core.util.PropertiesUtils.java
private static PropertyUpdate internalUpdateProperty(ManipulationSession session, Project p, boolean ignoreStrict, String key, String newValue, String resolvedValue, Properties props) throws ManipulationException { final CommonState state = session.getState(CommonState.class); final String oldValue = props.getProperty(key); logger.info("Updating property {} / {} with {} ", key, oldValue, newValue); PropertyUpdate found = PropertyUpdate.FOUND; // We'll only recursively resolve the property if its a single >${foo}<. If its one of // >${foo}value${foo}< // >${foo}${foo}< // >value${foo}< // >${foo}value< // it becomes hairy to verify strict compliance and to correctly split the old value and // update it with a portion of the new value. if (oldValue != null && oldValue.startsWith("${") && oldValue.endsWith("}") && !(StringUtils.countMatches(oldValue, "${") > 1)) { logger.debug("Recursively resolving {} ", oldValue.substring(2, oldValue.length() - 1)); if (updateProperties(session, p, ignoreStrict, oldValue.substring(2, oldValue.length() - 1), newValue) == PropertyUpdate.NOTFOUND) { logger.error("Recursive property not found for {} with {} ", oldValue, newValue); return PropertyUpdate.NOTFOUND; }//from w w w .ja va 2s. com } else { if (state.getStrict() && !ignoreStrict) { if (!checkStrictValue(session, resolvedValue, newValue)) { if (state.getFailOnStrictViolation()) { throw new ManipulationException( "Replacing original property version {} (fully resolved: {} ) with new version {} for {} violates the strict version-alignment rule!", oldValue, resolvedValue, newValue, key); } else { logger.warn( "Replacing original property version {} with new version {} for {} violates the strict version-alignment rule!", oldValue, newValue, key); // Ignore the dependency override. As found has been set to true it won't inject // a new property either. return found; } } } // TODO: Does not handle explicit overrides. if (oldValue != null && oldValue.contains("${") && !(oldValue.startsWith("${") && oldValue.endsWith("}")) || (StringUtils.countMatches(oldValue, "${") > 1)) { // This block handles // >${foo}value${foo}< // >${foo}${foo}< // >value${foo}< // >${foo}value< // We don't attempt to recursively resolve those as tracking the split of the variables, combined // with the update and strict version checking becomes overly fragile. if (ignoreStrict) { throw new ManipulationException("NYI : handling for versions with explicit overrides (" + oldValue + ") with multiple embedded properties is NYI. "); } if (resolvedValue.equals(newValue)) { logger.warn("Nothing to update as original key {} value matches new value {} ", key, newValue); found = PropertyUpdate.IGNORE; } newValue = oldValue + StringUtils.removeStart(newValue, resolvedValue); logger.info("Ignoring new value due to embedded property {} and appending {} ", oldValue, newValue); } props.setProperty(key, newValue); } return found; }
From source file:org.commonjava.maven.ext.core.util.PropertiesUtils.java
/** * This will check if the old version (e.g. in a plugin or dependency) is a property and if so * store the mapping in a map./* w ww .j a va2s.c om*/ * * * @param project the current project the needs to cache the value. * @param state CommonState to retrieve property clash value QoS. * @param versionPropertyUpdateMap the map to store any updates in * @param oldVersion original property name * @param newVersion new property value * @param originalType that this property is used in (i.e. a plugin or a dependency) * @param force Whether to check for an existing property or force the insertion * @return true if a property was found and cached. * @throws ManipulationException if an error occurs. */ public static boolean cacheProperty(Project project, CommonState state, Map<Project, Map<String, PropertyMapper>> versionPropertyUpdateMap, String oldVersion, String newVersion, Object originalType, boolean force) throws ManipulationException { final Map<String, PropertyMapper> projectProps = versionPropertyUpdateMap.computeIfAbsent(project, k -> new HashMap<>()); boolean result = false; if (oldVersion != null && oldVersion.contains("${")) { final int endIndex = oldVersion.indexOf('}'); final String oldProperty = oldVersion.substring(2, endIndex); // We don't attempt to cache any value that contains more than one property or contains a property // combined with a hardcoded value. if (oldVersion.contains("${") && !(oldVersion.startsWith("${") && oldVersion.endsWith("}")) || (StringUtils.countMatches(oldVersion, "${") > 1)) { logger.debug( "For {} ; original version contains hardcoded value or multiple embedded properties. Not caching value ( {} -> {} )", originalType, oldVersion, newVersion); } else if ("project.version".equals(oldProperty)) { logger.debug( "For {} ; original version was a property mapping. Not caching value as property is built-in ( {} -> {} )", originalType, oldProperty, newVersion); } else { logger.debug( "For {} ; original version was a property mapping; caching new value for update {} -> {} for project {} ", originalType, oldProperty, newVersion, project); final String oldVersionProp = oldVersion.substring(2, oldVersion.length() - 1); final PropertyMapper container = projectProps.computeIfAbsent(oldVersionProp, k -> new PropertyMapper()); // We check if we are replacing a property and there is already a mapping. While we don't allow // a property to be updated to two different versions, if a dependencyExclusion (i.e. a force override) // has been specified this will bypass the check. String existingPropertyMapping = container.getNewVersion(); if (existingPropertyMapping != null && !existingPropertyMapping.equals(newVersion)) { if (force) { logger.debug("Override property replacement of {} with force version override {}", existingPropertyMapping, newVersion); } else { if (state.getPropertyClashFails()) { logger.error( "Replacing property '{}' with a new version but the existing version does not match. Old value is {} and new is {}", oldVersionProp, existingPropertyMapping, newVersion); throw new ManipulationException( "Property replacement clash - updating property '{}' to both {} and {} ", oldVersionProp, existingPropertyMapping, newVersion); } else { logger.warn( "Replacing property '{}' with a new version would clash with existing version which does not match. Old value is {} and new is {}. Purging update of existing property.", oldVersionProp, existingPropertyMapping, newVersion); projectProps.remove(oldVersionProp); return false; } } } if (originalType instanceof ArtifactRef) { container.getDependencies().add(((ArtifactRef) originalType).asProjectRef()); } else if (originalType instanceof Plugin) { container.getDependencies().add(new SimpleProjectRef(((Plugin) originalType).getGroupId(), ((Plugin) originalType).getArtifactId())); } container.setOriginalVersion(findProperty(project, oldVersionProp)); container.setNewVersion(newVersion); logger.debug("Container is {} ", container); result = true; } } return result; }
From source file:org.commonjava.maven.ext.manip.util.PropertiesUtils.java
/** * Recursively update properties./* ww w. ja v a 2 s . c om*/ * * @param session the DependencyState * @param projects the current set of projects we are scanning. * @param ignoreStrict whether to ignore strict alignment. * @param key a key to look for. * @param newValue a value to look for. * @return {@code PropertyUpdate} enumeration showing status of any changes. * @throws ManipulationException if an error occurs */ public static PropertyUpdate updateProperties(ManipulationSession session, Set<Project> projects, boolean ignoreStrict, String key, String newValue) throws ManipulationException { final DependencyState state = session.getState(DependencyState.class); PropertyUpdate found = PropertyUpdate.NOTFOUND; final String resolvedValue = resolveProperties(new ArrayList<>(projects), "${" + key + '}'); logger.debug("Fully resolvedValue is {} for {} ", resolvedValue, key); if ("project.version".equals(key)) { logger.warn("Not updating key {} with {} ", key, newValue); return PropertyUpdate.IGNORE; } for (final Project p : projects) { if (p.getModel().getProperties().containsKey(key)) { final String oldValue = p.getModel().getProperties().getProperty(key); logger.info("Updating property {} / {} with {} ", key, oldValue, newValue); found = PropertyUpdate.FOUND; // We'll only recursively resolve the property if its a single >${foo}<. If its one of // >${foo}value${foo}< // >${foo}${foo}< // >value${foo}< // >${foo}value< // it becomes hairy to verify strict compliance and to correctly split the old value and // update it with a portion of the new value. if (oldValue != null && oldValue.startsWith("${") && oldValue.endsWith("}") && !(StringUtils.countMatches(oldValue, "${") > 1)) { logger.debug("Recursively resolving {} ", oldValue.substring(2, oldValue.length() - 1)); if (updateProperties(session, projects, ignoreStrict, oldValue.substring(2, oldValue.length() - 1), newValue) == PropertyUpdate.NOTFOUND) { logger.error("Recursive property not found for {} with {} ", oldValue, newValue); return PropertyUpdate.NOTFOUND; } } else { if (state.getStrict() && !ignoreStrict) { if (!checkStrictValue(session, resolvedValue, newValue)) { if (state.getFailOnStrictViolation()) { throw new ManipulationException( "Replacing original property version {} (fully resolved: {} ) with new version {} for {} violates the strict version-alignment rule!", oldValue, resolvedValue, newValue, key); } else { logger.warn( "Replacing original property version {} with new version {} for {} violates the strict version-alignment rule!", oldValue, newValue, key); // Ignore the dependency override. As found has been set to true it won't inject // a new property either. continue; } } } // TODO: Does not handle explicit overrides. if (oldValue != null && oldValue.contains("${") && !(oldValue.startsWith("${") && oldValue.endsWith("}")) || (StringUtils.countMatches(oldValue, "${") > 1)) { // This block handles // >${foo}value${foo}< // >${foo}${foo}< // >value${foo}< // >${foo}value< // We don't attempt to recursively resolve those as tracking the split of the variables, combined // with the update and strict version checking becomes overly fragile. if (ignoreStrict) { throw new ManipulationException("NYI : handling for versions with explicit overrides (" + oldValue + ") with multiple embedded properties is NYI. "); } if (resolvedValue.equals(newValue)) { logger.warn("Nothing to update as original key {} value matches new value {} ", key, newValue); found = PropertyUpdate.IGNORE; continue; } newValue = oldValue + StringUtils.removeStart(newValue, resolvedValue); logger.info("Ignoring new value due to embedded property {} and appending {} ", oldValue, newValue); } p.getModel().getProperties().setProperty(key, newValue); } } } return found; }