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:carnero.cgeo.original.libs.Base.java

public Trackable parseTrackable(String page) {
    if (page == null || page.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.parseTrackable: No page given");
        return null;
    }/* w  ww.j  av  a 2s .com*/

    final Pattern patternTrackableId = Pattern.compile(
            "<a id=\"ctl00_ContentBody_LogLink\" title=\"[^\"]*\" href=\".*log\\.aspx\\?wid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternGeocode = Pattern.compile(
            "<span id=\"ctl00_ContentBody_BugDetails_BugTBNum\" String=\"[^\"]*\">Use[^<]*<strong>(TB[0-9a-z]+)[^<]*</strong> to reference this item.[^<]*</span>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternName = Pattern.compile(
            "<h2>([^<]*<img[^>]*>)?[^<]*<span id=\"ctl00_ContentBody_lbHeading\">([^<]+)</span>[^<]*</h2>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternOwner = Pattern.compile(
            "<dt>[^\\w]*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternReleased = Pattern.compile(
            "<dt>[^\\w]*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternOrigin = Pattern.compile(
            "<dt>[^\\w]*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternSpottedCache = Pattern.compile(
            "<dt>[^\\w]*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternSpottedUser = Pattern.compile(
            "<dt>[^\\w]*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternSpottedUnknown = Pattern.compile(
            "<dt>[^\\w]*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternSpottedOwner = Pattern.compile(
            "<dt>[^\\w]*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternGoal = Pattern.compile(
            "<h3>[^\\w]*Current GOAL[^<]*</h3>[^<]*<p[^>]*>(.*)</p>[^<]*<h3>[^\\w]*About This Item[^<]*</h3>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternDetailsImage = Pattern.compile(
            "<h3>[^\\w]*About This Item[^<]*</h3>([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*<div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternLogs = Pattern.compile(
            "<table class=\"TrackableItemLogTable Table\">(.*)<\\/table>[^<]*<ul", Pattern.CASE_INSENSITIVE);
    final Pattern patternIcon = Pattern.compile(
            "<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternType = Pattern.compile(
            "<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternDistance = Pattern.compile(
            "<h4[^>]*[^\\w]*Tracking History \\(([0-9\\.,]+(km|mi))[^\\)]*\\)", Pattern.CASE_INSENSITIVE);

    final Trackable trackable = new Trackable();

    // trackable geocode
    try {
        final Matcher matcherGeocode = patternGeocode.matcher(page);
        while (matcherGeocode.find()) {
            if (matcherGeocode.groupCount() > 0) {
                trackable.geocode = matcherGeocode.group(1).toUpperCase();
            }
        }
    } catch (Exception e) {
        // failed to parse trackable geocode
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable geocode");
    }

    // trackable id
    try {
        final Matcher matcherTrackableId = patternTrackableId.matcher(page);
        while (matcherTrackableId.find()) {
            if (matcherTrackableId.groupCount() > 0) {
                trackable.guid = matcherTrackableId.group(1);
            }
        }
    } catch (Exception e) {
        // failed to parse trackable id
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable id");
    }

    // trackable icon
    try {
        final Matcher matcherTrackableIcon = patternIcon.matcher(page);
        while (matcherTrackableIcon.find()) {
            if (matcherTrackableIcon.groupCount() > 0) {
                trackable.iconUrl = matcherTrackableIcon.group(1);
            }
        }
    } catch (Exception e) {
        // failed to parse trackable icon
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable icon");
    }

    // trackable name
    try {
        final Matcher matcherName = patternName.matcher(page);
        while (matcherName.find()) {
            if (matcherName.groupCount() > 1) {
                trackable.name = matcherName.group(2);
            }
        }
    } catch (Exception e) {
        // failed to parse trackable name
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable name");
    }

    // trackable type
    if (trackable.name != null && trackable.name.length() > 0) {
        try {
            final Matcher matcherType = patternType.matcher(page);
            while (matcherType.find()) {
                if (matcherType.groupCount() > 0) {
                    trackable.type = matcherType.group(1);
                }
            }
        } catch (Exception e) {
            // failed to parse trackable type
            Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable type");
        }
    }

    // trackable owner name
    try {
        final Matcher matcherOwner = patternOwner.matcher(page);
        while (matcherOwner.find()) {
            if (matcherOwner.groupCount() > 0) {
                trackable.ownerGuid = matcherOwner.group(1);
                trackable.owner = matcherOwner.group(2);
            }
        }
    } catch (Exception e) {
        // failed to parse trackable owner name
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable owner name");
    }

    // trackable origin
    try {
        final Matcher matcherOrigin = patternOrigin.matcher(page);
        while (matcherOrigin.find()) {
            if (matcherOrigin.groupCount() > 0) {
                trackable.origin = matcherOrigin.group(1);
            }
        }
    } catch (Exception e) {
        // failed to parse trackable origin
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable origin");
    }

    // trackable spotted
    try {
        final Matcher matcherSpottedCache = patternSpottedCache.matcher(page);
        while (matcherSpottedCache.find()) {
            if (matcherSpottedCache.groupCount() > 0) {
                trackable.spottedGuid = matcherSpottedCache.group(1);
                trackable.spottedName = matcherSpottedCache.group(2);
                trackable.spottedType = Trackable.SPOTTED_CACHE;
            }
        }

        final Matcher matcherSpottedUser = patternSpottedUser.matcher(page);
        while (matcherSpottedUser.find()) {
            if (matcherSpottedUser.groupCount() > 0) {
                trackable.spottedGuid = matcherSpottedUser.group(1);
                trackable.spottedName = matcherSpottedUser.group(2);
                trackable.spottedType = Trackable.SPOTTED_USER;
            }
        }

        final Matcher matcherSpottedUnknown = patternSpottedUnknown.matcher(page);
        if (matcherSpottedUnknown.find()) {
            trackable.spottedType = Trackable.SPOTTED_UNKNOWN;
        }

        final Matcher matcherSpottedOwner = patternSpottedOwner.matcher(page);
        if (matcherSpottedOwner.find()) {
            trackable.spottedType = Trackable.SPOTTED_OWNER;
        }
    } catch (Exception e) {
        // failed to parse trackable last known place
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable last known place");
    }

    // released
    try {
        final Matcher matcherReleased = patternReleased.matcher(page);
        while (matcherReleased.find()) {
            if (matcherReleased.groupCount() > 0 && matcherReleased.group(1) != null) {
                try {
                    if (trackable.released == null) {
                        trackable.released = dateTbIn1.parse(matcherReleased.group(1));
                    }
                } catch (Exception e) {
                    //
                }

                try {
                    if (trackable.released == null) {
                        trackable.released = dateTbIn2.parse(matcherReleased.group(1));
                    }
                } catch (Exception e) {
                    //
                }
            }
        }
    } catch (Exception e) {
        // failed to parse trackable released date
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable released date");
    }

    // trackable distance
    try {
        final Matcher matcherDistance = patternDistance.matcher(page);
        while (matcherDistance.find()) {
            if (matcherDistance.groupCount() > 0) {
                trackable.distance = parseDistance(matcherDistance.group(1));
            }
        }
    } catch (Exception e) {
        // failed to parse trackable distance
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable distance");
    }

    // trackable goal
    try {
        final Matcher matcherGoal = patternGoal.matcher(page);
        while (matcherGoal.find()) {
            if (matcherGoal.groupCount() > 0) {
                trackable.goal = matcherGoal.group(1);
            }
        }
    } catch (Exception e) {
        // failed to parse trackable goal
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable goal");
    }

    // trackable details & image
    try {
        final Matcher matcherDetailsImage = patternDetailsImage.matcher(page);
        while (matcherDetailsImage.find()) {
            if (matcherDetailsImage.groupCount() > 0) {
                final String image = matcherDetailsImage.group(3);
                final String details = matcherDetailsImage.group(4);

                if (image != null) {
                    trackable.image = image;
                }
                if (details != null) {
                    trackable.details = details;
                }
            }
        }
    } catch (Exception e) {
        // failed to parse trackable details & image
        Log.w(Settings.tag, "cgeoBase.parseTrackable: Failed to parse trackable details & image");
    }

    // trackable logs
    try {
        final Matcher matcherLogs = patternLogs.matcher(page);
        while (matcherLogs.find()) {
            if (matcherLogs.groupCount() > 0) {
                final Pattern patternLog = Pattern.compile("[^>]*>"
                        + "[^<]*<td[^<]*<img src=[\"|'].*\\/icons\\/([^\\.]+)\\.[a-z]{2,5}[\"|'][^>]*>&nbsp;(\\d+).(\\d+).(\\d+)[^<]*</td>"
                        + "[^<]*<td>[^<]*<a href=[^>]+>([^<]+)<.a>([^<]*|[^<]*<a href=[\"|'].*guid=([^\"]*)\">([^<]*)</a>[^<]*)</td>"
                        + "[^<]*<td>[^<]*</td>" + "[^<]*<td[^<]*<a href=[^>]+>[^<]+</a>[^<]*</td>[^<]*</tr>"
                        + "[^<]*<tr[^>]*>[^<]*<td[^>]*>(.*?)</td>[^<]*</tr>.*" + "");
                // 1 filename == type
                // 2 month
                // 3 date
                // 4 year
                // 5 user
                // 6 action dependent
                // 7 cache guid
                // 8 cache name
                // 9 text
                final String[] logs = matcherLogs.group(1).split("<tr class=\"Data BorderTop");
                final int logsCnt = logs.length;

                for (int k = 1; k < logsCnt; k++) {
                    final Matcher matcherLog = patternLog.matcher(logs[k]);
                    if (matcherLog.find()) {
                        final CacheLog logDone = new CacheLog();

                        String logTmp = matcherLog.group(9);
                        logTmp = Pattern.compile("<p>").matcher(logTmp).replaceAll("\n");
                        logTmp = Pattern.compile("<br[^>]*>").matcher(logTmp).replaceAll("\n");
                        logTmp = Pattern.compile("<\\/p>").matcher(logTmp).replaceAll("");
                        logTmp = Pattern.compile("\r+").matcher(logTmp).replaceAll("\n");

                        int day = -1;
                        try {
                            day = Integer.parseInt(matcherLog.group(3));
                        } catch (Exception e) {
                            Log.w(Settings.tag, "Failed to parse logs date (day): " + e.toString());
                        }

                        int month = -1;
                        try {
                            month = Integer.parseInt(matcherLog.group(2));
                            month -= 1;
                        } catch (Exception e) {
                            Log.w(Settings.tag, "Failed to parse logs date (month): " + e.toString());
                        }

                        int year = -1;
                        try {
                            year = Integer.parseInt(matcherLog.group(4));
                        } catch (Exception e) {
                            Log.w(Settings.tag, "Failed to parse logs date (year): " + e.toString());
                        }

                        long logDate;
                        if (year > 0 && month >= 0 && day > 0) {
                            Calendar date = Calendar.getInstance();
                            date.set(year, month, day, 12, 0, 0);
                            logDate = date.getTimeInMillis();
                            logDate = (long) (Math.ceil(logDate / 1000)) * 1000;
                        } else {
                            logDate = 0;
                        }

                        if (logTypes.containsKey(matcherLog.group(1).toLowerCase()) == true) {
                            logDone.type = logTypes.get(matcherLog.group(1).toLowerCase());
                        } else {
                            logDone.type = logTypes.get("icon_note");
                        }

                        logDone.author = Html.fromHtml(matcherLog.group(5)).toString();
                        logDone.date = logDate;
                        logDone.log = logTmp;
                        if (matcherLog.group(7) != null && matcherLog.group(8) != null) {
                            logDone.cacheGuid = matcherLog.group(7);
                            logDone.cacheName = matcherLog.group(8);
                        }

                        trackable.logs.add(logDone);
                    }
                }
            }
        }
    } catch (Exception e) {
        // failed to parse logs
        Log.w(Settings.tag, "cgeoBase.parseCache: Failed to parse cache logs");
    }

    app.saveTrackable(trackable);

    return trackable;
}

