List of usage examples for java.util.regex Matcher appendReplacement
public Matcher appendReplacement(StringBuilder sb, String replacement)
From source file:org.akita.proxy.ProxyInvocationHandler.java
/** * Replace all the {} block in url to the actual params, * clear the params used in {block}, return cleared params HashMap and replaced url. * @param url such as http://server/{namespace}/1/do * @param params such as hashmap include (namespace->'mobile') * @return the parsed param will be removed in HashMap (params) *//*from w w w .ja v a2 s . c o m*/ private String parseUrlbyParams(String url, HashMap<String, String> params) throws AkInvokeException { StringBuffer sbUrl = new StringBuffer(); Pattern pattern = Pattern.compile("\\{(.+?)\\}"); Matcher matcher = pattern.matcher(url); while (matcher.find()) { String paramValue = params.get(matcher.group(1)); if (paramValue != null) { matcher.appendReplacement(sbUrl, paramValue); } else { // {name}? throw new AkInvokeException(AkInvokeException.CODE_PARAM_IN_URL_NOT_FOUND, "Parameter {" + matcher.group(1) + "}'s value not found of url " + url + "."); } params.remove(matcher.group(1)); } matcher.appendTail(sbUrl); return sbUrl.toString(); }
From source file:com.yukthi.persistence.NativeQueryFactory.java
/** * Fetches the query template with specified "name" and builds the query using specified "context". * If the query uses "param" directive, corresponding values will be collected into "paramValues". * //from w w w.j a v a 2s.com * @param name Name of the query to be fetched * @param paramValues Collected param values that needs to be passed to query as prepared statement params * @param context Context to be used to parse template into query * @return Built query */ public String buildQuery(String name, List<Object> paramValues, Object context) { Template template = templateMap.get(name); //if template is not found build it from raw query if (template == null) { String rawQuery = queryMap.get(name); //if no query found with specified name if (rawQuery == null) { throw new InvalidArgumentException("No query found with specified name - {}", name); } //build the free marker template from raw query try { template = new Template(name, rawQuery, configuration); templateMap.put(name, template); } catch (Exception ex) { throw new InvalidStateException(ex, "An error occurred while loading query template - {}", name); } } try { //process the template into query StringWriter writer = new StringWriter(); template.process(context, writer); writer.flush(); //build the final query (replacing the param expressions) String query = writer.toString(); StringBuffer finalQuery = new StringBuffer(); Matcher matcher = QUERY_PARAM_PATTERN.matcher(query); String property = null; while (matcher.find()) { property = matcher.group(1); matcher.appendReplacement(finalQuery, "?"); paramValues.add(PropertyUtils.getProperty(context, property)); } matcher.appendTail(finalQuery); return finalQuery.toString(); } catch (Exception ex) { throw new InvalidStateException(ex, "An exception occurred while building query: " + name); } }
From source file:de.mpg.mpdl.inge.citationmanager.utils.XsltHelper.java
/** * Converts snippet <span> tags to the HTML formatting, i.e. <code><b>, <i>, <u>, <s></code> * Text. Note: If at least one <span> css class will not match FontStyle css, the snippet * will be returned without any changes. * //from w w w .j a v a 2s . c om * @param snippet * @return converted snippet * @throws CitationStyleManagerException */ public static String convertSnippetToHtml(String snippet) throws CitationStyleManagerException { FontStyle fs; // snippet = removeI18N(snippet); FontStylesCollection fsc = XmlHelper.loadFontStylesCollection(); if (!Utils.checkVal(snippet) || fsc == null) return snippet; // logger.info("passed str:" + snippet); StringBuffer sb = new StringBuffer(); Matcher m = SPANS_WITH_CLASS.matcher(snippet); while (m.find()) { String cssClass = m.group(1); fs = fsc.getFontStyleByCssClass(cssClass); // logger.info("fs:" + fs); // Rigorous: if at list once no css class has been found return str // as it is if (fs == null) { return snippet; } else { String str = "$2"; if (fs.getIsStrikeThrough()) { str = "<s>" + str + "</s>"; } if (fs.getIsUnderline()) { str = "<u>" + str + "</u>"; } if (fs.getIsItalic()) { str = "<i>" + str + "</i>"; } if (fs.getIsBold()) { str = "<b>" + str + "</b>"; } str = "<span class=\"" + cssClass + "\">" + str + "</span>"; m.appendReplacement(sb, str); } } snippet = m.appendTail(sb).toString(); return snippet; }
From source file:nl.ivonet.epub.strategy.epub.KepubStrategy.java
@Override public void execute(final Epub epub) { LOG.debug("Applying {} on [{}]", getClass().getSimpleName(), epub.getOrigionalFilename()); if (epub.hasDropout(Dropout.CORRUPT_HTML)) { LOG.debug("Html corruption already detected so skipping kepub processing"); return;//from w w w .ja v a 2 s . c om } final List<Resource> htmlResources = epub.getContents().stream() .filter(HtmlCorruptDetectionStrategy::isHtml).collect(toList()); int idx = 1; for (final Resource content : htmlResources) { try { final String html = IOUtils.toString(content.getReader()); final Matcher matcher = PAT.matcher(html); final StringBuffer sb = new StringBuffer(); while (matcher.find()) { final String group = matcher.group(); if (doNotProcess(group)) { continue; } matcher.appendReplacement(sb, group.replace(">", String.format(KOBO, idx))); idx++; } matcher.appendTail(sb); content.setData(sb.toString().getBytes()); } catch (IOException e) { epub.addDropout(Dropout.READ_ERROR); } catch (IllegalArgumentException e) { epub.addDropout(Dropout.KEPBUB); } } }
From source file:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java
/** * Converts snippet <span> tags to the HTML formatting, * i.e. <code><b>, <i>, <u>, <s></code> * Text. Note: If at least one <span> css class will not match * FontStyle css, the snippet will be returned without any changes. * /*w w w. jav a2s.c om*/ * @param snippet * @return converted snippet * @throws CitationStyleManagerException */ public static String convertSnippetToHtml(String snippet) throws CitationStyleManagerException { FontStyle fs; // snippet = removeI18N(snippet); FontStylesCollection fsc = XmlHelper.loadFontStylesCollection(); if (!Utils.checkVal(snippet) || fsc == null) return snippet; // logger.info("passed str:" + snippet); StringBuffer sb = new StringBuffer(); Matcher m = SPANS_WITH_CLASS.matcher(snippet); while (m.find()) { String cssClass = m.group(1); fs = fsc.getFontStyleByCssClass(cssClass); // logger.info("fs:" + fs); // Rigorous: if at list once no css class has been found return str // as it is if (fs == null) { return snippet; } else { String str = "$2"; if (fs.getIsStrikeThrough()) { str = "<s>" + str + "</s>"; } if (fs.getIsUnderline()) { str = "<u>" + str + "</u>"; } if (fs.getIsItalic()) { str = "<i>" + str + "</i>"; } if (fs.getIsBold()) { str = "<b>" + str + "</b>"; } str = "<span class=\"" + cssClass + "\">" + str + "</span>"; m.appendReplacement(sb, str); } } snippet = m.appendTail(sb).toString(); return snippet; }
From source file:com.i10n.fleet.web.controllers.DriverAdminOperations.java
@SuppressWarnings("rawtypes") public boolean Uploading(HttpServletRequest request) throws FileUploadException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { LOG.debug("File Not Uploaded"); } else {//from www . j ava2s . c o m Iterator fileNames = null; fileNames = ((MultipartHttpServletRequest) request).getFileNames(); MultipartFile file = null; if (fileNames.hasNext()) { String fileName = (String) fileNames.next(); file = ((MultipartHttpServletRequest) request).getFile(fileName); String itemName = null; try { itemName = file.getOriginalFilename(); } catch (Exception e) { LOG.error(e); } Random generator = new Random(); int r = Math.abs(generator.nextInt()); String reg = "[.*]"; String replacingtext = ""; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(itemName); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(buffer, replacingtext); } int IndexOf = itemName.indexOf("."); String domainName = itemName.substring(IndexOf); finalimage = buffer.toString() + "_" + r + domainName; savedFile = new File("/usr/local/tomcat6/webapps/driverimage/" + finalimage); savedFile.getAbsolutePath(); try { file.transferTo(savedFile); /* * * transferTo uses the tranfering a file location to destination * */ } catch (IllegalStateException e1) { LOG.error(e1); } catch (IOException e1) { LOG.error(e1); } } } return true; }
From source file:net.firejack.platform.installation.processor.TemplateApplicationProcessor.java
public InputStream modify(InputStream stream, TemplateEvent event) throws IOException { String xml = IOUtils.toString(stream); IOUtils.closeQuietly(stream);/*from w w w .ja v a 2 s. c o m*/ Pattern pattern = Pattern.compile("package\\s+path\\s*=\\s*\"(.*?)\"\\s+name\\s*=\\s*\"(.*?)\""); Matcher matcher = pattern.matcher(xml); StringBuffer output = new StringBuffer(); while (matcher.find()) { event.setLookup(DiffUtils.lookup(matcher.group(1), matcher.group(2))); matcher.appendReplacement(output, "package path=\"" + event.getPath() + "\" name=\"" + event.getName() + "\""); } matcher.appendTail(output); pattern = Pattern.compile("uid\\s*=\\s*\"(.*?)\""); matcher = pattern.matcher(output); output = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(output, "uid=\"" + SecurityHelper.generateSecureId() + "\""); } matcher.appendTail(output); xml = output.toString().replaceAll(event.getLookup(), DiffUtils.lookup(event.getPath(), event.getName())); return IOUtils.toInputStream(xml); }
From source file:dk.dma.msinm.common.time.TimeTranslator.java
/** * Translate the time description//from www . ja v a 2 s . co m * @param time the time description to translate * @param translateRules the translation rules to apply * @return the result */ public String translate(String time, Map<String, String> translateRules) throws TimeException { BufferedReader reader = new BufferedReader(new StringReader(time)); String line; StringBuilder result = new StringBuilder(); try { while ((line = reader.readLine()) != null) { //line = line.trim().toLowerCase(); // Replace according to replace rules for (String key : translateRules.keySet()) { String value = translateRules.get(key); Matcher m = Pattern.compile(key, Pattern.CASE_INSENSITIVE).matcher(line); StringBuffer sb = new StringBuffer(); while (m.find()) { String text = m.group(); m.appendReplacement(sb, value); } m.appendTail(sb); line = sb.toString(); } // Capitalize, unless the line starts with something like "a) xxx" if (!line.matches("\\w\\) .*")) { line = StringUtils.capitalize(line); } result.append(line + "\n"); } } catch (Exception e) { throw new TimeException("Failed translating time description", e); } return result.toString().trim(); }
From source file:aurelienribon.utils.TemplateManager.java
/** * Processes the variables over the given string, and returns the result. *//*from w ww . j ava 2 s. c om*/ public String process(String input) { for (String var : replacements.keySet()) { input = input.replaceAll("@\\{" + var + "\\}", replacements.get(var)); } { Pattern p = Pattern.compile("@\\{ifdef (" + varPattern + ")\\}(.*?)@\\{endif\\}", Pattern.DOTALL); Matcher m = p.matcher(input); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String content = m.group(2); if (replacements.containsKey(var)) m.appendReplacement(sb, content); else m.appendReplacement(sb, ""); } m.appendTail(sb); input = sb.toString(); } { Pattern p = Pattern.compile("@\\{ifndef (" + varPattern + ")\\}(.*?)@\\{endif\\}", Pattern.DOTALL); Matcher m = p.matcher(input); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String content = m.group(2); if (!replacements.containsKey(var)) m.appendReplacement(sb, content); else m.appendReplacement(sb, ""); } m.appendTail(sb); input = sb.toString(); } return input; }
From source file:h2weibo.utils.filters.TcoStatusFilter.java
public String filter(String input) { // Create a pattern to match cat Pattern p = Pattern.compile("http://t.co/\\w+"); // Create a matcher with an input string Matcher m = p.matcher(input); StringBuffer sb = new StringBuffer(); boolean result = m.find(); // Loop through and create a new String with the replacements while (result) { String tcoUrl = m.group(); try {/*w ww . ja v a2 s . co m*/ String redirectUrl = getRedirectUrl(tcoUrl); if (redirectUrl != null) m.appendReplacement(sb, redirectUrl); } catch (IOException e) { // do nothing, skip } result = m.find(); } // Add the last segment of input to the new String m.appendTail(sb); return sb.toString(); }