Example usage for java.util.regex Matcher appendReplacement

List of usage examples for java.util.regex Matcher appendReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher appendReplacement.

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:com.dianping.lion.service.impl.DefaultConfigValueResolver.java

@Override
public String resolve(String configval, int envId) {
    if (configval == null) {
        return null;
    }/*from  www  .jav a2s .  c o  m*/
    if (configval.contains(ServiceConstants.REF_CONFIG_PREFIX)) {
        try {
            Matcher matcher = ServiceConstants.REF_EXPR_PATTERN.matcher(configval);
            boolean referenceFound = false;
            StringBuffer buffer = new StringBuffer(configval.length() * 2);
            while (matcher.find()) {
                referenceFound = true;
                String refkey = matcher.group(1);
                Config refconfig = configService.findConfigByKey(refkey);
                if (refconfig == null) {
                    logger.warn("Referenced config[" + refkey + "] not found.");
                    return null;
                }
                ConfigInstance refinstance = configService.findInstance(refconfig.getId(), envId,
                        ConfigInstance.NO_CONTEXT);
                if (refinstance == null) {
                    logger.warn("Referenced config[" + refkey + "] with env[" + envId + "] not found.");
                    return null;
                }
                String refval = refinstance.getValue();
                if (refval == null) {
                    logger.warn("Reference null-valued config[" + refkey + "] with env[" + envId + "].");
                    return null;
                }
                String refparams = matcher.group(3);
                if (StringUtils.isNotBlank(refparams)) {
                    String[] paramList = StringUtils.split(refparams, "&");
                    for (String paramstr : paramList) {
                        String[] paramentry = StringUtils.split(paramstr, "=");
                        refval = StringUtils.replace(refval, "${" + paramentry[0] + "}", paramentry[1]);
                    }
                }
                matcher.appendReplacement(buffer, Matcher.quoteReplacement(refval));
            }
            if (referenceFound) {
                matcher.appendTail(buffer);
                return buffer.toString();
            }
        } catch (RuntimeException e) {
            logger.error("Resolve referenced config expression[" + configval + "] failed.", e);
            throw e;
        }
    }
    return configval;
}

From source file:org.archive.wayback.replay.html.transformer.JSStringTransformer.java

public String transform(ReplayParseContext context, String input) {
    StringBuffer replaced = new StringBuffer(input.length());
    Matcher m = pattern.matcher(input);
    while (m.find()) {
        String rawUrl = m.group(1);
        String pre = input.substring(m.start(), m.start(1));
        String post = input.substring(m.end(1), m.end());

        String origUrl = sourceEscaping != null ? sourceEscaping.unescape(rawUrl) : rawUrl;
        String url = context.contextualizeUrl(origUrl);

        if (url != origUrl) {
            // reverse some changes made to url by contextualizeUrl method, that
            // may break assumptions in subsequent JavaScript processing.
            // eg. "http://example.org" -> "/20140101012345/http://example.org/"
            // eg. "https://domain" + ".example.org" -> "http://domain/" + ".example.org"
            // eg. "https://domain." + "example.org" -> "http://domain" + "example.org"

            // remove trailing "/" if origUrl doesn't have it.  As Wayback does not need
            // trailing slash, it may make sense to this everywhere.  Just doing this fix
            // in JavaScript for now.
            if (url.endsWith("/") && !origUrl.endsWith("/")) {
                url = url.substring(0, url.length() - 1);
            }//ww w  .  j  a va2 s  .  co m

            // add trailing "." (removed by canonicalizer) back, if origUrl has it.
            if (origUrl.endsWith(".") && !url.endsWith(".")) {
                url = url + ".";
            }

            if (sourceEscaping != null) {
                url = sourceEscaping.escape(url);
            }
        } else {
            // use the original rawUrl
            url = rawUrl;
        }
        m.appendReplacement(replaced, Matcher.quoteReplacement(pre + url + post));
    }
    m.appendTail(replaced);
    return replaced.toString();
}

From source file:org.pentaho.metadata.query.impl.sql.SqlGenerator.java

/**
 * Returns the generated SQL and additional metadata
 * //ww  w . j a  va2 s .  c  o m
 * @param model
 *          The business model.
 * @param selections
 *          The selected business columns.
 * @param conditions
 *          The conditions to apply (null = no conditions).
 * @param orderBy
 *          The ordering (null = no order by clause).
 * @param databaseMeta
 *          The meta info which determines the SQL generated.
 * @param locale
 *          The locale.
 * @param parameters
 *        Parameters to be used during query generation.
 * @param genAsPreparedStatement
 *        Forces the method generate query as prepared statement.
 * @param disableDistinct
 *          If true, disables default behavior of using DISTINCT when there are no groupings.
 * @param limit
 *          Maximum number of rows to be returned during query execution.
 * @param securityConstraint
 *          If provided, applies a global security constraint to the query.
 * 
 * @return Returns a SQL query based on a column selection, conditions and a locale.
 */
