Example usage for java.util.regex Pattern MULTILINE

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

Introduction

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

Prototype

int MULTILINE

To view the source code for java.util.regex Pattern MULTILINE.

Click Source Link

Document

Enables multiline mode.

Usage

From source file:org.apache.hadoop.metrics2.sink.RollingFileSystemSinkTestBase.java

/**
 * Assert that the given contents match what is expected from the test
 * metrics when there is pre-existing data.
 *
 * @param contents the file contents to test
 *///from  ww  w .jav  a  2  s . com
protected void assertExtraContents(String contents) {
    // Note that in the below expression we allow tags and metrics to go in
    // arbitrary order, but the records must be in order.
    final Pattern expectedContentPattern = Pattern
            .compile("Extra stuff[\\n\\r]*" + "^\\d+\\s+test1.testRecord1:\\s+Context=test1,\\s+"
                    + "(testTag1=testTagValue1,\\s+testTag2=testTagValue2|"
                    + "testTag2=testTagValue2,\\s+testTag1=testTagValue1)," + "\\s+Hostname=.*,\\s+"
                    + "(testMetric1=1,\\s+testMetric2=2|testMetric2=2,\\s+testMetric1=1)"
                    + "[\\n\\r]*^\\d+\\s+test1.testRecord2:\\s+Context=test1,"
                    + "\\s+testTag22=testTagValue22,\\s+Hostname=.*$[\\n\\r]*", Pattern.MULTILINE);

    assertTrue("Sink did not produce the expected output. Actual output was: " + contents,
            expectedContentPattern.matcher(contents).matches());
}

From source file:it.jnrpe.plugin.CheckHttp.java

/**
 * Apply logic to the http response and build metrics.
 * //from  www.j a  v  a 2s .  c om
 * @param opt
 *            -
 * @param response
 *            -
 * @param elapsed
 *            -
 * @return - The metrics
 * @throws MetricGatheringException
 *             List<Metric>
 */
private List<Metric> analyzeResponse(final ICommandLine opt, final String response, final int elapsed)
        throws MetricGatheringException {
    List<Metric> metrics = new ArrayList<Metric>();
    metrics.add(new Metric("time", "", new BigDecimal(elapsed), null, null));

    if (!opt.hasOption("certificate")) {
        if (opt.hasOption("string")) {
            boolean found = false;
            String string = opt.getOptionValue("string");
            found = response.contains(string);
            metrics.add(new Metric("string", "", new BigDecimal(Utils.getIntValue(found)), null, null));
        }
        if (opt.hasOption("expect")) {
            int count = 0;
            String[] values = opt.getOptionValue("expect").split(",");
            for (String value : values) {
                if (response.contains(value)) {
                    count++;
                }
            }
            metrics.add(new Metric("expect", String.valueOf(count) + " times. ", new BigDecimal(count), null,
                    null));
        }
        if (opt.hasOption("regex")) {
            String regex = opt.getOptionValue("regex");
            Pattern p = null;
            int flags = 0;
            if (opt.hasOption("eregi")) {
                flags = Pattern.CASE_INSENSITIVE;
            }
            if (opt.hasOption("linespan")) {
                flags = flags | Pattern.MULTILINE;
            }
            p = Pattern.compile(regex, flags);
            boolean found = p.matcher(response).find();
            if (opt.hasOption("invert-regex")) {
                metrics.add(new Metric("invert-regex", String.valueOf(found),
                        new BigDecimal(Utils.getIntValue(found)), null, null));
            } else {
                metrics.add(new Metric("regex", String.valueOf(found), new BigDecimal(Utils.getIntValue(found)),
                        null, null));
            }
        }
    }
    return metrics;
}

From source file:com.adgear.data.plugin.IDLSchemaMojo.java

/**
 * Inspect the source for dependency requirement statements
 *
 * @param source IDL source code/*from ww w  .  j  a  va  2s .  co  m*/
 * @return Collection of dependency names
 */
