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:com.adrup.saldo.bank.lf.LfBankManager.java

@Override
public Map<AccountHashKey, RemoteAccount> getAccounts(Map<AccountHashKey, RemoteAccount> accounts)
        throws BankException {
    Log.d(TAG, "getAccounts()");
    HttpClient httpClient = new SaldoHttpClient(mContext);

    try {//w w w  .  j av a2  s  .com
        // get login page
        Log.d(TAG, "getting login page");
        HttpContext httpContext = new BasicHttpContext();
        String res = HttpHelper.get(httpClient, LOGIN_URL, httpContext);
        HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        String action = currentHost.toURI() + currentReq.getURI();
        Log.e(TAG, "action=" + action);

        Matcher matcher = Pattern.compile(VIEWSTATE_REGEX).matcher(res);
        if (!matcher.find()) {
            Log.e(TAG, "No viewstate match.");
            Log.d(TAG, res);
            throw new LfBankException("No viewState match.");
        }
        String viewState = matcher.group(1);
        Log.d(TAG, "viewState= " + viewState);

        matcher = Pattern.compile(EVENTVALIDATION_REGEX).matcher(res);
        if (!matcher.find()) {
            Log.e(TAG, "No eventvalidation match.");
            Log.d(TAG, res);
            throw new LfBankException("No eventValidation match.");
        }
        String eventValidation = matcher.group(1);
        Log.d(TAG, "eventValidation= " + eventValidation);

        // do login post
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);

        parameters.add(new BasicNameValuePair("__LASTFOCUS", ""));
        parameters.add(new BasicNameValuePair("__EVENTTARGET", ""));
        parameters.add(new BasicNameValuePair("__EVENTARGUMENT", ""));
        parameters.add(new BasicNameValuePair(VIEWSTATE_PARAM, viewState));
        parameters.add(new BasicNameValuePair("selMechanism", "PIN-kod"));
        parameters.add(new BasicNameValuePair(USER_PARAM, mBankLogin.getUsername()));
        parameters.add(new BasicNameValuePair(PASS_PARAM, mBankLogin.getPassword()));
        parameters.add(new BasicNameValuePair("btnLogIn.x", "39"));
        parameters.add(new BasicNameValuePair("btnLogIn.y", "11"));
        parameters.add(new BasicNameValuePair(EVENTVALIDATION_PARAM, eventValidation));

        Log.d(TAG, "logging in...");
        res = HttpHelper.post(httpClient, action, parameters);

        if (res.contains("Felaktig inloggning")) {
            Log.d(TAG, "auth fail");
            throw new AuthenticationException("auth fail");
        }

        Log.d(TAG, "getting accountsUrl");

        // token
        matcher = Pattern.compile(TOKEN_REGEX).matcher(res);
        if (!matcher.find()) {
            Log.e(TAG, "No token match.");
            Log.d(TAG, res);
            throw new LfBankException("No token match.");
        }
        String token = matcher.group(1);
        Log.d(TAG, "token= " + token);

        // accountsUrl
        matcher = Pattern.compile(ACCOUNTS_URL_REGEX).matcher(res);

        if (!matcher.find()) {
            Log.e(TAG, "No accountsUrl match.");
            Log.d(TAG, res);
            throw new LfBankException("No accountsUrl match.");
        }
        String accountsUrl = Html.fromHtml(matcher.group(1)).toString();

        accountsUrl += "&_token=" + token;
        Log.d(TAG, "tokenized accountsUrl= " + accountsUrl);

        // get accounts page
        Log.d(TAG, "fetching accounts");
        res = HttpHelper.get(httpClient, accountsUrl);

        matcher = Pattern.compile(ACCOUNTS_REGEX).matcher(res);

        int remoteId = 1;
        int count = 0;
        while (matcher.find()) {
            count++;
            int groupCount = matcher.groupCount();
            for (int i = 1; i <= groupCount; i++) {
                Log.d(TAG, i + ":" + matcher.group(i));
            }
            if (groupCount < 2) {
                throw new BankException("Pattern match issue: groupCount < 2");
            }

            int ordinal = remoteId;
            String name = Html.fromHtml(matcher.group(1)).toString();
            long balance = Long.parseLong(matcher.group(2).replaceAll("\\,|\\.| ", "")) / 100;
            accounts.put(new AccountHashKey(String.valueOf(remoteId), mBankLogin.getId()),
                    new Account(String.valueOf(remoteId), mBankLogin.getId(), ordinal, name, balance));
            remoteId++;
        }
        if (count == 0) {
            Log.d(TAG, "no accounts added");
            Log.d(TAG, res);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new LfBankException(e.getMessage(), e);

    } catch (HttpException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new LfBankException(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return accounts;
}

From source file:cgeo.geocaching.cgBase.java

public static Map<String, Object> parseLatlon(String latlon) {
    final Map<String, Object> result = new HashMap<String, Object>();
    final Pattern patternLatlon = Pattern.compile(
            "([NS])[^\\d]*(\\d+)[^]* (\\d+)\\.(\\d+) ([WE])[^\\d]*(\\d+)[^]* (\\d+)\\.(\\d+)",
            Pattern.CASE_INSENSITIVE);
    final Matcher matcherLatlon = patternLatlon.matcher(latlon);

    while (matcherLatlon.find()) {
        if (matcherLatlon.groupCount() > 0) {
            result.put("latitudeString", (String) (matcherLatlon.group(1) + " " + matcherLatlon.group(2) + " "
                    + matcherLatlon.group(3) + "." + matcherLatlon.group(4)));
            result.put("longitudeString", (String) (matcherLatlon.group(5) + " " + matcherLatlon.group(6)
                    + " " + matcherLatlon.group(7) + "." + matcherLatlon.group(8)));
            int latNegative = -1;
            int lonNegative = -1;
            if (matcherLatlon.group(1).equalsIgnoreCase("N")) {
                latNegative = 1;/*from ww w  . ja v  a 2 s . c om*/
            }
            if (matcherLatlon.group(5).equalsIgnoreCase("E")) {
                lonNegative = 1;
            }
            result.put("latitude", Double.valueOf(latNegative * (Float.valueOf(matcherLatlon.group(2))
                    + Float.valueOf(matcherLatlon.group(3) + "." + matcherLatlon.group(4)) / 60)));
            result.put("longitude", Double.valueOf(lonNegative * (Float.valueOf(matcherLatlon.group(6))
                    + Float.valueOf(matcherLatlon.group(7) + "." + matcherLatlon.group(8)) / 60)));
        } else {
            Log.w(cgSettings.tag, "cgBase.parseLatlon: Failed to parse coordinates.");
        }
    }

    return result;
}

From source file:cgeo.geocaching.cgBase.java

public static List<Integer> parseTypes(String page) {
    if (StringUtils.isEmpty(page)) {
        return null;
    }/*from   w  ww.  j  av  a2  s .c o m*/

    final List<Integer> types = new ArrayList<Integer>();

    final Pattern typeBoxPattern = Pattern.compile(
            "<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>"
                    + "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>",
            Pattern.CASE_INSENSITIVE);
    final Matcher typeBoxMatcher = typeBoxPattern.matcher(page);
    String typesText = null;
    if (typeBoxMatcher.find()) {
        if (typeBoxMatcher.groupCount() > 0) {
            typesText = typeBoxMatcher.group(1);
        }
    }

    if (typesText != null) {
        final Pattern typePattern = Pattern.compile(
                "<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE);
        final Matcher typeMatcher = typePattern.matcher(typesText);
        while (typeMatcher.find()) {
            if (typeMatcher.groupCount() > 1) {
                final int type = Integer.parseInt(typeMatcher.group(2));

                if (type > 0) {
                    types.add(type);
                }
            }
        }
    }

    return types;
}

From source file:cgeo.geocaching.cgBase.java

public static List<cgTrackableLog> parseTrackableLog(String page) {
    if (StringUtils.isEmpty(page)) {
        return null;
    }/*from  w  w w. j a  va  2 s.co m*/

    final List<cgTrackableLog> trackables = new ArrayList<cgTrackableLog>();

    int startPos = -1;
    int endPos = -1;

    startPos = page.indexOf("<table id=\"tblTravelBugs\"");
    if (startPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: ID \"tblTravelBugs\" not found on page");
        return null;
    }

    page = page.substring(startPos); // cut on <table

    endPos = page.indexOf("</table>");
    if (endPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: end of ID \"tblTravelBugs\" not found on page");
        return null;
    }

    page = page.substring(0, endPos); // cut on </table>

    startPos = page.indexOf("<tbody>");
    if (startPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: tbody not found on page");
        return null;
    }

    page = page.substring(startPos); // cut on <tbody>

    endPos = page.indexOf("</tbody>");
    if (endPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: end of tbody not found on page");
        return null;
    }

    page = page.substring(0, endPos); // cut on </tbody>

    final Pattern trackablePattern = Pattern
            .compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>"
                    + "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>"
                    + "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>"
                    + "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+"
                    + "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE);
    final Matcher trackableMatcher = trackablePattern.matcher(page);
    while (trackableMatcher.find()) {
        if (trackableMatcher.groupCount() > 0) {
            final cgTrackableLog trackable = new cgTrackableLog();

            if (trackableMatcher.group(1) != null) {
                trackable.trackCode = trackableMatcher.group(1);
            } else {
                continue;
            }
            if (trackableMatcher.group(2) != null) {
                trackable.name = Html.fromHtml(trackableMatcher.group(2)).toString();
            } else {
                continue;
            }
            if (trackableMatcher.group(3) != null) {
                trackable.ctl = Integer.valueOf(trackableMatcher.group(3));
            } else {
                continue;
            }
            if (trackableMatcher.group(5) != null) {
                trackable.id = Integer.valueOf(trackableMatcher.group(5));
            } else {
                continue;
            }

            Log.i(cgSettings.tag, "Trackable in inventory (#" + trackable.ctl + "/" + trackable.id + "): "
                    + trackable.trackCode + " - " + trackable.name);

            trackables.add(trackable);
        }
    }

    return trackables;
}

From source file:com.kodemore.utility.Kmu.java

public static KmList<String> getRegexGroups(String source, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(source);
    boolean matches = matcher.matches();

    if (!matches)
        return null;

    KmList<String> v = new KmList<>();

    int n = matcher.groupCount();
    for (int i = 0; i < n; i++)
        v.add(matcher.group(i + 1));/*w  w  w  . j  a  v a2  s. co m*/

    return v;
}

From source file:com.admc.jcreole.Indexer.java

/**
 * This is a highly-modified fork of Tomcat's method
 * DefaultServlet.renderHtml()./*from   ww w.  ja  v a2 s.  c om*/
 *
 * @param directory  Will throw an IllegalArgumentException if this is not
 *        a real directory.
 * @param listUp  Generate an entry for "..".
 * @return HTML fragment that is a HTML table element.
 */
public StringBuilder generateTable(File directory, String displayName, boolean listUp,
        FileComparator.SortBy sortBy, boolean ascendSort) {
    /*
     * TODO: Use an EnumMap or something to cache FileComparators instead
     * of instantiating one for every method call.
     */
    Matcher matcher = null;
    if (!directory.isDirectory())
        throw new IllegalArgumentException("Not a directory:  " + directory.getAbsolutePath());
    if ((namePattern == null && nameFormatString != null) || (namePattern != null && nameFormatString == null))
        throw new IllegalStateException(
                "'namePattern' and 'nameFormatString' must either both be " + "set or both be null");
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);

    String name = displayName;

    sb.append("<table class=\"jcreole_dirindex\" width=\"100%\" "
            + "cellspacing=\"0\" cellpadding=\"5\" align=\"center\">\r\n");

    // Render the column headings
    sb.append("<tr>\r\n");
    sb.append("<td align=\"left\"><font size=\"+1\"><strong>");
    sb.append("<a href=\"?sort=");
    try {
        sb.append(URLEncoder.encode((sortBy == FileComparator.SortBy.NAME && ascendSort) ? "-" : "+", "UTF-8"));
        sb.append("NAME\">Nodename</a>");
        if (sortBy == FileComparator.SortBy.NAME)
            sb.append("<sup>").append(ascendSort ? '+' : '-').append("</sup>");
        sb.append("</strong></font></td>\r\n");
        sb.append("<td align=\"center\"><font size=\"+1\"><strong>");
        sb.append("<a href=\"?sort=");
        sb.append(URLEncoder.encode((sortBy == FileComparator.SortBy.SIZE && ascendSort) ? "-" : "+", "UTF-8"));
        sb.append("SIZE\">Size</a>");
        if (sortBy == FileComparator.SortBy.SIZE)
            sb.append("<sup>").append(ascendSort ? '+' : '-').append("</sup>");
        sb.append("</strong></font></td>\r\n");
        sb.append("<td align=\"right\"><font size=\"+1\"><strong>");
        sb.append("<a href=\"?sort=");
        sb.append(URLEncoder.encode((sortBy == FileComparator.SortBy.MODIFIED && ascendSort) ? "-" : "+",
                "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Unable to encode to UTF-8");
    }
    sb.append("MODIFIED\">Last Modified</a>");
    if (sortBy == FileComparator.SortBy.MODIFIED)
        sb.append("<sup>").append(ascendSort ? '+' : '-').append("</sup>");
    sb.append("</strong></font></td>\r\n");
    sb.append("</tr>");

    boolean shade = true;

    // DIR ENTRY:
    if (listUp) {
        sb.append("<tr");
        sb.append(" bgcolor=\"#eeeeee\"");
        sb.append(">\r\n");

        sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n");
        sb.append("<a href=\"../\"><tt><strong>..</strong>&nbsp;&nbsp;(");
        sb.append(StringEscapeUtils.escapeHtml(tailStripperPattern.matcher(displayName).replaceFirst("")));
        sb.append(")</tt></a></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        sb.append("&nbsp;");
        sb.append("</tt></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        sb.append(StringEscapeUtils
                .escapeHtml(isoDateTimeFormatter.format(directory.getParentFile().lastModified())));
        sb.append("</tt></td>\r\n");

        sb.append("</tr>\r\n");
    } // END DIR ENTRY

    List<File> fileList = Arrays.asList(directory.listFiles(filter));
    Collections.sort(fileList, new FileComparator(sortBy, ascendSort));

    // Render the directory entries within this directory
    for (File file : fileList) {
        String nodeName = file.getName();
        if (namePattern != null) {
            if (file.isFile()) {
                matcher = namePattern.matcher(nodeName);
                if (!matcher.matches())
                    continue;
            } else {
                matcher = null;
            }
        }

        shade = !shade;
        sb.append("<tr");
        if (shade)
            sb.append(" bgcolor=\"#eeeeee\"");
        sb.append(">\r\n");

        sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n");
        sb.append("<a href=\"");
        if (matcher == null) {
            sb.append(nodeName);
        } else {
            // Terrible hack dur to terrible Java varargs limitation:
            switch (matcher.groupCount()) {
            case 1:
                formatter.format(nameFormatString, matcher.group(1));
                break;
            case 2:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2));
                break;
            case 3:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3));
                break;
            case 4:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4));
                break;
            case 5:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5));
                break;
            case 6:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6));
                break;
            case 7:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6), matcher.group(7));
                break;
            case 8:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6), matcher.group(7),
                        matcher.group(8));
                break;
            case 9:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6), matcher.group(7),
                        matcher.group(8), matcher.group(9));
                break;
            default:
                throw new IllegalArgumentException(
                        "Pattern captured too many (" + matcher.groupCount() + ") groups: " + namePattern);
            }
        }
        if (file.isDirectory())
            sb.append('/');
        sb.append("\"><tt>");
        sb.append(StringEscapeUtils.escapeHtml(nodeName));
        if (file.isDirectory())
            sb.append('/');
        sb.append("</tt></a></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        if (file.isDirectory())
            sb.append("&nbsp;");
        else if (file.isFile())
            sb.append(file.length());
        sb.append("</tt></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        sb.append(StringEscapeUtils.escapeHtml(isoDateTimeFormatter.format(file.lastModified())));
        sb.append("</tt></td>\r\n");

        sb.append("</tr>\r\n");
    }

    // Render the page footer
    sb.append("</table>\r\n");

    return sb;
}

