List of usage examples for org.apache.commons.lang3 StringUtils countMatches
public static int countMatches(final CharSequence str, final char ch)
Counts how many times the char appears in the given string.
A null or empty ("") String input returns 0 .
StringUtils.countMatches(null, *) = 0 StringUtils.countMatches("", *) = 0 StringUtils.countMatches("abba", 0) = 0 StringUtils.countMatches("abba", 'a') = 2 StringUtils.countMatches("abba", 'b') = 2 StringUtils.countMatches("abba", 'x') = 0
From source file:org.silverpeas.components.projectmanager.model.TaskDetail.java
public TaskDetail(int id, int mereId, int chrono, String nom, String description, int organisateurId, int responsableId, float charge, float consomme, float raf, int statut, Date dateDebut, Date dateFin, String codeProjet, String descriptionProjet, int estDecomposee, String instanceId, String path) { this.id = id; this.mereId = mereId; this.chrono = chrono; this.nom = nom; this.description = description; this.organisateurId = organisateurId; this.responsableId = responsableId; this.charge = charge; this.consomme = consomme; this.raf = raf; this.statut = statut; this.dateDebut = dateDebut; this.dateFin = dateFin; this.codeProjet = codeProjet; this.descriptionProjet = descriptionProjet; this.estDecomposee = estDecomposee; this.instanceId = instanceId; this.path = path; // Initialize level because level has never been set before. this.level = StringUtils.countMatches(this.path, "/") - 2; }
From source file:org.silverpeas.web.silverstatistics.control.SilverStatisticsPeasSessionController.java
/** * Retrieve statistics on axis//w w w.j a v a 2s . c o m * @param statsFilter an axis stats filter * @return a Statistic value object */ public List<StatisticVO> getAxisStats(AxisStatsFilter statsFilter) { // Result list List<StatisticVO> stats = new ArrayList<>(); // Retrieve all the list of components List<String> components = buildCustomComponentListWhereToSearch(); // Global silver content declaration List<GlobalSilverContent> gSC = null; int curAxisId = statsFilter.getAxisId(); try { // Build day query String firstDayStr = statsFilter.getYearBegin() + "/" + statsFilter.getMonthBegin() + "/01"; String lastDayStr = statsFilter.getYearEnd() + "/" + statsFilter.getMonthEnd() + "/31"; // Retrieve statistics on componentIds List<AccessPublicationVO> accessPublis = SilverStatisticsPeasDAO.getListPublicationAccess(firstDayStr, lastDayStr); if (curAxisId == 0) { // Retrieve publication axis List<AxisHeader> axis = getPdcManager().getAxisByType("P"); // Retrieve publications on axis for (AxisHeader axisHeader : axis) { String axisId = axisHeader.getPK().getId(); int nbAxisAccess = 0; // String axisVlue = axisHeader.get gSC = getPdCPublications(axisId, "/0/", components); nbAxisAccess = computeAxisAccessStatistics(accessPublis, gSC); StatisticVO curStat = new StatisticVO(axisId, axisHeader.getName(), axisHeader.getDescription(), nbAxisAccess); stats.add(curStat); } } else { String axisValue = statsFilter.getAxisValue(); boolean axisFilter = false; int curLevel = 1; if (StringUtil.isDefined(axisValue)) { axisFilter = true; // Retrieve current value level + 1 curLevel = StringUtils.countMatches(axisValue, "/") - 1; } List<Value> values = getPdcManager().getAxisValues(statsFilter.getAxisId()); for (Value curValue : values) { String curAxisValue = curValue.getFullPath(); int nbAxisAccess = 0; // Check axis level number if ((axisFilter && curAxisValue.startsWith(axisValue) && curValue.getLevelNumber() == curLevel) || (!axisFilter && curValue.getLevelNumber() == 1)) { // Retrieve all the current axis publications gSC = getPdCPublications(Integer.toString(curAxisId), curAxisValue, components); nbAxisAccess = computeAxisAccessStatistics(accessPublis, gSC); // Create a new statistic value object StatisticVO curStat = new StatisticVO(Integer.toString(curAxisId), curValue.getName(), curValue.getDescription(), nbAxisAccess); curStat.setAxisValue(curValue.getFullPath()); curStat.setAxisLevel(curValue.getLevelNumber()); // Add this statistic to list stats.add(curStat); } } } } catch (PdcException | SQLException e) { SilverLogger.getLogger(this).error(e); } return stats; }
From source file:org.spdx.rdfparser.license.TestListedLicenses.java
@Test public void testLicenseListVersionFormat() { String licenseListversion = ListedLicenses.getListedLicenses().getLicenseListVersion(); Assert.assertEquals("Expected one point in license list version. ", 1, StringUtils.countMatches(licenseListversion, ".")); Assert.assertTrue("Number expected before the point in license list version (" + licenseListversion + ")", StringUtils.isNumeric(StringUtils.substringBefore(licenseListversion, "."))); Assert.assertTrue("Number expected after the point in license list version (" + licenseListversion + ")", StringUtils.isNumeric(StringUtils.substringAfter(licenseListversion, "."))); }
From source file:org.springframework.web.client.interceptors.ZeroLeggedOAuthInterceptorTest.java
@Test public void testInterceptor() throws Exception { final String url = "http://www.test.com/lrs?param1=val1¶m2=val2"; final String data = "test"; final String id = "test"; final String realm = "realm"; final String consumerKey = "consumerKey"; final String secretKey = "secretKey"; PropertyResolver resolver = mock(PropertyResolver.class); when(resolver.getProperty(eq("org.jasig.rest.interceptor.oauth." + id + ".realm"))).thenReturn(realm); when(resolver.getProperty(eq("org.jasig.rest.interceptor.oauth." + id + ".consumerKey"))) .thenReturn(consumerKey);/* ww w . j a v a 2 s .co m*/ when(resolver.getProperty(eq("org.jasig.rest.interceptor.oauth." + id + ".secretKey"))) .thenReturn(secretKey); // holder for the headers... HttpHeaders headers = new HttpHeaders(); // Mock guts of RestTemplate so no need to actually hit the web... ClientHttpResponse resp = mock(ClientHttpResponse.class); when(resp.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); when(resp.getHeaders()).thenReturn(new HttpHeaders()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ClientHttpRequest client = mock(ClientHttpRequest.class); when(client.getHeaders()).thenReturn(headers); when(client.getBody()).thenReturn(buffer); when(client.execute()).thenReturn(resp); ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class); when(factory.createRequest(any(URI.class), any(HttpMethod.class))).thenReturn(client); // add the new interceptor... ZeroLeggedOAuthInterceptor interceptor = new ZeroLeggedOAuthInterceptor(); interceptor.setPropertyResolver(resolver); interceptor.setId(id); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(interceptor); RestTemplate rest = new RestTemplate(factory); rest.setInterceptors(interceptors); rest.postForLocation(url, data, Collections.emptyMap()); // make sure auth header is correctly set... assertThat(headers, hasKey(Headers.Authorization.name())); String authHeader = headers.get(Headers.Authorization.name()).get(0); assertThat(authHeader, containsString("OAuth realm=\"" + realm + "\"")); assertThat(authHeader, containsString("oauth_consumer_key=\"" + consumerKey + "\"")); // for now, only supports HMAC-SHA1. May have to fix later... assertThat(authHeader, containsString("oauth_signature_method=\"HMAC-SHA1\"")); assertThat(authHeader, containsString("oauth_version=\"1.0\"")); assertThat(authHeader, containsString("oauth_timestamp=")); assertThat(authHeader, containsString("oauth_nonce=")); assertThat(authHeader, containsString("oauth_signature=")); // oauth lib will create 2 oauth_signature params if you call sign // multiple times. Make sure only get 1. assertThat(StringUtils.countMatches(authHeader, "oauth_signature="), is(1)); }
From source file:org.starnub.starnubserver.connections.player.session.PlayerSession.java
public static HashSet<PlayerSession> getRecentSessionsByIdentifier(String searchId, DateTime dateTime) { List<PlayerSession> allFromDateRangeToNow = PLAYER_SESSION_LOG_DB.getAllFromDateRangeToNow(END_TIME_COLUMN, dateTime);//from www . ja v a 2 s .c o m HashSet<PlayerSession> newList = new HashSet<>(); if (Players.isStarNubId(searchId)) { int starnubId = Integer.parseInt(searchId.replaceAll("[sS]", "")); for (PlayerSession playerSession : allFromDateRangeToNow) { Account account = playerSession.getPlayerCharacter().getAccount(); if (account != null && starnubId == account.getStarnubId()) { newList.add(playerSession); } } } else if (StringUtils.countMatches(searchId, "-") >= 4) { UUID uuid = UUID.fromString(searchId); allFromDateRangeToNow.forEach(playerSession -> { UUID characterUuid = playerSession.getPlayerCharacter().getUuid(); if (uuid.equals(characterUuid)) { newList.add(playerSession); } }); } else if (StringUtils.countMatches(searchId, ".") == 3) { allFromDateRangeToNow.forEach(playerSession -> { String ipString = playerSession.getSessionIpString(); if (ipString.equals(searchId)) { newList.add(playerSession); } }); } else { for (PlayerSession playerSession : allFromDateRangeToNow) { PlayerCharacter character = playerSession.getPlayerCharacter(); String searchName = searchId.toLowerCase(); String cleanName = character.getCleanName().toLowerCase(); String characterName = character.getName().toLowerCase(); if (cleanName.contains(searchName) || characterName.contains(searchName)) { newList.add(playerSession); } } } return newList; }
From source file:org.starnub.starnubserver.resources.connections.Players.java
/** * Recommended: For Plugin Developers & Anyone else. * <p>/*from w w w.j a v a2 s.c om*/ * Uses: This method is used to pull a player record using any type of * parameter. (Packet, Uuid, IP, NAME, clientCTX, Starbound ID, StarNub ID) * <p> * @param playerIdentifier Object that represent a player and it can take many forms * @return Player which represents the player that was retrieved by the provided playerIdentifier */ public PlayerSession getOnlinePlayerByAnyIdentifier(Object playerIdentifier) { if (playerIdentifier instanceof PlayerSession) { return (PlayerSession) playerIdentifier; } if (playerIdentifier instanceof Packet) { return playerByPacket((Packet) playerIdentifier); } if (playerIdentifier instanceof String) { String identifierString = (String) playerIdentifier; if (identifierString.length() <= 4 && NumberUtils.isNumber(identifierString)) { return playerByStarboundClientID(Integer.parseInt(identifierString)); } if (isStarNubId(identifierString)) { return playerByStarNubClientID(Integer.parseInt(identifierString.replaceAll("[sS]", ""))); } if (StringUtils.countMatches(identifierString, "-") == 4) { return playerByUUID(UUID.fromString(identifierString)); } if (StringUtils.countMatches(identifierString, ".") == 3) { try { return playerByIP(InetAddress.getByName(identifierString)); } catch (UnknownHostException e) { return null; } } return playerByName(identifierString); } if (playerIdentifier instanceof ChannelHandlerContext) { return playerByCTX((ChannelHandlerContext) playerIdentifier); } if (playerIdentifier instanceof Integer) { return playerByStarboundClientID((int) playerIdentifier); } if (playerIdentifier instanceof UUID) { return playerByUUID((UUID) playerIdentifier); } if (playerIdentifier instanceof InetAddress) { return playerByIP((InetAddress) playerIdentifier); } return null; }
From source file:org.talend.components.api.component.runtime.DependenciesReader.java
/** * expecting groupId:artifactId:type[:classifier]:version:scope and output. * //from ww w . j a v a 2s . c o m * <pre> * {@code * mvn-uri := 'mvn:' [ repository-url '!' ] group-id '/' artifact-id [ '/' [version] [ '/' [type] [ '/' classifier ] ] ] ] * } * </pre> * * @param s * @return pax-url formatted string */ String parseMvnUri(String dependencyString) { String s = dependencyString.trim(); int indexOfGpSeparator = s.indexOf(':'); String groupId = s.substring(0, indexOfGpSeparator); int indexOfArtIdSep = s.indexOf(':', indexOfGpSeparator + 1); String artifactId = s.substring(indexOfGpSeparator + 1, indexOfArtIdSep); int indexOfTypeSep = s.indexOf(':', indexOfArtIdSep + 1); String type = s.substring(indexOfArtIdSep + 1, indexOfTypeSep); int lastIndex = indexOfTypeSep; String classifier = null; if (StringUtils.countMatches(s, ":") > 4) {// we have a classifier too int indexOfClassifSep = s.indexOf(':', indexOfTypeSep + 1); classifier = s.substring(indexOfTypeSep + 1, indexOfClassifSep); lastIndex = indexOfClassifSep; } // else no classifier. int indexOfVersionSep = s.indexOf(':', lastIndex + 1); String version = s.substring(lastIndex + 1, indexOfVersionSep); // we ignor the scope here return "mvn:" + groupId + '/' + artifactId + '/' + version + '/' + type + (classifier != null ? '/' + classifier : ""); }
From source file:org.thelq.stackexchange.api.queries.methods.VectorQueryMethod.java
public VectorQueryMethod(@NonNull String raw, @NonNull String... vectorSingle) { Preconditions.checkArgument(StringUtils.countMatches(raw, "{}") == 1, "Raw method does not contain vector"); this.raw = raw; this.vectorSingle = vectorSingle; this.vectorCollection = null; }
From source file:org.thelq.stackexchange.api.queries.methods.VectorQueryMethod.java
public VectorQueryMethod(@NonNull String raw, @NonNull Collection<?> vectorCollection) { Preconditions.checkArgument(StringUtils.countMatches(raw, "{}") == 1, "Raw method does not contain vector"); Preconditions.checkArgument(!vectorCollection.isEmpty(), "Vector collection is empty"); Preconditions.checkArgument(vectorCollection.size() < 100, "Vectors do not support more than 100 elements"); this.raw = raw; this.vectorSingle = null; this.vectorCollection = vectorCollection; }
From source file:org.thelq.stackexchange.api.queries.methods.VectorQueryMethod.java
public String getFinal() { String methodFinal = raw;/*ww w. j a va2 s .c o m*/ if (vectorSingle != null) { String[] subsitutions = new String[vectorSingle.length]; Arrays.fill(subsitutions, "{}"); methodFinal = StringUtils.replaceEach(raw, subsitutions, vectorSingle); } else if (vectorCollection != null) { if (StringUtils.countMatches(raw, "{}") != 1) throw new RuntimeException("No more vectors to replace! Raw: " + raw + " | Final: " + methodFinal); //Verify vector if it is required Iterator<?> vectorItr = vectorCollection.iterator(); if (!vectorItr.hasNext()) throw new RuntimeException("Vector cannot be empty"); //Do the replace methodFinal = StringUtils.replaceOnce(raw, "{}", QueryUtils.PARAMETER_JOINER.join(vectorItr)); //Make sure we didn't miss anything if (methodFinal.contains("{}")) throw new RuntimeException("Still contains vector: " + methodFinal); } else throw new RuntimeException("No vector to replace! " + raw); return methodFinal; }