Java Code Examples for org.springframework.util.StringUtils#countOccurrencesOf()

The following examples show how to use org.springframework.util.StringUtils#countOccurrencesOf() . 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
private static Date getDeliveryDate(String dateString) throws Exception {
    Date startDate;
    try {
        Calendar startDateCalendar = new GregorianCalendar();
        if (dateString.contains(".") && StringUtils.countOccurrencesOf(dateString, ":") > 1) {
            startDate = new SimpleDateFormat(DATE_PARAMETER_FORMAT_WITH_SECOND).parse(dateString);
            startDateCalendar.setTime(startDate);
        } else if (dateString.contains(":")) {
            startDate = new SimpleDateFormat(DATE_PARAMETER_FORMAT_WITH_HOUR).parse(dateString);
            startDateCalendar.setTime(startDate);
        } else {
            startDate = new SimpleDateFormat(DATE_PARAMETER_FORMAT).parse(dateString);
            startDateCalendar.setTime(startDate);
            startDateCalendar.set(Calendar.HOUR_OF_DAY, 0);
        }
        startDateCalendar.set(Calendar.MINUTE, 0);
        startDateCalendar.set(Calendar.SECOND, 0);
        startDateCalendar.set(Calendar.MILLISECOND, 0);
        return startDateCalendar.getTime();
    } catch (ParseException e) {
        throw new Exception("Error while parsing start date: " + dateString, e);
    }
}
 
Example 2
protected static Date parseTimeBasedDate(String dateString, boolean isStartDate) throws Exception {
	Date date;
	 try {
		Calendar startDateCalendar = new GregorianCalendar();
		if (dateString.contains(".") && StringUtils.countOccurrencesOf(dateString, ":") > 1) {
			date = new SimpleDateFormat(DATE_PARAMETER_FORMAT_WITH_SECOND).parse(dateString);
			startDateCalendar.setTime(date);
		} else if (dateString.contains(":")) {
			date = new SimpleDateFormat(DATE_PARAMETER_FORMAT_WITH_HOUR).parse(dateString);
			startDateCalendar.setTime(date);
		} else {
			date = new SimpleDateFormat(DATE_PARAMETER_FORMAT).parse(dateString);
			startDateCalendar.setTime(date);
			startDateCalendar.set(Calendar.HOUR_OF_DAY, isStartDate ? 0 : 23);
		}
		startDateCalendar.set(Calendar.MINUTE, isStartDate ? 0 : 59);
		startDateCalendar.set(Calendar.SECOND, isStartDate ? 0 : 59);
		startDateCalendar.set(Calendar.MILLISECOND, isStartDate ? 0 : 999);
		date = startDateCalendar.getTime();
	} catch (ParseException e) {
		throw new Exception("Error while parsing date: " + dateString, e);
	}
	return date;
}
 
Example 3
private void printYamlHtmlKey(String key, String previousKey, BufferedWriter theBW) throws IOException {
    int lastDot = key.lastIndexOf(".");
    if (lastDot > -1) {
        String prefix = key.substring(0, lastDot);
        // If the prefix of the previous key was different up to this point, print it,
        // else ignore it
        if (previousKey.length() <= lastDot || !previousKey.substring(0, lastDot).equals(prefix)) {
            printYamlHtmlKey(prefix, previousKey, theBW);
            theBW.write("<br/>");
        }
        for (int i = 0; i < StringUtils.countOccurrencesOf(prefix, ".") + 1; i++) {
            theBW.write("  ");
        }
        theBW.write(key.substring(lastDot + 1));
    }
    else {
        theBW.write(key);
    }
    theBW.write(": ");
}
 
Example 4
private void printYamlKey(String key, String previousKey, BufferedWriter theBW) throws IOException {
    int lastDot = key.lastIndexOf(".");
    if (lastDot > -1) {
        String prefix = key.substring(0, lastDot);
        // If the prefix of the previous key was different up to this point, print it,
        // else ignore it
        if (previousKey.length() <= lastDot || !previousKey.substring(0, lastDot).equals(prefix)) {
            printYamlKey(prefix, previousKey, theBW);
            theBW.newLine();
        }
        for (int i = 0; i < StringUtils.countOccurrencesOf(prefix, ".") + 1; i++) {
            theBW.write("  ");
        }
        theBW.write(key.substring(lastDot + 1));
    }
    else {
        theBW.write(key);
    }
    theBW.write(": ");
}
 
Example 5
Source Project: Insights   File: WebHookServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validation of the Response Template which has been entered by the user
 * 
 * @param responseTemplate
 * @return
 * @throws InsightsCustomException
 */
