Example usage for java.util.regex MatchResult end

List of usage examples for java.util.regex MatchResult end

Introduction

In this page you can find the example usage for java.util.regex MatchResult end.

Prototype

public int end(int group);

Source Link

Document

Returns the offset after the last character of the subsequence captured by the given group during this match.

Usage

From source file:net.solarnetwork.util.StringMerger.java

/**
 * Merge from a String source into a StringBuilder.
 * /*w w  w  . jav a  2  s  . c  om*/
 * @param src
 *        the source String to substitute into
 * @param data
 *        the data object to substitute with
 * @param nullValue
 *        the value to substitute for null data
 * @param buf
 *        the StringBuilder to append the output to
 */
public static void mergeString(String src, Object data, String nullValue, StringBuilder buf) {
    Matcher matcher = MERGE_VAR_PAT.matcher(src);

    //MatchResult[] matches = MERGE_VAR_PAT.matcher(src);
    //REMatch[] matches = MERGE_VAR_RE.getAllMatches(src);
    if (!matcher.find()) {
        buf.append(src);
    } else {
        int endLastMatchIdx = 0;
        do {
            MatchResult matchResult = matcher.toMatchResult();

            // append everything from the end of the last
            // match to the start of this match
            buf.append(src.substring(endLastMatchIdx, matchResult.start()));

            // perform substitution here...
            if (data != null) {
                int s = matchResult.start(1);
                int e = matchResult.end(1);
                if ((s > -1) && (e > -1)) {
                    String varName = src.substring(s, e);
                    if (data instanceof java.util.Map<?, ?>) {
                        Object o = null;
                        int sepIdx = varName.indexOf('.');
                        if (sepIdx > 0) {
                            String varName2 = varName.substring(sepIdx + 1);
                            varName = varName.substring(0, sepIdx);
                            o = ((Map<?, ?>) data).get(varName);
                            if (o != null) {
                                try {
                                    o = PropertyUtils.getProperty(o, varName2);
                                } catch (Exception e2) {
                                    LOG.warn("Exception getting property '" + varName2 + "' out of "
                                            + o.getClass() + ": " + e2);
                                }
                            }
                        } else {
                            // simply check for key
                            o = ((Map<?, ?>) data).get(varName);
                        }
                        if (o == null || (String.class.isAssignableFrom(o.getClass())
                                && !StringUtils.hasText(o.toString()))) {
                            buf.append(nullValue);
                        } else {
                            buf.append(o);
                        }
                    } else {
                        // use reflection to get a bean property
                        try {
                            Object o = PropertyUtils.getProperty(data, varName);
                            if (o == null || (String.class.isAssignableFrom(o.getClass())
                                    && !StringUtils.hasText(o.toString()))) {
                                buf.append(nullValue);
                            } else {
                                buf.append(o);
                            }
                        } catch (Exception ex) {
                            LOG.warn("Exception getting property '" + varName + "' out of " + data.getClass()
                                    + ": " + ex);
                            buf.append(nullValue);
                        }
                    }
                }
                endLastMatchIdx = matchResult.end();
            }
        } while (matcher.find());

        if (endLastMatchIdx < src.length()) {
            buf.append(src.substring(endLastMatchIdx));
        }
    }
}

From source file:at.ac.tuwien.big.testsuite.impl.validator.XhtmlValidator.java