From source file:carnero.cgeo.cgBase.java

public HashMap<String, Object> parseLatlon(String latlon) {
    final HashMap<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;// ww  w  .  j  a v a2 s .c  om
            }
            if (matcherLatlon.group(5).equalsIgnoreCase("E")) {
                lonNegative = 1;
            }
            result.put("latitude", new Double(latNegative * (new Float(matcherLatlon.group(2))
                    + new Float(matcherLatlon.group(3) + "." + matcherLatlon.group(4)) / 60)));
            result.put("longitude", new Double(lonNegative * (new Float(matcherLatlon.group(6))
                    + new Float(matcherLatlon.group(7) + "." + matcherLatlon.group(8)) / 60)));
        } else {
            Log.w(cgSettings.tag, "cgBase.parseLatlon: Failed to parse coordinates.");
        }
    }

    return result;
}

From source file:carnero.cgeo.cgBase.java

public String findViewstate(String page, int index) {
    String viewstate = null;//  w  w  w . jav a2  s .  c  o  m

    if (index == 0) {
        final Matcher matcherViewstate = patternViewstate.matcher(page);
        while (matcherViewstate.find()) {
            if (matcherViewstate.groupCount() > 0) {
                viewstate = matcherViewstate.group(1);
            }
        }
    } else if (index == 1) {
        final Matcher matcherViewstate = patternViewstate1.matcher(page);
        while (matcherViewstate.find()) {
            if (matcherViewstate.groupCount() > 0) {
                viewstate = matcherViewstate.group(1);
            }
        }
    }

    return viewstate;
}