private Boolean checkResponseTemplate(String responseTemplate) throws InsightsCustomException {
	try {
		StringTokenizer st = new StringTokenizer(responseTemplate, ",");
		while (st.hasMoreTokens()) {
			String keyValuePairs = st.nextToken();
			int count = StringUtils.countOccurrencesOf(keyValuePairs, "=");
			if (count != 1) {
				throw new InsightsCustomException(PlatformServiceConstants.INCORRECT_RESPONSE_TEMPLATE);
			} else {
				String[] dataKeyMapper = keyValuePairs.split("=");
				log.debug(" {}  , {} ", dataKeyMapper[0].trim(), dataKeyMapper[1].trim());
			}
		}
		return true;
	} catch (InsightsCustomException e) {
		log.error("Error in Response Template.. {}", e.getMessage());
		throw new InsightsCustomException(PlatformServiceConstants.INCORRECT_RESPONSE_TEMPLATE);
	}
}
 
Example 6
/**
 * Recursively retrieve PortletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param portletContext the PortletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see org.springframework.web.portlet.context.PortletContextResource
 * @see javax.portlet.PortletContext#getResourcePaths
 */
protected void doRetrieveMatchingPortletContextResources(
		PortletContext portletContext, String fullPattern, String dir, Set<Resource> result) throws IOException {

	Set<String> candidates = portletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		for (Iterator<String> it = candidates.iterator(); it.hasNext();) {
			String currPath = it.next();
			if (currPath.endsWith("/") &&
					(dirDepthNotFixed ||
					StringUtils.countOccurrencesOf(currPath, "/") <= StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				doRetrieveMatchingPortletContextResources(portletContext, fullPattern, currPath, result);
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new PortletContextResource(portletContext, currPath));
			}
		}
	}
}
 
Example 7
public static  ResultValidator noOfTimesOccuranceValidator(final int occurance, final String arg) {
  return new ResultValidator() {
    int count = 0;
    @Override
    public Status validate(String output) {
      Log.getLogWriter().info("Validating command output for having :" + arg + " " + occurance + " times...");
      count = StringUtils.countOccurrencesOf(output, arg);
      if(count != occurance) {
        return Status.ERROR;
      }
      return Status.SUCCESS;
    }

    @Override
    public String getMessage() {
      return "We were expecting " + occurance + " occurance of " + arg  + " in command output but we got it " + count + " times.";
    }
  };
}
 
Example 8
public static ResultValidator onlyOneOccuranceValidator(final String... args) {
  return new ResultValidator() {

    private String failedString;
    int count = 0;
    @Override
    public Status validate(String output) {
      Log.getLogWriter().info("Validating command output for having :" + Arrays.toString(args) + " only once...");
      for (String arg : args) {
        count = StringUtils.countOccurrencesOf(output, arg);
        if (count != 1) {
          failedString = arg;
          return Status.ERROR;
        }
      }
      return Status.SUCCESS;
    }

    @Override
    public String getMessage() {
      return "We were expecting " + failedString + " to occur only once and we got it " + count + " times.";
    }
  };
}
 
Example 9
protected RemoteApplicationEvent(Object source, String originService,
		String destinationService) {
	super(source);
	this.originService = originService;
	if (destinationService == null) {
		destinationService = "**";
	}
	// If the destinationService is not already a wildcard, match everything that
	// follows
	// if there at most two path elements, and last element is not a global wildcard
	// already
	if (!"**".equals(destinationService)) {
		if (StringUtils.countOccurrencesOf(destinationService, ":") <= 1
				&& !StringUtils.endsWithIgnoreCase(destinationService, ":**")) {
			// All instances of the destination unless specifically requested
			destinationService = destinationService + ":**";
		}
	}
	this.destinationService = destinationService;
	this.id = UUID.randomUUID().toString();
}
 
Example 10
public static  ResultValidator noOfTimesOccuranceValidator(final int occurance, final String arg) {
  return new ResultValidator() {
    int count = 0;
    @Override
    public Status validate(String output) {
      Log.getLogWriter().info("Validating command output for having :" + arg + " " + occurance + " times...");
      count = StringUtils.countOccurrencesOf(output, arg);
      if(count != occurance) {
        return Status.ERROR;
      }
      return Status.SUCCESS;
    }

    @Override
    public String getMessage() {
      return "We were expecting " + occurance + " occurance of " + arg  + " in command output but we got it " + count + " times.";
    }
  };
}
 
Example 11
public static ResultValidator onlyOneOccuranceValidator(final String... args) {
  return new ResultValidator() {

    private String failedString;
    int count = 0;
    @Override
    public Status validate(String output) {
      Log.getLogWriter().info("Validating command output for having :" + Arrays.toString(args) + " only once...");
      for (String arg : args) {
        count = StringUtils.countOccurrencesOf(output, arg);
        if (count != 1) {
          failedString = arg;
          return Status.ERROR;
        }
      }
      return Status.SUCCESS;
    }

    @Override
    public String getMessage() {
      return "We were expecting " + failedString + " to occur only once and we got it " + count + " times.";
    }
  };
}
 
