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:com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider.java

private String createPasswdCompatibleHash(String algo, String password)
        throws UnsupportedEncodingException, NoSuchAlgorithmException {
    byte[] salt = new byte[saltByteSize];
    random.nextBytes(salt);/*from  w  ww . ja  va2s. c  o m*/
    String saltString = Base64.encodeBase64String(salt);
    if (saltString.length() > 8)
        saltString = saltString.substring(0, 8);
    saltString.replaceAll(Pattern.quote("+"), Pattern.quote("."));
    return createPasswdCompatibleHash(algo, password, saltString);
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.MessageActivityXmlParser.java

/**
 * {@inheritDoc}/*from  ww  w .  j a v  a2 s  .c  om*/
 * <p>
 * This method applies custom handling for setting field values. This method will construct the signature to use for
 * the message from the specified value, which is assumed to be a string containing the inputs required for the
 * message signature calculation, with each input separated by the delimiter specified in property
 * {@code SignatureDelim}.
 * <p>
 * The signature items MUST be specified in the following order:
 * <ol>
 * <li>Message Type</li>
 * <li>Message Format</li>
 * <li>Message ID</li>
 * <li>Message User</li>
 * <li>Message Application Type</li>
 * <li>Message Application Name</li>
 * <li>Message Date</li>
 * <li>Message Time</li>
 * </ol>
 * <p>
 * Individual items can be omitted, but must contain a place holder (except for trailing items).
 */
@Override
protected void applyFieldValue(ActivityInfo ai, ActivityField field, Object value) throws ParseException {
    StreamFieldType fieldType = field.getFieldType();
    if (fieldType != null) {
        switch (fieldType) {
        case Correlator:
        case TrackingId:
            Object[] sigItems = null;
            if (value instanceof Object[]) {
                sigItems = (Object[]) value;
            } else if (value instanceof String) {
                String sigStr = (String) value;
                if (sigStr.contains(sigDelim)) {
                    sigItems = sigStr.split(Pattern.quote(sigDelim));
                }
            }
            if (sigItems != null) {
                MessageType msgType = null;
                String msgFormat = null;
                byte[] msgId = null;
                String msgUser = null;
                String msgApplType = null;
                String msgApplName = null;
                String msgPutDate = null;
                String msgPutTime = null;
                for (int i = 0; i < sigItems.length; i++) {
                    Object item = sigItems[i];
                    if (item == null) {
                        continue;
                    }
                    switch (i) {
                    case 0:
                        msgType = MessageType.valueOf(item instanceof Number ? ((Number) item).intValue()
                                : Integer.parseInt(item.toString()));
                        break;
                    case 1:
                        msgFormat = item.toString();
                        break;
                    case 2:
                        msgId = item instanceof byte[] ? (byte[]) item : item.toString().getBytes();
                        break;
                    case 3:
                        msgUser = item.toString();
                        break;
                    case 4:
                        msgApplType = item.toString();
                        break;
                    case 5:
                        msgApplName = item.toString();
                        break;
                    case 6:
                        msgPutDate = item.toString();
                        break;
                    case 7:
                        msgPutTime = item.toString();
                        break;
                    default:
                        break;
                    }
                }
                value = Utils.computeSignature(msgType, msgFormat, msgId, msgUser, msgApplType, msgApplName,
                        msgPutDate, msgPutTime);
                logger().log(OpLevel.TRACE,
                        StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                                "MessageActivityXmlParser.msg.signature"),
                        value, msgType, msgFormat, msgId == null ? "null" : Utils.encodeHex(msgId),
                        msgId == null ? "null" : new String(msgId), msgUser, msgApplType, msgApplName,
                        msgPutDate, msgPutTime);
            }
            break;
        default:
            break;
        }
    }
    super.applyFieldValue(ai, field, value);
}

From source file:io.wcm.testing.mock.jcr.MockSession.java

/**
 * Remove item incl. children//from w  w w .j  ava  2s  .  c  o m
 * @param path Item path
 */
void removeItemWithChildren(final String path) {
    List<String> pathsToRemove = new ArrayList<String>();

    // build regex pattern for node and all its children
    Pattern pattern = Pattern.compile("^" + Pattern.quote(path) + "(/.+)?$");

    for (String itemPath : this.items.keySet()) {
        if (pattern.matcher(itemPath).matches()) {
            pathsToRemove.add(itemPath);
        }
    }
    for (String pathToRemove : pathsToRemove) {
        this.items.remove(pathToRemove);
    }
}