protected Collection<String> collectDependencies(String source) {
    HashSet<String> found = new HashSet<String>();
    Matcher start = Pattern.compile("/\\*\\*", Pattern.MULTILINE).matcher(source);
    Matcher end = Pattern.compile("\\*/", Pattern.MULTILINE).matcher(source);
    if (start.find() && end.find()) {
        String doc = source.substring(start.start() + 3, end.end() - 2);
        Matcher dep = docstringPattern.matcher(doc);
        if (dep.find()) {
            Matcher required = Pattern.compile("([a-zA-Z0-9$_\\.]+)", Pattern.MULTILINE).matcher(dep.group(1));
            while (required.find()) {
                String name = required.group(1);
                found.add(name);
                getLog().debug("Registering dependency '" + name + "'");
            }
        }
    }
    return found;
}

From source file:org.zanata.adapter.TSAdapter.java

private String getContext(Event event) {
    // TODO: Numerusform bug workaround, remove when fixed
    StartGroup startGroup = event.getStartGroup();
    {/* w w  w.  ja v  a  2s .c o  m*/
        Pattern pattern = Pattern.compile("<name>(.+)</name>", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(startGroup.toString());
        if (startGroup.getName() == null && matcher.find()) {
            log.info("Qt ts context bug encountered, returning {} from {}", matcher.group(1),
                    startGroup.toString());
            return matcher.group(1);
        }
    }
    return startGroup.getName() == null ? "" : event.getStartGroup().getName();
}

From source file:com.avapira.bobroreader.hanabira.HanabiraParser.java

private void formatTwoLevelBulletList() {
    Pattern p = Pattern.compile("^(\\*\\s){1,2}([^\\*\\s].*?)$", Pattern.MULTILINE);
    Matcher m = p.matcher(builder);

    // when happens replacement with such strings as old.length!=new.length, actual size of builder changing and
    // indexing broken for following matching. Since that we need to track that discrepancy
    int delta = 0;
    final int replacementLength = 2; // == " ".length() == "? ".length()

    while (m.find()) {
        int start = m.start() - delta;
        int paraLength = m.group().length();
        boolean single = !m.group().substring(0, m.start(2) - m.start()).matches("\\*\\s\\*\\s");
        String replacement = single ? "? " : " ";
        int level = single ? 1 : 2;
        int oldStringLength = 2 * level; // "* " or "* * "
        int diff = oldStringLength - replacementLength;

        builder.replace(start, start + oldStringLength, replacement);
        builder.setSpan(new BulletListSpan(level), start - delta, start + paraLength - delta - diff, 0);
        delta += diff;/*w ww  .  j  a v  a 2 s.c om*/
    }
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * Logs response details to debug and logs error message as error if found
 * @param filePost/*  ww w .j  a  v a2  s  .  com*/
 * @throws IOException
 */
private void logResponseDetails(HttpMethodBase filePost) throws IOException {
    InputStream stream = filePost.getResponseBodyAsStream();
    if (stream == null) {
        throw new IOException("Null response stream");
    }

    String responseBody = IOUtils.toString(stream);
    getLog().debug("Response body: " + responseBody);

    String errorPattern = "(?<=<span class=\"error_line\">)(.+)(?=</span>)";
    Pattern regex = Pattern.compile(errorPattern,
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
    Matcher matcher = regex.matcher(responseBody);

    StringBuilder errorMessage = new StringBuilder();

    while (matcher.find()) {
        errorMessage.append(matcher.group() + " ");
    }

    if (!StringUtils.isEmpty(errorMessage.toString())) {
        getLog().error(errorMessage.toString());
    }
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.TrafficController.java

private Map<Integer, Integer> parseStatsString(String stats) {
    //Example class stats segment (multiple present in tc output)
    //  class htb 42:4 parent 42:3 prio 0 rate 1000Kbit ceil 7000Kbit burst1600b cburst 1598b
    //   Sent 77921300 bytes 52617 pkt (dropped 0, overlimits 0 requeues 0)
    //   rate 6973Kbit 589pps backlog 0b 39p requeues 0
    //   lended: 3753 borrowed: 22514 giants: 0
    //   tokens: -122164 ctokens: -52488

    String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(stats);
    Pattern tcClassPattern = Pattern.compile(String.format("class htb %d:(\\d+) .*", ROOT_QDISC_HANDLE));
    Pattern bytesPattern = Pattern.compile("Sent (\\d+) bytes.*");

    int currentClassId = -1;
    Map<Integer, Integer> containerClassIdStats = new HashMap<>();

    for (String lineSplit : lines) {
        String line = lineSplit.trim();

        if (!line.isEmpty()) {
            //Check if we encountered a stats segment for a container class
            Matcher classMatcher = tcClassPattern.matcher(line);
            if (classMatcher.matches()) {
                int classId = Integer.parseInt(classMatcher.group(1));
                if (classId >= MIN_CONTAINER_CLASS_ID) {
                    currentClassId = classId;
                    continue;
                }//from  w  ww  . j a  va 2s. c om
            }

            //Check if we encountered a stats line
            Matcher bytesMatcher = bytesPattern.matcher(line);
            if (bytesMatcher.matches()) {
                //we found at least one class segment
                if (currentClassId != -1) {
                    int bytes = Integer.parseInt(bytesMatcher.group(1));
                    containerClassIdStats.put(currentClassId, bytes);
                } else {
                    LOG.warn("Matched a 'bytes sent' line outside of a class stats " + "segment : " + line);
                }
                continue;
            }

            //skip other kinds of non-empty lines - since we aren't interested in
            //them.
        }
    }

    return containerClassIdStats;
}

From source file:org.xwiki.commons.internal.DefaultMailSender.java

private Multipart generateMimeMultipart(Mail mail) throws MessagingException {
    Multipart contentsMultipart = new MimeMultipart("alternative");
    List<String> foundEmbeddedImages = new ArrayList<String>();
    boolean hasAttachment = false;

    if (mail.getContents().size() == 1) // To add an alternative plain part
    {//from  ww  w  .  j  av a2s .co  m
        String[] content = mail.getContents().get(0);
        if (content[0].equals("text/plain")) {
            BodyPart alternativePart = new MimeBodyPart();
            alternativePart.setContent(content[1], content[0] + "; charset=" + EMAIL_ENCODING);
            alternativePart.setHeader("Content-Disposition", "inline");
            alternativePart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            contentsMultipart.addBodyPart(alternativePart);
        }
        if (content[0].equals("text/html")) {
            BodyPart alternativePart = new MimeBodyPart();
            String parsedText = createPlain(content[1]);
            alternativePart.setContent(parsedText, "text/plain; charset=" + EMAIL_ENCODING);
            alternativePart.setHeader("Content-Disposition", "inline");
            alternativePart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            contentsMultipart.addBodyPart(alternativePart);
        }
    }

    for (String[] content : mail.getContents()) {
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content[1], content[0] + "; charset=" + EMAIL_ENCODING);
        contentPart.setHeader("Content-Disposition", "inline");
        contentPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
        if (content[0].equals("text/html")) {
            boolean hasEmbeddedImages = false;
            List<MimeBodyPart> embeddedImages = new ArrayList<MimeBodyPart>();
            Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            Matcher matcher = cidPattern.matcher(content[1]);
            String filename;
            while (matcher.find()) {
                filename = matcher.group(2);
                for (Attachment attachment : mail.getAttachments()) {
                    if (filename.equals(attachment.getFilename())) {
                        hasEmbeddedImages = true;
                        MimeBodyPart part = createAttachmentPart(attachment);
                        embeddedImages.add(part);
                        foundEmbeddedImages.add(filename);
                    }
                }
            }
            if (hasEmbeddedImages) {
                Multipart htmlMultipart = new MimeMultipart("related");
                htmlMultipart.addBodyPart(contentPart);
                for (MimeBodyPart imagePart : embeddedImages) {
                    htmlMultipart.addBodyPart(imagePart);
                }
                BodyPart HtmlWrapper = new MimeBodyPart();
                HtmlWrapper.setContent(htmlMultipart);
                contentsMultipart.addBodyPart(HtmlWrapper);
            } else
                contentsMultipart.addBodyPart(contentPart);
        } else {
            contentsMultipart.addBodyPart(contentPart);
        }
    }

    Multipart attachmentsMultipart = new MimeMultipart();
    for (Attachment attachment : mail.getAttachments()) {
        if (!foundEmbeddedImages.contains(attachment.getFilename())) {
            hasAttachment = true;
            MimeBodyPart part = this.createAttachmentPart(attachment);
            attachmentsMultipart.addBodyPart(part);
        }
    }
    if (hasAttachment) {
        Multipart wrapper = new MimeMultipart("mixed");
        BodyPart body = new MimeBodyPart();
        body.setContent(contentsMultipart);
        wrapper.addBodyPart(body);
        BodyPart attachments = new MimeBodyPart();
        attachments.setContent(attachmentsMultipart);
        wrapper.addBodyPart(attachments);
        return wrapper;
    }
    return contentsMultipart;
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Creates a Multipart MIME Message (multiple content-types within the same message) from an existing mail
 * //from w  w w.j  a  v  a  2 s .  c o  m
 * @param mail The original Mail
 * @return The Multipart MIME message
 */
public Multipart createMimeMultipart(Mail mail, XWikiContext context)
        throws MessagingException, XWikiException, IOException {
    Multipart multipart;
    List<Attachment> rawAttachments = mail.getAttachments() != null ? mail.getAttachments()
            : new ArrayList<Attachment>();

    if (mail.getHtmlPart() == null && mail.getAttachments() != null) {
        multipart = new MimeMultipart("mixed");

        // Create the text part of the email
        BodyPart textPart = new MimeBodyPart();
        textPart.setContent(mail.getTextPart(), "text/plain; charset=" + EMAIL_ENCODING);
        multipart.addBodyPart(textPart);

        // Add attachments to the main multipart
        for (Attachment attachment : rawAttachments) {
            multipart.addBodyPart(createAttachmentBodyPart(attachment, context));
        }
    } else {
        multipart = new MimeMultipart("mixed");
        List<Attachment> attachments = new ArrayList<Attachment>();
        List<Attachment> embeddedImages = new ArrayList<Attachment>();

        // Create the text part of the email
        BodyPart textPart;
        textPart = new MimeBodyPart();
        textPart.setText(mail.getTextPart());

        // Create the HTML part of the email, define the html as a multipart/related in case there are images
        Multipart htmlMultipart = new MimeMultipart("related");
        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(mail.getHtmlPart(), "text/html; charset=" + EMAIL_ENCODING);
        htmlPart.setHeader("Content-Disposition", "inline");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
        htmlMultipart.addBodyPart(htmlPart);

        // Find images used with src="cid:" in the email HTML part
        Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher matcher = cidPattern.matcher(mail.getHtmlPart());
        List<String> foundEmbeddedImages = new ArrayList<String>();
        while (matcher.find()) {
            foundEmbeddedImages.add(matcher.group(2));
        }

        // Loop over the attachments of the email, add images used from the HTML to the list of attachments to be
        // embedded with the HTML part, add the other attachements to the list of attachments to be attached to the
        // email.
        for (Attachment attachment : rawAttachments) {
            if (foundEmbeddedImages.contains(attachment.getFilename())) {
                embeddedImages.add(attachment);
            } else {
                attachments.add(attachment);
            }
        }

        // Add the images to the HTML multipart (they should be hidden from the mail reader attachment list)
        for (Attachment image : embeddedImages) {
            htmlMultipart.addBodyPart(createAttachmentBodyPart(image, context));
        }

        // Wrap the HTML and text parts in an alternative body part and add it to the main multipart
        Multipart alternativePart = new MimeMultipart("alternative");
        BodyPart alternativeMultipartWrapper = new MimeBodyPart();
        BodyPart htmlMultipartWrapper = new MimeBodyPart();
        alternativePart.addBodyPart(textPart);
        htmlMultipartWrapper.setContent(htmlMultipart);
        alternativePart.addBodyPart(htmlMultipartWrapper);
        alternativeMultipartWrapper.setContent(alternativePart);
        multipart.addBodyPart(alternativeMultipartWrapper);

        // Add attachments to the main multipart
        for (Attachment attachment : attachments) {
            multipart.addBodyPart(createAttachmentBodyPart(attachment, context));
        }
    }

    return multipart;
}

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  a  2s .com
    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();
    }
}