Example 12
/**
 * Returns an array of all namespace declarations, found on wsdl-level.
 *
 * @param wsdl
 * @return
 */
private String[] extractNamespacesOnWsdlLevel(XmlObject wsdl) {
    int cursor = wsdl.xmlText().indexOf(":") + ":definitions ".length();
    String nsWsdlOrig = wsdl.xmlText().substring(cursor, wsdl.xmlText().indexOf(">", cursor));
    int noNs = StringUtils.countOccurrencesOf(nsWsdlOrig, "xmlns:");
    String[] namespacesWsdl = new String[noNs];
    cursor = 0;
    for (int i=0; i<noNs; i++) {
        int begin = nsWsdlOrig.indexOf("xmlns:", cursor);
        int end = nsWsdlOrig.indexOf("\"", begin + 20);
        namespacesWsdl[i] = nsWsdlOrig.substring(begin, end) + "\"";
        cursor = end;
    }
    return namespacesWsdl;
}
 
Example 13
@Test
public void shouldGenerateContractTestsForPactAndMaintainIndents() throws Exception {
	File basedir = getBasedir("pact");

	executeMojo(basedir, "generateTests", defaultPackageForTests());

	assertFilesPresent(basedir,
			"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java");
	File test = new File(basedir,
			"target/generated-test-sources/contracts/org/springframework/cloud/contract/verifier/tests/ContractVerifierTest.java");
	String testContents = readFileToString(test, defaultCharset());
	int countOccurrencesOf = StringUtils.countOccurrencesOf(testContents,
			"\t\tMockMvcRequestSpecification");
	then(countOccurrencesOf).isEqualTo(4);
}
 
Example 14
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 15
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 16
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 17
private static String getActionNameFromObjects(ApiActionMetadata apiActionMetadata) {

		String uri = apiActionMetadata.getResource().getUri();
		String name = convertActionTypeToIntent(apiActionMetadata.getActionType(), doesUriEndsWithParam(uri));

		if (apiActionMetadata.getActionType().equals(RamlActionType.GET)) {
			Map<String, ApiBodyMetadata> responseBody = apiActionMetadata.getResponseBody();
			if (responseBody.size() > 0) {
				ApiBodyMetadata apiBodyMetadata = responseBody.values().iterator().next();
				String responseObjectName = cleanNameForJava(StringUtils.capitalize(apiBodyMetadata.getName()));
				if (apiBodyMetadata.isArray()) {
					responseObjectName = StringUtils.capitalize(NamingHelper.pluralize(responseObjectName));
				}
				name += responseObjectName;
			} else {
				name += "Object";
			}

			name = appendActionNameWithSingleParameter(apiActionMetadata, name);

		} else if (apiActionMetadata.getActionType().equals(RamlActionType.DELETE)) {

			// for DELETE method we'll still use resource name
			String url = cleanLeadingAndTrailingNewLineAndChars(apiActionMetadata.getResource().getUri());
			String[] splitUrl = SLASH.split(url);
			String resourceNameToUse = null;
			if (splitUrl.length > 1 && StringUtils.countOccurrencesOf(splitUrl[splitUrl.length - 1], "{") > 0) {
				resourceNameToUse = splitUrl[splitUrl.length - 2];
			} else {
				resourceNameToUse = splitUrl[splitUrl.length - 1];
			}

			name = name + StringUtils.capitalize(cleanNameForJava(singularize(resourceNameToUse)));
			name = appendActionNameWithSingleParameter(apiActionMetadata, name);

		} else {
			ApiBodyMetadata requestBody = apiActionMetadata.getRequestBody();
			String creationObject;
			if (requestBody != null) {
				creationObject = requestBody.getName();
			} else {
				creationObject = apiActionMetadata.getParent().getResourceUri();
				creationObject = creationObject.substring(creationObject.lastIndexOf('/') + 1);
			}
			return name + cleanNameForJava(StringUtils.capitalize(creationObject));
		}

		return name;
	}
 
Example 18
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 19
Source Project: cloud-config   File: ZkPath.java    License: MIT License 4 votes vote down vote up
public int getDepth() {
    return path.isEmpty() ? 0 : StringUtils.countOccurrencesOf(path, "/")+1;
}
 
Example 20
/**
 * @param sql Base SQL.
 * @return Randomized SQL string.
 */
private String randomizeSql(String sql) {
    int cnt = StringUtils.countOccurrencesOf(sql, "%s");

    Integer[] sub = new Integer[cnt];

    for (int i = 0; i < cnt; i++)
        sub[i] = nextRandom(args.range());

    sql = String.format(sql, sub);

    return sql;
}