@Override
public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception {
    HttpPost request = new HttpPost(W3C_XHTML_VALIDATOR_URL);
    List<ValidationResultEntry> validationResultEntries = new ArrayList<>();

    try {//from  ww  w.j  a v a 2 s  . com
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("uploaded_file", new FileBody(fileToValidate, "text/html"));
        multipartEntity.addPart("charset", new StringBody("(detect automatically)"));
        multipartEntity.addPart("doctype", new StringBody("Inline"));
        multipartEntity.addPart("group", new StringBody("0"));

        request.setEntity(multipartEntity);
        Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request));

        String doctype = DomUtils.textByXpath(doc.getDocumentElement(),
                "//form[@id='form']/table//tr[4]/td[1]");

        if (!"XHTML 1.1".equals(doctype.trim()) && !doctype.contains("XHTML+ARIA 1.0")) {
            validationResultEntries.add(new DefaultValidationResultEntry("Doctype Validation",
                    "The given document is not XHTML 1.1 compatible, instead the guessed doctype is '" + doctype
                            + "'",
                    ValidationResultEntryType.ERROR));
        }

        Document fileToValidateDocument = null;

        Element warningsContainer = DomUtils.byId(doc.getDocumentElement(), "warnings");

        if (warningsContainer != null) {
            for (Element warningChildElement : DomUtils.asList(warningsContainer.getChildNodes())) {
                if (IGNORED_MESSAGES.contains(warningChildElement.getAttribute("id"))) {
                    continue;
                }

                ValidationResultEntryType type = getEntryType(warningChildElement.getAttribute("class"));
                String title = getTitle(
                        DomUtils.firstByClass(warningChildElement.getElementsByTagName("span"), "msg"));
                StringBuilder descriptionSb = new StringBuilder();

                for (Element descriptionElement : DomUtils.listByXpath(warningChildElement,
                        ".//p[position()>1]")) {
                    descriptionSb.append(descriptionElement.getTextContent());
                }

                validationResultEntries
                        .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type));
            }
        }

        Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "error_loop");

        if (errorsContainer != null) {
            for (Element errorChildElement : DomUtils.asList(errorsContainer.getChildNodes())) {
                ValidationResultEntryType type = getEntryType(errorChildElement.getAttribute("class"));
                StringBuilder titleSb = new StringBuilder();
                NodeList errorEms = errorChildElement.getElementsByTagName("em");

                if (errorEms.getLength() > 0) {
                    titleSb.append(getTitle((Element) errorEms.item(0)));
                    titleSb.append(": ");
                }

                titleSb.append(
                        getTitle(DomUtils.firstByClass(errorChildElement.getElementsByTagName("span"), "msg")));
                StringBuilder descriptionSb = new StringBuilder();

                for (Element descriptionElement : DomUtils.listByXpath(errorChildElement, ".//div/p")) {
                    descriptionSb.append(descriptionElement.getTextContent());
                }

                String title = titleSb.toString();

                if (TestsuiteConstants.EX_ID_LAB3.equals(exerciseId)) {
                    // This is more a hack than anything else but we have to ignore the errors that were produced by JSF specific artifacts.
                    // We basically extract the line and column number from the reported errors and look for the 2 elements that match these
                    // numbers and check if they really are the input elements produced by forms that cant be wrapped by block containers.
                    // More specifically we check for inputs with type hidden, one is for the ViewState of JSF and the other is for recognition
                    // of the form that was submitted.
                    Matcher matcher = LINE_AND_COLUMN_NUMBER_PATTERN.matcher(title);

                    if (title.contains("document type does not allow element \"input\" here")
                            && matcher.matches()) {
                        if (fileToValidateDocument == null) {
                            fileToValidateDocument = DomUtils.createDocument(fileToValidate);
                        }

                        boolean excludeEntry = false;
                        int expectedLineNumber = Integer.parseInt(matcher.group(1));
                        int expectedColumnNumber = Integer.parseInt(matcher.group(2));

                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(new FileInputStream(fileToValidate)))) {
                            String line;

                            while ((line = reader.readLine()) != null) {
                                if (--expectedLineNumber == 0) {
                                    Matcher lineMatcher = HIDDEN_FORM_INPUT_PATTERN.matcher(line);

                                    if (lineMatcher.matches()) {
                                        MatchResult matchResult = lineMatcher.toMatchResult();
                                        if (matchResult.start(1) <= expectedColumnNumber
                                                && matchResult.end(1) >= expectedColumnNumber) {
                                            excludeEntry = true;
                                            break;
                                        }
                                    }

                                    lineMatcher = HIDDEN_VIEW_STATE_INPUT_PATTERN.matcher(line);

                                    if (lineMatcher.matches()) {
                                        MatchResult matchResult = lineMatcher.toMatchResult();
                                        if (matchResult.start(1) <= expectedColumnNumber
                                                && matchResult.end(1) >= expectedColumnNumber) {
                                            excludeEntry = true;
                                            break;
                                        }
                                    }

                                    System.out.println("Could not match potential wrong error.");

                                    break;
                                }
                            }
                        }

                        if (excludeEntry) {
                            continue;
                        }
                    }
                }

                validationResultEntries
                        .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type));
            }
        }
    } finally {
        request.releaseConnection();
    }

    return new DefaultValidationResult("XHTML Validation", fileToValidate.getName(),
            new DefaultValidationResultType("XHTML"), validationResultEntries);
}