Example usage for java.util.regex Matcher groupCount

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

Introduction

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

Prototype

public int groupCount() 

Source Link

Document

Returns the number of capturing groups in this matcher's pattern.

Usage

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Parse the reconnection policy./*w  ww  . j a  va2s .  co  m*/
 */
public static ReconnectionPolicy parseReconnectionPolicy(String reconnectionPolicyString)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException,
        SecurityException, IllegalArgumentException, InvocationTargetException {
    String lb_regex = "([a-zA-Z]*Policy)(\\()(.*)(\\))";
    Pattern lb_pattern = Pattern.compile(lb_regex);
    Matcher lb_matcher = lb_pattern.matcher(reconnectionPolicyString);
    if (lb_matcher.matches()) {
        if (lb_matcher.groupCount() > 0) {
            // Primary LB policy has been specified
            String primaryReconnectionPolicy = lb_matcher.group(1);
            String reconnectionPolicyParams = lb_matcher.group(3);
            return getReconnectionPolicy(primaryReconnectionPolicy, reconnectionPolicyParams);
        }
    }
    return null;
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Parse the load balancing policy./*from   ww w .j  a va 2  s. co  m*/
 */
public static LoadBalancingPolicy parseLbPolicy(String loadBalancingPolicyString)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException,
        SecurityException, IllegalArgumentException, InvocationTargetException {
    String lb_regex = "([a-zA-Z]*Policy)(\\()(.*)(\\))";
    Pattern lb_pattern = Pattern.compile(lb_regex);
    if (!loadBalancingPolicyString.contains("(")) {
        loadBalancingPolicyString += "()";
    }
    Matcher lb_matcher = lb_pattern.matcher(loadBalancingPolicyString);

    if (lb_matcher.matches()) {
        if (lb_matcher.groupCount() > 0) {
            // Primary LB policy has been specified
            String primaryLoadBalancingPolicy = lb_matcher.group(1);
            String loadBalancingPolicyParams = lb_matcher.group(3);
            return getLbPolicy(primaryLoadBalancingPolicy, loadBalancingPolicyParams);
        }
    }
    return null;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
  * Method to compare two passwords. The method attempts to encode the user
  * password based on the ldap password encoding extracted from the storage
  * format (e.g. {SHA}g0bbl3d3g00ka12@#19/=).
  *//from  w w w .  j a  v  a2s.com
  * @param userPassword
  *        the password that the user entered
  * @param ldapPassword
  *        the password from the ldap directory
  * @return true if userPassword equals ldapPassword with respect to encoding
  */
private static boolean passwordsMatch(String userPassword, String ldapPassword) {
    Matcher m = LDAP_PASSWORD_PATTERN.matcher(ldapPassword);

    boolean match = false;
    if (m.find() && m.groupCount() == 2) {
        // if password is encoded in the LDAP, encode the password before
        // compare
        String encoding = m.group(1);
        String password = m.group(2);
        if (log.isDebugEnabled()) {
            log.debug("Encoding: {}, Password: {}", encoding, password);
        }

        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance(encoding.toUpperCase());
        } catch (NoSuchAlgorithmException e) {
            log.error("Unsupported Algorithm used: {}", encoding);
            log.error(e.getMessage());
            return false;
        }

        byte[] resultBytes = digest.digest(userPassword.getBytes());
        byte[] result = Base64.encodeBase64(resultBytes);

        String pwd = new String(password);
        String ldp = new String(result);
        match = pwd.equals(ldp);
    } else {
        // if passwords are not encoded, just do raw compare
        match = userPassword.equals(ldapPassword);
    }

    return match;
}

From source file:org.apache.hadoop.hbase.migration.nineteen.regionserver.HStoreFile.java

private static boolean isReference(final Path p, final Matcher m) {
    if (m == null || !m.matches()) {
        LOG.warn("Failed match of store file name " + p.toString());
        throw new RuntimeException("Failed match of store file name " + p.toString());
    }//from w  ww . j a  v  a2 s  . c o  m
    return m.groupCount() > 1 && m.group(2) != null;
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtil.java

/**
 * Puts part of line, which matches regexp into given template
 * on positions $n where 'n' is number of matched part in line.
 * @param template the string to expand.
 * @param lineToPlaceInTemplate contains expression which should be placed into string.
 * @param regexp expression to find in comment.
 * @return the string, based on template filled with given lines
 */// w  w w  . ja v  a  2s  .  c  o m
public static String fillTemplateWithStringsByRegexp(String template, String lineToPlaceInTemplate,
        Pattern regexp) {
    final Matcher matcher = regexp.matcher(lineToPlaceInTemplate);
    String result = template;
    if (matcher.find()) {
        for (int i = 0; i <= matcher.groupCount(); i++) {
            // $n expands comment match like in Pattern.subst().
            result = result.replaceAll("\\$" + i, matcher.group(i));
        }
    }
    return result;
}

From source file:com.omertron.thetvdbapi.tools.TvdbParser.java

/**
 * Parse the error message to return a more user friendly message
 *
 * @param errorMessage//  w  w w.  jav a 2  s.  com
 * @return
 */
public static String parseErrorMessage(String errorMessage) {
    StringBuilder response = new StringBuilder();

    Pattern pattern = Pattern.compile(".*?/series/(\\d*?)/default/(\\d*?)/(\\d*?)/.*?");
    Matcher matcher = pattern.matcher(errorMessage);

    // See if the error message matches the pattern and therefore we can decode it
    if (matcher.find() && matcher.groupCount() == ERROR_MSG_GROUP_COUNT) {
        int seriesId = Integer.parseInt(matcher.group(ERROR_MSG_SERIES));
        int seasonId = Integer.parseInt(matcher.group(ERROR_MSG_SEASON));
        int episodeId = Integer.parseInt(matcher.group(ERROR_MSG_EPISODE));

        response.append("Series Id: ").append(seriesId);
        response.append(", Season: ").append(seasonId);
        response.append(", Episode: ").append(episodeId);
        response.append(": ");

        if (episodeId == 0) {
            // We should probably try an scrape season 0/episode 1
            response.append("Episode seems to be a misnamed pilot episode.");
        } else if (episodeId > MAX_EPISODE) {
            response.append("Episode number seems to be too large.");
        } else if (seasonId == 0 && episodeId > 1) {
            response.append("This special episode does not exist.");
        } else if (errorMessage.toLowerCase().contains(ERROR_NOT_ALLOWED_IN_PROLOG)) {
            response.append(ERROR_RETRIEVE_EPISODE_INFO);
        } else {
            response.append("Unknown episode error: ").append(errorMessage);
        }
    } else {
        // Don't recognise the error format, so just return it
        if (errorMessage.toLowerCase().contains(ERROR_NOT_ALLOWED_IN_PROLOG)) {
            response.append(ERROR_RETRIEVE_EPISODE_INFO);
        } else {
            response.append("Episode error: ").append(errorMessage);
        }
    }

    return response.toString();
}

From source file:ch.entwine.weblounge.common.impl.util.config.ConfigurationUtils.java

/**
 * Parses <code>duration</code> to determine the number of milliseconds that
 * it represents. <code>duration</code> may either be a <code>Long</code>
 * value or a duration encoded using the following characters:
 * <ul>//from ww  w . j  a va2 s.  c o  m
 * <li><b>y</b> - years</li>
 * <li><b>m</b> - months</li>
 * <li><b>w</b> - weeks</li>
 * <li><b>d</b> - days</li>
 * <li><b>H</b> - hours</li>
 * <li><b>M</b> - minutes</li>
 * <li><b>S</b> - seconds</li>
 * </ul>
 * Therefore, an example representing 1 week, 3 days and 25 minutes would
 * result in <code>1w3d25m</code>.
 * 
 * @param duration
 *          the duration either in milliseconds or encoded
 * @return the duration in milliseconds
 * @throws IllegalArgumentException
 *           if the duration cannot be parsed
 */
public static long parseDuration(String duration) throws IllegalArgumentException {
    if (duration == null)
        return 0;
    long millis = 0;
    try {
        return Long.parseLong(duration);
    } catch (NumberFormatException e) {
        Pattern p = Pattern.compile("^([\\d]+y)?([\\d]+m)?([\\d]+w)?([\\d]+d)?([\\d]+H)?([\\d]+M)?([\\d]+S)?$");
        Matcher m = p.matcher(duration);
        if (m.matches()) {
            for (int i = 1; i <= m.groupCount(); i++) {
                String match = m.group(i);
                if (match == null)
                    continue;
                if (match.endsWith("y"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_YEAR;
                if (match.endsWith("m"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_MONTH;
                if (match.endsWith("w"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_WEEK;
                if (match.endsWith("d"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_DAY;
                if (match.endsWith("H"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_HOUR;
                if (match.endsWith("M"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_MIN;
                if (match.endsWith("S"))
                    millis += Long.parseLong(match.substring(0, match.length() - 1)) * Times.MS_PER_SECOND;
            }
        } else {
            throw new IllegalArgumentException("Unknown duration format: " + duration);
        }
    }
    return millis;
}

From source file:fr.cls.atoll.motu.processor.wps.framework.WPSUtils.java

/**
 * Decode processlet exception error message.
 * /* w ww.j a va  2s.co  m*/
 * @param msg the msg
 * 
 * @return the list< string>
 */
public static List<String> decodeProcessletExceptionErrorMessage(String msg) {

    List<String> result = new ArrayList<String>();

    String regExpr = "(" + WPSUtils.PROCESSLET_EXCEPTION_FORMAT_CODE + ")(.*)("
            + WPSUtils.PROCESSLET_EXCEPTION_FORMAT_MSG + ")(.*)";

    Pattern p = Pattern.compile(regExpr);

    Matcher matcher = p.matcher(msg);
    boolean matchFound = matcher.find();

    // Find all matches
    if (matchFound) {
        // Get all groups for this match
        for (int i = 0; i <= matcher.groupCount(); i++) {
            String groupStr = matcher.group(i);
            result.add(groupStr);
        }
    }

    return result;
}

From source file:org.andrewberman.sync.InheritMe.java

static LinkedHashMap<String, String> getPDFsFromPage(String pageURL, String pageContent) throws Exception {
    LinkedHashMap<String, String> idToURL = new LinkedHashMap<String, String>();
    Matcher m = pdfURL.matcher(pageContent);
    while (m.find()) {
        String aid = m.group(m.groupCount());
        String url = m.group(m.groupCount() - 1);
        //         System.out.printf("  PDF %s %s\n",aid,url);
        url = relativeToAbsoluteURL(pageURL, url);
        idToURL.put(aid, url);// w  w w. j av  a 2  s .c o  m
    }
    return idToURL;
}

From source file:org.andrewberman.sync.InheritMe.java

static LinkedHashMap<String, String> getArticlesFromPage(String pageURL, String pageContent) throws Exception {
    System.out.println(pageURL);/*from   w  w w .j a v  a  2s .  com*/
    LinkedHashMap<String, String> idToURL = new LinkedHashMap<String, String>();
    Matcher m = articleURL.matcher(pageContent);
    while (m.find()) {
        String aid = m.group(m.groupCount());
        String url = m.group(m.groupCount() - 1);
        //         System.out.printf("%s %s\n", aid,url);
        /*
         * If it's a PDF link, then we don't want to keep it in here.
         */
        if (pdfURL.matcher(url).matches())
            continue;
        url = relativeToAbsoluteURL(pageURL, url);
        idToURL.put(aid, url);
    }
    return idToURL;
}