Example usage for java.util.regex Matcher hitEnd

List of usage examples for java.util.regex Matcher hitEnd

Introduction

In this page you can find the example usage for java.util.regex Matcher hitEnd.

Prototype

boolean hitEnd

To view the source code for java.util.regex Matcher hitEnd.

Click Source Link

Document

Boolean indicating whether or not more input could change the results of the last match.

Usage

From source file:org.openmrs.module.patientflags.evaluator.SQLFlagEvaluator.java

@Override
public String evalMessage(Flag flag, int patientId) {
    String literal = "\\$\\{\\d{1,2}\\}";
    String message = flag.getMessage();

    if (!message.matches(".*(" + literal + ")+.*")) {
        return message;
    }/*  w w w. j av  a 2s  .c o m*/

    log.info("Replacing values in " + message);

    Patient p = Context.getPatientService().getPatient(patientId);
    if (p.isVoided())
        throw new APIException("VOIDED PATIENT");

    String criteria = flag.getCriteria();

    // pull out the "*.patient_id" clause
    // is this robust enough?
    Matcher matcher = Pattern.compile("(\\w+\\.patient_id)").matcher(criteria);
    matcher.find(); // just check for the first occurrence of the pattern... is this enough?
    String patientIdColumn = matcher.group();

    // since we are going to append a where/and to the end of this sql statement, we need to trim off trailing ";" and any trailing whitespace
    matcher = Pattern.compile(";?\\s*$").matcher(criteria);
    criteria = matcher.replaceFirst(""); // replace first, because there should only be one occurrence

    // create the criteria for a single patient by appending a "where" or "and" clause
    String toEval = criteria + (criteria.matches("(?i)(?s).*where.*") ? " and " : " where ") + patientIdColumn
            + " = " + p.getPatientId();

    try {
        Context.addProxyPrivilege("SQL Level Access");
        List<List<Object>> resultSet = Context.getAdministrationService().executeSQL(toEval, true);
        // list would for sure contain one only one patient
        if (!resultSet.isEmpty()) {// empty resultset means no one matched the criteria
            Matcher m = Pattern.compile(literal).matcher(message);
            while (!m.hitEnd() && m.find()) {// replace each instance until end
                String replaceString = m.group();
                try {
                    //get index between the brackets ${indexNumber}
                    int index = Integer.parseInt(replaceString.replace("${", "").replace("}", ""));
                    if (index < resultSet.get(0).size()) {// do nothing if index is invalid
                        message = message.replace(replaceString, resultSet.get(0).get(index).toString());
                        log.info("Replaced " + replaceString + " ON " + index);
                    }
                } catch (Exception e) {
                    //do nothing. text would remain unreplaced
                }
            }
        } else {
            log.info("result set empty");
        }
    } catch (Exception e) {
        throw new APIException(
                "Unable to evaluate SQL Flag Message" + flag.getName() + ", " + e.getLocalizedMessage(), e);
    } finally {
        Context.removeProxyPrivilege("SQL Level Access");
    }

    return message;
}

From source file:com.todoroo.astrid.adapter.UpdateAdapter.java

