List of usage examples for java.util.regex Matcher appendTail
public StringBuilder appendTail(StringBuilder sb)
From source file:org.etudes.mneme.impl.ExportQtiServiceImpl.java
/** * Creates elements for all embed media with in itembody element. Use this for question text * // www .j av a2 s . co 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.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 w ww.ja v a 2 s .co m } 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:org.pentaho.metadata.query.impl.ietl.InlineEtlQueryExecutor.java
public List<QueryConstraint> parseConstraints(Query query, Map<String, Object> parameters) { List<QueryConstraint> constraints = new ArrayList<QueryConstraint>(); for (Constraint constraint : query.getConstraints()) { QueryConstraint qc = new QueryConstraint(); qc.orig = constraint;/* w w w. ja v a2 s .c o m*/ // parse out all the [] fields Pattern p = Pattern.compile("\\[([^\\]]*)\\]"); //$NON-NLS-1$ Matcher m = p.matcher(constraint.getFormula()); StringBuffer sb = new StringBuffer(); while (m.find()) { String match = m.group(1); if (match.startsWith("param:")) { //$NON-NLS-1$ String paramName = match.substring(6); Object paramValue = parameters.get(paramName); String openFormulaValue = ""; //$NON-NLS-1$ if (paramValue instanceof Boolean) { // need to get and then render either true or false function. if (((Boolean) paramValue).booleanValue()) { openFormulaValue = "TRUE()"; //$NON-NLS-1$ } else { openFormulaValue = "FALSE()"; //$NON-NLS-1$ } } else if (paramValue instanceof Double) { openFormulaValue = paramValue.toString(); } else { // assume a string, string literal quote openFormulaValue = "\"" + paramValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ } m.appendReplacement(sb, openFormulaValue); } else { String[] seg = match.split("\\."); //$NON-NLS-1$ if (seg != null && seg.length > 1) { Category cat = query.getLogicalModel().findCategory(seg[0]); LogicalColumn col = cat.findLogicalColumn(seg[1]); if (col == null) { logger.error(Messages.getErrorString( "InlineEtlQueryExecutor.ERROR_0001_FAILED_TO_LOCATE_COLUMN", seg[0], seg[1])); //$NON-NLS-1$ } String fieldName = (String) col.getProperty(InlineEtlPhysicalColumn.FIELD_NAME); AggregationType agg = null; if (seg.length > 2) { agg = AggregationType.valueOf(seg[2].toUpperCase()); } Selection sel = new Selection(cat, col, agg); if (!qc.selections.contains(sel)) { qc.selections.add(sel); if (sel.getActiveAggregationType() != null && sel.getActiveAggregationType() != AggregationType.NONE) { qc.groupby = true; } } // this may be different in the group by context. m.appendReplacement(sb, "[" + fieldName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ } else { logger.error(Messages.getErrorString( "InlineEtlQueryExecutor.ERROR_0002_FAILED_TO_PARSE_FORMULA", match)); //$NON-NLS-1$ } } } m.appendTail(sb); qc.formula = sb.toString(); if (logger.isDebugEnabled()) { logger.debug("PARSED FORMULA: " + qc.formula); //$NON-NLS-1$ } constraints.add(qc); } return constraints; }
From source file:org.apache.synapse.mediators.experimental.MockFactoryMediator.java
/** * Replaces the payload format with SynapsePath arguments which are evaluated using getArgValues(). * * @param format//from w w w . j av 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:com.ibm.jaggr.core.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 w ww . j a v a 2s . c o m*/ * * @param req * The request associated with the call. * @param css * The current CSS containing @import statements to be * processed * @param res * The resource for the CSS file. * @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 = dequote(importNameMatch); importNameMatch = forwardSlashPattern.matcher(importNameMatch).replaceAll("/"); //$NON-NLS-1$ 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); URI uri = null; if (importRes.exists()) { uri = importRes.getURI(); } else if (includeAMDPaths && importNameMatch.contains("/") && !importNameMatch.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$ // Resource not found using relative path to res. If path is not relative (starts with .) // then try to find the resource using config paths and packages. uri = aggregator.getConfig().locateModuleResource(importNameMatch); if (uri != null) { uri = aggregator.newResource(uri).getURI(); } } if (uri == null) { throw new NotFoundException(importNameMatch); } String importCss = null; importCss = readToString( new CommentStrippingReader(new InputStreamReader(uri.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:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java
/** * Replace <code>url(<<i>relative-path</i>>)</code> references in the * input CSS with/* w w w .jav a 2s . co m*/ * <code>url(data:<<i>mime-type</i>>;<<i>base64-encoded-data</i>></code> * ). The conversion is controlled by option settings as described in * {@link CSSModuleBuilder}. * * @param css * The input CSS * @param uri * The URI for the input CSS * @return The transformed CSS with images in-lined as determined by option * settings. */ protected String inlineImageUrls(HttpServletRequest req, String css, IResource res) { if (imageSizeThreshold == 0 && inlinedImageIncludeList.size() == 0) { // nothing to do return css; } // In-lining of imports can be disabled by request parameter for debugging if (!TypeUtil.asBoolean(req.getParameter(INLINEIMAGES_REQPARAM_NAME), true)) { return css; } StringBuffer buf = new StringBuffer(); Matcher m = urlPattern.matcher(css); while (m.find()) { String fullMatch = m.group(0); String urlMatch = m.group(1); // remove quotes. urlMatch = quotedStringPattern.matcher(urlMatch).replaceAll(""); //$NON-NLS-1$ urlMatch = forwardSlashPattern.matcher(urlMatch).replaceAll("/"); //$NON-NLS-1$ // Don't do anything with non-relative URLs if (urlMatch.startsWith("/") || urlMatch.startsWith("#") || protocolPattern.matcher(urlMatch).find()) { //$NON-NLS-1$ //$NON-NLS-2$ m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } URI imageUri = res.getURI().resolve(urlMatch); boolean exclude = false, include = false; // Determine if this image is in the include list for (Pattern regex : inlinedImageIncludeList) { if (regex.matcher(imageUri.getPath()).find()) { include = true; break; } } // Determine if this image is in the exclude list for (Pattern regex : inlinedImageExcludeList) { if (regex.matcher(imageUri.getPath()).find()) { exclude = true; break; } } // If there's an include list, then only the files in the include list // will be inlined if (inlinedImageIncludeList.size() > 0 && !include || exclude) { m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } boolean imageInlined = false; InputStream in = null; try { // In-line the image. URLConnection connection = imageUri.toURL().openConnection(); in = connection.getInputStream(); int size = connection.getContentLength(); String type = connection.getContentType(); if (type == null) { type = "content/unknown"; //$NON-NLS-1$ } if (include || inlineableImageTypes.contains(type) && size <= imageSizeThreshold) { String base64 = getBase64(connection); m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append("url('data:" + type + //$NON-NLS-1$ ";base64," + base64 + "')"); //$NON-NLS-1$ //$NON-NLS-2$ imageInlined = true; } } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, MessageFormat.format(Messages.CSSModuleBuilder_0, new Object[] { imageUri }), ex); } } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } if (!imageInlined) { // Image not in-lined. Write the original URL m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); } } m.appendTail(buf); return buf.toString(); }
From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java
/** * Replace <code>url(<<i>relative-path</i>>)</code> references in the * input CSS with//from w w w . j av a 2 s . c om * <code>url(data:<<i>mime-type</i>>;<<i>base64-encoded-data</i>></code> * ). The conversion is controlled by option settings as described in * {@link CSSModuleBuilder}. * * @param req * The request associated with the call. * @param css * The input CSS * @param res * The resource for the CSS file * @return The transformed CSS with images in-lined as determined by option * settings. */ protected String inlineImageUrls(HttpServletRequest req, String css, IResource res) { if (imageSizeThreshold == 0 && inlinedImageIncludeList.size() == 0) { // nothing to do return css; } // In-lining of imports can be disabled by request parameter for debugging if (!TypeUtil.asBoolean(req.getParameter(INLINEIMAGES_REQPARAM_NAME), true)) { return css; } StringBuffer buf = new StringBuffer(); Matcher m = urlPattern.matcher(css); while (m.find()) { String fullMatch = m.group(0); String urlMatch = m.group(1); // remove quotes. urlMatch = dequote(urlMatch); urlMatch = forwardSlashPattern.matcher(urlMatch).replaceAll("/"); //$NON-NLS-1$ // Don't do anything with non-relative URLs if (urlMatch.startsWith("/") || urlMatch.startsWith("#") || protocolPattern.matcher(urlMatch).find()) { //$NON-NLS-1$ //$NON-NLS-2$ m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } URI imageUri = res.resolve(urlMatch).getURI(); boolean exclude = false, include = false; // Determine if this image is in the include list for (Pattern regex : inlinedImageIncludeList) { if (regex.matcher(imageUri.getPath()).find()) { include = true; break; } } // Determine if this image is in the exclude list for (Pattern regex : inlinedImageExcludeList) { if (regex.matcher(imageUri.getPath()).find()) { exclude = true; break; } } // If there's an include list, then only the files in the include list // will be inlined if (inlinedImageIncludeList.size() > 0 && !include || exclude) { m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } boolean imageInlined = false; String type = URLConnection.getFileNameMap().getContentTypeFor(imageUri.getPath()); String extension = PathUtil.getExtension(imageUri.getPath()); if (type == null) { type = inlineableImageTypeMap.get(extension); } if (type == null) { type = "content/unknown"; //$NON-NLS-1$ } if (include || inlineableImageTypes.contains(type) || inlineableImageTypeMap.containsKey(extension)) { InputStream in = null; try { // In-line the image. URLConnection connection = imageUri.toURL().openConnection(); if (include || connection.getContentLength() <= imageSizeThreshold) { in = connection.getInputStream(); String base64 = getBase64(connection); m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append("url('data:" + type + //$NON-NLS-1$ ";base64," + base64 + "')"); //$NON-NLS-1$ //$NON-NLS-2$ imageInlined = true; } } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, MessageFormat.format(Messages.CSSModuleBuilder_0, new Object[] { imageUri }), ex); } } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } if (!imageInlined) { // Image not in-lined. Write the original URL m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); } } m.appendTail(buf); return buf.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 . ja va 2s. 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:br.com.capanema.kers.velocity.util.BuildManagerUtil.java
/** * Increment source code of filePath using template fragment. * /*from w w w. jav a 2s . c o m*/ * @param filePath * @param incrementPath * @param incrementPattern * @param dataGroup */ public static void incrementSourceCode(String filePath, String incrementPath, String incrementPattern, String firstAfter, Map<String, String> params, TemplateDataGroup dataGroup) { try { HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); //map for velocity variables velocityVariables.put("data", dataGroup); //conjunto de vriaveis que podem ser usados no template if (params != null && params.size() > 0) { /* for (String name : params.keySet()) { velocityVariables.put("params."+name, params.get(name)); }*/ velocityVariables.put("params", params); } //rodando velocity do incremento TemplateEngine templateEngine = TemplateEngineFactory.getEngine(incrementPath, true); String incrementSource = templateEngine.runFile(incrementPath, velocityVariables); // Create the pattern Pattern pattern = Pattern.compile("[\r\n]*[\t]*" + incrementPattern, Pattern.DOTALL); //o "[\r\n]*" para pegar as quebras de linhas que podem existir no incremento Matcher matcher = pattern.matcher(""); //novo incremento //aqui vai executar o pattern no prprio incremento... se o pattern estiver errado no ir encontrar nada e vai abortar o incremento matcher.reset(incrementSource); Map<String, String[]> mapGroupIncrement = new LinkedHashMap<String, String[]>(); while (matcher.find()) { String[] groups = new String[matcher.groupCount()]; for (int i = 0; i < matcher.groupCount(); i++) { groups[i] = matcher.group(i + 1); } String increment = matcher.group(); //new increment mapGroupIncrement.put(increment, groups); //map increment vs groups } if (mapGroupIncrement.size() == 0) { //no encontrou groups no incremento (usado para as comparaes), aborta return; } //le o arquivo atual FileInputStream inputFilePath = new FileInputStream(filePath); BufferedInputStream bufferedInput = new BufferedInputStream(inputFilePath); StringBuffer filePathContent = new StringBuffer(); int ch = 0; while ((ch = bufferedInput.read()) > -1) { filePathContent.append((char) ch); } inputFilePath.close(); bufferedInput.close(); //procura no arquivo todo pela expresso regular matcher = pattern.matcher(""); matcher.reset(filePathContent); StringBuffer newContentFile = new StringBuffer(); int countMatcher = 0; Map<String, String[]> mapGroupFile = new HashMap<String, String[]>(); while (matcher.find()) { //verifica cada ocorrncia da expresso no arquivo String[] groups = new String[matcher.groupCount()]; //pega os groups "()" do matcher para fazer a comparao com os groups do incremento que est sendo gerado for (int i = 0; i < matcher.groupCount(); i++) { groups[i] = matcher.group(i + 1); } mapGroupFile.put(matcher.group(), groups); //adiciona esse group em uma lista para ser avaliado depois countMatcher++; //isso vai contar onde esta o ltimo matcher } //valida quais incrementos so realmente novos, comparando os groups List<String> newIncrements = new LinkedList<String>(); for (String groupIncrement : mapGroupIncrement.keySet()) { String[] groups1 = mapGroupIncrement.get(groupIncrement); //groups do incremento boolean itemFound = false; for (String groupFile : mapGroupFile.keySet()) { String[] groups2 = mapGroupFile.get(groupFile); //groups do incremento if (ArrayUtil.equals(groups1, groups2)) { //se no arquivo tem o cdigo que est sendo gerado, no precisa adicionar esse incremnto itemFound = true; } } if (!itemFound) { //se no arquivo no tem o cdigo que est sendo gerado, adiciona em um array newIncrements.add(groupIncrement); } } //realiza uma quebra de linha adicional para o primeiro item do incremento, para no ficar na mesma linha do ltimo matcher no arquivo StringBuffer newIncrementSource = new StringBuffer(); int i = 0; for (String incremento : newIncrements) { if (i == 0 && incremento.indexOf("\r\n\r\n") != 0) { //s coloca quebra de linha se precisar newIncrementSource.append("\r\n"); } newIncrementSource.append(incremento); i++; } if (newIncrements.size() > 0) { //no encontrou nenhum increment no arquivo, ento procura pelo firstAfter para inserir o primeiro incremento if (countMatcher == 0 && firstAfter != null && !firstAfter.equals("")) { pattern = Pattern.compile(firstAfter, Pattern.DOTALL); matcher = pattern.matcher(""); matcher.reset(filePathContent); //esse loop s serviu para contar e achar o ltimo matcher. No consegui fazer sem isso :( countMatcher = 0; while (matcher.find()) { //verifica cada ocorrncia da expresso countMatcher++; } } //aqui vou realmente substituir os valores, j sabendo qual a ltima ocorrencia da palavra no arquivo i = 0; matcher.reset(); while (matcher.find()) { //verifica cada ocorrncia da expresso i++; if (countMatcher == i) { //se encontrou a ltima ocorrencia String matcherGroup = matcher.group(); matcher.appendReplacement(newContentFile, matcherGroup + newIncrementSource); //substitui a ultima ocorrencia do firstIncrement } } matcher.appendTail(newContentFile); } //save new file if (newContentFile.length() > 0) { FileUtil.writeFile(filePath, newContentFile.toString()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * parse content resource urls/*from w w w . jav a 2s.c o m*/ * @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(); }