Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:net.oauth.jsontoken.JsonTokenTest.java

public void testPublicKey() throws Exception {

    RsaSHA256Signer signer = new RsaSHA256Signer("google.com", "key1", privateKey);

    JsonToken token = new JsonToken(signer, clock);
    token.setParam("bar", 15);
    token.setParam("foo", "some value");
    token.setExpiration(clock.now().withDurationAdded(60, 1));

    String tokenString = token.serializeAndSign();

    assertNotNull(token.toString());//w  ww .j ava 2 s  .  c om

    JsonTokenParser parser = new JsonTokenParser(clock, locators, new IgnoreAudience());
    token = parser.verifyAndDeserialize(tokenString);
    assertEquals("google.com", token.getIssuer());
    assertEquals(15, token.getParamAsPrimitive("bar").getAsLong());
    assertEquals("some value", token.getParamAsPrimitive("foo").getAsString());

    // now test what happens if we tamper with the token
    JsonObject payload = new JsonParser()
            .parse(StringUtils.newStringUtf8(Base64.decodeBase64(tokenString.split(Pattern.quote("."))[1])))
            .getAsJsonObject();
    payload.remove("bar");
    payload.addProperty("bar", 14);
    String payloadString = new Gson().toJson(payload);
    String[] parts = tokenString.split("\\.");
    parts[1] = Base64.encodeBase64URLSafeString(payloadString.getBytes());
    assertEquals(3, parts.length);

    String tamperedToken = parts[0] + "." + parts[1] + "." + parts[2];

    try {
        token = parser.verifyAndDeserialize(tamperedToken);
        fail("verification should have failed");
    } catch (SignatureException e) {
        // expected
    }
}

From source file:net.dv8tion.jda.entities.impl.MessageImpl.java

@Override
public String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }//from   w  ww.j  av  a 2 s  .c o  m
        }

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Stack<FormatToken> stack = new Stack<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.empty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start) {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.empty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.empty()) {
                    //close tag closed the block
                    inBlock = false;
                }
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start) {
                out.append(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.substring(currIndex));
        }
        //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
        strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
    return strippedContent;
}

From source file:uk.ac.kcl.at.ElasticGazetteerAcceptanceTest.java

private int getHitCount(Mutant mutant, int count, ArrayList<String> arHits) {
    for (String hit : arHits) {
        boolean hitFound = false;
        for (String token : mutant.getOutputTokens()) {
            if (hit.matches(Pattern.quote(token))) {
                hitFound = true;/*  ww w. j a  v a  2s . c om*/
            }
        }
        if (hitFound && !hit.equalsIgnoreCase("") && !hit.equalsIgnoreCase("-")) {
            count++;
        }
    }
    return count;
}

From source file:com.blackducksoftware.integration.hub.detect.detector.maven.MavenCodeLocationPackager.java

String calculateCurrentLevelAndCleanLine(final String line) {
    level = 0;/*from  www . j  a v a 2s. c o m*/
    String cleanedLine = line;
    for (final String pattern : indentationStrings) {
        while (cleanedLine.contains(pattern)) {
            level++;
            cleanedLine = cleanedLine.replaceFirst(Pattern.quote(pattern), "");
        }
    }

    return cleanedLine;
}

From source file:de.da_sense.moses.client.abstraction.apks.ExternalApplication.java

/**
 * Replaces all "\r\n" and "\n" in the String with the LINEBREAK_SUBST
 * /*from www.ja  va2 s.co m*/
 * @param s
 *            The original String
 * @return The String with the replacements
 */
private static String toLinebreakSubst(String s) {
    return s.replaceAll(Pattern.quote("\r\n"), LINEBREAK_SUBST).replaceAll(Pattern.quote("\n"),
            LINEBREAK_SUBST);
}

From source file:org.obiba.onyx.core.service.impl.ConfigurablePasswordValidationStrategyImpl.java

