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.norconex.commons.lang.url.URLNormalizer.java

/**
 * <p>Converts <code>http</code> scheme to <code>https</code>.</p>
 * <code>http://www.example.com/ &rarr; https://www.example.com/</code>
 * @return this instance/*from   w w w . ja va  2s  . co  m*/
 */
public URLNormalizer secureScheme() {
    Matcher m = PATTERN_SCHEMA.matcher(url);
    if (m.find()) {
        String schema = m.group(1);
        if ("http".equalsIgnoreCase(schema)) {
            url = m.replaceFirst(schema + "s$2");
        }
    }
    return this;
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * <p>Converts <code>https</code> scheme to <code>http</code>.</p>
 * <code>https://www.example.com/ &rarr; http://www.example.com/</code>
 * @return this instance/*w ww.j  a  v  a  2  s.  c  o  m*/
 */
public URLNormalizer unsecureScheme() {
    Matcher m = PATTERN_SCHEMA.matcher(url);
    if (m.find()) {
        String schema = m.group(1);
        if ("https".equalsIgnoreCase(schema)) {
            url = m.replaceFirst(StringUtils.stripEnd(schema, "Ss") + "$2");
        }
    }
    return this;
}

From source file:org.opennms.web.rest.AlarmRestServiceBase.java

protected void translateParameters(final MultivaluedMap<String, String> params) {
    // this is handled by a @QueryParam annotation, ignore it from the UriInfo object
    params.remove("severities");

    if (params.containsKey("nodeId")) {
        final String nodeId = params.getFirst("nodeId");
        params.remove("nodeId");
        params.add("node.id", nodeId);
    }/*  ww w  .  ja v  a 2  s  .c  om*/

    if (params.containsKey("nodeLabel")) {
        final String nodeLabel = params.getFirst("nodeLabel");
        params.remove("nodeLabel");
        params.add("node.label", nodeLabel);
    }

    final String query = params.getFirst("query");
    // System.err.println("tranlateSeverity: query = " + query + ", pattern = " + p);
    if (query != null) {
        final Matcher m = m_severityPattern.matcher(query);
        if (m.find()) {
            // System.err.println("translateSeverity: group(1) = '" + m.group(1) + "', group(2) = '" + m.group(2) + "', group(3) = '" + m.group(3) + "'");
            final String alias = m.group(1);
            final String comparator = m.group(2);
            final String severity = m.group(3);
            final OnmsSeverity onmsSeverity = OnmsSeverity.get(severity);
            // System.err.println("translateSeverity: " + severity + " = " + onmsSeverity);

            final String newQuery = m.replaceFirst(
                    " " + (alias == null ? "" : alias) + "severity " + comparator + " " + onmsSeverity.getId());
            params.remove("query");
            params.add("query", newQuery);
            // System.err.println("translateSeverity: newQuery = '" + newQuery + "'");
        } else {
            // System.err.println("translateSeverity: failed to find pattern");
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.JdbcScimUserProvisioning.java

private String makeCaseInsensitive(String where, Pattern pattern, String template, String valueTemplate,
        Map<String, Object> values) {
    String output = where;// w  ww  .j  a  va  2 s .  c o  m
    Matcher matcher = pattern.matcher(output);
    int count = values.size();
    while (matcher.matches()) {
        values.put("value" + count, String.format(valueTemplate, matcher.group(3).toLowerCase()));
        String query = template.replace("?", "value" + count);
        output = matcher
                .replaceFirst(String.format(query, matcher.group(1), matcher.group(2), matcher.group(4)));
        matcher = pattern.matcher(output);
        count++;
    }
    return output;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java

private String htmlDecode(String text) {
    final Pattern hexEntity = Pattern.compile("&#x([0-9a-f]{2});");
    while (true) {
        final Matcher matcher = hexEntity.matcher(text);
        if (matcher.find() == false) {
            return text;
        }//from   ww  w .ja  v a  2  s  .com
        char ch = (char) Integer.parseInt(matcher.group(1), 16);
        text = matcher.replaceFirst(Character.toString(ch));
    }
}

From source file:org.tdwg.dwca.wikipedia.taxonbox.TaxonInfoBase.java

/**
 * Expand abbreviated names like:/*from  ww  w . j  av  a  2s .  c om*/
 *   V[ipera]. a[mmodytes]. transcaucasiana - Bruno, 1985
 *
 * @param name
 * @return
 */
private String expandName(String name) {
    if (name == null)
        return null;

    if (!Strings.isNullOrEmpty(getGenus())) {
        Pattern gen = Pattern.compile("^ *" + genus.charAt(0) + "\\. *");
        Matcher m = gen.matcher(getScientificName());
        if (m.find()) {
            String expandedName = m.replaceFirst(genus + " ");
            String epithet = null;
            if (!Strings.isNullOrEmpty(speciesEpithet)) {
                epithet = speciesEpithet;
            } else if (!Strings.isNullOrEmpty(species)) {
                epithet = StringUtils.substringAfterLast(species, " ");
            }

            if (!Strings.isNullOrEmpty(epithet)) {
                Pattern specEpi = Pattern.compile("^" + genus + " " + epithet.charAt(0) + "\\. *");
                m = specEpi.matcher(expandedName);
                if (m.find()) {
                    expandedName = m.replaceFirst(getGenus() + " " + epithet + " ");
                }
            }

            log.debug("Expanding abbreviated name {} with {}", getScientificName(), expandedName);
            return expandedName;
        }
    }
    return name;
}

From source file:jenkins.model.RunIdMigrator.java

private void doMigrate(File dir) {
    idToNumber = new TreeMap<String, Integer>();
    File[] kids = dir.listFiles();
    // Need to process symlinks first so we can rename to them.
    List<File> kidsList = new ArrayList<File>(Arrays.asList(kids));
    Iterator<File> it = kidsList.iterator();
    while (it.hasNext()) {
        File kid = it.next();// w  w  w . j a v a 2s.c o  m
        String name = kid.getName();
        try {
            Integer.parseInt(name);
        } catch (NumberFormatException x) {
            LOGGER.log(FINE, "ignoring nonnumeric entry {0}", name);
            continue;
        }
        try {
            if (Util.isSymlink(kid)) {
                LOGGER.log(FINE, "deleting build number symlink {0}  {1}",
                        new Object[] { name, Util.resolveSymlink(kid) });
            } else if (kid.isDirectory()) {
                LOGGER.log(FINE, "ignoring build directory {0}", name);
                continue;
            } else {
                LOGGER.log(WARNING, "need to delete anomalous file entry {0}", name);
            }
            Util.deleteFile(kid);
            it.remove();
        } catch (Exception x) {
            LOGGER.log(WARNING, "failed to process " + kid, x);
        }
    }
    it = kidsList.iterator();
    while (it.hasNext()) {
        File kid = it.next();
        try {
            String name = kid.getName();
            try {
                Integer.parseInt(name);
                LOGGER.log(FINE, "skipping new build dir {0}", name);
                continue;
            } catch (NumberFormatException x) {
                // OK, next
            }
            if (!kid.isDirectory()) {
                LOGGER.log(FINE, "skipping non-directory {0}", name);
                continue;
            }
            long timestamp;
            try {
                synchronized (legacyIdFormatter) {
                    timestamp = legacyIdFormatter.parse(name).getTime();
                }
            } catch (ParseException x) {
                LOGGER.log(WARNING, "found unexpected dir {0}", name);
                continue;
            }
            File buildXml = new File(kid, "build.xml");
            if (!buildXml.isFile()) {
                LOGGER.log(WARNING, "found no build.xml in {0}", name);
                continue;
            }
            String xml = FileUtils.readFileToString(buildXml, Charsets.UTF_8);
            Matcher m = NUMBER_ELT.matcher(xml);
            if (!m.find()) {
                LOGGER.log(WARNING, "could not find <number> in {0}/build.xml", name);
                continue;
            }
            int number = Integer.parseInt(m.group(1));
            String nl = m.group(2);
            xml = m.replaceFirst(
                    "  <id>" + name + "</id>" + nl + "  <timestamp>" + timestamp + "</timestamp>" + nl);
            File newKid = new File(dir, Integer.toString(number));
            move(kid, newKid);
            FileUtils.writeStringToFile(new File(newKid, "build.xml"), xml, Charsets.UTF_8);
            LOGGER.log(FINE, "fully processed {0}  {1}", new Object[] { name, number });
            idToNumber.put(name, number);
        } catch (Exception x) {
            LOGGER.log(WARNING, "failed to process " + kid, x);
        }
    }
}

From source file:SportsBroadcastsSpeechlet.java

/**
 * Parse JSON-formatted list of events/births/deaths from Wikipedia, extract list of events and
 * split the events into a String array of individual events. Run Regex matchers to make the
 * list pretty by adding a comma after the year to add a pause, and by removing a unicode char.
 * //  w  w  w . jav  a 2s .co m
 * @param text
 *            the JSON formatted list of events/births/deaths for a certain date
 * @return String array of events for that date, 1 event per element of the array
 */
private ArrayList<String> parseJson(String text) {
    // sizeOf (\nEvents\n) is 10
    text = text.substring(text.indexOf("\\nEvents\\n") + SIZE_OF_EVENTS, text.indexOf("\\n\\n\\nBirths"));
    ArrayList<String> events = new ArrayList<String>();
    if (text.isEmpty()) {
        return events;
    }
    int startIndex = 0, endIndex = 0;
    while (endIndex != -1) {
        endIndex = text.indexOf("\\n", startIndex + DELIMITER_SIZE);
        String eventText = (endIndex == -1 ? text.substring(startIndex) : text.substring(startIndex, endIndex));
        // replace dashes returned in text from Wikipedia's API
        Pattern pattern = Pattern.compile("\\\\u2013\\s*");
        Matcher matcher = pattern.matcher(eventText);
        eventText = matcher.replaceAll("");
        // add comma after year so Alexa pauses before continuing with the sentence
        pattern = Pattern.compile("(^\\d+)");
        matcher = pattern.matcher(eventText);
        if (matcher.find()) {
            eventText = matcher.replaceFirst(matcher.group(1) + ",");
        }
        eventText = "In " + eventText;
        startIndex = endIndex + 2;
        events.add(eventText);
    }
    Collections.reverse(events);
    return events;
}

From source file:com.flipkart.poseidon.serviceclients.generator.ServiceGenerator.java

private JInvocation createRequest(ServiceIDL serviceIdl, JCodeModel jCodeModel, EndPoint endPoint, JBlock block,
        String requestParamWithLimit, String listElementVarName) {
    String baseUri = serviceIdl.getService().getBaseUri();
    String endPointUri = endPoint.getUri();
    String uri = (baseUri + endPointUri).replaceAll("//", "/");
    Set<String> argsList = new LinkedHashSet<>();
    Set<String> argsListQueryParams = new LinkedHashSet<>();

    Matcher matcher = PARAMETERS_PATTERN.matcher(uri);
    while (matcher.find()) {
        uri = matcher.replaceFirst("%s");
        argsList.add(matcher.group(1));/*from   w ww  . jav a  2  s .co  m*/
        matcher.reset(uri);
    }
    if (argsList.isEmpty()) {
        block.decl(jCodeModel.ref("String"), "uri", JExpr.lit(uri));
    } else {
        JInvocation invocation = JExpr.ref("String").invoke("format").arg(uri);
        for (String arg : argsList) {
            Parameter parameter = serviceIdl.getParameters().get(arg);
            if (endPoint.getRequestParamWithLimit() != null && requestParamWithLimit.equals(arg)) {
                arg = listElementVarName;
            }
            if (parameter.getType().equals("String")) {
                invocation.arg(JExpr.invoke("encodeUrl").arg(JExpr.ref(arg)));
            } else if (parameter.getType().endsWith("[]")) {
                JExpression joinerExpression = jCodeModel.ref(Joiner.class).staticInvoke("on")
                        .arg(JExpr.lit(',')).invoke("join").arg(JExpr.ref(arg));
                invocation.arg(JExpr.invoke("encodeUrl").arg(joinerExpression));
            } else if (parameter.getType().startsWith("java.util.List")) {
                invocation.arg(
                        jCodeModel.ref(StringUtils.class).staticInvoke("join").arg(JExpr.ref(arg)).arg(","));
            } else {
                invocation.arg(JExpr.ref(arg));
            }
        }
        block.decl(jCodeModel.ref("String"), "uri", invocation);
    }
    if (endPoint.getParameters() != null) {
        for (String paramName : endPoint.getParameters()) {
            Parameter parameter = serviceIdl.getParameters().get(paramName);
            if (!parameter.getOptional()) {
                if (parameter.getType().equalsIgnoreCase("string") || parameter.getType().endsWith("[]")) {
                    block.add(jCodeModel.ref(Validate.class).staticInvoke("notEmpty").arg(JExpr.ref(paramName))
                            .arg(paramName + " can not be null/empty"));
                } else {
                    block.add(jCodeModel.ref(Validate.class).staticInvoke("notNull").arg(JExpr.ref(paramName))
                            .arg(paramName + " can not be null"));
                }
            }

            if (argsList.contains(paramName))
                continue;

            argsListQueryParams.add(paramName);
        }
    }

    if (!argsListQueryParams.isEmpty()) {
        JInvocation invocation = jCodeModel.ref(Arrays.class).staticInvoke("asList");
        for (String arg : argsListQueryParams) {
            Parameter parameter = serviceIdl.getParameters().get(arg);
            String argRef = arg;
            if (endPoint.getRequestParamWithLimit() != null && requestParamWithLimit.equals(arg)) {
                argRef = listElementVarName;
            }
            String paramName = Optional.ofNullable(parameter.getName()).orElse(arg);
            if (!parameter.getOptional()) {
                if (parameter.isMultiValue()) {
                    invocation.arg(JExpr.invoke("getMultiValueParamURI").arg(paramName).arg(JExpr.ref(argRef)));
                } else if (parameter.getType().equals("String")) {
                    invocation.arg(
                            JExpr.lit(paramName + "=").plus(JExpr.invoke("encodeUrl").arg(JExpr.ref(argRef))));
                } else if (parameter.getType().endsWith("[]")) {
                    JExpression joinerExpression = jCodeModel.ref(Joiner.class).staticInvoke("on")
                            .arg(JExpr.lit(',')).invoke("join").arg(JExpr.ref(argRef));
                    invocation.arg(
                            JExpr.lit(paramName + "=").plus(JExpr.invoke("encodeUrl").arg(joinerExpression)));
                } else if (parameter.getType().startsWith("java.util.List")) {
                    JExpression joinerExpression = jCodeModel.ref(StringUtils.class).staticInvoke("join")
                            .arg(JExpr.ref(argRef)).arg(",");
                    invocation.arg(
                            JExpr.lit(paramName + "=").plus(JExpr.invoke("encodeUrl").arg(joinerExpression)));
                } else {
                    invocation.arg(JExpr.lit(paramName + "=").plus(JExpr.ref(argRef)));
                }
            } else {
                if (parameter.isMultiValue()) {
                    invocation.arg(JExpr.invoke("getMultiValueParamURI").arg(paramName).arg(JExpr.ref(argRef)));
                } else {
                    invocation.arg(JExpr.invoke("getOptURI").arg(paramName).arg(JExpr.ref(argRef)));
                }
            }
        }
        block.assign(JExpr.ref("uri"), JExpr.ref("uri").plus(JExpr.invoke("getQueryURI").arg(invocation)));
    }

    Map<String, String> headersMap = getAllHeaders(serviceIdl, endPoint);
    if (headersMap.size() > 0) {
        JClass mapClass = jCodeModel.ref(Map.class).narrow(jCodeModel.ref("String"), jCodeModel.ref("String"));
        JClass hashMapClass = jCodeModel.ref(HashMap.class).narrow(jCodeModel.ref("String"),
                jCodeModel.ref("String"));
        block.decl(mapClass, "headersMap", JExpr._new(hashMapClass));
        for (Map.Entry<String, String> headerMapEntry : headersMap.entrySet()) {
            String key = headerMapEntry.getKey();
            String value = headerMapEntry.getValue();
            JInvocation invocation = JExpr.invoke(JExpr.ref("headersMap"), "put").arg(key);
            matcher = PARAMETERS_PATTERN.matcher(value);
            if (matcher.find()) {
                String paramName = matcher.group(1);
                invocation.arg(jCodeModel.ref("String").staticInvoke("valueOf").arg(JExpr.ref(paramName)));
                Parameter parameter = serviceIdl.getParameters().get(paramName);
                if (parameter.getOptional()) {
                    block._if(JExpr.ref(paramName).ne(JExpr._null()))._then().add(invocation);
                } else {
                    block.add(invocation);
                }
            } else {
                invocation.arg(value);
                block.add(invocation);
            }
        }
    }

    if (endPoint.getResponseObject() != null && !endPoint.getResponseObject().isEmpty()) {
        // If responseObject contains generic types, use TypeReference. Else use Class of the responseObject.
        // http://wiki.fasterxml.com/JacksonDataBinding
        // For uniformity, TypeReference or Class is then converted to a JavaType to deserialize service response.
        // For generic types, creating an anonymous inner class for every service call would have overhead which is
        // compensated by the type safety it ensures at compilation time as well as easy code generation
        JInvocation invocation = JExpr.invoke("execute");
        JType definedClass = jCodeModel._ref(ServiceExecutePropertiesBuilder.class);
        JInvocation nestedInvocation = JExpr.invoke("getJavaType");
        if (!endPoint.getResponseObject().contains("<")) {
            if (endPoint.getResponseObject().contains(".")) {
                JInvocation classDecl = jCodeModel.ref(Class.class).staticInvoke("forName")
                        .arg(endPoint.getResponseObject());
                nestedInvocation.arg(classDecl);
            } else {
                JFieldRef ref = JExpr.ref(JExpr.ref(endPoint.getResponseObject()), "class");
                nestedInvocation.arg(ref);
            }
        } else {
            JClass typeReferenceClass = jCodeModel.ref(TypeReference.class)
                    .narrow(getJType(jCodeModel, endPoint.getResponseObject()));
            nestedInvocation.arg(JExpr._new(jCodeModel.anonymousClass(typeReferenceClass)));
        }
        JInvocation builderInvocation = JExpr.invoke(JExpr._new(definedClass), "setJavaType")
                .arg(nestedInvocation);
        if (endPoint.getErrorResponseObject() != null && !endPoint.getErrorResponseObject().isEmpty()) {
            JInvocation nestedErrorInvocation = JExpr.invoke("getErrorType");
            if (!endPoint.getErrorResponseObject().contains("<")) {
                if (endPoint.getErrorResponseObject().contains(".")) {
                    JInvocation classDecl = jCodeModel.ref(Class.class).staticInvoke("forName")
                            .arg(endPoint.getErrorResponseObject());
                    nestedErrorInvocation.arg(classDecl);
                } else {
                    JFieldRef ref = JExpr.ref(JExpr.ref(endPoint.getErrorResponseObject()), "class");
                    nestedErrorInvocation.arg(ref);
                }
            } else {
                JClass typeReferenceClass = jCodeModel.ref(TypeReference.class)
                        .narrow(getJType(jCodeModel, endPoint.getErrorResponseObject()));
                nestedErrorInvocation.arg(JExpr._new(jCodeModel.anonymousClass(typeReferenceClass)));
            }
            builderInvocation = builderInvocation.invoke("setErrorType").arg(nestedErrorInvocation);
        }
        builderInvocation = builderInvocation.invoke("setUri").arg(JExpr.ref("uri"));
        builderInvocation = builderInvocation.invoke("setHttpMethod").arg(endPoint.getHttpMethod());

        if (headersMap.size() > 0) {
            builderInvocation = builderInvocation.invoke("setHeadersMap").arg(JExpr.ref("headersMap"));
        }

        if (endPoint.getRequestObject() != null && !endPoint.getRequestObject().isEmpty()) {
            String requestObjectName;
            if (endPoint.getRequestSplitterClass() != null && endPoint.getRequestParamWithLimit() == null) {
                requestObjectName = REQUEST_OBJECT_LOOP_VAR_NAME;
            } else {
                requestObjectName = REQUEST_OBJECT_VAR_NAME;
            }
            builderInvocation = builderInvocation.invoke("setRequestObject").arg(JExpr.ref(requestObjectName));
        }

        if (endPoint.getCommandName() != null && !endPoint.getCommandName().isEmpty()) {
            builderInvocation = builderInvocation.invoke("setCommandName").arg(endPoint.getCommandName());
        }

        if (endPoint.isRequestCachingEnabled()) {
            builderInvocation = builderInvocation.invoke("setRequestCachingEnabled").arg(JExpr.lit(true));
        }
        builderInvocation = builderInvocation.invoke("build");
        return invocation.arg(builderInvocation);
    }
    return null;
}

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

/**
 * Executes the search.//from w ww  .  j a  v a2  s .  co m
 *
 * @param commandLine The command line for the search.
 * @return The search results.
 */
public List<SearchMatch> executeSearch(CommandLine commandLine) throws Exception {
    int context = -1;
    if (commandLine.hasOption(Options.CONTEXT_OPTION)) {
        context = getContext(commandLine.getValue(Options.CONTEXT_OPTION));
    }
    String project = commandLine.getValue(Options.NAME_OPTION);
    String scope = commandLine.getValue(Options.SCOPE_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String offset = commandLine.getValue(Options.OFFSET_OPTION);
    String length = commandLine.getValue(Options.LENGTH_OPTION);
    String pat = commandLine.getValue(Options.PATTERN_OPTION);

    SearchPattern pattern = null;
    IJavaProject javaProject = project != null ? JavaUtils.getJavaProject(project) : null;

    // element search
    if (file != null && offset != null && length != null) {
        int charOffset = getOffset(commandLine);
        IJavaElement element = getElement(javaProject, file, charOffset, Integer.parseInt(length));
        if (element != null) {
            // user requested a contextual search.
            if (context == -1) {
                context = getElementContextualContext(element);
            }
            pattern = SearchPattern.createPattern(element, context);
        }

        // pattern search
    } else if (pat != null) {
        if (context == -1) {
            context = IJavaSearchConstants.DECLARATIONS;
        }

        int matchType = SearchPattern.R_EXACT_MATCH;

        // wild card character supplied, use pattern matching.
        if (pat.indexOf('*') != -1 || pat.indexOf('?') != -1) {
            matchType = SearchPattern.R_PATTERN_MATCH;

            // all upper case, add camel case support.
        } else if (pat.equals(pat.toUpperCase())) {
            matchType |= SearchPattern.R_CAMELCASE_MATCH;
        }

        boolean caseSensitive = !commandLine.hasOption(Options.CASE_INSENSITIVE_OPTION);
        if (caseSensitive) {
            matchType |= SearchPattern.R_CASE_SENSITIVE;
        }

        int type = getType(commandLine.getValue(Options.TYPE_OPTION));

        // hack for inner classes
        Matcher matcher = INNER_CLASS.matcher(pat);
        if (matcher.matches()) {
            // pattern search doesn't support org.test.Type$Inner or
            // org.test.Type.Inner, so convert it to org.test.*Inner, then filter
            // the results.
            pattern = SearchPattern.createPattern(matcher.replaceFirst("$1*$3"), type, context, matchType);
            Pattern toMatch = Pattern.compile(pat.replace(".", "\\.").replace("$", "\\$").replace("(", "\\(")
                    .replace(")", "\\)").replace("*", ".*").replace("?", "."));
            List<SearchMatch> matches = search(pattern, getScope(scope, javaProject));
            Iterator<SearchMatch> iterator = matches.iterator();
            while (iterator.hasNext()) {
                SearchMatch match = iterator.next();
                String name = JavaUtils.getFullyQualifiedName((IJavaElement) match.getElement()).replace("#",
                        ".");
                if (!toMatch.matcher(name).matches()) {
                    iterator.remove();
                }
            }
            return matches;
        }

        pattern = SearchPattern.createPattern(pat, type, context, matchType);

        // bad search request
    } else {
        throw new IllegalArgumentException(Services.getMessage("java_search.indeterminate"));
    }

    List<SearchMatch> matches = search(pattern, getScope(scope, javaProject));
    return matches;
}