From source file:de.codesourcery.jasm16.ide.AssemblyProject.java

protected String getNameWithoutSuffix(IResource resource) {

    String name;//from  w w w .  j  av a  2 s.  c  o  m
    if (resource instanceof FileResource) {
        FileResource file = (FileResource) resource;
        name = file.getFile().getName();
    } else {
        name = resource.getIdentifier();
    }

    // get base name
    final String[] components = name.split("[" + Pattern.quote("\\/") + "]");
    if (components.length == 1) {
        name = components[0];
    } else {
        name = components[components.length - 1];
    }
    if (!name.contains(".")) {
        return name;
    }
    final String[] dots = name.split("\\.");
    return StringUtils.join(ArrayUtils.subarray(dots, 0, dots.length - 1));
}

From source file:functionaltests.job.log.TestJobServerLogs.java

@Test
public void test() throws Exception {
    JobId simpleJobId = schedulerHelper.submitJob(new File(simpleJobDescriptor.toURI()).getAbsolutePath());

    String taskName = "task1";

    TaskInfo ti = schedulerHelper.waitForEventTaskRunning(simpleJobId, taskName);
    String taskLogs = schedulerHelper.getSchedulerInterface().getTaskServerLogs(simpleJobId.toString(),
            taskName);/*from  www  .j a  v a2 s .  com*/

    if (!taskLogs
            .contains("task " + ti.getTaskId() + " (" + ti.getTaskId().getReadableName() + ")" + " started")) {
        log("Incorrect task server logs:");
        log(taskLogs);
        fail("Task " + ti.getTaskId() + " was not scheduled");
    }

    schedulerHelper.waitForEventJobFinished(simpleJobId);
    String jobLogs = schedulerHelper.getSchedulerInterface().getJobServerLogs(simpleJobId.toString());
    for (int i = 0; i < TASKS_IN_SIMPLE_JOB; i++) {
        TaskId taskId = TaskIdImpl.createTaskId(simpleJobId, "task" + (i + 1), i);
        String taskIdString = taskId.toString();
        String taskIdStringQuoted = Pattern.quote(taskIdString);

        if (!matchLine(jobLogs, "task " + taskIdStringQuoted + " \\(task[12]\\) started")) {
            log("Incorrect job server logs");
            log(jobLogs);
            fail("Task " + taskIdString + " was not scheduled");
        }
        if (!matchLine(jobLogs, "task " + taskIdStringQuoted + " \\(task[12]\\) finished")) {
            log("Incorrect job server logs");
            log(jobLogs);
            fail("Task " + taskIdString + " was not finished");
        }
    }

    checkRemoval(simpleJobId);

    JobId pendingJobId = schedulerHelper.submitJob(createPendingJob());
    Thread.sleep(5000);
    jobLogs = schedulerHelper.getSchedulerInterface().getJobServerLogs(pendingJobId.toString());
    if (!jobLogs.contains("will get 0 nodes")) {
        log("Incorrect job server logs");
        log(jobLogs);
        fail("RM output is not correct");
    }

    if (!jobLogs.contains(SCRIPT_OUTPUT)) {
        log("Incorrect job server logs");
        log(jobLogs);
        fail("No script output");
    }

    checkRemoval(pendingJobId);
}

From source file:com.flowpowered.cerealization.config.AbstractConfiguration.java

@Override
public void setPathSeparator(String pathSeparator) {
    this.pathSeparator = pathSeparator;
    this.pathSeparatorPattern = Pattern.compile(Pattern.quote(pathSeparator));
}

From source file:com.pinplanet.pintact.GcmIntentService.java

