List of usage examples for java.util.regex Matcher replaceFirst
public String replaceFirst(Function<MatchResult, String> replacer)
From source file:com.almende.eve.protocol.jsonrpc.NamespaceUtil.java
/** * _get.//from ww w. ja v a 2 s . c om * * @param destination * the destination * @param path * the path * @return the call tuple * @throws IllegalAccessException * the illegal access exception * @throws InvocationTargetException * the invocation target exception * @throws NoSuchMethodException * the no such method exception * @throws UnsupportedOperationException * the unsupported operation exception */ private CallTuple _get(final Object destination, final String path) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, UnsupportedOperationException { final CallTuple result = new CallTuple(); String reducedPath = ""; String reducedMethod = path; if (path.indexOf('.') >= 0) { reducedPath = destination.getClass().getName() + "." + path; final Matcher matcher = PATTERN.matcher(reducedPath); reducedPath = matcher.replaceFirst(""); reducedMethod = matcher.group().substring(1); } if (!CACHE.containsKey(reducedPath)) { final AnnotatedMethod[] methods = new AnnotatedMethod[1]; final String newSteps = destination.getClass().getName(); CACHE.put("", new AnnotatedMethod[0]); populateCache(destination, newSteps, methods); } if (!CACHE.containsKey(reducedPath)) { try { throw new IllegalStateException("Non resolveable path given:'" + path + "' \n checked:" + JOM.getInstance().writeValueAsString(CACHE)); } catch (final JsonProcessingException e) { throw new IllegalStateException("Non resolveable path given:'" + path + "' \n checked:" + CACHE); } } final AnnotatedMethod[] methodPath = CACHE.get(reducedPath); Object newDestination = destination; for (final AnnotatedMethod method : methodPath) { if (method != null) { newDestination = method.getActualMethod().invoke(newDestination, (Object[]) null); } } if (newDestination == null) { // Oops, namespace getter returned null pointer! return result; } result.setDestination(newDestination); final AnnotatedClass newClazz = AnnotationUtil.get(newDestination.getClass()); final List<AnnotatedMethod> methods = newClazz.getMethods(reducedMethod); if (!methods.isEmpty()) { // TODO: If we ever want to support method overloading, this needs // to be fixed to return multiple methods. if (methods.size() > 1) { throw new UnsupportedOperationException( "Method '" + reducedMethod + "' in class '" + newClazz.getActualClass().getName() + "' is overloaded, which is not supported by this JSON-RPC implementation."); } result.setMethod(methods.get(0)); } return result; }
From source file:org.goko.core.gcode.rs274ngcv3.parser.GCodeLexer.java
/** * Recursive method used to split the stringCommand into a list of tokens * @param stringCommand the string command * @param tokens the list of token/*from ww w. j a va2 s .c o m*/ * @throws GkException GkException */ protected List<GCodeToken> createTokens(String pStringCommand, List<GCodeToken> tokens, IValidationTarget validationTarget, int lineNumber, int columnNumber) throws GkException { String stringCommand = pStringCommand; int totalColumn = columnNumber + StringUtils.length(stringCommand); if (StringUtils.isBlank(stringCommand)) { return tokens; } Matcher spaceMatcher = spacePattern.matcher(stringCommand); if (spaceMatcher.find()) { String remainingString = spaceMatcher.replaceFirst(StringUtils.EMPTY); return createTokens(remainingString, tokens, validationTarget, lineNumber, totalColumn - StringUtils.length(remainingString)); } Matcher multilineCommentMatcher = multilineCommentPattern.matcher(stringCommand); if (multilineCommentMatcher.find()) { String remainingString = extractToken(multilineCommentMatcher, tokens, GCodeTokenType.MULTILINE_COMMENT); return createTokens(remainingString, tokens, validationTarget, lineNumber, totalColumn - StringUtils.length(remainingString)); } Matcher simpleCommentMatcher = simpleCommentPattern.matcher(stringCommand); if (simpleCommentMatcher.find()) { String remainingString = extractToken(simpleCommentMatcher, tokens, GCodeTokenType.SIMPLE_COMMENT); return createTokens(remainingString, tokens, validationTarget, lineNumber, totalColumn - StringUtils.length(remainingString)); } // Remove all white spaces ( comments already removed ) while (StringUtils.startsWith(stringCommand, " ")) { stringCommand = stringCommand.replaceFirst("\\s", StringUtils.EMPTY); columnNumber += 1; } Matcher lineNumberMatcher = lineNumberPattern.matcher(stringCommand); if (lineNumberMatcher.find()) { String remainingString = extractToken(lineNumberMatcher, tokens, GCodeTokenType.LINE_NUMBER); return createTokens(remainingString, tokens, validationTarget, lineNumber, totalColumn - StringUtils.length(remainingString)); } Matcher wordMatcher = wordPattern.matcher(stringCommand); if (wordMatcher.find()) { String remainingString = extractToken(wordMatcher, tokens, GCodeTokenType.WORD); return createTokens(remainingString, tokens, validationTarget, lineNumber, totalColumn - StringUtils.length(remainingString)); } Matcher percentMatcher = percentPattern.matcher(stringCommand); if (percentMatcher.find()) { String remainingString = extractToken(percentMatcher, tokens, GCodeTokenType.PERCENT); return createTokens(remainingString, tokens, validationTarget, lineNumber, totalColumn - StringUtils.length(remainingString)); } if (validationTarget != null) { ValidationElement vElement = new ValidationElement(ValidationSeverity.ERROR, new Location(lineNumber, columnNumber), StringUtils.length(stringCommand), MessageFormat.format(MessageResource.getMessage("GCO-101"), stringCommand)); validationTarget.addValidationElement(vElement); return tokens; } else { throw new GkFunctionalException("GCO-101", stringCommand); } }
From source file:org.rhq.plugins.jbosscache3.test.CacheComponentTest.java
@Test public void testDiscovery() throws Exception { PluginContainer.getInstance().getInventoryManager().executeServiceScanImmediately(); Set<Resource> resources = TestHelper .getResources(TestHelper.getResourceType(CACHE_RESOURCE_TYPE_NAME, CACHE_PLUGIN_NAME)); ObjectName testResource = new ObjectName(ADDED_RESOURCE); for (int i = 0; i < RESOURCE_TYPES.length - 1; i++) { System.out.println(RESOURCE_TYPES[i]); ResourceType type = TestHelper.getResourceType(RESOURCE_TYPES[i], CACHE_PLUGIN_NAME); if (type != null) { Set<Resource> res = TestHelper.getResources(type); List<EmsBean> beans = connection.queryBeans(searchString + JMX_COMPONENT_NAMES[i]); assert (res.size() == beans.size()); resources.addAll(res);//from w w w .j a v a 2 s .c om } else { assert (connection.queryBeans(searchString + JMX_COMPONENT_NAMES[i]).size() == 0); } } boolean isTestExamplePresent = false; Set cacheNames = new HashSet(); Pattern p = Pattern.compile(REGEX); for (Resource resource : resources) { ObjectName resourceName = new ObjectName(resource.getResourceKey()); if (resourceName.equals(testResource)) { isTestExamplePresent = true; } String beanName = resource.getResourceKey(); Matcher m = p.matcher(beanName); if (m.find()) { beanName = m.replaceFirst(m.group(2).equals(",") ? m.group(1) : ""); if (!cacheNames.contains(beanName)) { EmsBean bean = connection.getBean(beanName); if (bean != null) cacheNames.add(beanName); } } } ResourceType type = TestHelper.getResourceType(CACHE_RESOURCE_TYPE_NAME, CACHE_PLUGIN_NAME); Set<Resource> res = TestHelper.getResources(type); for (Resource resource : res) { assert (cacheNames.contains(resource.getResourceKey())); } assert (res.size() == cacheNames.size()); assert !resources.isEmpty(); assert isTestExamplePresent; }
From source file:com.adaptris.core.services.metadata.ReplaceMetadataValue.java
@Override public String reformat(String src, AdaptrisMessage msg) throws Exception { Matcher searchMatcher = searchPattern.matcher(src); String replacement = buildReplacementValue(searchMatcher, msg.resolve(replacementValue())); return replaceAll() ? searchMatcher.replaceAll(replacement) : searchMatcher.replaceFirst(replacement); }
From source file:com.mfalaize.ant.LocalizeTask.java
@Override public void execute() throws BuildException { for (ResourceBundle resourceBundle : getAvailableResourceBundles()) { // Create the directory in which store all the files translated for this resourceBundle File directory = new File(targetDirectory + File.separator + resourceBundle.getLocale().getLanguage()); if (!directory.mkdirs()) { log(String.format("Cannot create directory %s.", directory.getAbsolutePath()), Project.MSG_ERR); continue; } else {/*from www .j a va 2 s .c o m*/ log(String.format("Creating directory for locale %s.", resourceBundle.getLocale().getLanguage()), Project.MSG_VERBOSE); } DirectoryScanner ds = getDirectoryScanner(translateDirectory); String[] files = ds.getIncludedFiles(); log(String.format("Translating %d files for locale %s...", files.length, resourceBundle.getLocale().getLanguage())); for (int i = 0; i < files.length; i++) { File file = new File(translateDirectory + File.separator + files[i]); log(String.format("Translating %s...", files[i]), Project.MSG_VERBOSE); try { String fileString = FileUtils.readFileToString(file, encoding); Pattern pattern = Pattern.compile(LOCALIZE_PATTERN); Matcher matcher = pattern.matcher(fileString); while (matcher.find()) { String key = matcher.group(2); fileString = matcher.replaceFirst(resourceBundle.getString(key)); log(String.format("Replacing occurrence of %s by %s.", matcher.group(), resourceBundle.getString(key)), Project.MSG_DEBUG); matcher = pattern.matcher(fileString); } // localize-task.js inclusion removal matcher = Pattern.compile(LOCALIZE_JS_PATTERN).matcher(fileString); if (matcher.find()) { fileString = matcher.replaceFirst(""); log("Removing the localize-task.js inclusion.", Project.MSG_DEBUG); } String newFilePath = directory.getAbsolutePath() + File.separator + org.apache.tools.ant.util.FileUtils.getRelativePath(projectDirectory, file); FileUtils.writeStringToFile(new File(newFilePath), fileString, encoding); } catch (Throwable ex) { log(String.format("An exception occured : %s", ex.getMessage()), Project.MSG_ERR); throw new BuildException(ex); } } } }
From source file:GIST.IzbirkomExtractor.AbbrList.java
/** * Creates a list of all possible expansions of a given streetName. * stretName itself will be the first element of the expansion list. * /* w ww . j a v a 2 s . c om*/ * @param streetName * @return */ public ArrayList<String> createAllExpansions(String streetName) { ArrayList<String> expansions = new ArrayList<String>(); expansions.add(streetName); Matcher mat = getAbbreviationsPattern().matcher(streetName); if (mat.find()) { for (String exp : abbrevs.get(mat.group(1)).getExpansions()) { StringBuffer str = new StringBuffer(mat.replaceFirst(exp)); /* get rid of abbreviations with dash */ if (streetName.length() > mat.start(1) + 1 && streetName.charAt(mat.start(1) + 1) == '-') { str.setCharAt(mat.start(1) + exp.length(), ' '); } if (exp.endsWith("-")) { // support for ?-, ?-, -; remove space, downcase following letter /* skip replacement and the end of string */ if (str.toString().endsWith(exp)) continue; str.delete(mat.start(1) + exp.length() - 1, mat.start(1) + exp.length() + 1); char upcase = str.charAt(mat.start(1) + exp.length() - 1); str.setCharAt(mat.start(1) + exp.length() - 1, Character.toLowerCase(upcase)); } expansions.add(str.toString()); } } return expansions; }
From source file:de.pksoftware.springstrap.sapi.util.WebappZipper.java
/** * Zip it// w w w . j a v a 2 s .c om * @param zipFile output ZIP file location */ public void addResource(String resourcePath, boolean fromContext) { byte[] buffer = new byte[1024]; try { logger.info("Adding resource: {}", resourcePath); PathMatchingResourcePatternResolver resolver; if (fromContext) { resolver = new ServletContextResourcePatternResolver(servletContext); } else { resolver = new PathMatchingResourcePatternResolver(); } // Ant-style path matching Resource[] resources = resolver.getResources(resourcePath); for (Resource resource : resources) { String fileAbsolute = resource.getURL().toString(); String fileRelative = null; boolean addFile = false; if (fromContext) { //File comes from webapp folder fileRelative = "www" + servletContext.getContextPath() + ((ServletContextResource) resource).getPath(); if (!fileRelative.endsWith("/")) { addFile = true; } } else { //Files comes from webjar int jarSeparatorIndex = fileAbsolute.indexOf("!/"); if (jarSeparatorIndex != -1) { String relativeFileName = fileAbsolute.substring(jarSeparatorIndex); Pattern pathPattern = Pattern.compile("\\!\\/webjar(\\/[a-z0-9_]+)+\\/www\\/"); Matcher pathMatcher = pathPattern.matcher(relativeFileName); if (pathMatcher.find()) { fileRelative = pathMatcher.replaceFirst("www" + servletContext.getContextPath() + "/"); addFile = true; } } } if (addFile && null != fileRelative) { logger.debug("Adding File: {} => {}", fileAbsolute, fileRelative); if (null != files.get(fileRelative)) { continue; } if (fileRelative.startsWith("temp")) { logger.error(fileAbsolute); } files.put(fileRelative, resource); ZipEntry ze = new ZipEntry(fileRelative); zos.putNextEntry(ze); InputStream in = null; try { in = resource.getInputStream(); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } } catch (FileNotFoundException fio) { logger.error(fio.getMessage()); } finally { if (null != in) { in.close(); } } } } zos.closeEntry(); //remember close it logger.info("Done"); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:org.rhq.core.pluginapi.util.ResponseTimeLogParser.java
protected String applyTransforms(String url) { String transformedUrl = null; if (this.transforms != null) { for (RegexSubstitution transform : this.transforms) { Matcher matcher = transform.getPattern().matcher(url); if (matcher.find()) { transformedUrl = matcher.replaceFirst(transform.getReplacement()); log.debug("URL '" + url + "' transformed to '" + transformedUrl + "' by transform '" + transform + "'."); break; }// w ww . ja v a 2 s . com } } return (transformedUrl != null) ? transformedUrl : url; }
From source file:org.gbif.common.search.builder.SearchResponseBuilder.java
/** * Cleans all occurrences of highlighted tags/marks in the parameter and returns an new instance clean of those * marks.//from w ww . j a v a2 s . c om */ private String cleanHighlightingMarks(final String hlText) { String hlLiteral = hlText; int indexPre = hlLiteral.indexOf(HL_PRE); while (indexPre > -1) { int indexPost = hlLiteral.indexOf(HL_POST, indexPre + HL_PRE.length()); if (indexPost > -1) { String post = hlLiteral.substring(indexPost + HL_POST.length()); String pre = hlLiteral.substring(0, indexPost); Matcher preMatcher = HL_PRE_REGEX.matcher(pre); pre = preMatcher.replaceFirst(""); hlLiteral = pre + post; } indexPre = hlLiteral.indexOf(HL_PRE); } return hlLiteral; }
From source file:org.alfresco.integrations.google.docs.utils.FileNameUtil.java
public String incrementFileName(String name, String mimetype) { String newname = null;/*from ww w. ja v a2s.co m*/ String extension = mimetypeService.getExtension(mimetype); log.debug("Extension: " + extension); Pattern p = Pattern.compile(FULL_PATTERN + extension + "$"); Matcher m = p.matcher(name); if (m.find()) { log.debug("Matching filename found: " + name); Pattern pattern = Pattern.compile(DUP_NUMBER); Matcher matcher = pattern.matcher(m.group()); matcher.find(); newname = m.replaceFirst("-" + (Integer.parseInt(matcher.group()) + 1) + ".") + extension; log.debug("Increment filename from: " + name + " to: " + newname); } else { Pattern p_ = Pattern.compile(FULL_PATTERN.substring(0, 2) + "$"); Matcher m_ = p_.matcher(name); if (m_.find()) { log.debug("Matching filename found: " + name); Pattern pattern = Pattern.compile(DUP_NUMBER); Matcher matcher = pattern.matcher(m_.group()); matcher.find(); newname = m_.replaceFirst("-" + (Integer.parseInt(matcher.group()) + 1)); log.debug("Increment filename from: " + name + " to: " + newname); } else { Pattern p_ext = Pattern.compile("\\." + extension + "$"); Matcher m_ext = p_ext.matcher(name); if (m_ext.find()) { log.debug("Matching filename found: " + name); String sansExtention = name.substring(0, name.length() - (extension.length() + 1)); newname = sansExtention.concat(FIRST_DUP).concat(extension); log.debug("Increment filename from: " + name + " to: " + newname); } else { log.debug("Matching filename not found: " + name); newname = name.concat(FIRST_DUP.substring(0, 2)); log.debug("Increment filename from: " + name + " to: " + newname); } } } return newname; }