private String[] getEscapedAllowedCharacterGroups() {
    String[] escapedAllowedCharacterGroups = new String[allowedCharacterGroups.length];
    for (int i = 0; i < allowedCharacterGroups.length; i++) {
        Matcher rangeMatcher = characterRangePattern.matcher(allowedCharacterGroups[i]); // Match A-Z, 0-9, etc.
        Matcher characterListMatcher = characterListPattern.matcher(allowedCharacterGroups[i]); // Match [()&], [[^@#]]
        if (rangeMatcher.matches()) {
            String startRangeCharacter = Pattern.quote(rangeMatcher.group(1));
            String endRangeCharacter = Pattern.quote(rangeMatcher.group(2));
            escapedAllowedCharacterGroups[i] = startRangeCharacter + "-" + endRangeCharacter;
        } else if (characterListMatcher.matches()) {
            String characterList = characterListMatcher.group(1);
            escapedAllowedCharacterGroups[i] = Pattern.quote(characterList);
        }/*  ww w.  jav  a2  s .  c o m*/
    }
    return escapedAllowedCharacterGroups;
}

From source file:com.clustercontrol.monitor.run.util.EventCache.java

/**
 * ????????????<br>/*w w w  . ja v a  2  s  .  c  o  m*/
 * (SQL?like???[%??_??:NOT??)
 * 
 * @param filter
 * @param check
 * @return
 */
private static boolean matchLike(String filter, String check) {
    String filter2 = filter;
    boolean notInc = false;
    if (filter2.startsWith(SEARCH_PARAM_NOT_INCLUDE)) {
        notInc = true;
        filter2 = filter2.substring(SEARCH_PARAM_NOT_INCLUDE.length(), filter2.length());
    }
    if (filter2.contains(SEARCH_PARAM_PART_MATCH) || filter2.contains(SEARCH_PARAM_ONCE_MATCH)) {
        filter2 = Pattern.quote(filter2);
        filter2 = filter2.replace(SEARCH_PARAM_PART_MATCH, "\\E" + SEARCH_PARAM_PART_MATCH + "\\Q");
        filter2 = filter2.replace(SEARCH_PARAM_PART_MATCH, ".*");
        filter2 = filter2.replace(SEARCH_PARAM_ONCE_MATCH, "\\E" + SEARCH_PARAM_ONCE_MATCH + "\\Q");
        filter2 = filter2.replace(SEARCH_PARAM_ONCE_MATCH, ".");
        if (check.matches(filter2)) {
            if (notInc) {
                return false;
            }
        } else {
            if (!notInc) {
                return false;
            }
        }
    } else {
        if (!filter2.equals(check)) {
            if (!notInc) {
                return false;
            }
        } else {
            if (notInc) {
                return false;
            }
        }
    }
    return true;
}

From source file:com.microsoft.tfs.client.common.ui.controls.connect.AddServerControl.java

private void refresh() {
    // Bail if the server name validator found an error.
    if (validator.getValidity().isValid() == false) {
        SWTUtil.setCompositeEnabled(connectionDetailsGroup, true);
        serverURI = null;/*  w  w w .  j  av  a2 s .co m*/
        previewText.setText(validator.getValidity().getFirstMessage().getMessage());
        return;
    }

    final String serverName = serverText.getText().trim();

    /*
     * Look for a colon in the server name - this would be an invalid
     * hostname (unless it begins with a '[' and is an ipv6 address) and we
     * thus treat it as a URI. (We're more opportunistic about what we
     * determine to be a URI.)
     */
    if (serverName.contains(":") && !serverName.startsWith("[")) //$NON-NLS-1$ //$NON-NLS-2$
    {
        try {
            serverURI = ServerURIUtils.normalizeURI(URIUtils.newURI(serverName), true);

            /* Make sure this is a complete URI. */
            if (serverURI.getHost() != null) {
                SWTUtil.setCompositeEnabled(connectionDetailsGroup, false);

                if (ServerURIUtils.isHosted(serverURI)) {
                    serverURI = URIUtils.newURI(ServerURIUtils.HOSTED_SERVICE_DEFAULT_SCHEME,
                            serverURI.getAuthority(), null, null, null);
                }

                previewText.setText(serverURI.toString());
                return;
            }
        } catch (final Exception e) {
            log.error("Error processing server URL: ", e); //$NON-NLS-1$
        }

        serverURI = null;
        previewText.setText(Messages.getString("AddServerControl.ErrorServerNameEmpty")); //$NON-NLS-1$
        return;
    }

    /* The user is entering a hostname, not a URI. */

    final String enteredPath = pathText.getText().trim();
    final String path = enteredPath.startsWith("/") ? enteredPath : "/" + enteredPath; //$NON-NLS-1$ //$NON-NLS-2$
    final String port = portText.getText().trim();
    final boolean https = httpsButton.getSelection();
    final String scheme = https ? "https" : "http"; //$NON-NLS-1$ //$NON-NLS-2$

    /*
     * If the host name matches our hosted service, choose the correct
     * scheme for the user. Split off any path part they may have typed so
     * we can rejoin it when we build the URI (VS does this).
     */
    final String[] serverNameAndPath = serverName.split(Pattern.quote("/"), 2); //$NON-NLS-1$
    if (serverNameAndPath.length > 0) {
        final String uriServerName = serverNameAndPath[0];

        // Check for match with a hosted suffix
        final boolean isHosted = ServerURIUtils.isHosted(uriServerName);

        // DNS names may end with a final ".", so check for both.
        if (isHosted) {
            SWTUtil.setCompositeEnabled(connectionDetailsGroup, false);

            try {
                serverURI = ServerURIUtils.normalizeURI(URIUtils.newURI(
                        ServerURIUtils.HOSTED_SERVICE_DEFAULT_SCHEME, uriServerName, null, null, null), true);
            } catch (final IllegalArgumentException e) {
                log.error("Error processing server URL: ", e); //$NON-NLS-1$
                serverURI = null;
                previewText.setText(Messages.getString("AddServerControl.ErrorServerNameEmpty")); //$NON-NLS-1$
                return;
            }

            previewText.setText(serverURI.toString());
            return;
        }
    }

    /*
     * Reenable connection details group if this is the first time through
     * the refresh after user clears a URI.
     */
    SWTUtil.setCompositeEnabled(connectionDetailsGroup, true);

    /* Server name is required. */
    if (serverName.length() == 0) {
        serverURI = null;
        previewText.setText(Messages.getString("AddServerControl.ErrorServerNameEmpty")); //$NON-NLS-1$
        return;
    }

    /* Port is required. */
    if (StringUtil.isNullOrEmpty(port)) {
        serverURI = null;
        previewText.setText(Messages.getString("AddServerControl.ErrorPortEmpty")); //$NON-NLS-1$
        return;
    }

    /* Check port for validity. */
    try {
        Integer.parseInt(port);
    } catch (final NumberFormatException e) {
        serverURI = null;
        previewText.setText(Messages.getString("AddServerControl.ErrorPortEmpty")); //$NON-NLS-1$
        return;
    }

    /*
     * Determine the authority - the host:port pair. Only specify the port
     * if it is not the well-known port for the scheme (ie, port 80 for
     * http.)
     */
    final String authority;

    if ((!https && WELL_KNOWN_PORT_HTTP.equals(port)) || (https && WELL_KNOWN_PORT_HTTPS.equals(port))) {
        authority = serverName;
    } else {
        authority = MessageFormat.format("{0}:{1}", serverName, port); //$NON-NLS-1$
    }

    try {
        serverURI = ServerURIUtils.normalizeURI(URIUtils.newURI(scheme, authority, path, null, null), true);
    } catch (final IllegalArgumentException e) {
        log.error("Error processing server URL: ", e); //$NON-NLS-1$
        serverURI = null;
        previewText.setText(Messages.getString("AddServerControl.ErrorServerNameEmpty")); //$NON-NLS-1$
        return;
    }

    previewText.setText(serverURI.toString());
}