public static Spanned getUpdateComment(final AstridActivity context, UserActivity activity, User user,
        String linkColor, String fromView) {
    String userDisplay;/*  ww w.  j a va2 s  . com*/
    if (activity.getValue(UserActivity.USER_UUID).equals(Task.USER_ID_SELF)) {
        userDisplay = context.getString(R.string.update_string_user_self);
    } else if (user == null) {
        userDisplay = context.getString(R.string.ENA_no_user);
    } else {
        userDisplay = user.getDisplayName(USER_NAME, USER_FIRST_NAME, USER_LAST_NAME);
    }
    if (TextUtils.isEmpty(userDisplay))
        userDisplay = context.getString(R.string.ENA_no_user);
    String targetName = activity.getValue(UserActivity.TARGET_NAME);
    String action = activity.getValue(UserActivity.ACTION);
    String message = activity.getValue(UserActivity.MESSAGE);

    int commentResource = 0;
    if (UserActivity.ACTION_TASK_COMMENT.equals(action)) {
        if (fromView.equals(FROM_TASK_VIEW) || TextUtils.isEmpty(targetName))
            commentResource = R.string.update_string_default_comment;
        else
            commentResource = R.string.update_string_task_comment;
    } else if (UserActivity.ACTION_TAG_COMMENT.equals(action)) {
        if (fromView.equals(FROM_TAG_VIEW) || TextUtils.isEmpty(targetName))
            commentResource = R.string.update_string_default_comment;
        else
            commentResource = R.string.update_string_tag_comment;
    }

    if (commentResource == 0)
        return Html.fromHtml(String.format("%s %s", userDisplay, message)); //$NON-NLS-1$

    String original = context.getString(commentResource, userDisplay, targetName, message);
    int taskLinkIndex = original.indexOf(TARGET_LINK_PREFIX);

    if (taskLinkIndex < 0)
        return Html.fromHtml(original);

    String[] components = original.split(" "); //$NON-NLS-1$
    SpannableStringBuilder builder = new SpannableStringBuilder();
    StringBuilder htmlStringBuilder = new StringBuilder();

    for (String comp : components) {
        Matcher m = TARGET_LINK_PATTERN.matcher(comp);
        if (m.find()) {
            builder.append(Html.fromHtml(htmlStringBuilder.toString()));
            htmlStringBuilder.setLength(0);

            String linkType = m.group(1);
            CharSequence link = getLinkSpan(context, activity, targetName, linkColor, linkType);
            if (link != null) {
                builder.append(link);
                if (!m.hitEnd()) {
                    builder.append(comp.substring(m.end()));
                }
                builder.append(' ');
            }
        } else {
            htmlStringBuilder.append(comp);
            htmlStringBuilder.append(' ');
        }
    }

    if (htmlStringBuilder.length() > 0)
        builder.append(Html.fromHtml(htmlStringBuilder.toString()));

    return builder;
}

From source file:org.xchain.framework.jsl.TemplateSourceBuilder.java

/**
 * Parses an attribute value template into fixed and dynamic parts.  This list will always start with a fixed part and
 * then include alternating dynamic and fixed parts.
 *//*from  w  w w .j a v a2  s.c o m*/
public static List<String> parseAttributeValueTemplate(String attributeValueTemplate) throws SAXException {
    // the result.
    ArrayList<String> result = new ArrayList<String>();

    // create the matcher.
    Matcher matcher = ATTRIBUTE_VALUE_TEMPLATE_PATTERN.matcher(attributeValueTemplate);

    while (matcher.find()) {
        String fixedPart = matcher.group(1);
        String dynamicPart = matcher.group(2);

        if (result.isEmpty() && fixedPart == null) {
            result.add("");
        }

        if (fixedPart != null) {
            result.add(fixedPart.replaceAll("\\{\\{", "{").replaceAll("\\}\\}", "}"));
        }
        if (dynamicPart != null) {
            result.add(dynamicPart);
        }
    }

    if (!matcher.hitEnd()) {
        throw new SAXException(
                "The attribute value template '" + attributeValueTemplate + "' has an error between characters "
                        + matcher.regionStart() + " and " + matcher.regionEnd() + ".");
    }

    return result;
}

From source file:com.streamsets.pipeline.lib.parser.log.ExtendedFormatParser.java