protected MappedQuery getSQL(LogicalModel model, List<Selection> selections, List<Constraint> conditions,
        List<Order> orderBy, DatabaseMeta databaseMeta, String locale, Map<String, Object> parameters,
        boolean genAsPreparedStatement, boolean disableDistinct, int limit, Constraint securityConstraint)
        throws PentahoMetadataException {

    SQLQueryModel query = new SQLQueryModel();

    // Get settings for the query model
    Object val = null;
    val = model.getProperty("delay_outer_join_conditions"); //$NON-NLS-1$
    if ((val != null) && (val instanceof Boolean)) {
        query.setDelayOuterJoinConditions(((Boolean) val).booleanValue());
    }

    Map<String, String> columnsMap = new HashMap<String, String>();

    // generate the formula objects for constraints
    Map<Constraint, SqlOpenFormula> constraintFormulaMap = new HashMap<Constraint, SqlOpenFormula>();
    for (Constraint constraint : conditions) {
        SqlOpenFormula formula = new SqlOpenFormula(model, databaseMeta, constraint.getFormula(), null,
                parameters, genAsPreparedStatement);
        formula.parseAndValidate();
        constraintFormulaMap.put(constraint, formula);
    }
    if (securityConstraint != null) {
        SqlOpenFormula formula = new SqlOpenFormula(model, databaseMeta, securityConstraint.getFormula(), null,
                parameters, genAsPreparedStatement);
        formula.parseAndValidate();
        constraintFormulaMap.put(securityConstraint, formula);
    }

    // These are the tables involved in the field selection
    //
    List<LogicalTable> tabs = getTablesInvolved(model, selections, conditions, orderBy, constraintFormulaMap,
            parameters, genAsPreparedStatement, databaseMeta, locale, securityConstraint);

    // Now get the shortest path between these tables.
    Path path = getShortestPathBetween(model, tabs);
    if (path == null) {
        throw new PentahoMetadataException(
                Messages.getErrorString("SqlGenerator.ERROR_0002_FAILED_TO_FIND_PATH")); //$NON-NLS-1$
    }

    List<LogicalTable> usedBusinessTables = path.getUsedTables();
    if (path.size() == 0) {
        // just a selection from 1 table: pick any column...
        // Otherwise, why bother, right?
        if (selections.size() > 0) {
            usedBusinessTables.add(selections.get(0).getLogicalColumn().getLogicalTable());
        }
    }

    Map<LogicalTable, String> tableAliases = null;

    if (usedBusinessTables.size() > 0) {

        // generate tableAliases mapping

        int maxAliasNameWidth = SQLDialectFactory.getSQLDialect(databaseMeta).getMaxTableNameLength();
        tableAliases = new HashMap<LogicalTable, String>();
        for (LogicalTable table : usedBusinessTables) {
            String uniqueAlias = generateUniqueAlias(table.getId(), maxAliasNameWidth, tableAliases.values());
            tableAliases.put(table, uniqueAlias);
        }

        boolean group = hasFactsInIt(model, selections, conditions, constraintFormulaMap, parameters,
                genAsPreparedStatement, databaseMeta, locale);

        generateSelect(query, model, databaseMeta, selections, disableDistinct, limit, group, locale,
                tableAliases, columnsMap, parameters, genAsPreparedStatement);
        generateFromAndWhere(query, usedBusinessTables, model, path, conditions, tableAliases,
                constraintFormulaMap, parameters, genAsPreparedStatement, databaseMeta, locale);
        if (group) {
            generateGroupBy(query, model, selections, tableAliases, parameters, genAsPreparedStatement,
                    databaseMeta, locale);
        }
        generateOrderBy(query, model, orderBy, databaseMeta, locale, tableAliases, columnsMap, parameters,
                genAsPreparedStatement);

        if (securityConstraint != null) {
            // apply current table aliases
            SqlOpenFormula securityFormula = constraintFormulaMap.get(securityConstraint);
            securityFormula.setTableAliases(tableAliases);

            // generate sql
            String sqlFormula = securityFormula.generateSQL(locale);
            query.setSecurityConstraint(sqlFormula, securityFormula.hasAggregate());
        }
    }

    // this is available to classes that override sql generation behavior
    preprocessQueryModel(query, selections, tableAliases, databaseMeta);

    // Convert temporary param placements with Sql Prepared Statement ? values
    SQLDialectInterface dialect = SQLDialectFactory.getSQLDialect(databaseMeta);
    List<String> paramNames = null;
    String sql = dialect.generateSelectStatement(query);
    Pattern p = Pattern.compile("___PARAM\\[(.*?)\\]___"); //$NON-NLS-1$
    Matcher m = p.matcher(sql);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String paramName = m.group(1);
        String repl = "?";
        if (parameters.get(paramName) instanceof Object[]) {
            Object[] paramz = (Object[]) parameters.get(paramName);
            for (int i = 1; i < paramz.length; i++) {
                repl += ", ?";
            }
        }
        m.appendReplacement(sb, repl); //$NON-NLS-1$
        if (paramNames == null) {
            paramNames = new ArrayList<String>();
        }
        paramNames.add(paramName);
    }
    m.appendTail(sb);

    String sqlStr = sb.toString();
    if (logger.isTraceEnabled()) {
        logger.trace(sqlStr);
    }
    // this is available to classes that override sql generation behavior
    String sqlOutput = processGeneratedSql(sb.toString());

    return new MappedQuery(sqlOutput, columnsMap, selections, paramNames);
}

