List of usage examples for java.util.regex Matcher appendTail
public StringBuilder appendTail(StringBuilder sb)
From source file:com.android.email.activity.MessageView.java
/** * Reload the body from the provider cursor. This must only be called from the UI thread. * * @param bodyText text part// w w w .j av a 2 s . co m * @param bodyHtml html part * * TODO deal with html vs text and many other issues */ private void reloadUiFromBody(String bodyText, String bodyHtml) { 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(); } mShowPicturesSection.setVisibility(hasImages ? View.VISIBLE : View.GONE); if (mMessageContentView != null) { mMessageContentView.loadDataWithBaseURL("email://", text, "text/html", "utf-8", null); } // Ask for attachments after body mLoadAttachmentsTask = new LoadAttachmentsTask(); mLoadAttachmentsTask.execute(mMessage.mId); }
From source file:org.intermine.bio.dataconversion.SgdConverter.java
private String getCasedName(String name) throws Exception { String newname = name;// ww w. j av a2 s . co m StringBuffer sb = new StringBuffer(); Matcher m = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(name); while (m.find()) { m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2).toLowerCase()); } newname = m.appendTail(sb) + "p".toString(); return newname; }
From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java
/** * Processes the input CSS to replace @import statements with the * contents of the imported CSS. The imported CSS is minified, image * URLs in-lined, and this method recursively called to in-line nested * @imports./*from www . j a v a2 s.c o m*/ * * @param css * The current CSS containing @import statements to be * processed * @param uri * The URI for the current CSS * @param path * The path, as specified in the @import statement used to * import the current CSS, or null if this is the top level CSS. * * @return The input CSS with @import statements replaced with the * contents of the imported files. * * @throws IOException */ protected String inlineImports(HttpServletRequest req, String css, IResource res, String path) throws IOException { // In-lining of imports can be disabled by request parameter for debugging if (!TypeUtil.asBoolean(req.getParameter(INLINEIMPORTS_REQPARAM_NAME), true)) { return css; } StringBuffer buf = new StringBuffer(); IAggregator aggregator = (IAggregator) req.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME); IOptions options = aggregator.getOptions(); /* * True if we should include the name of imported CSS files in a comment at * the beginning of the file. */ boolean includePreamble = TypeUtil.asBoolean(req.getAttribute(IHttpTransport.SHOWFILENAMES_REQATTRNAME)) && (options.isDebugMode() || options.isDevelopmentMode()); if (includePreamble && path != null && path.length() > 0) { buf.append("/* @import " + path + " */\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ } Matcher m = importPattern.matcher(css); while (m.find()) { String fullMatch = m.group(0); String importNameMatch = m.group(2); String mediaTypes = m.group(4); /* * CSS rules require that all @import statements appear before any * style definitions within a document. Most browsers simply ignore * @import statements which appear following any styles definitions. * This means that once we've inlined an @import, then we can't not * inline any subsequent @imports. The implication is that all * @imports which cannot be inlined (i.e. non-relative url or device * specific media types) MUST appear before any @import that is * inlined. For this reason, we throw an error if we encounter an * @import which we cannot inline if we have already inlined a * previous @import. */ //Only process media type "all" or empty media type rules. if (mediaTypes.length() > 0 && !"all".equals(StringUtils.trim(mediaTypes))) { //$NON-NLS-1$ m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } // remove quotes. importNameMatch = quotedStringTrimPattern.matcher(importNameMatch).replaceAll(""); //$NON-NLS-1$ importNameMatch = forwardSlashPattern.matcher(importNameMatch).replaceAll("/"); //$NON-NLS-1$ // if name is not relative, then bail if (importNameMatch.startsWith("/") || protocolPattern.matcher(importNameMatch).find()) { //$NON-NLS-1$ m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } IResource importRes = res.resolve(importNameMatch); String importCss = null; importCss = readToString(new CommentStrippingReader( new InputStreamReader(importRes.getURI().toURL().openStream(), "UTF-8" //$NON-NLS-1$ ))); importCss = minify(importCss, importRes); // Inline images importCss = inlineImageUrls(req, importCss, importRes); if (inlineImports) { importCss = inlineImports(req, importCss, importRes, importNameMatch); } m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(importCss); } m.appendTail(buf); css = buf.toString(); /* * Now re-write all relative URLs in url(...) statements to make them relative * to the importing CSS */ if (path != null && path.length() > 0) { int idx = path.lastIndexOf("/"); //$NON-NLS-1$ //Make a file path based on the last slash. //If no slash, so must be just a file name. Use empty string then. path = (idx != -1) ? path.substring(0, idx + 1) : ""; //$NON-NLS-1$ buf = new StringBuffer(); m = urlPattern.matcher(css); while (m.find()) { String fullMatch = m.group(0); String urlMatch = m.group(1); urlMatch = StringUtils.trim(urlMatch.replace("\\", "/")); //$NON-NLS-1$ //$NON-NLS-2$ String quoted = ""; //$NON-NLS-1$ if (urlMatch.charAt(0) == '"' && urlMatch.charAt(urlMatch.length() - 1) == '"') { quoted = "\""; //$NON-NLS-1$ urlMatch = urlMatch.substring(1, urlMatch.length() - 1); } else if (urlMatch.charAt(0) == '\'' && urlMatch.charAt(urlMatch.length() - 1) == '\'') { quoted = "'"; //$NON-NLS-1$ urlMatch = urlMatch.substring(1, urlMatch.length() - 1); } // Don't modify non-relative URLs if (urlMatch.startsWith("/") || urlMatch.startsWith("#") //$NON-NLS-1$//$NON-NLS-2$ || protocolPattern.matcher(urlMatch).find()) { m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } String fixedUrl = path + ((path.endsWith("/") || path.length() == 0) ? "" : "/") + urlMatch; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //Collapse '..' and '.' String[] parts = fixedUrl.split("/"); //$NON-NLS-1$ for (int i = parts.length - 1; i > 0; i--) { if (".".equals(parts[i])) { //$NON-NLS-1$ parts = (String[]) ArrayUtils.remove(parts, i); } else if ("..".equals(parts[i])) { //$NON-NLS-1$ if (i != 0 && !"..".equals(parts[i - 1])) { //$NON-NLS-1$ parts = (String[]) ArrayUtils.remove(parts, i - 1); parts = (String[]) ArrayUtils.remove(parts, i - 1); } } } m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append("url(") //$NON-NLS-1$ .append(quoted).append(StringUtils.join(parts, "/")) //$NON-NLS-1$ .append(quoted).append(")"); //$NON-NLS-1$ } m.appendTail(buf); css = buf.toString(); } return css; }
From source file:org.muse.mneme.impl.AttachmentServiceImpl.java
/** * {@inheritDoc}// w ww . j ava 2 s. com */ public String translateEmbeddedReferences(String data, List<Translation> translations) { if (data == null) return data; if (translations == null) return data; // pattern to find any src= or href= text // groups: 0: the whole matching text 1: src|href 2: the string in the quotes Pattern p = Pattern.compile("(src|href)[\\s]*=[\\s]*\"([^\"]*)\""); Matcher m = p.matcher(data); StringBuffer sb = new StringBuffer(); // process each "harvested" string (avoiding like strings that are not in src= or href= patterns) while (m.find()) { if (m.groupCount() == 2) { String ref = m.group(2); // harvest any content hosting reference int index = ref.indexOf("/access/content/"); if (index != -1) { // except for any in /user/ or /public/ if (ref.indexOf("/access/content/user/") != -1) { index = -1; } else if (ref.indexOf("/access/content/public/") != -1) { index = -1; } } // harvest also the mneme docs references if (index == -1) index = ref.indexOf("/access/mneme/content/"); if (index != -1) { // save just the reference part (i.e. after the /access); String normal = ref.substring(index + 7); // deal with %20 and other encoded URL stuff try { normal = URLDecoder.decode(normal, "UTF-8"); } catch (UnsupportedEncodingException e) { M_log.warn("harvestAttachmentsReferenced: " + e); } // translate the normal form String translated = normal; for (Translation translation : translations) { translated = translation.translate(translated); } // URL encode translated String escaped = EscapeRefUrl.escapeUrl(translated); // if changed, replace if (!normal.equals(translated)) { m.appendReplacement(sb, Matcher.quoteReplacement( m.group(1) + "=\"" + ref.substring(0, index + 7) + escaped + "\"")); } } } } m.appendTail(sb); return sb.toString(); }
From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java
/** * BringIn embed media from instrcutions * /*from ww w.j av a 2s . c om*/ * @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: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/*from w w w.ja v a 2s .c o m*/ * @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.codehaus.groovy.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()); }/* w ww. j a v a2s. co m*/ } if (paramValues == null) paramValues = Collections.EMPTY_MAP; 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 += UrlMapping.OPTIONAL_EXTENSION_WILDCARD; } Matcher m = OPTIONAL_EXTENSION_WILDCARD_PATTERN.matcher(token); if (m.find()) { 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()); } else if (prop.isNullable()) { break; } } 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:mondrian.olap.Util.java
/** * Replaces tokens in a string./*from w w w . j av a2 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: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//ww w . j a v a 2s . 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: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 www .j a va 2 s .c om*/ * @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(); }