private void sendNotification(String msg, String customData) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    String type = null;// ww w.  j a v  a  2s . c om
    if (customData != null) {

        customData = customData.replace("\"{", "{");
        customData = customData.replaceFirst(Pattern.quote("}\""), "}");
        Log.d(TAG, "CustomData2: " + customData);
    }
    try {
        JSONObject jsonObject = new JSONObject(customData);
        Log.d(TAG, "jsonObject: " + jsonObject.toString());
        type = jsonObject.getString("type");
        switch (type) {
        case "NEW_CHAT_MESSAGE":
            if (customData != null) {
                sendChatNotification(customData);
            }
            break;
        default:
            sendDefaultNotification();
            break;
        }
    } catch (JSONException e) {
        Log.d(TAG, "JSONException in GcmIntentService: " + e.toString());
        e.printStackTrace();
    }

    //        Intent it = new Intent(this, GroupContactsActivity.class);
    //        //it.putExtra(LeftDeckActivity.SELECTED_OPTIONS, LeftDeckActivity.OPTION_NOTIFY);
    //        // add the following line would show Pintact to the preview page.
    //        // it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    //        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);
    //
    //        NotificationCompat.Builder mBuilder =
    //                new NotificationCompat.Builder(this)
    //                        .setSmallIcon(R.drawable.ic_launcher)
    //                        .setContentTitle("Pintact Update")
    //                        .setStyle(new NotificationCompat.BigTextStyle()
    //                                .bigText(msg))
    //                        .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
    //                        .setContentText(msg);
    //
    //        mBuilder.setContentIntent(contentIntent);
    //        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    //        SingletonLoginData.getInstance().mNotificationManager = mNotificationManager;
}

From source file:net.sf.texprinter.utils.StringUtils.java

/**
 * Escapes HTML entities and tags to a TeX format. This method tries to
 * replace HTML code by the TeX equivalent macros.
 *
 * @param text The input text./*from w  ww.j  a  v a 2s.  c o  m*/
 * @return A new text formatted from HTML to TeX.
 */
public static String escapeHTMLtoTeX(String text) {

    // replace bold tags
    String newText = text.replaceAll("<b>", "\\\\textbf{");
    newText = newText.replaceAll("</b>", "}");

    // replace bold tags
    newText = newText.replaceAll("<strong>", "\\\\textbf{");
    newText = newText.replaceAll("</strong>", "}");

    // replace italic tags
    newText = newText.replaceAll("<i>", "\\\\textit{");
    newText = newText.replaceAll("</i>", "}");

    // replace emphasized tags
    newText = newText.replaceAll("<em>", "\\\\emph{");
    newText = newText.replaceAll("</em>", "}");

    // replace paragraphs tags
    newText = newText.replaceAll("<p>", "");
    newText = newText.replaceAll("</p>", "\n\n");

    // replace ordered lists tags
    newText = newText.replaceAll("<ol>", "\\\\begin{enumerate}\n");
    newText = newText.replaceAll("</ol>", "\\\\end{enumerate}\n");

    // replace unordered lists tags
    newText = newText.replaceAll("<ul>", "\\\\begin{itemize}\n");
    newText = newText.replaceAll("</ul>", "\\\\end{itemize}\n");

    // replace item tags
    newText = newText.replaceAll("<li>", "\\\\item ");
    newText = newText.replaceAll("</li>", "\n");

    // replace blockquote tags
    newText = newText.replaceAll("<blockquote>", "\\\\begin{quotation}\n");
    newText = newText.replaceAll("</blockquote>", "\\\\end{quotation}\n");

    // replace code tags
    newText = newText.replaceAll("<pre><code>", "\\\\begin{TeXPrinterListing}\n");
    newText = newText.replaceAll("<pre class=.*\"><code>", "\\\\begin{TeXPrinterListing}\n");
    newText = newText.replaceAll("</code></pre>", "\\\\end{TeXPrinterListing}\n\n");

    // replace inline code tags
    newText = newText.replaceAll("<code>", "\\\\lstinline|");
    newText = newText.replaceAll("</code>", "|");

    // replace links tags
    newText = newText.replaceAll("alt=\".*\" ", "");

    // parse the text
    Document docLinks = Jsoup.parse(newText);

    // get all the links
    Elements links = docLinks.getElementsByTag("a");

    // if there are links
    if (links.size() > 0) {

        // for every link
        for (Element link : links) {

            // get the outer HTML
            String temp = link.outerHtml();

            // replace it
            newText = newText.replaceFirst(Pattern.quote(temp),
                    "\\\\href{" + link.attr("href") + "}{" + link.text() + "}");

        }
    }

    // create a list of images
    ArrayList<ImageGroup> images = new ArrayList<ImageGroup>();

    // parse the current text
    Document doc = Jsoup.parse(text);

    // fetch all the media found
    Elements media = doc.select("[src]");

    // for all media found
    for (Element m : media) {

        // if it's an image tag
        if (m.tagName().equals("img")) {

            // create a new image group with the image link
            ImageGroup image = new ImageGroup(m.attr("abs:src"));

            // add to the list of images
            images.add(image);

            // set the current image to null
            image = null;
        }
    }

    // create a new loop saver
    LoopSaver lps = null;

    // for every image in the list of images
    for (ImageGroup img : images) {

        // create a new object
        lps = new LoopSaver();

        // while there are references for that image in the text
        while (newText.indexOf(img.getURL()) != -1) {

            // tick loop
            lps.tick();

            // replace the occurrence of that image
            newText = newText.replaceFirst("<img src=\"" + img.getURL() + "\" />",
                    "\\\\begin{figure}[h!]\n\\\\centering\n\\\\includegraphics[scale=0.5]{" + img.getName()
                            + "}\n\\\\end{figure}");
        }

        // lets try
        try {

            // finally, download the image to the current directory
            Downloader.download(img.getURL(), img.getName());

        } catch (Exception exception) {

            // log message
            log.log(Level.WARNING,
                    "An error occurred while getting the current image. Trying to set the replacement image instead. MESSAGE: {0}",
                    StringUtils.printStackTrace(exception));

            // image could not be downloaded for any reason
            try {

                // open a file stream
                FileOutputStream f = new FileOutputStream(img.getName());

                // write a replacement image
                f.write(Base64.decode(
                        "iV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ZzaQP26LVTHiEIVjRmJWWpM1ptBGIOkPxRvv1Jcr4sCNWuJojW0q513gjrhwmicvPB3RALXqwPMTUc5qgsCaI0JMyvtedLEaJ8oVgedb8b7cZzCCQEPpEPrao2eIycIcouo3qE6Ho1k59fe7ESXYLch4Zy1ZbWWvKIzXvKnK0HU+nAnk6CQpdw5LBsf0pryAd/7EpkjUANQeiGKvOzkAK3IM3mJc3ibQVxiirNyDwMtCLEPEgNySkMmCBOoXkdIyaIdXx1ClITxCk0r2PEBLGOr05BaoI4heZ1jJgg1vHVKUhNEKfQvI4RE8Q6vjoFqQniFJrXMWKCWMdXpyA1QZxC8zpGTBDr+OoUpP8Arv92hCPEu+kAAAAASUVORK5CYII="));

                // close the file
                f.close();

            } catch (IOException ioexception) {

                // log message
                log.log(Level.SEVERE,
                        "An IO exception occured while trying to create the image replacement. MESSAGE: {0}",
                        StringUtils.printStackTrace(ioexception));

            } catch (Exception except) {

                // log message
                log.log(Level.SEVERE,
                        "An error occured while trying to create the image replacement. MESSAGE: {0}",
                        StringUtils.printStackTrace(except));

            }

        }

    }

    // unescape all HTML entities
    newText = StringEscapeUtils.unescapeHtml(newText);

    // return new text
    return newText;
}

