List of usage examples for java.util.regex Matcher appendReplacement
public Matcher appendReplacement(StringBuilder sb, String replacement)
From source file:cn.suishen.email.activity.MessageViewFragmentBase.java
/** * Reload the body from the provider cursor. This must only be called from the UI thread. * * @param bodyText text part/* w ww .j a va 2 s.c om*/ * @param bodyHtml html part * * TODO deal with html vs text and many other issues <- WHAT DOES IT MEAN?? */ private void reloadUiFromBody(String bodyText, String bodyHtml, boolean autoShowPictures) { String text = null; mHtmlTextRaw = null; boolean hasImages = false; if (bodyHtml == null) { text = bodyText; /* * Convert the plain text to HTML */ StringBuffer sb = new StringBuffer("<html><body>"); if (text != null) { // Escape any inadvertent HTML in the text message text = EmailHtmlUtil.escapeCharacterToDisplay(text); // Find any embedded URL's and linkify Matcher m = Patterns.WEB_URL.matcher(text); while (m.find()) { int start = m.start(); /* * WEB_URL_PATTERN may match domain part of email address. To detect * this false match, the character just before the matched string * should not be '@'. */ if (start == 0 || text.charAt(start - 1) != '@') { String url = m.group(); Matcher proto = WEB_URL_PROTOCOL.matcher(url); String link; if (proto.find()) { // This is work around to force URL protocol part be lower case, // because WebView could follow only lower case protocol link. link = proto.group().toLowerCase() + url.substring(proto.end()); } else { // Patterns.WEB_URL matches URL without protocol part, // so added default protocol to link. link = "http://" + url; } String href = String.format("<a href=\"%s\">%s</a>", link, url); m.appendReplacement(sb, href); } else { m.appendReplacement(sb, "$0"); } } m.appendTail(sb); } sb.append("</body></html>"); text = sb.toString(); } else { text = bodyHtml; mHtmlTextRaw = bodyHtml; hasImages = IMG_TAG_START_REGEX.matcher(text).find(); } // TODO this is not really accurate. // - Images aren't the only network resources. (e.g. CSS) // - If images are attached to the email and small enough, we download them at once, // and won't need network access when they're shown. if (hasImages) { if (mRestoredPictureLoaded || autoShowPictures) { blockNetworkLoads(false); addTabFlags(TAB_FLAGS_PICTURE_LOADED); // Set for next onSaveInstanceState // Make sure to reset the flag -- otherwise this will keep taking effect even after // moving to another message. mRestoredPictureLoaded = false; } else { addTabFlags(TAB_FLAGS_HAS_PICTURES); } } setMessageHtml(text); // Ask for attachments after body new LoadAttachmentsTask().executeParallel(mMessage.mId); mIsMessageLoadedForTest = true; }
From source file:org.etudes.mneme.impl.ExportQtiServiceImpl.java
/** * Creates elements for all embed media with in itembody element. Use this for question text * //w w w . j av a2 s.c o m * @param zip * @param subFolder * @param text * @param itemBody * @param mediaFiles * @return */ private Element translateEmbedData(ZipOutputStream zip, String subFolder, String text, Element itemBody, List<String> mediaFiles, Document questionDocument) { if (text == null || text.length() == 0) return itemBody; Element media = null; try { Pattern pa = Pattern.compile("<(img|a|embed)\\s+.*?/*>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL); // TODO: write all attributes Pattern p_srcAttribute = Pattern.compile("(src|href)[\\s]*=[\\s]*\"([^#\"]*)([#\"])", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); Matcher m = pa.matcher(text); StringBuffer sb = new StringBuffer(); subFolder = (subFolder == null || subFolder.length() == 0) ? "Resources/" : subFolder; String embedSubFolder = "Resources/"; int start = 0; while (m.find()) { int startIdx = m.start(); String img_content = m.group(0); Matcher m_src = p_srcAttribute.matcher(img_content); if (m_src.find()) { String ref = m_src.group(2); if (!ref.contains("/access/mneme/content/")) continue; Element div = questionDocument.createElement("div"); if (startIdx <= text.length()) { String divText = text.substring(start, startIdx); div.setTextContent(divText); start = m.end(); } ref = ref.replaceAll("%20", " "); String resource_id = ref.replace("/access/mneme", ""); String embedFileName = ref.substring(ref.lastIndexOf("/") + 1); ref = subFolder + embedFileName; mediaFiles.add(ref); media = questionDocument.createElement(m.group(1)); if ("a".equalsIgnoreCase(m.group(1))) media.setAttribute("target", "_blank"); media.setAttribute(m_src.group(1), embedSubFolder + embedFileName); m.appendReplacement(sb, ""); String fileName = Validator.getFileName(resource_id); fileName = fileName.replaceAll("%20", " "); fileName = Validator.escapeResourceName(fileName); writeContentResourceToZip(zip, subFolder, resource_id, fileName); itemBody.appendChild(div); itemBody.appendChild(media); } } m.appendTail(sb); if (start > 0 && start < text.length()) { Element div = questionDocument.createElement("div"); div.setTextContent(text.substring(start)); itemBody.appendChild(div); } return itemBody; } catch (Exception e) { M_log.debug("error in translating embed up blank img tags:" + e.getMessage()); } return itemBody; }
From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java
/** * BringIn embed media from instrcutions * //from w w w .j a v a2 s . c o m * @param unzipBackUpLocation * @param context * @param text * @param embedMedia * @return * @throws Exception */ private String processInstructionsEmbedMedia(String unzipBackUpLocation, String context, String text, List<String> embedMedia) throws Exception { Pattern p = Pattern.compile("(src|href)[\\s]*=[\\s]*\"([^#\"]*)([#\"])", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); StringBuffer sb = new StringBuffer(); Matcher m = p.matcher(text); while (m.find()) { if (m.groupCount() != 3) continue; String fileName = m.group(2); if (embedMedia != null) embedMedia.add(fileName); // add to collection Reference ref = transferEmbeddedData(unzipBackUpLocation + File.separator + fileName, fileName, context); if (ref == null) continue; // replace with collection Url String ref_id = attachmentService.processMnemeUrls(ref.getId()); m.appendReplacement(sb, m.group(1) + "= \"" + ref_id + "\""); } m.appendTail(sb); return sb.toString(); }
From source file:mondrian.olap.Util.java
/** * Replaces tokens in a string./* ww w. ja va2 s. c o m*/ * * <p>Replaces the tokens "${key}" if "key" occurs in the key-value map. * Otherwise "${key}" is left in the string unchanged. * * @param text Source string * @param env Map of key-value pairs * @return String with tokens substituted */ public static String replaceProperties(String text, Map<String, String> env) { // As of JDK 1.5, cannot use StringBuilder - appendReplacement requires // the antediluvian StringBuffer. StringBuffer buf = new StringBuffer(text.length() + 200); Pattern pattern = Pattern.compile("\\$\\{([^${}]+)\\}"); Matcher matcher = pattern.matcher(text); while (matcher.find()) { String varName = matcher.group(1); String varValue = env.get(varName); if (varValue != null) { matcher.appendReplacement(buf, varValue); } else { matcher.appendReplacement(buf, "\\${$1}"); } } matcher.appendTail(buf); return buf.toString(); }
From source file:org.grails.web.mapping.RegexUrlMapping.java
@SuppressWarnings({ "unchecked" }) private String createURLInternal(Map paramValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); }/*from www . j a v a2 s.com*/ } if (paramValues == null) paramValues = Collections.emptyMap(); StringBuilder uri = new StringBuilder(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (i == tokens.length - 1 && urlData.hasOptionalExtension()) { token += OPTIONAL_EXTENSION_WILDCARD; } Matcher m = OPTIONAL_EXTENSION_WILDCARD_PATTERN.matcher(token); if (m.find()) { boolean tokenSet = false; if (token.startsWith(CAPTURED_WILDCARD)) { ConstrainedProperty prop = constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = paramValues.get(propName); usedParams.add(propName); if (value != null) { token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), value.toString()); tokenSet = true; } else { token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), ""); } } else { tokenSet = true; } if (tokenSet) { uri.append(SLASH); } ConstrainedProperty prop = constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = paramValues.get(propName); usedParams.add(propName); if (value != null) { String ext = "." + value; uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', ext) .replace(OPTIONAL_EXTENSION_WILDCARD, ext)); } else { uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', "") .replace(OPTIONAL_EXTENSION_WILDCARD, "")); } continue; } if (token.endsWith("?")) { token = token.substring(0, token.length() - 1); } m = DOUBLE_WILDCARD_PATTERN.matcher(token); if (m.find()) { StringBuffer buf = new StringBuffer(); do { ConstrainedProperty prop = constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = paramValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) { throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + paramValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); } else if (value == null) { m.appendReplacement(buf, ""); } else { m.appendReplacement(buf, Matcher.quoteReplacement(value.toString())); } } while (m.find()); m.appendTail(buf); try { String v = buf.toString(); if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (String segment : segs) { uri.append(SLASH).append(encode(segment, encoding)); } } else if (v.length() > 0) { // original behavior uri.append(SLASH).append(encode(v, encoding)); } else { // Stop processing tokens once we hit an empty one. break; } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + paramValues + "], problem encoding URL part [" + buf + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(paramValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + paramValues + "]"); } return uri.toString(); }
From source file:com.hichinaschool.flashcards.anki.Reviewer.java
/** * Converts characters in Unicode Supplementary Multilingual Plane (SMP) to their equivalent Html Entities. * This is done because webview has difficulty displaying these characters. * @param text/*from w w w . j a v a 2 s.c o m*/ * @return */ private String SmpToHtmlEntity(String text) { StringBuffer sb = new StringBuffer(); Matcher m = Pattern.compile("([^\u0000-\uFFFF])").matcher(text); while (m.find()) { String a = "&#x" + Integer.toHexString(m.group(1).codePointAt(0)) + ";"; m.appendReplacement(sb, a); } m.appendTail(sb); return sb.toString(); }
From source file:org.apache.synapse.mediators.experimental.MockFactoryMediator.java
/** * Replaces the payload format with SynapsePath arguments which are evaluated using getArgValues(). * * @param format/* w ww. j a v a 2 s .c om*/ * @param result * @param synCtx */ private void replace(String format, StringBuffer result, MessageContext synCtx) { HashMap<String, String>[] argValues = getArgValues(synCtx); HashMap<String, String> replacement; Map.Entry<String, String> replacementEntry; String replacementValue = null; Matcher matcher; if (mediaType != null && mediaType.equals(JSON_TYPE)) { matcher = pattern.matcher(format); } else { matcher = pattern.matcher("<pfPadding>" + format + "</pfPadding>"); } try { while (matcher.find()) { String matchSeq = matcher.group(); int argIndex; try { argIndex = Integer.parseInt(matchSeq.substring(1, matchSeq.length())); } catch (NumberFormatException e) { argIndex = Integer.parseInt(matchSeq.substring(2, matchSeq.length() - 1)); } replacement = argValues[argIndex - 1]; replacementEntry = replacement.entrySet().iterator().next(); if (mediaType.equals(JSON_TYPE) && inferReplacementType(replacementEntry).equals(XML_TYPE)) { // XML to JSON conversion here try { replacementValue = "<jsonObject>" + replacementEntry.getKey() + "</jsonObject>"; OMElement omXML = AXIOMUtil.stringToOM(replacementValue); replacementValue = JsonUtil.toJsonString(omXML).toString(); } catch (XMLStreamException e) { handleException( "Error parsing XML for JSON conversion, please check your xPath expressions return valid XML: ", synCtx); } catch (AxisFault e) { handleException("Error converting XML to JSON", synCtx); } } else if (mediaType.equals(XML_TYPE) && inferReplacementType(replacementEntry).equals(JSON_TYPE)) { // JSON to XML conversion here try { OMElement omXML = JsonUtil.toXml(IOUtils.toInputStream(replacementEntry.getKey()), false); if (JsonUtil.isAJsonPayloadElement(omXML)) { // remove <jsonObject/> from result. Iterator children = omXML.getChildElements(); String childrenStr = ""; while (children.hasNext()) { childrenStr += (children.next()).toString().trim(); } replacementValue = childrenStr; } else { ///~ replacementValue = omXML.toString(); } //replacementValue = omXML.toString(); } catch (AxisFault e) { handleException( "Error converting JSON to XML, please check your JSON Path expressions return valid JSON: ", synCtx); } } else { // No conversion required, as path evaluates to regular String. replacementValue = replacementEntry.getKey(); } matcher.appendReplacement(result, replacementValue); } } catch (ArrayIndexOutOfBoundsException e) { log.error("#replace. Mis-match detected between number of formatters and arguments", e); } matcher.appendTail(result); }
From source file:io.manasobi.utils.StringUtils.java
/** * ? ?? ? ? ?? ? <br><br> * * StringUtils.replaceLast("Anyframe Java Test Anyframe Java Test", "Anyframe", "Enterprise") = "Anyframe Java Test Enterprise Java Test" * * @param source ?//from w w w . j a va 2 s . c o m * @param regex ? * @param replacement ? * @return ? ? ?? ? */ public static String replaceLast(String source, String regex, String replacement) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(source); if (!matcher.find()) { return source; } int lastMatchStart = 0; do { lastMatchStart = matcher.start(); } while (matcher.find()); matcher.find(lastMatchStart); StringBuffer sb = new StringBuffer(source.length()); matcher.appendReplacement(sb, replacement); matcher.appendTail(sb); return sb.toString(); }
From source file:com.hichinaschool.flashcards.anki.Reviewer.java
/** * Parses content in question and answer to see, whether someone has hard coded the font size in a card layout. * If this is so, then the font size must be replaced with one corrected by the relative font size. If a relative * CSS unit measure is used (e.g. 'em'), then only the outer tag 'span' or 'div' tag in a hierarchy of such tags * is adjusted./*from w w w . j a v a2 s .co m*/ * This is not bullet-proof, a combination of font-size in span and in css classes will break this logic, but let's * just avoid building an HTML parser for this feature. * Anything that threatens common sense will break this logic, eg nested span/divs with CSS classes having font-size * declarations with relative units (40% dif inside 120% div inside 60% div). Broken HTML also breaks this. * Feel free to improve, but please keep it short and fast. * * @param content The HTML content that will be font-size-adjusted. * @param percentage The relative font size percentage defined in preferences * @return */ private String recalculateHardCodedFontSize(String content, int percentage) { if (percentage == 100 || null == content || 0 == content.trim().length()) { return content.trim(); } StringBuffer sb = new StringBuffer(); int tagDepth = 0; // to find out whether a relative CSS unit measure is within another one int lastRelUnitnTagDepth = 100; // the hierarchy depth of the current outer relative span double doubleSize; // for relative css measurement values int lastMatch = 0; String contentPart; Matcher m2; Matcher m = fFontSizePattern.matcher(content); while (m.find()) { contentPart = content.substring(lastMatch, m.start()); m2 = fSpanDivPattern.matcher(contentPart); while (m2.find()) { if (m2.group(1).equals("/")) { --tagDepth; } else { ++tagDepth; } if (tagDepth < lastRelUnitnTagDepth) { // went outside of previous scope lastRelUnitnTagDepth = 100; } } lastMatch = m.end(); try { doubleSize = Double.parseDouble(m.group(1)); doubleSize = doubleSize * percentage / 100; } catch (NumberFormatException e) { continue; // ignore this one } if (fRelativeCssUnits.contains(m.group(2))) { // handle relative units if (lastRelUnitnTagDepth < tagDepth) { m.appendReplacement(sb, m.group()); continue; } lastRelUnitnTagDepth = tagDepth; } m.appendReplacement(sb, String.format(Locale.US, "font-size:%.2f%s;", doubleSize, m.group(2))); } m.appendTail(sb); String a = sb.toString(); return a; }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * parse content resource urls/*from w ww.j ava 2 s .c om*/ * @param message * - message * @param embeddedRefs * - embedded references * @return * - modified content */ private String parseContentResourceUrls(String message, Set<String> embeddedRefs) { StringBuffer sb = new StringBuffer(); Pattern p = getContentResourcePattern(); Matcher m = p.matcher(message); while (m.find()) { if (m.groupCount() == 2) { String ref = m.group(2); embeddedRefs.add("embeded_jf_content/content/group" + ref); String siteId = ToolManager.getCurrentPlacement().getContext(); m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + ServerConfigurationService.getServerUrl() + "/access/content/group/" + siteId + Validator.escapeUrl(ref) + "\"")); } } m.appendTail(sb); return sb.toString(); }