@Override
public Map<String, Field> parseLogLine(StringBuilder logLine) throws DataParserException {
    Map<String, Field> map = new HashMap<>();

    // Parse headers
    Matcher m = HEADER_PATTERN.matcher(logLine);
    int counter = 0;
    int index = 0;
    int headerCount = 1;
    while (counter < headerCount && m.find()) {
        String val = logLine.substring(index, m.start());

        if (counter == 0) {
            Field formatVersion = getExtFormatVersion(val);
            map.put(formatType.label + "Version", formatVersion);
            headerCount = getNumHeaderFields(formatType, formatVersion);
        } else {/*from ww  w  .java  2s  .c o m*/
            map.put(getHeaderFieldName(counter), Field.create(val));
        }

        index = m.end();
        counter++;
    }

    if (counter < headerCount) {
        throw new DataParserException(Errors.LOG_PARSER_12, formatName, headerCount, counter);
    }

    // For LEEF 2.0, there is an optional field in the header, so we check for it, and
    // advance the index, if necessary, to get to the start of the extensions
    char attrSeparator = getExtensionAttrSeparator(m, index, logLine);
    if (!m.hitEnd()) {
        index = m.end();
    }

    // Calls to trim() will strip off whitespace, but if format is LEEF 2.0 and a custom
    // delimiter is being used, we need to offset the start index of extension keys
    int offset = 0;
    if (!Character.isWhitespace(attrSeparator)) {
        offset = 1;
    }

    // Process extensions
    Map<String, Field> extMap = new HashMap<>();
    Map<String, String> labelMap = new HashMap<>();
    String ext = logLine.substring(index);
    m = EXT_PATTERN.matcher(ext);
    index = 0;
    String key = null;
    String value;

    while (m.find()) {
        if (key == null) {
            key = ext.substring(index, m.start());
            index = m.end();
            if (!m.find()) {
                break;
            }
        }
        // Regex will search for unescaped '=' character to find the split between keys
        // and values. We'll need to figure out where the separator is to determine the
        // end of the value, and then go back for the next KV pair
        value = ext.substring(index, m.start());
        index = m.end();
        int lastSepIndex = value.lastIndexOf(attrSeparator);
        if (lastSepIndex > 0) {
            String temp = value.substring(0, lastSepIndex).trim();
            putLabelIntoAppropriateMap(labelMap, extMap, key, temp);
            key = value.substring(lastSepIndex + offset).trim();
        }
    }
    value = ext.substring(index);

    // Build a map of Label extensions to apply later
    putLabelIntoAppropriateMap(labelMap, extMap, key, value);

    // Apply the labels to custom fields
    for (Map.Entry<String, String> label : labelMap.entrySet()) {
        if (extMap.containsKey(label.getKey())) {
            Field field = extMap.remove(label.getKey());
            extMap.put(label.getValue(), field);
        }
    }

    map.put("extensions", Field.create(extMap));

    return map;
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

private List<String> _getTransients(Entity entity, boolean parent) throws Exception {

    File modelFile = null;/*from  w  w  w.jav a  2 s .  com*/

    if (parent) {
        modelFile = new File(_outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java");
    } else {
        modelFile = new File(_outputPath + "/model/impl/" + entity.getName() + "Impl.java");
    }

    String content = FileUtils.readFileToString(modelFile);

    Matcher matcher = _getterPattern.matcher(content);

    Set<String> getters = new HashSet<>();

    while (!matcher.hitEnd()) {
        boolean found = matcher.find();

        if (found) {
            String property = matcher.group();

            if (property.contains("get")) {
                property = property.substring(property.indexOf("get") + 3, property.length() - 1);
            } else {
                property = property.substring(property.indexOf("is") + 2, property.length() - 1);
            }

            if (!entity.hasColumn(property) && !entity.hasColumn(Introspector.decapitalize(property))) {

                property = Introspector.decapitalize(property);

                getters.add(property);
            }
        }
    }

    matcher = _setterPattern.matcher(content);

    Set<String> setters = new HashSet<>();

    while (!matcher.hitEnd()) {
        boolean found = matcher.find();

        if (found) {
            String property = matcher.group();

            property = property.substring(property.indexOf("set") + 3, property.length() - 1);

            if (!entity.hasColumn(property) && !entity.hasColumn(Introspector.decapitalize(property))) {

                property = Introspector.decapitalize(property);

                setters.add(property);
            }
        }
    }

    getters.retainAll(setters);

    List<String> transients = new ArrayList<>(getters);

    Collections.sort(transients);

    return transients;
}