From source file:org.esigate.impl.UrlRewriter.java

/**
 * Fixes all resources urls and returns the result.
 * /*from w w w .  j a va2 s. c  o m*/
 * @param input
 *            The html to be processed.
 * 
 * @param requestUrl
 *            The request URL.
 * @param baseUrlParam
 *            The base URL selected for this request.
 * @param visibleBaseUrl
 *            The base URL viewed by the browser.
 * @param absolute
 *            Should the rewritten urls contain the scheme host and port
 * 
 * @return the result of this renderer.
 */
public CharSequence rewriteHtml(CharSequence input, String requestUrl, String baseUrlParam,
        String visibleBaseUrl, boolean absolute) {
    StringBuffer result = new StringBuffer(input.length());
    Matcher m = URL_PATTERN.matcher(input);
    while (m.find()) {
        String url = input.subSequence(m.start(3) + 1, m.end(3) - 1).toString();
        String tag = m.group(0);
        String quote = input.subSequence(m.end(3) - 1, m.end(3)).toString();

        // Browsers tolerate urls with white spaces before or after
        String trimmedUrl = StringUtils.trim(url);

        String rewrittenUrl = url;

        trimmedUrl = unescapeHtml(trimmedUrl);

        if (trimmedUrl.isEmpty()) {
            LOG.debug("empty url kept unchanged");
        } else if (trimmedUrl.startsWith("#")) {
            LOG.debug("anchor url kept unchanged: [{}]", url);
        } else if (JAVASCRIPT_CONCATENATION_PATTERN.matcher(trimmedUrl).find()) {
            LOG.debug("url in javascript kept unchanged: [{}]", url);
        } else if (m.group(2).equalsIgnoreCase("content")) {
            if (META_REFRESH_PATTERN.matcher(tag).find()) {
                rewrittenUrl = rewriteRefresh(trimmedUrl, requestUrl, baseUrlParam, visibleBaseUrl);
                rewrittenUrl = escapeHtml(rewrittenUrl);
                LOG.debug("refresh url [{}] rewritten [{}]", url, rewrittenUrl);
            } else {
                LOG.debug("content attribute kept unchanged: [{}]", url);
            }
        } else {
            rewrittenUrl = rewriteUrl(trimmedUrl, requestUrl, baseUrlParam, visibleBaseUrl, absolute);
            rewrittenUrl = escapeHtml(rewrittenUrl);
            LOG.debug("url [{}] rewritten [{}]", url, rewrittenUrl);
        }

        m.appendReplacement(result, ""); // Copy what is between the previous match and the current match
        result.append("<");
        result.append(m.group(1));
        result.append(m.group(2));
        result.append("=");
        result.append(quote);
        result.append(rewrittenUrl);
        result.append(quote);
        if (m.groupCount() > 3) {
            result.append(m.group(4));
        }
        result.append(">");
    }

    m.appendTail(result); // Copy the reminder of the input

    return result;
}

