Example usage for java.util.regex Matcher replaceFirst

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

Introduction

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

Prototype

public String replaceFirst(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces the first subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:com.jsmartframework.web.manager.FilterControl.java

private String completeHeader(HttpServletRequest httpRequest, Matcher htmlMatcher, String html) {
    // Try to place the css as the first link in the head tag
    Matcher startHeadMatcher = START_HEAD_PATTERN.matcher(html);
    if (startHeadMatcher.find()) {
        html = startHeadMatcher.replaceFirst("$1" + Matcher.quoteReplacement(headerStyles.toString()));
    } else {//from  ww w. j  a  va  2s. c  o  m
        Head head = new Head();
        head.addText(headerStyles);
        html = htmlMatcher.replaceFirst("$1" + Matcher.quoteReplacement(head.getHtml().toString()));
    }

    // Place the CSRF token as Meta tags
    String tokenName = (String) httpRequest.getAttribute(REQUEST_META_DATA_CSRF_TOKEN_NAME);
    if (tokenName != null) {
        String tokenValue = (String) httpRequest.getAttribute(REQUEST_META_DATA_CSRF_TOKEN_VALUE);
        startHeadMatcher = START_HEAD_PATTERN.matcher(html);

        Tag csrfName = new Meta().addAttribute("name", CSRF_TOKEN_NAME).addAttribute("content", tokenName);
        Tag csrfToken = new Meta().addAttribute("name", CSRF_TOKEN_VALUE).addAttribute("content", tokenValue);
        StringBuilder metaTags = csrfName.getHtml().append(csrfToken.getHtml());

        html = startHeadMatcher.replaceFirst("$1" + Matcher.quoteReplacement(metaTags.toString()));
    }
    return html;
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private String completeScripts(HttpServletRequest httpRequest, String html) {
    // Stand alone script with mapped exposed variables
    Script varScript = getExposeVarScripts(httpRequest);

    // Stand alone functions mapped via function tag
    Script funcScript = getFunctionScripts(httpRequest);

    // General page scripts executed when document is ready
    DocScript docScript = (DocScript) httpRequest.getAttribute(REQUEST_PAGE_DOC_SCRIPT_ATTR);

    StringBuilder scriptBuilder = new StringBuilder(headerScripts);
    if (varScript != null) {
        scriptBuilder.append(varScript.getHtml());
    }/*from  w  w  w .j a v  a2 s .c  o  m*/
    if (funcScript != null) {
        scriptBuilder.append(funcScript.getHtml());
    }
    if (docScript != null) {
        scriptBuilder.append(docScript.getHtml());
    }

    // Place the scripts before the last script tag inside body
    Matcher scriptMatcher = SCRIPT_BODY_PATTERN.matcher(html);
    if (scriptMatcher.find()) {
        return scriptMatcher.replaceFirst("$1" + Matcher.quoteReplacement(scriptBuilder.toString()) + "$2");
    }

    // Place the scripts before the end body tag
    Matcher bodyMatcher = CLOSE_BODY_PATTERN.matcher(html);
    if (!bodyMatcher.find()) {
        throw new RuntimeException("HTML tag [body] could not be find. Please insert the body tag in your JSP");
    }
    return bodyMatcher.replaceFirst(Matcher.quoteReplacement(scriptBuilder.toString()) + "$1");
}

From source file:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * This method takes a given document path and localizes - i.e. truncates -
 * it to the suffix left over when matching the given XPath expression
 * against the path.// w  w w.j  a  v a 2s . c o  m
 *
 * @param xpathExpression the XPath expression translated to a regular expression
 * @param path            the path to localize
 * @return <code>null</code>, if the XPath expression does not match the
 *         given path, the localized path suffix otherwise. Note that
 *         <code>""</code> is returned as a suffix when the XPath expression
 *         fully matches the path.
 */
private String localizePath(Pattern xpathExpression, String path) {
    String localizedPath = null;

    Matcher matcher = xpathExpression.matcher(path);
    if (matcher.find()) {
        String replacement = "/" + matcher.group(matcher.groupCount());
        localizedPath = matcher.replaceFirst(replacement);
    }

    return localizedPath;
}

From source file:org.yes.cart.bulkexport.csv.impl.CsvExportColumnImpl.java

/**
 * {@inheritDoc}// w  w  w.j  av  a 2  s .  co m
 */
public String getValue(final Object rawValue, final ValueAdapter adapter, final ExportTuple tuple) {
    if (getValueConstant() != null) {
        return getValueConstant();
    } else if (rawValue != null) {

        final String strValue = (String) adapter.fromRaw(rawValue, ImpExColumn.STRING, this, tuple);

        if (strValue != null) {
            if (getPattern() != null) {

                Matcher matcher = getPattern().matcher(strValue);
                if (StringUtils.isBlank(getValueRegExTemplate())) {
                    if (matcher.find()) {
                        return matcher.group(getValueRegExGroup()).trim();
                    } else {
                        return null;
                    }
                } else {
                    if (matcher.matches()) {
                        return matcher.replaceFirst(getValueRegExTemplate()).trim();
                    } else {
                        return null;
                    }
                }
            }
            return strValue;
        }
    }
    return null;

}

From source file:org.yes.cart.bulkimport.csv.impl.CsvImportColumnImpl.java

/**
 * {@inheritDoc}//from  ww  w .j  a v  a 2 s .  c o m
 */
public Object getValue(final String rawValue, final ValueAdapter adapter) {
    if (getValueConstant() != null) {
        return adapter.fromRaw(getValueConstant(), getDataType());
    } else if (rawValue != null) {
        if (getPattern() != null) {
            Matcher matcher = getPattern().matcher(rawValue);
            if (StringUtils.isBlank(getValueRegExTemplate())) {
                if (matcher.find()) {
                    return adapter.fromRaw(matcher.group(getValueRegExGroup()).trim(), getDataType());
                } else {
                    return null;
                }
            } else {
                if (matcher.matches()) {
                    return adapter.fromRaw(matcher.replaceFirst(getValueRegExTemplate()).trim(), getDataType());
                } else {
                    return null;
                }
            }
        }
        return adapter.fromRaw(rawValue, getDataType());
    }
    return null;

}

From source file:org.bibsonomy.webapp.controller.actions.BatchEditController.java

/**
 * If the referer points to /bedit{bib,url}/abc, we redirect to /abc, otherwise
 * to /user/loginUserName//from  w  w  w . j ava 2s.  co m
 * 
 * @param referer
 * @param loginUserName
 * @return
 */
private View getFinalRedirect(final String referer, final String loginUserName) {
    String redirectUrl = referer;
    if (present(referer)) {
        /*
         * if we come from bedit{bib, burl}/{group, user}/{groupname, username},
         * we remove this prefix to get back to the simple resource view in the group or user section
         */
        final Matcher prefixMatcher = BATCH_EDIT_URL_PATTERN.matcher(referer);
        if (prefixMatcher.find()) {
            redirectUrl = prefixMatcher.replaceFirst("");
        }
    }
    /*
     * if no URL is given, we redirect to the user's page
     */
    if (!present(redirectUrl)) {
        redirectUrl = UrlUtils.safeURIEncode("/user" + loginUserName); // TODO: should be done by the URLGenerator
    }
    return new ExtendedRedirectView(redirectUrl);
}

From source file:org.apache.jackrabbit.core.query.lucene.FacetHandler.java

private void extractFacetInfo(NamedList<Object> info, SolrParams solrParams) {
    // Parse the queries
    _facetQuery = new LinkedHashMap<String, Long>();
    NamedList<Long> fq = (NamedList<Long>) info.get("facet_queries");
    if (fq != null) {
        for (Map.Entry<String, Long> entry : fq) {
            _facetQuery.put(entry.getKey(), entry.getValue());
        }/*from   w w w.  j av a  2s.c o  m*/
    }

    // Parse the facet info into fields
    // TODO?? The list could be <int> or <long>? If always <long> then we can switch to <Long>
    NamedList<NamedList<Number>> ff = (NamedList<NamedList<Number>>) info.get("facet_fields");
    Map<String, FieldType> fieldTypeMap = new HashMap<>();
    if (ff != null) {
        _facetFields = new ArrayList<FacetField>(ff.size());
        _limitingFacets = new ArrayList<FacetField>(ff.size());
        long minsize = totalSize;
        for (Map.Entry<String, NamedList<Number>> facet : ff) {
            String key = StringUtils.substringBeforeLast(facet.getKey(),
                    SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR);
            String fieldInIndex = StringUtils.substringAfterLast(facet.getKey(),
                    SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR);
            FacetField f = new FacetField(key);
            if (!fieldTypeMap.containsKey(key)) {
                try {
                    //Find a key like f.field_name#unknownumber.facet.nodetype
                    Pattern facetNodetype = Pattern.compile("f\\." + key + "#[0-9]+\\.facet\\.nodetype");
                    String nodetypeName = null;
                    Iterator<String> parameterNamesIterator = solrParams.getParameterNamesIterator();
                    while (parameterNamesIterator.hasNext()) {
                        String next = parameterNamesIterator.next();
                        if (facetNodetype.matcher(next).matches()) {
                            nodetypeName = solrParams.get(next);
                            break;
                        }
                    }
                    ExtendedPropertyDefinition epd = NodeTypeRegistry.getInstance().getNodeType(nodetypeName)
                            .getPropertyDefinition(key);
                    fieldTypeMap.put(key, getType(epd));
                } catch (NoSuchNodeTypeException e) {
                    log.error(e.getMessage(), e);
                }
            }
            for (Map.Entry<String, Number> entry : facet.getValue()) {
                String facetValue = entry.getKey();
                String query = fieldTypeMap.get(key).toInternal(entry.getKey());
                Matcher matcher = valueWithQuery.matcher(facetValue);
                if (matcher.matches()) {
                    query = matcher.group(2);
                    facetValue = matcher.replaceFirst("$1");
                }
                f.add(facetValue, entry.getValue().longValue());
                f.getValues().get(f.getValueCount() - 1).setFilterQuery(
                        ClientUtils.escapeQueryChars(fieldInIndex) + ":" + ClientUtils.escapeQueryChars(query));
            }

            _facetFields.add(f);
            FacetField nl = f.getLimitingFields(minsize);
            if (nl.getValueCount() > 0) {
                _limitingFacets.add(nl);
            }
        }
    }

    // Parse date facets
    NamedList<NamedList<Object>> df = (NamedList<NamedList<Object>>) info.get("facet_dates");
    if (df != null) {
        // System.out.println(df);
        _facetDates = new ArrayList<FacetField>(df.size());
        for (Map.Entry<String, NamedList<Object>> facet : df) {
            // System.out.println("Key: " + facet.getKey() + " Value: " + facet.getValue());
            NamedList<Object> values = facet.getValue();
            String gap = (String) values.get("gap");
            Date end = (Date) values.get("end");
            FacetField f = new FacetField(StringUtils.substringBeforeLast(facet.getKey(),
                    SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR), gap, end);

            for (Map.Entry<String, Object> entry : values) {
                try {
                    String key = StringUtils.substringBeforeLast(entry.getKey(),
                            SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR);
                    String query = StringUtils.substringAfterLast(entry.getKey(),
                            SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR);
                    f.add(key, Long.parseLong(entry.getValue().toString()));
                    if (!StringUtils.isEmpty(query)) {
                        String rangePrefix = null;
                        if (query.contains(RANGEFROM_EXCLUSIVE_PREFIX)) {
                            rangePrefix = RANGEFROM_EXCLUSIVE_PREFIX;
                        } else if (query.contains(RANGEFROM_INCLUSIVE_PREFIX)) {
                            rangePrefix = RANGEFROM_INCLUSIVE_PREFIX;
                        }
                        if (!StringUtils.isEmpty(rangePrefix)) {
                            f.getValues().get(f.getValueCount() - 1)
                                    .setFilterQuery(ClientUtils
                                            .escapeQueryChars(StringUtils.substringBefore(query, rangePrefix))
                                            + rangePrefix + StringUtils.substringAfter(query, rangePrefix));
                        }
                    }
                } catch (NumberFormatException e) {
                    // Ignore for non-number responses which are already handled above
                }
            }

            _facetDates.add(f);
        }
    }

    // Parse range facets
    NamedList<NamedList<Object>> rf = (NamedList<NamedList<Object>>) info.get("facet_ranges");
    if (rf != null) {
        // System.out.println(df);
        _facetRanges = new ArrayList<RangeFacet>(rf.size());
        for (Map.Entry<String, NamedList<Object>> facet : rf) {
            NamedList<Object> values = facet.getValue();
            Object rawGap = values.get("gap");

            RangeFacet rangeFacet;
            if (rawGap instanceof Number) {
                Number gap = (Number) rawGap;
                Number start = (Number) values.get("start");
                Number end = (Number) values.get("end");

                Number before = (Number) values.get("before");
                Number after = (Number) values.get("after");

                rangeFacet = new RangeFacet.Numeric(StringUtils.substringBeforeLast(facet.getKey(),
                        SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR), start, end, gap, before, after);
            } else {
                String gap = (String) rawGap;
                Date start = (Date) values.get("start");
                Date end = (Date) values.get("end");

                Number before = (Number) values.get("before");
                Number after = (Number) values.get("after");

                rangeFacet = new RangeFacet.Date(StringUtils.substringBeforeLast(facet.getKey(),
                        SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR), start, end, gap, before, after);
            }

            NamedList<Integer> counts = (NamedList<Integer>) values.get("counts");
            for (Map.Entry<String, Integer> entry : counts) {
                try {
                    String key = StringUtils.substringBeforeLast(entry.getKey(),
                            SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR);
                    String query = StringUtils.substringAfterLast(entry.getKey(),
                            SimpleJahiaJcrFacets.PROPNAME_INDEX_SEPARATOR);

                    rangeFacet.addCount(key, entry.getValue());

                    if (!StringUtils.isEmpty(query)) {
                        String rangePrefix = null;
                        if (query.contains(RANGEFROM_EXCLUSIVE_PREFIX)) {
                            rangePrefix = RANGEFROM_EXCLUSIVE_PREFIX;
                        } else if (query.contains(RANGEFROM_INCLUSIVE_PREFIX)) {
                            rangePrefix = RANGEFROM_INCLUSIVE_PREFIX;
                        }
                        if (!StringUtils.isEmpty(rangePrefix)) {
                            ((RangeFacet.Count) rangeFacet.getCounts().get(rangeFacet.getCounts().size() - 1))
                                    .setFilterQuery(ClientUtils
                                            .escapeQueryChars(StringUtils.substringBefore(query, rangePrefix))
                                            + rangePrefix + StringUtils.substringAfter(query, rangePrefix));
                        }
                    }
                } catch (NumberFormatException e) {
                    // Ignore for non-number responses which are already handled above
                }
            }

            _facetRanges.add(rangeFacet);
        }
    }
}

From source file:com.wavemaker.studio.StudioService.java

@ExposeToClient
public Hashtable<String, Object> getLogUpdate(String filename, String lastStamp) throws IOException {
    java.io.File logFolder = new java.io.File(System.getProperty("catalina.home") + "/logs/ProjectLogs",
            this.projectManager.getCurrentProject().getProjectName());
    java.io.File logFile = new java.io.File(logFolder, filename);
    if (!logFile.exists()) {
        Hashtable<String, Object> PEmpty = new Hashtable<String, Object>();
        PEmpty.put(LOG_UPDATE_LOGS, "");
        PEmpty.put(LOG_UPDATE_LAST_STAMP, 0);
        return PEmpty;
    }/*from  w  w w.  j  a  v  a2 s  .  c om*/
    InputStream inputStream = new FileInputStream(logFile);
    try {
        String logFileContent = IOUtils.toString(inputStream);
        if (lastStamp.length() > 0) {
            // remove everything up to START_WM_LOG_LINE lastStamp
            Pattern pattern = Pattern.compile("^.*START_WM_LOG_LINE\\s+" + lastStamp + "\\s+", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(logFileContent);
            logFileContent = matcher.replaceFirst("");
            // Replace everything from the start of whats left of this line to END_WM_LOG_LINE
            logFileContent = logFileContent.replaceFirst("^.*?END_WM_LOG_LINE", "");
        }

        Pattern htmlTagPattern = Pattern
                .compile("(START_WM_LOG_LINE\\s+\\d+\\:\\d+\\:\\d+,\\d+\\s+)(\\S+) (\\(.*\\))");
        Matcher htmlTagMatcher = htmlTagPattern.matcher(logFileContent);
        logFileContent = htmlTagMatcher
                .replaceAll("$1<span class='LogType$2'>$2</span> <span class='LogLocation'>$3</span>");

        Pattern p = Pattern.compile("START_WM_LOG_LINE\\s+\\d+\\:\\d+\\:\\d+,\\d+");
        Matcher m = p.matcher(logFileContent);
        String timestamp = "";
        while (m.find()) {
            timestamp = m.group();
            timestamp = timestamp.replaceFirst("START_WM_LOG_LINE\\s+.*?", "");
        }
        Hashtable<String, Object> logUpdate = new Hashtable<String, Object>();
        logFileContent = m.replaceAll(""); // remove all START_WM_LOG_LINE xxx:xxx:xxx,xxx
        logFileContent = logFileContent.replaceAll(" END_WM_LOG_LINE", "");
        if (logFileContent.matches("^\\s+$")) {
            logFileContent = "";
        }
        logFileContent = logFileContent.replaceAll("(\\S+)(\\n\\r|\\r\\n|\\n|\\r)", "$1<br/>");
        Pattern trimPattern = Pattern.compile("^\\s*", Pattern.MULTILINE);
        Matcher trimMatcher = trimPattern.matcher(logFileContent);
        logFileContent = trimMatcher.replaceAll("");
        logUpdate.put(LOG_UPDATE_LOGS, logFileContent);
        logUpdate.put(LOG_UPDATE_LAST_STAMP, timestamp);
        return logUpdate;
    } finally {
        inputStream.close();
    }
}

From source file:nya.miku.wishmaster.chans.newnullchan.NewNullchanModule.java

@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    updateSession(listener, task);/*from  w w  w .j ava  2  s.  c o  m*/

    String url = null;
    String parent = null;
    String comment = model.comment;

    if (model.threadNumber != null) {
        Pattern referencePattern = Pattern.compile("^\\s*>>(\\d+)");
        Matcher matcher = referencePattern.matcher(comment);
        if (matcher.find()) {
            parent = matcher.group(1);
            JSONObject post = getPost(parent, listener, task);
            if (post.optString("threadId").equals(model.threadNumber)) {
                comment = matcher.replaceFirst("");
            } else {
                parent = getOpPostID(model, listener, task);
            }
        } else {
            parent = getOpPostID(model, listener, task);
        }
        url = getUsingUrl() + "api/thread/reply?parent=" + parent + "&session=" + sessionId;
    } else {
        url = getUsingUrl() + "api/thread/create?board=" + model.boardName + "&session=" + sessionId;
    }
    JSONObject jsonPayload = new JSONObject();
    jsonPayload.put("board", model.boardName);
    jsonPayload.put("thread", model.threadNumber != null ? model.threadNumber : JSONObject.NULL);
    jsonPayload.put("parent", parent != null ? parent : JSONObject.NULL);
    jsonPayload.put("message", comment);

    if (model.attachments != null && model.attachments.length > 0) {
        JSONArray images = new JSONArray();
        for (int i = 0; i < model.attachments.length; ++i) {
            images.put(uploadFile(model.attachments[i], listener, task));
        }
        jsonPayload.put("images", images);
    }

    String captchaId = null;
    try {
        captchaId = captchas.keySet().iterator().next();
    } catch (NoSuchElementException e) {
    }
    captchaId = validateCaptcha(captchaId, listener, task);
    jsonPayload.put("captcha", captchaId != null ? captchaId : JSONObject.NULL);
    JSONEntry payload = new JSONEntry(jsonPayload);
    HttpRequestModel request = HttpRequestModel.builder().setPOST(payload).setNoRedirect(true).build();
    String response = null;
    JSONObject result = null;
    try {
        response = HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, null, task, true);
    } catch (HttpWrongStatusCodeException e1) {
        try {
            result = new JSONObject(e1.getHtmlString());
        } catch (JSONException e2) {
        }
        if (result != null) {
            int errorCode = result.optInt("error", 0);
            if (errorCode == 403) {
                String require = result.getJSONObject("details").optString("require");
                if (require.equals("captcha")) {
                    throw new NewNullchanCaptchaException();
                } else
                    throw new Exception(result.optString("message"));
            }
        }
        checkCloudflareError(e1, url);
        throw e1;
    }
    result = new JSONObject(response);
    if (!result.optBoolean("ok", false)) {
        JSONArray errors = result.optJSONArray("errors");
        if (errors != null && errors.length() > 0) {
            String errorMessage = errors.optString(0, "");
            if (errorMessage.length() > 0)
                throw new Exception(errorMessage);
        }
        throw new Exception(response);
    }
    JSONObject post = result.getJSONObject("post");
    UrlPageModel urlModel = new UrlPageModel();
    urlModel.type = UrlPageModel.TYPE_THREADPAGE;
    urlModel.boardName = post.optString("boardDir", model.boardName);
    urlModel.chanName = getChanName();
    urlModel.threadNumber = post.optString("threadId", model.threadNumber);
    urlModel.postNumber = post.optString("id", null);
    return this.buildUrl(urlModel);
}