From source file:cgeo.geocaching.cgBase.java

public String getMapUserToken(Handler noTokenHandler) {
    final cgResponse response = request(false, "www.geocaching.com", "/map/default.aspx", "GET", "", 0, false);
    final String data = response.getData();
    String usertoken = null;/*from ww  w. j  av  a  2s .c o  m*/

    if (StringUtils.isNotBlank(data)) {
        final Pattern pattern = Pattern.compile("var userToken[^=]*=[^']*'([^']+)';",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

        final Matcher matcher = pattern.matcher(data);
        while (matcher.find()) {
            if (matcher.groupCount() > 0) {
                usertoken = matcher.group(1);
            }
        }
    }

    if (noTokenHandler != null && StringUtils.isBlank(usertoken)) {
        noTokenHandler.sendEmptyMessage(0);
    }

    return usertoken;
}

From source file:cgeo.geocaching.cgBase.java

public Map<String, cgRating> getRating(List<String> guids, List<String> geocodes) {
    if (guids == null && geocodes == null) {
        return null;
    }/*from w  w w .j  a va  2s.c  o m*/

    final Map<String, cgRating> ratings = new HashMap<String, cgRating>();

    try {
        final Map<String, String> params = new HashMap<String, String>();
        if (settings.isLogin()) {
            final Map<String, String> login = settings.getGCvoteLogin();
            if (login != null) {
                params.put("userName", login.get("username"));
                params.put("password", login.get("password"));
            }
        }
        if (CollectionUtils.isNotEmpty(guids)) {
            params.put("cacheIds", implode(",", guids.toArray()));
        } else {
            params.put("waypoints", implode(",", geocodes.toArray()));
        }
        params.put("version", "cgeo");
        final String votes = request(false, "gcvote.com", "/getVotes.php", "GET", params, false, false, false)
                .getData();
        if (votes == null) {
            return null;
        }

        final Pattern patternLogIn = Pattern.compile("loggedIn='([^']+)'", Pattern.CASE_INSENSITIVE);
        final Pattern patternGuid = Pattern.compile("cacheId='([^']+)'", Pattern.CASE_INSENSITIVE);
        final Pattern patternRating = Pattern.compile("voteAvg='([0-9.]+)'", Pattern.CASE_INSENSITIVE);
        final Pattern patternVotes = Pattern.compile("voteCnt='([0-9]+)'", Pattern.CASE_INSENSITIVE);
        final Pattern patternVote = Pattern.compile("voteUser='([0-9.]+)'", Pattern.CASE_INSENSITIVE);

        String voteData = null;
        final Pattern patternVoteElement = Pattern.compile("<vote ([^>]+)>", Pattern.CASE_INSENSITIVE);
        final Matcher matcherVoteElement = patternVoteElement.matcher(votes);
        while (matcherVoteElement.find()) {
            if (matcherVoteElement.groupCount() > 0) {
                voteData = matcherVoteElement.group(1);
            }

            if (voteData == null) {
                continue;
            }

            String guid = null;
            cgRating rating = new cgRating();
            boolean loggedIn = false;

            try {
                final Matcher matcherGuid = patternGuid.matcher(voteData);
                if (matcherGuid.find()) {
                    if (matcherGuid.groupCount() > 0) {
                        guid = (String) matcherGuid.group(1);
                    }
                }
            } catch (Exception e) {
                Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse guid");
            }

            try {
                final Matcher matcherLoggedIn = patternLogIn.matcher(votes);
                if (matcherLoggedIn.find()) {
                    if (matcherLoggedIn.groupCount() > 0) {
                        if (matcherLoggedIn.group(1).equalsIgnoreCase("true")) {
                            loggedIn = true;
                        }
                    }
                }
            } catch (Exception e) {
                Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse loggedIn");
            }

            try {
                final Matcher matcherRating = patternRating.matcher(voteData);
                if (matcherRating.find()) {
                    if (matcherRating.groupCount() > 0) {
                        rating.rating = Float.parseFloat(matcherRating.group(1));
                    }
                }
            } catch (Exception e) {
                Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse rating");
            }

            try {
                final Matcher matcherVotes = patternVotes.matcher(voteData);
                if (matcherVotes.find()) {
                    if (matcherVotes.groupCount() > 0) {
                        rating.votes = Integer.parseInt(matcherVotes.group(1));
                    }
                }
            } catch (Exception e) {
                Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse vote count");
            }

            if (loggedIn) {
                try {
                    final Matcher matcherVote = patternVote.matcher(voteData);
                    if (matcherVote.find()) {
                        if (matcherVote.groupCount() > 0) {
                            rating.myVote = Float.parseFloat(matcherVote.group(1));
                        }
                    }
                } catch (Exception e) {
                    Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse user's vote");
                }
            }

            if (StringUtils.isNotBlank(guid)) {
                ratings.put(guid, rating);
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.getRating: " + e.toString());
    }

    return ratings;
}

From source file:cgeo.geocaching.cgBase.java

public int postLog(cgeoapplication app, String geocode, String cacheid, String[] viewstates, int logType,
        int year, int month, int day, String log, List<cgTrackableLog> trackables) {
    if (isEmpty(viewstates)) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate given");
        return 1000;
    }/* w w w. java 2 s .  c  o m*/

    if (logTypes2.containsKey(logType) == false) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: Unknown logtype");
        return 1000;
    }

    if (StringUtils.isBlank(log)) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No log text given");
        return 1001;
    }

    // fix log (non-Latin characters converted to HTML entities)
    final int logLen = log.length();
    final StringBuilder logUpdated = new StringBuilder();

    for (int i = 0; i < logLen; i++) {
        char c = log.charAt(i);

        if (c > 300) {
            logUpdated.append("&#");
            logUpdated.append(Integer.toString((int) c));
            logUpdated.append(';');
        } else {
            logUpdated.append(c);
        }
    }
    log = logUpdated.toString();

    log = log.replace("\n", "\r\n"); // windows' eol

    if (trackables != null) {
        Log.i(cgSettings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: "
                + year + "." + month + "." + day + ", log: " + log + "; trackables: " + trackables.size());
    } else {
        Log.i(cgSettings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: "
                + year + "." + month + "." + day + ", log: " + log + "; trackables: 0");
    }

    final String host = "www.geocaching.com";
    final String path = "/seek/log.aspx?ID=" + cacheid;
    final String method = "POST";
    final Map<String, String> params = new HashMap<String, String>();

    setViewstates(viewstates, params);
    params.put("__EVENTTARGET", "");
    params.put("__EVENTARGUMENT", "");
    params.put("__LASTFOCUS", "");
    params.put("ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", String.format("%02d", month) + "/"
            + String.format("%02d", day) + "/" + String.format("%04d", year));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day));
    params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year));
    params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
    params.put("ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry");
    params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
    if (trackables != null && trackables.isEmpty() == false) { //  we have some trackables to proceed
        final StringBuilder hdnSelected = new StringBuilder();

        for (cgTrackableLog tb : trackables) {
            final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);

            if (tb.action > 0) {
                hdnSelected.append(action);
                hdnSelected.append(',');
            }
        }

        params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables
        params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
    }

    String page = request(false, host, path, method, params, false, false, false).getData();
    if (checkLogin(page) == false) {
        int loginState = login();
        if (loginState == 1) {
            page = request(false, host, path, method, params, false, false, false).getData();
        } else {
            Log.e(cgSettings.tag, "cgeoBase.postLog: Can not log in geocaching (error: " + loginState + ")");
            return loginState;
        }
    }

    if (StringUtils.isBlank(page)) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No data from server");
        return 1002;
    }

    // maintenance, archived needs to be confirmed
    final Pattern pattern = Pattern.compile(
            "<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>",
            Pattern.CASE_INSENSITIVE);
    final Matcher matcher = pattern.matcher(page);

    try {
        if (matcher.find() && matcher.groupCount() > 0) {
            final String[] viewstatesConfirm = getViewstates(page);

            if (isEmpty(viewstatesConfirm)) {
                Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate for confirm log");
                return 1000;
            }

            params.clear();
            setViewstates(viewstatesConfirm, params);
            params.put("__EVENTTARGET", "");
            params.put("__EVENTARGUMENT", "");
            params.put("__LASTFOCUS", "");
            params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes");
            params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
            params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
            if (trackables != null && trackables.isEmpty() == false) { //  we have some trackables to proceed
                final StringBuilder hdnSelected = new StringBuilder();

                for (cgTrackableLog tb : trackables) {
                    String ctl = null;
                    final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);

                    if (tb.ctl < 10) {
                        ctl = "0" + Integer.toString(tb.ctl);
                    } else {
                        ctl = Integer.toString(tb.ctl);
                    }

                    params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$repTravelBugs$ctl" + ctl
                            + "$ddlAction", action);
                    if (tb.action > 0) {
                        hdnSelected.append(action);
                        hdnSelected.append(',');
                    }
                }

                params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions",
                        hdnSelected.toString()); // selected trackables
                params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
            }

            page = request(false, host, path, method, params, false, false, false).getData();
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.postLog.confim: " + e.toString());
    }

    try {
        final Pattern patternOk = Pattern.compile(
                "<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        final Matcher matcherOk = patternOk.matcher(page);
        if (matcherOk.find()) {
            Log.i(cgSettings.tag, "Log successfully posted to cache #" + cacheid);

            if (app != null && geocode != null) {
                app.saveVisitDate(geocode);
            }

            return 1;
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.postLog.check: " + e.toString());
    }

    Log.e(cgSettings.tag, "cgeoBase.postLog: Failed to post log because of unknown error");
    return 1000;
}

From source file:carnero.cgeo.cgBase.java

public static Double parseDistance(String dst) {
    Double distance = null;//from w  w  w  . j a v  a  2s  .co m

    final Pattern pattern = Pattern.compile("([0-9\\.,]+)[ ]*(km|mi)", Pattern.CASE_INSENSITIVE);
    final Matcher matcher = pattern.matcher(dst);
    while (matcher.find()) {
        if (matcher.groupCount() > 1) {
            if (matcher.group(2).equalsIgnoreCase("km") == true) {
                distance = new Double(matcher.group(1));
            } else {
                distance = new Double(matcher.group(1)) / kmInMiles;
            }
        }
    }

    return distance;
}