Example usage for java.util.regex Matcher replaceAll

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

Introduction

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

Prototype

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

Source Link

Document

Replaces every 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:org.jumpmind.metl.ui.views.admin.LoggingPanel.java

@Override
@SuppressWarnings("unchecked")
public Object onBackgroundDataRefresh() {
    StringBuilder builder = null;
    if (logFile != null && logFile.exists() && autoRefreshOn.getValue()) {
        try {//from  ww  w.  jav a  2s .  c om
            builder = new StringBuilder();
            Pattern pattern = Pattern.compile("^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d .*");
            String filterValue = filter.getValue();
            boolean isFiltering = !StringUtils.isBlank(filterValue);
            Pattern filter = Pattern.compile("(.*)(" + filterValue + ")(.*)");
            ReversedLinesFileReader reader = new ReversedLinesFileReader(logFile);
            try {
                int lines = Integer.parseInt(bufferSize.getValue());
                int counter = 0;
                String line = null;
                do {
                    if (!isFiltering) {
                        line = StringEscapeUtils.escapeHtml(reader.readLine());
                    } else {
                        StringBuilder multiLine = new StringBuilder();
                        while ((line = StringEscapeUtils.escapeHtml(reader.readLine())) != null) {
                            if (pattern.matcher(line).matches()) {
                                multiLine.insert(0, line);
                                line = multiLine.toString();
                                break;
                            } else {
                                multiLine.insert(0, line + "<br/>");
                                counter++;
                            }
                        }
                    }

                    if (line != null) {
                        boolean showLine = !isFiltering;
                        if (isFiltering) {
                            Matcher matcher = filter.matcher(line);
                            if (showLine = matcher.matches()) {
                                line = matcher.replaceAll("$1<font color='red'>$2</font>$3");
                            }
                        }
                        if (showLine) {
                            builder.insert(0, line + "<br/>");
                            counter++;
                        }
                    }
                } while (line != null && counter < lines);
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return builder;
}

From source file:com.gs.obevo.db.apps.reveng.AbstractDdlReveng.java

/**
 * TODO move to Sybase subclass.//  w  ww .  ja  va2  s  .  c om
 */
public String removeQuotesFromProcxmode(String input) {
    Pattern compile = Pattern.compile("sp_procxmode '(?:\")(.*?)(?:\")'", Pattern.DOTALL);

    Matcher matcher = compile.matcher(input);
    if (matcher.find()) {
        return matcher.replaceAll("sp_procxmode '" + matcher.group(1) + "'");
    } else {
        return input;
    }
}

From source file:org.cfeclipse.cfml.frameworks.actions.BaseAction.java

/**
 * @param actionText//  w w  w  . j  ava  2  s .co  m
 * @return
 */
private String doXPathFunctions(String actionText) {
    String xpathfunctions = "xpath\\s*\\(\\s*\"([^\"]*)\"\\s*,\\s*\"([^\"]*)\"\\)"; //for xpath .. working regEx xpath\s*\(\s*"([^"]*)"\s*,\s*"([^"]*)"\)

    Pattern stage2Pattern = Pattern.compile(xpathfunctions);
    Matcher stage2Matcher = stage2Pattern.matcher(actionText);

    while (stage2Matcher.find()) {
        String string = doXPath(stage2Matcher.group(1), stage2Matcher.group(2));
        actionText = stage2Matcher.replaceAll(string);
    }
    return actionText;
}

From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.ReplaceRegExpOperation.java

/**
 * Returns modified XML Document of the job configuration.
 *
 * Replace the strings in the job configuration: only applied to strings in text nodes, so the XML structure is never destroyed.
 *
 * @param doc//from www.  ja v  a  2 s  .  c o  m
 *            XML Document of the job to be copied (job/NAME/config.xml)
 * @param env
 *            Variables defined in the build.
 * @param logger
 *            The output stream to log.
 * @return modified XML Document. Return null if an error occurs.
 * @see jp.ikedam.jenkins.plugins.jobcopy_builder.AbstractXmlJobcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(final Document doc, final EnvVars env, final PrintStream logger) {
    final String fromStr = getFromStr();
    String toStr = getToStr();

    if (StringUtils.isEmpty(fromStr)) {
        logger.println("From String is empty");
        return null;
    }
    if (toStr == null) {
        toStr = "";
    }
    final String expandedFromStr = isExpandFromStr() ? env.expand(fromStr) : maskSpecialChars(fromStr);

    Pattern pattern;
    try {
        pattern = Pattern.compile(expandedFromStr);
    } catch (final PatternSyntaxException e) {
        logger.println("Error on regular expression: " + e.getMessage());
        return null;
    }

    String expandedToStr = isExpandToStr() ? env.expand(toStr) : maskSpecialChars(toStr);
    if (StringUtils.isEmpty(expandedFromStr)) {
        logger.println("From String got to be empty");
        return null;
    }
    if (expandedToStr == null) {
        expandedToStr = "";
    }

    logger.print("Replacing with RegExp: " + expandedFromStr + " -> " + expandedToStr);
    try {
        // Retrieve all text nodes.
        final NodeList textNodeList = getNodeList(doc, "//text()");

        // Perform replacing to all text nodes.
        // NodeList does not implement Collection, and foreach is not usable.
        for (int i = 0; i < textNodeList.getLength(); ++i) {
            final Node node = textNodeList.item(i);
            final String nodeValue = node.getNodeValue();
            String newNodeValue = nodeValue;
            final Matcher matcher = pattern.matcher(nodeValue);
            // check all occurance
            while (matcher.find()) {
                newNodeValue = matcher.replaceAll(expandedToStr);
            }
            node.setNodeValue(newNodeValue);
        }
        logger.println("");

        return doc;
    } catch (final Exception e) {
        logger.print("Error occured in XML operation");
        e.printStackTrace(logger);
        return null;
    }
}

From source file:de.escidoc.core.test.sm.ReportIT.java

/**
 * triggers preprocessing via jmx-console.
 *
 * @param methodIndex methodIndex/*from   ww  w .ja va  2s.co  m*/
 * @throws Exception If anything fails.
 */
private void triggerPreprocessing(final String methodIndex) throws Exception {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.YEAR, 2009);

    String urlParameters = PREPROCESSING_URL + cal.getTimeInMillis();

    Matcher methodIndexMatcher = METHOD_INDEX_PATTERN.matcher(urlParameters);
    urlParameters = methodIndexMatcher.replaceAll(methodIndex);

    String httpUrl = getFrameworkUrl() + Constants.ESCIDOC_BASE_URI + urlParameters;
    long time = System.currentTimeMillis();
    HttpResponse result = HttpHelper.executeHttpRequest(Constants.HTTP_METHOD_GET, httpUrl, null, "", null);
    String response = EntityUtils.toString(result.getEntity(), HTTP.UTF_8);
    response = " preprocessing needed " + (System.currentTimeMillis() - time) + response;
    try {
        assertMatches("String does not match es expected. " + response,
                "Operation completed successfully without a return value", response);
    } catch (final AssertionError e) {
        if (methodIndex.equals(STATISTIC_PREPROCESSOR_METHOD_INDEX)) {
            triggerPreprocessing("1");
        } else {
            throw e;
        }
    }
}

From source file:org.apereo.services.persondir.support.ldap.LdapPersonAttributeDao.java

@Override
protected List<IPersonAttributes> getPeopleForQuery(final LogicalFilterWrapper queryBuilder,
        final String queryUserName) {
    final String generatedLdapQuery = queryBuilder.encode();

    //If no query is generated return null since the query cannot be run
    if (StringUtils.isBlank(generatedLdapQuery)) {
        return null;
    }/*from   www. j  a va  2 s.  c o  m*/

    //Insert the generated query into the template if it is configured
    final String ldapQuery;
    if (this.queryTemplate == null) {
        ldapQuery = generatedLdapQuery;
    } else {
        final Matcher queryMatcher = QUERY_PLACEHOLDER.matcher(this.queryTemplate);
        ldapQuery = queryMatcher.replaceAll(generatedLdapQuery);
        if (logger.isDebugEnabled()) {
            logger.debug("Final ldapQuery after applying queryTemplate: '" + ldapQuery + "'");
        }
    }

    //Execute the query
    @SuppressWarnings("unchecked")
    final List<Map<String, List<Object>>> queryResults = this.ldapTemplate.search(this.baseDN, ldapQuery,
            this.searchControls, MAPPER);

    final List<IPersonAttributes> peopleAttributes = new ArrayList<>(queryResults.size());
    for (final Map<String, List<Object>> queryResult : queryResults) {
        final IPersonAttributes person;

        // Choose a username from the best available option
        final String userNameAttribute = this.getConfiguredUserNameAttribute();
        if (this.isUserNameAttributeConfigured() && queryResult.containsKey(userNameAttribute)) {
            // Option #1:  An attribute is named explicitly in the config, 
            // and that attribute is present in the results from LDAP;  use it
            person = new CaseInsensitiveAttributeNamedPersonImpl(userNameAttribute, queryResult);
        } else if (queryUserName != null) {
            // Option #2:  Use the userName attribute provided in the query 
            // parameters.  (NB:  I'm not entirely sure this choice is 
            // preferable to Option #3.  Keeping it because it most closely 
            // matches the legacy behavior there the new option -- Option #1 
            // -- doesn't apply.  ~drewwills)
            person = new CaseInsensitiveNamedPersonImpl(queryUserName, queryResult);
        } else {
            // Option #3:  Create the IPersonAttributes doing a best-guess 
            // at a userName attribute
            person = new CaseInsensitiveAttributeNamedPersonImpl(userNameAttribute, queryResult);
        }

        peopleAttributes.add(person);
    }

    return peopleAttributes;
}

From source file:com.clustercontrol.custom.factory.RunCustomString.java

/**
 * ????<br/>/*  w  w  w  .  j  av  a 2  s  .  c om*/
 * 
 * @throws HinemosUnknown
 *             ??????
 * @throws MonitorNotFound
 *             ??????
 * @throws CustomInvalid
 *             ??????
 */
@Override
public void monitor() throws HinemosUnknown, MonitorNotFound, CustomInvalid {
    // Local Variables
    MonitorInfo monitor = null;

    int priority = PriorityConstant.TYPE_UNKNOWN;
    String facilityPath = "";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(HinemosTime.getTimeZone());
    String msg = "";
    String msgOrig = "";

    boolean isMonitorJob = result.getRunInstructionInfo() != null;

    // MAIN
    try {
        monitor = new MonitorSettingControllerBean().getMonitor(result.getMonitorId());

        String executeDate = dateFormat.format(result.getExecuteDate());
        String exitDate = dateFormat.format(result.getExitDate());
        String collectDate = dateFormat.format(result.getCollectDate());

        facilityPath = new RepositoryControllerBean().getFacilityPath(result.getFacilityId(), null);
        if (result.getTimeout() || result.getStdout() == null || result.getStdout().isEmpty()
                || result.getResults() == null) {
            if (m_log.isDebugEnabled()) {
                m_log.debug("command monitoring : timeout or no stdout [" + result + "]");
            }
            // if command execution failed (timeout or no stdout)
            if (isMonitorJob || monitor.getMonitorFlg()) {
                msg = "FAILURE : command execution failed (timeout, no stdout or not unexecutable command)...";

                msgOrig = "FAILURE : command execution failed (timeout, no stdout or unexecutable command)...\n\n"
                        + "COMMAND : " + result.getCommand() + "\n" + "COLLECTION DATE : " + collectDate + "\n"
                        + "executed at " + executeDate + "\n" + "exited (or timeout) at " + exitDate + "\n"
                        + "EXIT CODE : " + (result.getExitCode() != null ? result.getExitCode() : "timeout")
                        + "\n\n" + "[STDOUT]\n" + result.getStdout() + "\n" + "[STDERR]\n" + result.getStderr()
                        + "\n";

                // 
                if (!isMonitorJob) {
                    notify(PriorityConstant.TYPE_UNKNOWN, monitor, result.getFacilityId(), facilityPath, null,
                            msg, msgOrig, HinemosModuleConstant.MONITOR_CUSTOM_S);
                } else {
                    // 
                    this.monitorJobEndNodeList.add(new MonitorJobEndNode(result.getRunInstructionInfo(),
                            HinemosModuleConstant.MONITOR_CUSTOM_S, makeJobOrgMessage(monitor, msgOrig), "",
                            RunStatusConstant.END, MonitorJobWorker.getReturnValue(
                                    result.getRunInstructionInfo(), PriorityConstant.TYPE_UNKNOWN)));
                }
            }
        } else {
            // if command stdout was returned Monitor
            msg = result.getStdout();
            // Stdout???
            Pattern patternMsg = Pattern.compile("\r\n$|\n$");
            Matcher matcherMsg = patternMsg.matcher(msg);
            msg = matcherMsg.replaceAll("");

            if (m_log.isDebugEnabled()) {
                m_log.debug("command monitoring : values [" + msg + "]");
            }

            // ?
            if (monitor.getCollectorFlg()) { // collector each value
                List<StringSample> sampleList = new ArrayList<StringSample>();
                StringSample sample = new StringSample(new Date(HinemosTime.currentTimeMillis()),
                        monitor.getMonitorId());
                // 
                sample.set(result.getFacilityId(), "custom", msg);

                sampleList.add(sample);
                if (!sampleList.isEmpty()) {
                    CollectStringDataUtil.store(sampleList);
                }
            }

            // 
            int orderNo = 0;
            if (isMonitorJob || monitor.getMonitorFlg()) { // monitor each value
                for (MonitorStringValueInfo stringValueInfo : monitor.getStringValueInfo()) {
                    ++orderNo;
                    if (m_log.isDebugEnabled()) {
                        m_log.info(String.format(
                                "monitoring (monitorId = %s, orderNo = %d, patten = %s, enabled = %s, casesensitive = %s)",
                                monitor.getMonitorId(), orderNo, stringValueInfo.getPattern(),
                                stringValueInfo.getValidFlg(), stringValueInfo.getCaseSensitivityFlg()));
                    }
                    if (!stringValueInfo.getValidFlg()) {
                        // ?????
                        continue;
                    }
                    // ?
                    if (m_log.isDebugEnabled()) {
                        m_log.debug(String.format("filtering customtrap (regex = %s, Msg = %s",
                                stringValueInfo.getPattern(), msg));
                    }
                    try {
                        Pattern pattern = null;
                        if (stringValueInfo.getCaseSensitivityFlg()) {
                            // ?????
                            pattern = Pattern.compile(stringValueInfo.getPattern(),
                                    Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
                        } else {
                            // ???
                            pattern = Pattern.compile(stringValueInfo.getPattern(), Pattern.DOTALL);
                        }
                        Matcher matcher = pattern.matcher(msg);
                        if (matcher.matches()) {
                            if (stringValueInfo.getProcessType()) {
                                msgOrig = MessageConstant.LOGFILE_PATTERN.getMessage() + "="
                                        + stringValueInfo.getPattern() + "\n"
                                        + MessageConstant.LOGFILE_LINE.getMessage() + "=" + msg + "\n\n"
                                        + "COMMAND : " + result.getCommand() + "\n" + "COLLECTION DATE : "
                                        + collectDate + "\n" + "executed at " + executeDate + "\n"
                                        + "exited (or timeout) at " + exitDate + "\n" + "EXIT CODE : "
                                        + (result.getExitCode() != null ? result.getExitCode() : "timeout")
                                        + "\n\n" + "[STDOUT]\n" + result.getStdout() + "\n\n" + "[STDERR]\n"
                                        + result.getStderr() + "\n";

                                msg = makeMsg(stringValueInfo, msg);

                                priority = stringValueInfo.getPriority();
                                if (!isMonitorJob) {
                                    // 
                                    notify(priority, monitor, result.getFacilityId(), facilityPath,
                                            stringValueInfo.getPattern(), msg, msgOrig,
                                            HinemosModuleConstant.MONITOR_CUSTOM_S);
                                } else {
                                    // 
                                    this.monitorJobEndNodeList
                                            .add(new MonitorJobEndNode(result.getRunInstructionInfo(),
                                                    HinemosModuleConstant.MONITOR_CUSTOM_S,
                                                    makeJobOrgMessage(monitor, msgOrig), "",
                                                    RunStatusConstant.END, MonitorJobWorker.getReturnValue(
                                                            result.getRunInstructionInfo(), priority)));
                                }
                            } else {
                                m_log.debug(String.format("not ProcessType (regex = %s, Msg = %s",
                                        stringValueInfo.getPattern(), result.getStdout()));
                            }
                            break;// Syslog??????
                        }
                    } catch (RuntimeException e) {
                        m_log.warn("filtering failure. (regex = " + stringValueInfo.getPattern() + ") . "
                                + e.getMessage(), e);
                    }
                }
            }
        }
    } catch (MonitorNotFound | CustomInvalid | HinemosUnknown e) {
        m_log.warn("unexpected internal failure occurred. [" + result + "]");
        throw e;
    } catch (Exception e) {
        m_log.warn("unexpected internal failure occurred. [" + result + "]", e);
        throw new HinemosUnknown("unexpected internal failure occurred. [" + result + "]", e);
    }
}

From source file:de.escidoc.core.test.sm.ReportTest.java

/**
 * triggers preprocessing via jmx-console.
 *
 * @param methodIndex methodIndex/*from w ww  .  j a  v  a 2 s  . c o  m*/
 * @throws Exception If anything fails.
 */
private void triggerPreprocessing(final String methodIndex) throws Exception {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.YEAR, 2009);

    String urlParameters = PREPROCESSING_URL + cal.getTimeInMillis();

    Matcher methodIndexMatcher = METHOD_INDEX_PATTERN.matcher(urlParameters);
    urlParameters = methodIndexMatcher.replaceAll(methodIndex);

    String httpUrl = HttpHelper.createUrl(Constants.PROTOCOL, Constants.HOST_PORT,
            Constants.ESCIDOC_BASE_URI + urlParameters);
    long time = System.currentTimeMillis();
    HttpResponse result = HttpHelper.executeHttpRequest(Constants.HTTP_METHOD_GET, httpUrl, null, "", null);
    String response = EntityUtils.toString(result.getEntity(), HTTP.UTF_8);
    response = " preprocessing needed " + (System.currentTimeMillis() - time) + response;
    try {
        assertMatches("String does not match es expected. " + response,
                "Operation completed successfully without a return value", response);
    } catch (final AssertionError e) {
        if (methodIndex.equals(STATISTIC_PREPROCESSOR_METHOD_INDEX)) {
            triggerPreprocessing("1");
        } else {
            throw e;
        }
    }
}

From source file:com.fujitsu.dc.core.rs.odata.ODataLinksResource.java

/**
 * POST??? link??.//from   ww w .j  av a  2  s . co m
 * ????204.?????Location????
 * InsertLink Request
 * If an InsertLink Request is successful, the response MUST have a 204 status code,
 * as specified in [RFC2616], and contain an empty response body.
 * @param uriInfo UriInfo
 * @param reqBody 
 * @return JAX-RS Response
 */
@POST
public Response createLink(@Context UriInfo uriInfo, final Reader reqBody) {

    // 
    this.checkWriteAccessContext();

    // ???
    this.odataResource.beforeLinkCreate(this.sourceEntity, this.targetNavProp);

    // $links ? POST?Nav Prop??????????
    if (this.targetEntityKey != null) {
        throw DcCoreException.OData.KEY_FOR_NAVPROP_SHOULD_NOT_BE_SPECIFIED;
    }
    log.debug("POSTING $LINK");
    OEntityId newTargetEntity = parseRequestUri(DcCoreUtils.createUriInfo(uriInfo, NUM_LEVELS_FROM_SVC_ROOT),
            reqBody);

    // URL????Body?????????
    Pattern p = Pattern.compile("(.+)/([^/]+)$");
    Matcher m = p.matcher(newTargetEntity.getEntitySetName());
    String bodyNavProp = m.replaceAll("$2");
    String targetEntitySetName = null;
    // ???$links????Account
    if (ReceivedMessage.EDM_NPNAME_FOR_ACCOUNT.equals(this.targetNavProp)) {
        targetEntitySetName = Account.EDM_TYPE_NAME;
        // ???$links????ReceivedMessage
    } else if (Account.EDM_NPNAME_FOR_RECEIVED_MESSAGE.equals(this.targetNavProp)) {
        targetEntitySetName = ReceivedMessage.EDM_TYPE_NAME;
    } else {
        targetEntitySetName = this.targetNavProp.substring(1);
    }
    if (!targetEntitySetName.equals(bodyNavProp)) {
        throw DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(Common.DC_FORMAT_PATTERN_URI);
    }

    this.odataProducer.createLink(sourceEntity, targetNavProp, newTargetEntity);
    return noContent();
}

From source file:io.personium.core.rs.odata.ODataLinksResource.java

/**
 * POST??? link??./*w w  w.  j av a  2 s.  co  m*/
 * ????204.?????Location????
 * InsertLink Request
 * If an InsertLink Request is successful, the response MUST have a 204 status code,
 * as specified in [RFC2616], and contain an empty response body.
 * @param uriInfo UriInfo
 * @param reqBody 
 * @return JAX-RS Response
 */
@POST
public Response createLink(@Context UriInfo uriInfo, final Reader reqBody) {

    // 
    this.checkWriteAccessContext();

    // ???
    this.odataResource.beforeLinkCreate(this.sourceEntity, this.targetNavProp);

    // $links ? POST?Nav Prop??????????
    if (this.targetEntityKey != null) {
        throw PersoniumCoreException.OData.KEY_FOR_NAVPROP_SHOULD_NOT_BE_SPECIFIED;
    }
    log.debug("POSTING $LINK");
    OEntityId newTargetEntity = parseRequestUri(
            PersoniumCoreUtils.createUriInfo(uriInfo, NUM_LEVELS_FROM_SVC_ROOT), reqBody);

    // URL????Body?????????
    Pattern p = Pattern.compile("(.+)/([^/]+)$");
    Matcher m = p.matcher(newTargetEntity.getEntitySetName());
    String bodyNavProp = m.replaceAll("$2");
    String targetEntitySetName = null;
    // ???$links????Account
    if (ReceivedMessage.EDM_NPNAME_FOR_ACCOUNT.equals(this.targetNavProp)) {
        targetEntitySetName = Account.EDM_TYPE_NAME;
        // ???$links????ReceivedMessage
    } else if (Account.EDM_NPNAME_FOR_RECEIVED_MESSAGE.equals(this.targetNavProp)) {
        targetEntitySetName = ReceivedMessage.EDM_TYPE_NAME;
    } else {
        targetEntitySetName = this.targetNavProp.substring(1);
    }
    if (!targetEntitySetName.equals(bodyNavProp)) {
        throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(Common.P_FORMAT_PATTERN_URI);
    }

    this.odataProducer.createLink(sourceEntity, targetNavProp, newTargetEntity);
    return noContent();
}