From source file:carnero.cgeo.cgBase.java

public int parseFindCount(String page) {
    if (page == null || page.length() == 0) {
        return -1;
    }//  w  ww  .j  a  va 2 s  .  c  o  m

    int findCount = -1;

    try {
        final Pattern findPattern = Pattern.compile("<strong>Caches Found:<\\/strong>([^<]+)<br",
                Pattern.CASE_INSENSITIVE);
        final Matcher findMatcher = findPattern.matcher(page);
        if (findMatcher.find() == true) {
            if (findMatcher.groupCount() > 0) {
                String count = findMatcher.group(1);

                if (count != null) {
                    count = count.trim();

                    if (count.length() == 0) {
                        findCount = 0;
                    } else {
                        findCount = Integer.parseInt(count);
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.w(cgSettings.tag, "cgBase.parseFindCount: " + e.toString());
    }

    return findCount;
}

From source file:carnero.cgeo.cgBase.java

public ArrayList<Integer> parseTypes(String page) {
    if (page == null || page.length() == 0) {
        return null;
    }/*  ww w. j  a  v a 2 s.  com*/

    final ArrayList<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:carnero.cgeo.cgBase.java

public ArrayList<cgTrackableLog> parseTrackableLog(String page) {
    if (page == null || page.length() == 0) {
        return null;
    }//from  ww w .j a  v  a  2 s  .  c om

    final ArrayList<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 = new Integer(trackableMatcher.group(3));
            } else {
                continue;
            }
            if (trackableMatcher.group(5) != null) {
                trackable.id = new Integer(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:carnero.cgeo.cgBase.java

public HashMap<String, cgRating> getRating(ArrayList<String> guids, ArrayList<String> geocodes) {
    if (guids == null && geocodes == null) {
        return null;
    }//from   ww w .  j a  v a2 s.c  om

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

    try {
        final HashMap<String, String> params = new HashMap<String, String>();
        if (settings.isLogin() == true) {
            final HashMap<String, String> login = settings.getGCvoteLogin();
            if (login != null) {
                params.put("userName", login.get("username"));
                params.put("password", login.get("password"));
            }
        }
        if (guids != null && guids.size() > 0) {
            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") == 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 == true) {
                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 (guid != null) {
                ratings.put(guid, rating);
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.getRating: " + e.toString());
    }

    return ratings;
}

From source file:carnero.cgeo.original.libs.Base.java

public CacheWrap parseSearch(SearchThread thread, String url, String page, boolean showCaptcha) {
    if (page == null || page.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: No page given");
        return null;
    }//w  ww  .  j a  va  2s  .  co m

    final CacheWrap caches = new CacheWrap();
    final ArrayList<String> cids = new ArrayList<String>();
    final ArrayList<String> guids = new ArrayList<String>();
    String recaptchaChallenge = null;
    String recaptchaText = null;

    caches.url = url;

    final Pattern patternCacheType = Pattern.compile(
            "<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^\\.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternGuidAndDisabled = Pattern.compile(
            "<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternTbs = Pattern.compile(
            "<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTbsInside = Pattern.compile(
            "(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternDirection = Pattern.compile(
            "<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternCode = Pattern.compile("\\|[^\\w]*(GC[a-z0-9]+)[^\\|]*\\|",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternId = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"", Pattern.CASE_INSENSITIVE);
    final Pattern patternFavourite = Pattern.compile(
            "<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTotalCnt = Pattern.compile(
            "<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptcha = Pattern.compile(
            "<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptchaChallenge = Pattern.compile("challenge : '([^']+)'",
            Pattern.CASE_INSENSITIVE);

    caches.viewstate = findViewstate(page, 0);
    caches.viewstate1 = findViewstate(page, 1);

    // recaptcha
    if (showCaptcha == true) {
        try {
            String recaptchaJsParam = null;
            final Matcher matcherRecaptcha = patternRecaptcha.matcher(page);
            while (matcherRecaptcha.find()) {
                if (matcherRecaptcha.groupCount() > 0) {
                    recaptchaJsParam = matcherRecaptcha.group(1);
                }
            }

            if (recaptchaJsParam != null) {
                final String recaptchaJs = request(false, "www.google.com", "/recaptcha/api/challenge", "GET",
                        "k=" + urlencode_rfc3986(recaptchaJsParam.trim()), 0, true).getData();

                if (recaptchaJs != null && recaptchaJs.length() > 0) {
                    final Matcher matcherRecaptchaChallenge = patternRecaptchaChallenge.matcher(recaptchaJs);
                    while (matcherRecaptchaChallenge.find()) {
                        if (matcherRecaptchaChallenge.groupCount() > 0) {
                            recaptchaChallenge = matcherRecaptchaChallenge.group(1).trim();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse recaptcha challenge
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge");
        }

        if (thread != null && recaptchaChallenge != null && recaptchaChallenge.length() > 0) {
            thread.setChallenge(recaptchaChallenge);
            thread.notifyNeed();
        }
    }

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

    startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\"");
    if (startPos == -1) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page");
        return null;
    }

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

    startPos = page.indexOf(">");
    endPos = page.indexOf("ctl00_ContentBody_UnitTxt");
    if (startPos == -1 || endPos == -1) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page");
        return null;
    }

    page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table>

    final String[] rows = page.split("<tr class=");
    final int rows_count = rows.length;

    for (int z = 1; z < rows_count; z++) {
        Cache cache = new Cache();
        String row = rows[z];

        // check for cache type presence
        if (row.indexOf("images/wpttypes") == -1) {
            continue;
        }

        try {
            final Matcher matcherGuidAndDisabled = patternGuidAndDisabled.matcher(row);

            while (matcherGuidAndDisabled.find()) {
                if (matcherGuidAndDisabled.groupCount() > 0) {
                    guids.add(matcherGuidAndDisabled.group(1));

                    cache.guid = matcherGuidAndDisabled.group(1);
                    if (matcherGuidAndDisabled.group(4) != null) {
                        cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString();
                    }
                    if (matcherGuidAndDisabled.group(6) != null) {
                        cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString();
                    }

                    final String attr = matcherGuidAndDisabled.group(2);
                    if (attr != null) {
                        if (attr.contains("Strike") == true) {
                            cache.disabled = true;
                        } else {
                            cache.disabled = false;
                        }

                        if (attr.contains("OldWarning") == true) {
                            cache.archived = true;
                        } else {
                            cache.archived = false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse GUID and/or Disabled
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data");
        }

        if (settings.excludeDisabled == 1 && (cache.disabled == true || cache.archived == true)) {
            // skip disabled and archived caches
            cache = null;
            continue;
        }

        String inventoryPre = null;

        // GC* code
        try {
            final Matcher matcherCode = patternCode.matcher(row);
            while (matcherCode.find()) {
                if (matcherCode.groupCount() > 0) {
                    cache.geocode = matcherCode.group(1).toUpperCase();
                }
            }
        } catch (Exception e) {
            // failed to parse code
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache code");
        }

        // cache type
        try {
            final Matcher matcherCacheType = patternCacheType.matcher(row);
            while (matcherCacheType.find()) {
                if (matcherCacheType.groupCount() > 0) {
                    cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase());
                }
            }
        } catch (Exception e) {
            // failed to parse type
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache type");
        }

        // cache direction - image
        try {
            final Matcher matcherDirection = patternDirection.matcher(row);
            while (matcherDirection.find()) {
                if (matcherDirection.groupCount() > 0) {
                    cache.directionImg = matcherDirection.group(1);
                }
            }
        } catch (Exception e) {
            // failed to parse direction image
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache direction image");
        }

        // cache inventory
        try {
            final Matcher matcherTbs = patternTbs.matcher(row);
            while (matcherTbs.find()) {
                if (matcherTbs.groupCount() > 0) {
                    cache.inventoryItems = Integer.parseInt(matcherTbs.group(1));
                    inventoryPre = matcherTbs.group(2);
                }
            }
        } catch (Exception e) {
            // failed to parse inventory
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)");
        }

        if (inventoryPre != null && inventoryPre.trim().length() > 0) {
            try {
                final Matcher matcherTbsInside = patternTbsInside.matcher(inventoryPre);
                while (matcherTbsInside.find()) {
                    if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null) {
                        final String inventoryItem = matcherTbsInside.group(2).toLowerCase();
                        if (inventoryItem.equals("premium member only cache")) {
                            continue;
                        } else {
                            if (cache.inventoryItems <= 0) {
                                cache.inventoryItems = 1;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // failed to parse cache inventory info
                Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info");
            }
        }

        // premium cache
        if (row.indexOf("/images/small_profile.gif") != -1) {
            cache.members = true;
        } else {
            cache.members = false;
        }

        // found it
        if (row.indexOf("/images/icons/icon_smile.png") != -1) {
            cache.found = true;
        } else {
            cache.found = false;
        }

        // own it
        if (row.indexOf("/images/silk/star.png") != -1) {
            cache.own = true;
        } else {
            cache.own = false;
        }

        // id
        try {
            final Matcher matcherId = patternId.matcher(row);
            while (matcherId.find()) {
                if (matcherId.groupCount() > 0) {
                    cache.cacheid = matcherId.group(1);
                    cids.add(cache.cacheid);
                }
            }
        } catch (Exception e) {
            // failed to parse cache id
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache id");
        }

        // favourite count
        try {
            final Matcher matcherFavourite = patternFavourite.matcher(row);
            while (matcherFavourite.find()) {
                if (matcherFavourite.groupCount() > 0) {
                    cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
                }
            }
        } catch (Exception e) {
            // failed to parse favourite count
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse favourite count");
        }

        if (cache.nameSp == null) {
            cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name);
            if (cache.disabled == true || cache.archived == true) { // strike
                cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        caches.cacheList.add(cache);
    }

    // total caches found
    try {
        final Matcher matcherTotalCnt = patternTotalCnt.matcher(page);
        while (matcherTotalCnt.find()) {
            if (matcherTotalCnt.groupCount() > 0) {
                if (matcherTotalCnt.group(1) != null) {
                    caches.totalCnt = new Integer(matcherTotalCnt.group(1));
                }
            }
        }
    } catch (Exception e) {
        // failed to parse cache count
        Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache count");
    }

    if (thread != null && recaptchaChallenge != null) {
        if (thread.getText() == null) {
            thread.waitForUser();
        }

        recaptchaText = thread.getText();
    }

    if (cids.size() > 0 && (recaptchaChallenge == null
            || (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0))) {
        Log.i(Settings.tag, "Trying to get .loc for " + cids.size() + " caches");

        try {
            // get coordinates for parsed caches
            final String host = "www.geocaching.com";
            final String path = "/seek/nearest.aspx";
            final StringBuilder params = new StringBuilder();
            params.append("__EVENTTARGET=");
            params.append("&");
            params.append("__EVENTARGUMENT=");
            params.append("&");
            params.append("__VIEWSTATE=");
            params.append(urlencode_rfc3986(caches.viewstate));
            if (caches.viewstate1 != null) {
                params.append("&");
                params.append("__VIEWSTATE1=");
                params.append(urlencode_rfc3986(caches.viewstate1));
                params.append("&");
                params.append("__VIEWSTATEFIELDCOUNT=2");
            }

            for (String cid : cids) {
                params.append("&");
                params.append("CID=");
                params.append(urlencode_rfc3986(cid));
            }

            if (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0) {
                params.append("&");
                params.append("recaptcha_challenge_field=");
                params.append(urlencode_rfc3986(recaptchaChallenge));
                params.append("&");
                params.append("recaptcha_response_field=");
                params.append(urlencode_rfc3986(recaptchaText));
            }
            params.append("&");
            params.append("ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints");

            final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData();

            if (coordinates != null && coordinates.length() > 0) {
                if (coordinates.indexOf(
                        "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com") > -1) {
                    Log.i(Settings.tag,
                            "User has not agreed to the license agreement. Can\'t download .loc file.");

                    caches.error = errorRetrieve.get(-7);

                    return caches;
                }
            }

            if (coordinates != null && coordinates.length() > 0) {
                final HashMap<String, Coord> cidCoords = new HashMap<String, Coord>();
                final Pattern patternCidCode = Pattern.compile("name id=\"([^\"]+)\"");
                final Pattern patternCidLat = Pattern.compile("lat=\"([^\"]+)\"");
                final Pattern patternCidLon = Pattern.compile("lon=\"([^\"]+)\"");
                // premium only >>
                final Pattern patternCidDif = Pattern.compile("<difficulty>([^<]+)</difficulty>");
                final Pattern patternCidTer = Pattern.compile("<terrain>([^<]+)</terrain>");
                final Pattern patternCidCon = Pattern.compile("<container>([^<]+)</container>");
                // >> premium only

                final String[] points = coordinates.split("<waypoint>");

                // parse coordinates
                for (String point : points) {
                    final Coord pointCoord = new Coord();
                    final Matcher matcherCidCode = patternCidCode.matcher(point);
                    final Matcher matcherLatCode = patternCidLat.matcher(point);
                    final Matcher matcherLonCode = patternCidLon.matcher(point);
                    final Matcher matcherDifCode = patternCidDif.matcher(point);
                    final Matcher matcherTerCode = patternCidTer.matcher(point);
                    final Matcher matcherConCode = patternCidCon.matcher(point);
                    HashMap<String, Object> tmp = null;

                    if (matcherCidCode.find() == true) {
                        pointCoord.name = matcherCidCode.group(1).trim().toUpperCase();
                    }
                    if (matcherLatCode.find() == true) {
                        tmp = parseCoordinate(matcherLatCode.group(1), "lat");
                        pointCoord.latitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherLonCode.find() == true) {
                        tmp = parseCoordinate(matcherLonCode.group(1), "lon");
                        pointCoord.longitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherDifCode.find() == true) {
                        pointCoord.difficulty = new Float(matcherDifCode.group(1));
                    }
                    if (matcherTerCode.find() == true) {
                        pointCoord.terrain = new Float(matcherTerCode.group(1));
                    }
                    if (matcherConCode.find() == true) {
                        final int size = Integer.parseInt(matcherConCode.group(1));

                        if (size == 1) {
                            pointCoord.size = "not chosen";
                        } else if (size == 2) {
                            pointCoord.size = "micro";
                        } else if (size == 3) {
                            pointCoord.size = "regular";
                        } else if (size == 4) {
                            pointCoord.size = "large";
                        } else if (size == 5) {
                            pointCoord.size = "virtual";
                        } else if (size == 6) {
                            pointCoord.size = "other";
                        } else if (size == 8) {
                            pointCoord.size = "small";
                        } else {
                            pointCoord.size = "unknown";
                        }
                    }

                    cidCoords.put(pointCoord.name, pointCoord);
                }

                Log.i(Settings.tag, "Coordinates found in .loc file: " + cidCoords.size());

                // save found cache coordinates
                for (Cache oneCache : caches.cacheList) {
                    if (cidCoords.containsKey(oneCache.geocode) == true) {
                        Coord thisCoords = cidCoords.get(oneCache.geocode);

                        oneCache.latitude = thisCoords.latitude;
                        oneCache.longitude = thisCoords.longitude;
                        oneCache.difficulty = thisCoords.difficulty;
                        oneCache.terrain = thisCoords.terrain;
                        oneCache.size = thisCoords.size;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgBase.parseSearch.CIDs: " + e.toString());
        }
    }

    // get direction images
    DirectionImg dirImgDownloader = new DirectionImg(settings);
    for (Cache oneCache : caches.cacheList) {
        if (oneCache.latitude == null && oneCache.longitude == null && oneCache.direction == null
                && oneCache.directionImg != null) {
            dirImgDownloader.getDrawable(oneCache.geocode, oneCache.directionImg);
        }
    }
    dirImgDownloader = null;

    return caches;
}

From source file:carnero.cgeo.cgBase.java

public int postLog(cgeoapplication app, String geocode, String cacheid, String viewstate, String viewstate1,
        int logType, int year, int month, int day, String log, ArrayList<cgTrackableLog> trackables) {
    if (viewstate == null || viewstate.length() == 0) {
        Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate given");
        return 1000;
    }//from  ww  w .  j a  v  a 2s.co m

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

    if (log == null || log.length() == 0) {
        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 HashMap<String, String> params = new HashMap<String, String>();

    params.put("__VIEWSTATE", viewstate);
    if (viewstate1 != null) {
        params.put("__VIEWSTATE1", viewstate1);
        params.put("__VIEWSTATEFIELDCOUNT", "2");
    }
    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 (page == null || page.length() == 0) {
        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() == true && matcher.groupCount() > 0) {
            final String viewstateConfirm = findViewstate(page, 0);
            final String viewstate1Confirm = findViewstate(page, 1);

            if (viewstateConfirm == null || viewstateConfirm.length() == 0) {
                Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate for confirm log");
                return 1000;
            }

            params.clear();
            params.put("__VIEWSTATE", viewstateConfirm);
            if (viewstate1 != null) {
                params.put("__VIEWSTATE1", viewstate1Confirm);
                params.put("__VIEWSTATEFIELDCOUNT", "2");
            }
            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() == true) {
            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:fr.cls.atoll.motu.library.misc.intfce.Organizer.java

/**
 * Gets the tDS dataset id.//from w  ww  .ja  v  a2s .co  m
 * 
 * @param locationData the location data
 * 
 * @return the tDS dataset id
 */
public static String getTDSDatasetUrlPath(String locationData) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getTDSDatasetId(String) - start - locationData=" + locationData);
    }

    String value = "";

    Matcher matcher = matchTDSCatalogUrl(locationData);
    if (matcher == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getTDSDatasetId(String) - end - matcher is null");
        }
        return null;
    }

    try {
        value = matcher.group(matcher.groupCount());
    } catch (Exception e) {
        LOG.error("getTDSDatasetId(String) - matcher.group", e);

        // Do nothing else
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("getTDSDatasetId(String) - end");
    }
    return value;

}