From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Processes the input CSS to replace &#064;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
 * &#064;imports.//www  . j  a  v a2s  .  c o  m
 * 
 * @param css
 *            The current CSS containing &#064;import statements to be
 *            processed
 * @param uri
 *            The URI for the current CSS
 * @param path
 *            The path, as specified in the &#064;import statement used to
 *            import the current CSS, or null if this is the top level CSS.
 * 
 * @return The input CSS with &#064;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.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;//from  w  ww .  j  a  v  a 2s. 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:com.threerings.getdown.data.Application.java

/** Replaces the application directory and version in any argument. */
protected String processArg(String arg) {
    arg = arg.replace("%APPDIR%", _appdir.getAbsolutePath());
    arg = arg.replace("%VERSION%", String.valueOf(_version));

    // if this argument contains %ENV.FOO% replace those with the associated values looked up
    // from the environment
    if (arg.contains(ENV_VAR_PREFIX)) {
        StringBuffer sb = new StringBuffer();
        Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
        while (matcher.find()) {
            String varName = matcher.group(1), varValue = System.getenv(varName);
            if (varName == null)
                varName = "MISSING:" + varName;
            matcher.appendReplacement(sb, varValue);
        }//w w w.  ja va2 s. c om
        matcher.appendTail(sb);
        arg = sb.toString();
    }

    return arg;
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Processes the input CSS to replace &#064;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
 * &#064;imports./*w ww . j  a v  a  2s  .c  o  m*/
 *
 * @param req
 *            The request associated with the call.
 * @param css
 *            The current CSS containing &#064;import statements to be
 *            processed
 * @param res
 *            The resource for the CSS file.
 * @param path
 *            The path, as specified in the &#064;import statement used to
 *            import the current CSS, or null if this is the top level CSS.
 *
 * @return The input CSS with &#064;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:org.apache.sling.resourceresolver.impl.ResourceResolverImpl.java

private String unmangleNamespaces(String absPath) {
    if (factory.isMangleNamespacePrefixes() && absPath.contains(MANGLE_NAMESPACE_IN_PREFIX)) {
        final Matcher m = MANGLE_NAMESPACE_IN_PATTERN.matcher(absPath);
        final StringBuffer buf = new StringBuffer();
        while (m.find()) {
            final String namespace = m.group(1);
            try {

                // throws if "namespace" is not a registered
                // namespace prefix
                final Session session = getSession();
                if (session != null) {
                    session.getNamespaceURI(namespace);
                    final String replacement = MANGLE_NAMESPACE_OUT_PREFIX + namespace
                            + MANGLE_NAMESPACE_OUT_SUFFIX;
                    m.appendReplacement(buf, replacement);
                } else {
                    logger.debug("unmangleNamespaces: '{}' is not a prefix, not unmangling", namespace);
                }//from  ww  w  . j  a v a  2 s  .  c om

            } catch (final NamespaceException ne) {

                // not a valid prefix
                logger.debug("unmangleNamespaces: '{}' is not a prefix, not unmangling", namespace);

            } catch (final RepositoryException re) {

                logger.warn("unmangleNamespaces: Problem checking namespace '{}'", namespace, re);

            }
        }
        m.appendTail(buf);
        absPath = buf.toString();
    }

    return absPath;
}

From source file:org.apache.sling.resourceresolver.impl.ResourceResolverImpl.java

private String mangleNamespaces(String absPath) {
    if (factory.isMangleNamespacePrefixes() && absPath != null
            && absPath.contains(MANGLE_NAMESPACE_OUT_SUFFIX)) {
        final Matcher m = MANLE_NAMESPACE_OUT_PATTERN.matcher(absPath);

        final StringBuffer buf = new StringBuffer();
        while (m.find()) {
            final String namespace = m.group(1);
            try {

                // throws if "namespace" is not a registered
                // namespace prefix
                final Session session = getSession();
                if (session != null) {
                    session.getNamespaceURI(namespace);
                    final String replacement = MANGLE_NAMESPACE_IN_PREFIX + namespace
                            + MANGLE_NAMESPACE_IN_SUFFIX;
                    m.appendReplacement(buf, replacement);
                } else {
                    logger.debug("mangleNamespaces: '{}' is not a prefix, not mangling", namespace);
                }/*from  www .  j a  v  a 2  s.c o  m*/

            } catch (final NamespaceException ne) {

                // not a valid prefix
                logger.debug("mangleNamespaces: '{}' is not a prefix, not mangling", namespace);

            } catch (final RepositoryException re) {

                logger.warn("mangleNamespaces: Problem checking namespace '{}'", namespace, re);

            }
        }

        m.appendTail(buf);

        absPath = buf.toString();
    }

    return absPath;
}