From source file:com.lonepulse.zombielink.request.UriProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with the {@link HttpRequestBase} and forms 
 * the complete request URI by appending the request subpath to the root path defined on the 
 * endpoint. Any placeholders in the URI are replaced with their matching path parameters found 
 * in the request arguments annotated with @{@link PathParam}.</p>
 * /*from   w w  w.j a  v a2 s.  c  o  m*/
 * <p>Any processors which extract information from the <i>complete</i> request URI or those which 
 * seek to manipulate the URI should use this processor as a prerequisite.</p>
 * 
 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} used to discover root and subpath information  
 * <br><br>
 * @param request
 *          the {@link HttpRequestBase} whose URI will be initialized to the complete URI formulated 
 *          using the endpoint's root path, the request's subpath and any path parameters
 * <br><br>
  * @return the same instance of {@link HttpRequestBase} which was given for processing the URI
 * <br><br>
 * @throws RequestProcessorException
 *          if a URI failed to be created using the information found on the endpoint definition
 * <br><br>
 * @since 1.3.0
 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {

    try {

        Endpoint endpoint = context.getEndpoint().getAnnotation(Endpoint.class);
        String path = endpoint.value() + Metadata.findPath(context.getRequest());

        List<Entry<PathParam, Object>> pathParams = Metadata.onParams(PathParam.class, context);

        for (Entry<PathParam, Object> entry : pathParams) {

            String name = entry.getKey().value();
            Object value = entry.getValue();

            if (!(value instanceof CharSequence)) {

                StringBuilder errorContext = new StringBuilder().append("Path parameters can only be of type ")
                        .append(CharSequence.class.getName())
                        .append(". Please consider implementing CharSequence ")
                        .append("and providing a meaningful toString() representation for the ")
                        .append("<name> of the path parameter. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            path = path.replaceAll(Pattern.quote("{" + name + "}"), ((CharSequence) value).toString());
        }

        request.setURI(URI.create(path));

        return request;
    } catch (Exception e) {

        throw new RequestProcessorException(context, getClass(), e);
    }
}

From source file:uk.ac.kcl.it.DeIdentificationPKPartitionWithoutScheduling.java

@Test
public void deidentificationPerformanceTest() {
    dbmsTestUtils.createBasicInputTable();
    dbmsTestUtils.createBasicOutputTable();
    dbmsTestUtils.createDeIdInputTable();
    List<Mutant> mutants = testUtils.insertTestDataForDeidentification(env.getProperty("tblIdentifiers"),
            env.getProperty("tblInputDocs"), mutatortype);
    int totalTruePositives = 0;
    int totalFalsePositives = 0;
    int totalFalseNegatives = 0;

    for (Mutant mutant : mutants) {
        Set<Pattern> mutatedPatterns = new HashSet<>();
        mutant.setDeidentifiedString(elasticGazetteerService.deIdentifyString(mutant.getFinalText(),
                String.valueOf(mutant.getDocumentid())));
        Set<String> set = new HashSet<>(mutant.getOutputTokens());
        mutatedPatterns.addAll(//  w ww  .  j av  a  2s  . c om
                set.stream().map(string -> Pattern.compile(Pattern.quote(string), Pattern.CASE_INSENSITIVE))
                        .collect(Collectors.toSet()));
        List<MatchResult> results = new ArrayList<>();
        for (Pattern pattern : mutatedPatterns) {
            Matcher matcher = pattern.matcher(mutant.getFinalText());
            while (matcher.find()) {
                results.add(matcher.toMatchResult());
            }
        }

        int truePositives = getTruePositiveTokenCount(mutant);
        int falsePositives = getFalsePositiveTokenCount(mutant);
        int falseNegatives = getFalseNegativeTokenCount(mutant);

        System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives
                + " unmasked identifiers from a total of " + (falseNegatives + truePositives));
        System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falsePositives
                + " inaccurately masked tokens from a total of " + (falsePositives + truePositives));
        System.out.println("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives);
        System.out.println("Doc ID precision " + calcPrecision(falsePositives, truePositives));
        System.out.println("Doc ID recall " + calcRecall(falseNegatives, truePositives));
        System.out.println(mutant.getDeidentifiedString());
        System.out.println(mutant.getFinalText());
        System.out.println(mutant.getInputTokens());
        System.out.println(mutant.getOutputTokens());
        System.out.println();
        if (env.getProperty("elasticgazetteerTestOutput") != null) {
            try {
                try (BufferedWriter bw = new BufferedWriter(
                        new FileWriter(new File(env.getProperty("elasticgazetteerTestOutput") + File.separator
                                + mutant.getDocumentid())))) {
                    bw.write("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives
                            + " unmasked identifiers from a total of " + (falseNegatives + truePositives));
                    bw.newLine();
                    bw.write("Doc ID " + mutant.getDocumentid() + " has " + falsePositives
                            + " inaccurately masked tokens from a total of "
                            + (falsePositives + truePositives));
                    bw.newLine();
                    bw.write("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives);
                    bw.newLine();
                    bw.write("Doc ID precision " + calcPrecision(falsePositives, truePositives));
                    bw.newLine();
                    bw.write("Doc ID recall " + calcRecall(falseNegatives, truePositives));
                    bw.newLine();
                    bw.write(mutant.getDeidentifiedString());
                    bw.newLine();
                    bw.write(mutant.getFinalText());
                    bw.newLine();
                    bw.write(mutant.getInputTokens().toString());
                    bw.newLine();
                    bw.write(mutant.getOutputTokens().toString());

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        totalTruePositives += truePositives;
        totalFalsePositives += falsePositives;
        totalFalseNegatives += falseNegatives;
    }
    System.out.println();
    System.out.println();
    System.out.println("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: "
            + totalFalseNegatives);
    System.out.println("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives));
    System.out.println("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives));
    if (env.getProperty("elasticgazetteerTestOutput") != null) {
        try {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(
                    new File(env.getProperty("elasticgazetteerTestOutput") + File.separator + "summary")))) {
                bw.write("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: "
                        + totalFalseNegatives);
                bw.newLine();
                bw.write("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives));
                bw.newLine();
                bw.write("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}