List of usage examples for java.util.regex Matcher groupCount
public int groupCount()
From source file:cgeo.geocaching.cgBase.java
public cgTrackable parseTrackable(String page) { if (StringUtils.isBlank(page)) { Log.e(cgSettings.tag, "cgeoBase.parseTrackable: No page given"); return null; }// ww w . j ava 2 s . co m final cgTrackable trackable = new cgTrackable(); // trackable geocode try { final Matcher matcherGeocode = PATTERN_TRACKABLE_Geocode.matcher(page); if (matcherGeocode.find() && matcherGeocode.groupCount() > 0) { trackable.geocode = matcherGeocode.group(1).toUpperCase(); } } catch (Exception e) { // failed to parse trackable geocode Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable geocode"); } // trackable id try { final Matcher matcherTrackableId = PATTERN_TRACKABLE_TrackableId.matcher(page); if (matcherTrackableId.find() && matcherTrackableId.groupCount() > 0) { trackable.guid = matcherTrackableId.group(1); } } catch (Exception e) { // failed to parse trackable id Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable id"); } // trackable icon try { final Matcher matcherTrackableIcon = PATTERN_TRACKABLE_Icon.matcher(page); if (matcherTrackableIcon.find() && matcherTrackableIcon.groupCount() > 0) { trackable.iconUrl = matcherTrackableIcon.group(1); } } catch (Exception e) { // failed to parse trackable icon Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable icon"); } // trackable name try { final Matcher matcherName = PATTERN_TRACKABLE_Name.matcher(page); if (matcherName.find() && matcherName.groupCount() > 1) { trackable.name = matcherName.group(2); } } catch (Exception e) { // failed to parse trackable name Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable name"); } // trackable type if (StringUtils.isNotBlank(trackable.name)) { try { final Matcher matcherType = PATTERN_TRACKABLE_Type.matcher(page); if (matcherType.find() && matcherType.groupCount() > 0) { trackable.type = matcherType.group(1); } } catch (Exception e) { // failed to parse trackable type Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable type"); } } // trackable owner name try { final Matcher matcherOwner = PATTERN_TRACKABLE_Owner.matcher(page); if (matcherOwner.find() && matcherOwner.groupCount() > 0) { trackable.ownerGuid = matcherOwner.group(1); trackable.owner = matcherOwner.group(2); } } catch (Exception e) { // failed to parse trackable owner name Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable owner name"); } // trackable origin try { final Matcher matcherOrigin = PATTERN_TRACKABLE_Origin.matcher(page); if (matcherOrigin.find() && matcherOrigin.groupCount() > 0) { trackable.origin = matcherOrigin.group(1); } } catch (Exception e) { // failed to parse trackable origin Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable origin"); } // trackable spotted try { final Matcher matcherSpottedCache = PATTERN_TRACKABLE_SpottedCache.matcher(page); if (matcherSpottedCache.find() && matcherSpottedCache.groupCount() > 0) { trackable.spottedGuid = matcherSpottedCache.group(1); trackable.spottedName = matcherSpottedCache.group(2); trackable.spottedType = cgTrackable.SPOTTED_CACHE; } final Matcher matcherSpottedUser = PATTERN_TRACKABLE_SpottedUser.matcher(page); if (matcherSpottedUser.find() && matcherSpottedUser.groupCount() > 0) { trackable.spottedGuid = matcherSpottedUser.group(1); trackable.spottedName = matcherSpottedUser.group(2); trackable.spottedType = cgTrackable.SPOTTED_USER; } final Matcher matcherSpottedUnknown = PATTERN_TRACKABLE_SpottedUnknown.matcher(page); if (matcherSpottedUnknown.find()) { trackable.spottedType = cgTrackable.SPOTTED_UNKNOWN; } final Matcher matcherSpottedOwner = PATTERN_TRACKABLE_SpottedOwner.matcher(page); if (matcherSpottedOwner.find()) { trackable.spottedType = cgTrackable.SPOTTED_OWNER; } } catch (Exception e) { // failed to parse trackable last known place Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable last known place"); } // released try { final Matcher matcherReleased = PATTERN_TRACKABLE_Released.matcher(page); if (matcherReleased.find() && 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(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable released date"); } // trackable distance try { final Matcher matcherDistance = PATTERN_TRACKABLE_Distance.matcher(page); if (matcherDistance.find() && matcherDistance.groupCount() > 0) { try { trackable.distance = DistanceParser.parseDistance(matcherDistance.group(1), settings.units); } catch (NumberFormatException e) { trackable.distance = null; throw e; } } } catch (Exception e) { // failed to parse trackable distance Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable distance"); } // trackable goal try { final Matcher matcherGoal = PATTERN_TRACKABLE_Goal.matcher(page); if (matcherGoal.find() && matcherGoal.groupCount() > 0) { trackable.goal = matcherGoal.group(1); } } catch (Exception e) { // failed to parse trackable goal Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable goal"); } // trackable details & image try { final Matcher matcherDetailsImage = PATTERN_TRACKABLE_DetailsImage.matcher(page); if (matcherDetailsImage.find() && 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(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable details & image"); } // trackable logs try { final Matcher matcherLogs = PATTERN_TRACKABLE_Log.matcher(page); /* * 1. Type (img) * 2. Date * 3. Author * 4. Cache-GUID * 5. Cache-name * 6. Logtext */ while (matcherLogs.find()) { final cgLog logDone = new cgLog(); if (logTypes.containsKey(matcherLogs.group(1).toLowerCase())) { logDone.type = logTypes.get(matcherLogs.group(1).toLowerCase()); } else { logDone.type = logTypes.get("icon_note"); } logDone.author = Html.fromHtml(matcherLogs.group(3)).toString(); try { logDone.date = parseGcCustomDate(matcherLogs.group(2)).getTime(); } catch (ParseException e) { } logDone.log = matcherLogs.group(6).trim(); if (matcherLogs.group(4) != null && matcherLogs.group(5) != null) { logDone.cacheGuid = matcherLogs.group(4); logDone.cacheName = matcherLogs.group(5); } trackable.logs.add(logDone); } } catch (Exception e) { // failed to parse logs Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache logs"); } app.saveTrackable(trackable); return trackable; }
From source file:de.uni_koblenz.jgralab.utilities.rsa.Rsa2Tg.java
/** * Creates {@link EdgeClass} names for all EdgeClass objects, which do have * an empty String or a String, which ends with a '.'. *//*from www . j a va 2 s.c om*/ private void createEdgeClassNames() { System.out.println("Creating missing edge class names..."); for (EdgeClass ec : sg.getEdgeClassVertices()) { String name = ec.get_qualifiedName().trim(); // invent an edgeclass name String ecName = null; Matcher m = GENNAME_PATTERN.matcher(name); if (m.matches()) { name = m.group(1); ecName = m.group(m.groupCount()); } if (!name.equals("") && !name.endsWith(".")) { continue; } IncidenceClass to = null; IncidenceClass from = null; for (ConnectsToEdgeClass ctec : ec.getIncidentEdges(ConnectsToEdgeClass.class)) { IncidenceClass inc = (IncidenceClass) ctec.getAlpha(); if (inc.get_direction() == de.uni_koblenz.jgralab.grumlschema.structure.Direction.VERTEX_TO_EDGE) { if (from == null) { from = inc; } } else { if (to == null) { to = inc; } } } assert to != null && from != null; String toRole = to.get_roleName(); if ((toRole == null) || toRole.equals("")) { toRole = ((VertexClass) ((ConnectsToVertexClass) to .getFirstIncidence(ConnectsToVertexClass_incidenceClassAtVertex.class).getEdge()) .getOmega()).get_qualifiedName(); int p = toRole.lastIndexOf('.'); if (p >= 0) { toRole = toRole.substring(p + 1); } } else { toRole = Character.toUpperCase(toRole.charAt(0)) + toRole.substring(1); } // There must be a 'to' role name, which is different than null and // not empty. if ((toRole == null) || (toRole.length() <= 0)) { throw new ProcessingException(getFileName(), "There is no role name 'to' for the edge '" + name + "' defined."); } if (ecName == null) { if ((from.get_incidenceType() != IncidenceType.EDGE) || (to.get_incidenceType() != IncidenceType.EDGE)) { if (to.get_incidenceType() != IncidenceType.EDGE) { ecName = "Contains" + toRole; } else { ecName = "IsPartOf" + toRole; } } else { ecName = "LinksTo" + toRole; } } else { ecName += toRole; } if (isUseFromRole()) { String fromRole = from.get_roleName(); if ((fromRole == null) || fromRole.equals("")) { fromRole = ((VertexClass) ((ConnectsToVertexClass) from .getFirstIncidence(ConnectsToVertexClass_incidenceClassAtVertex.class).getEdge()) .getOmega()).get_qualifiedName(); int p = fromRole.lastIndexOf('.'); if (p >= 0) { fromRole = fromRole.substring(p + 1); } } else { fromRole = Character.toUpperCase(fromRole.charAt(0)) + fromRole.substring(1); } // There must be a 'from' role name, which is different than // null and not empty. if ((fromRole == null) || (fromRole.length() <= 0)) { throw new ProcessingException(getFileName(), "There is no role name of 'from' for the edge '" + name + "' defined."); } name += fromRole; } assert (ecName != null) && (ecName.length() > 0); ec.set_qualifiedName(name + ecName); } }
From source file:cgeo.geocaching.cgBase.java
public cgCacheWrap parseSearch(cgSearchThread thread, String url, String page, boolean showCaptcha) { if (StringUtils.isBlank(page)) { Log.e(cgSettings.tag, "cgeoBase.parseSearch: No page given"); return null; }/*from www. j a v a2s . c om*/ final cgCacheWrap caches = new cgCacheWrap(); final List<String> cids = new ArrayList<String>(); final List<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.viewstates = getViewstates(page); // recaptcha if (showCaptcha) { 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 (StringUtils.isNotBlank(recaptchaJs)) { 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(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge"); } if (thread != null && StringUtils.isNotBlank(recaptchaChallenge)) { thread.setChallenge(recaptchaChallenge); thread.notifyNeed(); } } if (!page.contains("SearchResultsTable")) { // there are no results. aborting here avoids a wrong error log in the next parsing step return caches; } int startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\""); if (startPos == -1) { Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page"); return null; } page = page.substring(startPos); // cut on <table startPos = page.indexOf(">"); int endPos = page.indexOf("ctl00_ContentBody_UnitTxt"); if (startPos == -1 || endPos == -1) { Log.e(cgSettings.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++) { cgCache cache = new cgCache(); String row = rows[z]; // check for cache type presence if (!row.contains("images/wpttypes")) { 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")) { cache.disabled = true; } else { cache.disabled = false; } if (attr.contains("OldWarning")) { cache.archived = true; } else { cache.archived = false; } } } } } catch (Exception e) { // failed to parse GUID and/or Disabled Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data"); } if (settings.excludeDisabled == 1 && (cache.disabled || cache.archived)) { // 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(cgSettings.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(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache type"); } // cache direction - image if (settings.getLoadDirImg()) { 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(cgSettings.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(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)"); } if (StringUtils.isNotBlank(inventoryPre)) { 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(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info"); } } // premium cache cache.members = row.contains("/images/small_profile.gif"); // found it cache.found = row.contains("/images/icons/icon_smile"); // own it cache.own = row.contains("/images/silk/star.png"); // 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(cgSettings.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(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse favourite count"); } if (cache.nameSp == null) { cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name); if (cache.disabled || cache.archived) { // 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 = Integer.valueOf(matcherTotalCnt.group(1)); } } } } catch (Exception e) { // failed to parse cache count Log.w(cgSettings.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 && StringUtils.isNotBlank(recaptchaText)))) { Log.i(cgSettings.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=&__EVENTARGUMENT="); if (ArrayUtils.isNotEmpty(caches.viewstates)) { params.append("&__VIEWSTATE="); params.append(urlencode_rfc3986(caches.viewstates[0])); if (caches.viewstates.length > 1) { for (int i = 1; i < caches.viewstates.length; i++) { params.append("&__VIEWSTATE" + i + "="); params.append(urlencode_rfc3986(caches.viewstates[i])); } params.append("&__VIEWSTATEFIELDCOUNT=" + caches.viewstates.length); } } for (String cid : cids) { params.append("&CID="); params.append(urlencode_rfc3986(cid)); } if (recaptchaChallenge != null && StringUtils.isNotBlank(recaptchaText)) { params.append("&recaptcha_challenge_field="); params.append(urlencode_rfc3986(recaptchaChallenge)); params.append("&recaptcha_response_field="); params.append(urlencode_rfc3986(recaptchaText)); } params.append("&ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints"); final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData(); if (StringUtils.isNotBlank(coordinates)) { if (coordinates.contains( "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")) { Log.i(cgSettings.tag, "User has not agreed to the license agreement. Can\'t download .loc file."); caches.error = errorRetrieve.get(-7); return caches; } } LocParser.parseLoc(caches, coordinates); } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.parseSearch.CIDs: " + e.toString()); } } // get direction images if (settings.getLoadDirImg()) { for (cgCache oneCache : caches.cacheList) { if (oneCache.coords == null && oneCache.directionImg != null) { cgDirectionImg.getDrawable(oneCache.geocode, oneCache.directionImg); } } } // get ratings if (guids.size() > 0) { Log.i(cgSettings.tag, "Trying to get ratings for " + cids.size() + " caches"); try { final Map<String, cgRating> ratings = getRating(guids, null); if (CollectionUtils.isNotEmpty(ratings)) { // save found cache coordinates for (cgCache oneCache : caches.cacheList) { if (ratings.containsKey(oneCache.guid)) { cgRating thisRating = ratings.get(oneCache.guid); oneCache.rating = thisRating.rating; oneCache.votes = thisRating.votes; oneCache.myVote = thisRating.myVote; } } } } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.parseSearch.GCvote: " + e.toString()); } } return caches; }
From source file:cgeo.geocaching.cgBase.java
public cgCacheWrap parseCache(String page, int reason) { if (StringUtils.isBlank(page)) { Log.e(cgSettings.tag, "cgeoBase.parseCache: No page given"); return null; }//ww w . ja v a 2s . co m final cgCacheWrap caches = new cgCacheWrap(); final cgCache cache = new cgCache(); if (page.contains("Cache is Unpublished")) { caches.error = "cache was unpublished"; return caches; } if (page.contains("Sorry, the owner of this listing has made it viewable to Premium Members only.")) { caches.error = "requested cache is for premium members only"; return caches; } if (page.contains("has chosen to make this cache listing visible to Premium Members only.")) { caches.error = "requested cache is for premium members only"; return caches; } cache.disabled = page.contains("<li>This cache is temporarily unavailable."); cache.archived = page.contains("<li>This cache has been archived,"); cache.members = page.contains("<p class=\"Warning\">This is a Premium Member Only cache.</p>"); cache.reason = reason; // cache geocode try { final Matcher matcherGeocode = patternGeocode.matcher(page); if (matcherGeocode.find() && matcherGeocode.groupCount() > 0) { cache.geocode = getMatch(matcherGeocode.group(1)); } } catch (Exception e) { // failed to parse cache geocode Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache geocode"); } // cache id try { final Matcher matcherCacheId = patternCacheId.matcher(page); if (matcherCacheId.find() && matcherCacheId.groupCount() > 0) { cache.cacheId = getMatch(matcherCacheId.group(1)); } } catch (Exception e) { // failed to parse cache id Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache id"); } // cache guid try { final Matcher matcherCacheGuid = patternCacheGuid.matcher(page); if (matcherCacheGuid.find() && matcherCacheGuid.groupCount() > 0) { cache.guid = getMatch(matcherCacheGuid.group(1)); } } catch (Exception e) { // failed to parse cache guid Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache guid"); } // name try { final Matcher matcherName = patternName.matcher(page); if (matcherName.find() && matcherName.groupCount() > 0) { cache.name = Html.fromHtml(matcherName.group(1)).toString(); } } catch (Exception e) { // failed to parse cache name Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache name"); } // owner real name try { final Matcher matcherOwnerReal = patternOwnerReal.matcher(page); if (matcherOwnerReal.find() && matcherOwnerReal.groupCount() > 0) { cache.ownerReal = URLDecoder.decode(matcherOwnerReal.group(1)); } } catch (Exception e) { // failed to parse owner real name Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner real name"); } final String username = settings.getUsername(); if (cache.ownerReal != null && username != null && cache.ownerReal.equalsIgnoreCase(username)) { cache.own = true; } int pos = -1; String tableInside = page; pos = tableInside.indexOf("id=\"cacheDetails\""); if (pos == -1) { Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"cacheDetails\" not found on page"); return null; } tableInside = tableInside.substring(pos); pos = tableInside.indexOf("<div class=\"CacheInformationTable\""); if (pos == -1) { Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"CacheInformationTable\" not found on page"); return null; } tableInside = tableInside.substring(0, pos); if (StringUtils.isNotBlank(tableInside)) { // cache terrain try { final Matcher matcherTerrain = patternTerrain.matcher(tableInside); if (matcherTerrain.find() && matcherTerrain.groupCount() > 0) { cache.terrain = new Float( Pattern.compile("_").matcher(matcherTerrain.group(1)).replaceAll(".")); } } catch (Exception e) { // failed to parse terrain Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache terrain"); } // cache difficulty try { final Matcher matcherDifficulty = patternDifficulty.matcher(tableInside); if (matcherDifficulty.find() && matcherDifficulty.groupCount() > 0) { cache.difficulty = new Float( Pattern.compile("_").matcher(matcherDifficulty.group(1)).replaceAll(".")); } } catch (Exception e) { // failed to parse difficulty Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache difficulty"); } // owner try { final Matcher matcherOwner = patternOwner.matcher(tableInside); if (matcherOwner.find() && matcherOwner.groupCount() > 0) { cache.owner = Html.fromHtml(matcherOwner.group(2)).toString(); } } catch (Exception e) { // failed to parse owner Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner"); } // hidden try { final Matcher matcherHidden = patternHidden.matcher(tableInside); if (matcherHidden.find() && matcherHidden.groupCount() > 0) { cache.hidden = parseGcCustomDate(matcherHidden.group(1)); } } catch (ParseException e) { // failed to parse cache hidden date Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hidden date"); } if (cache.hidden == null) { // event date try { final Matcher matcherHiddenEvent = patternHiddenEvent.matcher(tableInside); if (matcherHiddenEvent.find() && matcherHiddenEvent.groupCount() > 0) { cache.hidden = parseGcCustomDate(matcherHiddenEvent.group(1)); } } catch (ParseException e) { // failed to parse cache event date Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache event date"); } } // favourite try { final Matcher matcherFavourite = patternFavourite.matcher(tableInside); if (matcherFavourite.find() && matcherFavourite.groupCount() > 0) { cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1)); } } catch (Exception e) { // failed to parse favourite count Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse favourite count"); } // cache size try { final Matcher matcherSize = patternSize.matcher(tableInside); if (matcherSize.find() && matcherSize.groupCount() > 0) { cache.size = CacheSize.FIND_BY_ID.get(getMatch(matcherSize.group(1)).toLowerCase()); } } catch (Exception e) { // failed to parse size Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache size"); } } // cache found cache.found = patternFound.matcher(page).find() || patternFoundAlternative.matcher(page).find(); // cache type try { final Matcher matcherType = patternType.matcher(page); if (matcherType.find() && matcherType.groupCount() > 0) { cache.type = cacheTypes.get(matcherType.group(1).toLowerCase()); } } catch (Exception e) { // failed to parse type Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache type"); } // on watchlist try { final Matcher matcher = patternOnWatchlist.matcher(page); cache.onWatchlist = matcher.find(); } catch (Exception e) { // failed to parse watchlist state Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse watchlist state"); } // latitude and logitude try { final Matcher matcherLatLon = patternLatLon.matcher(page); if (matcherLatLon.find() && matcherLatLon.groupCount() > 0) { cache.latlon = getMatch(matcherLatLon.group(2)); // first is <b> Map<String, Object> tmp = cgBase.parseLatlon(cache.latlon); if (tmp.size() > 0) { cache.coords = new Geopoint((Double) tmp.get("latitude"), (Double) tmp.get("longitude")); cache.latitudeString = (String) tmp.get("latitudeString"); cache.longitudeString = (String) tmp.get("longitudeString"); cache.reliableLatLon = true; } tmp = null; } } catch (Exception e) { // failed to parse latitude and/or longitude Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache coordinates"); } // cache location try { final Matcher matcherLocation = patternLocation.matcher(page); if (matcherLocation.find() && matcherLocation.groupCount() > 0) { cache.location = getMatch(matcherLocation.group(1)); } } catch (Exception e) { // failed to parse location Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache location"); } // cache hint try { final Matcher matcherHint = patternHint.matcher(page); if (matcherHint.find() && matcherHint.group(1) != null) { // replace linebreak and paragraph tags String hint = Pattern.compile("<(br|p)[^>]*>").matcher(matcherHint.group(1)).replaceAll("\n"); if (hint != null) { cache.hint = hint.replaceAll(Pattern.quote("</p>"), "").trim(); } } } catch (Exception e) { // failed to parse hint Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hint"); } checkFields(cache); /* * // short info debug * Log.d(cgSettings.tag, "gc-code: " + cache.geocode); * Log.d(cgSettings.tag, "id: " + cache.cacheid); * Log.d(cgSettings.tag, "guid: " + cache.guid); * Log.d(cgSettings.tag, "name: " + cache.name); * Log.d(cgSettings.tag, "terrain: " + cache.terrain); * Log.d(cgSettings.tag, "difficulty: " + cache.difficulty); * Log.d(cgSettings.tag, "owner: " + cache.owner); * Log.d(cgSettings.tag, "owner (real): " + cache.ownerReal); * Log.d(cgSettings.tag, "hidden: " + dateOutShort.format(cache.hidden)); * Log.d(cgSettings.tag, "favorite: " + cache.favouriteCnt); * Log.d(cgSettings.tag, "size: " + cache.size); * if (cache.found) { * Log.d(cgSettings.tag, "found!"); * } else { * Log.d(cgSettings.tag, "not found"); * } * Log.d(cgSettings.tag, "type: " + cache.type); * Log.d(cgSettings.tag, "latitude: " + String.format("%.6f", cache.latitude)); * Log.d(cgSettings.tag, "longitude: " + String.format("%.6f", cache.longitude)); * Log.d(cgSettings.tag, "location: " + cache.location); * Log.d(cgSettings.tag, "hint: " + cache.hint); */ // cache personal note try { final Matcher matcherPersonalNote = patternPersonalNote.matcher(page); if (matcherPersonalNote.find() && matcherPersonalNote.groupCount() > 0) { cache.personalNote = getMatch(matcherPersonalNote.group(1)); } } catch (Exception e) { // failed to parse cache personal note Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache personal note"); } // cache short description try { final Matcher matcherDescShort = patternDescShort.matcher(page); if (matcherDescShort.find() && matcherDescShort.groupCount() > 0) { cache.shortdesc = getMatch(matcherDescShort.group(1)); } } catch (Exception e) { // failed to parse short description Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache short description"); } // cache description try { final Matcher matcherDesc = patternDesc.matcher(page); if (matcherDesc.find() && matcherDesc.groupCount() > 0) { cache.description = getMatch(matcherDesc.group(1)); } } catch (Exception e) { // failed to parse short description Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache description"); } // cache attributes try { final Matcher matcherAttributes = patternAttributes.matcher(page); if (matcherAttributes.find() && matcherAttributes.groupCount() > 0) { final String attributesPre = matcherAttributes.group(1); final Matcher matcherAttributesInside = patternAttributesInside.matcher(attributesPre); while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && matcherAttributesInside.group(2).equalsIgnoreCase("blank") != true) { if (cache.attributes == null) { cache.attributes = new ArrayList<String>(); } // by default, use the tooltip of the attribute String attribute = matcherAttributesInside.group(2).toLowerCase(); // if the image name can be recognized, use the image name as attribute String imageName = matcherAttributesInside.group(1).trim(); if (imageName.length() > 0) { int start = imageName.lastIndexOf('/'); int end = imageName.lastIndexOf('.'); if (start >= 0 && end >= 0) { attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase(); } } cache.attributes.add(attribute); } } } } catch (Exception e) { // failed to parse cache attributes Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache attributes"); } // cache spoilers try { final Matcher matcherSpoilers = patternSpoilers.matcher(page); if (matcherSpoilers.find()) { final Matcher matcherSpoilersInside = patternSpoilersInside.matcher(matcherSpoilers.group(1)); while (matcherSpoilersInside.find()) { final cgImage spoiler = new cgImage(); spoiler.url = matcherSpoilersInside.group(1); if (matcherSpoilersInside.group(2) != null) { spoiler.title = matcherSpoilersInside.group(2); } if (matcherSpoilersInside.group(3) != null) { spoiler.description = matcherSpoilersInside.group(3); } if (cache.spoilers == null) { cache.spoilers = new ArrayList<cgImage>(); } cache.spoilers.add(spoiler); } } } catch (Exception e) { // failed to parse cache spoilers Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache spoilers"); } // cache inventory try { cache.inventoryItems = 0; final Matcher matcherInventory = patternInventory.matcher(page); if (matcherInventory.find()) { if (cache.inventory == null) { cache.inventory = new ArrayList<cgTrackable>(); } if (matcherInventory.groupCount() > 1) { final String inventoryPre = matcherInventory.group(2); if (StringUtils.isNotBlank(inventoryPre)) { final Matcher matcherInventoryInside = patternInventoryInside.matcher(inventoryPre); while (matcherInventoryInside.find()) { if (matcherInventoryInside.groupCount() > 0) { final cgTrackable inventoryItem = new cgTrackable(); inventoryItem.guid = matcherInventoryInside.group(1); inventoryItem.name = matcherInventoryInside.group(2); cache.inventory.add(inventoryItem); cache.inventoryItems++; } } } } } } catch (Exception e) { // failed to parse cache inventory Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache inventory (2)"); } // cache logs counts try { final Matcher matcherLogCounts = patternCountLogs.matcher(page); if (matcherLogCounts.find()) { final Matcher matcherLog = patternCountLog.matcher(matcherLogCounts.group(1)); while (matcherLog.find()) { String typeStr = matcherLog.group(1); String countStr = matcherLog.group(2).replaceAll("[.,]", ""); if (StringUtils.isNotBlank(typeStr) && logTypes.containsKey(typeStr.toLowerCase()) && StringUtils.isNotBlank(countStr)) { cache.logCounts.put(logTypes.get(typeStr.toLowerCase()), Integer.parseInt(countStr)); } } } } catch (Exception e) { // failed to parse logs Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache log count"); } // cache logs loadLogsFromDetails(page, cache); int wpBegin = 0; int wpEnd = 0; wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints final Pattern patternWpType = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg", Pattern.CASE_INSENSITIVE); final Pattern patternWpPrefixOrLookupOrLatlon = Pattern .compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>", Pattern.CASE_INSENSITIVE); final Pattern patternWpName = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>", Pattern.CASE_INSENSITIVE); final Pattern patternWpNote = Pattern.compile("colspan=\"6\">(.*)<\\/td>", Pattern.CASE_INSENSITIVE); String wpList = page.substring(wpBegin); wpEnd = wpList.indexOf("</p>"); if (wpEnd > -1 && wpEnd <= wpList.length()) { wpList = wpList.substring(0, wpEnd); } if (!wpList.contains("No additional waypoints to display.")) { wpEnd = wpList.indexOf("</table>"); wpList = wpList.substring(0, wpEnd); wpBegin = wpList.indexOf("<tbody>"); wpEnd = wpList.indexOf("</tbody>"); if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) { wpList = wpList.substring(wpBegin + 7, wpEnd); } final String[] wpItems = wpList.split("<tr"); String[] wp; for (int j = 1; j < wpItems.length; j++) { final cgWaypoint waypoint = new cgWaypoint(); wp = wpItems[j].split("<td"); // waypoint type try { final Matcher matcherWpType = patternWpType.matcher(wp[3]); if (matcherWpType.find() && matcherWpType.groupCount() > 0) { waypoint.type = matcherWpType.group(1).trim(); } } catch (Exception e) { // failed to parse type Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint type"); } // waypoint prefix try { final Matcher matcherWpPrefix = patternWpPrefixOrLookupOrLatlon.matcher(wp[4]); if (matcherWpPrefix.find() && matcherWpPrefix.groupCount() > 1) { waypoint.setPrefix(matcherWpPrefix.group(2).trim()); } } catch (Exception e) { // failed to parse prefix Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint prefix"); } // waypoint lookup try { final Matcher matcherWpLookup = patternWpPrefixOrLookupOrLatlon.matcher(wp[5]); if (matcherWpLookup.find() && matcherWpLookup.groupCount() > 1) { waypoint.lookup = matcherWpLookup.group(2).trim(); } } catch (Exception e) { // failed to parse lookup Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint lookup"); } // waypoint name try { final Matcher matcherWpName = patternWpName.matcher(wp[6]); while (matcherWpName.find()) { if (matcherWpName.groupCount() > 0) { waypoint.name = matcherWpName.group(1); if (StringUtils.isNotBlank(waypoint.name)) { waypoint.name = waypoint.name.trim(); } } if (matcherWpName.find() && matcherWpName.groupCount() > 0) { waypoint.name = matcherWpName.group(1).trim(); } } } catch (Exception e) { // failed to parse name Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint name"); } // waypoint latitude and logitude try { final Matcher matcherWpLatLon = patternWpPrefixOrLookupOrLatlon.matcher(wp[7]); if (matcherWpLatLon.find() && matcherWpLatLon.groupCount() > 1) { waypoint.latlon = Html.fromHtml(matcherWpLatLon.group(2)).toString(); final Map<String, Object> tmp = cgBase.parseLatlon(waypoint.latlon); if (tmp.size() > 0) { waypoint.coords = new Geopoint((Double) tmp.get("latitude"), (Double) tmp.get("longitude")); waypoint.latitudeString = (String) tmp.get("latitudeString"); waypoint.longitudeString = (String) tmp.get("longitudeString"); } } } catch (Exception e) { // failed to parse latitude and/or longitude Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint coordinates"); } j++; if (wpItems.length > j) { wp = wpItems[j].split("<td"); } // waypoint note try { final Matcher matcherWpNote = patternWpNote.matcher(wp[3]); if (matcherWpNote.find() && matcherWpNote.groupCount() > 0) { waypoint.note = matcherWpNote.group(1).trim(); } } catch (Exception e) { // failed to parse note Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint note"); } if (cache.waypoints == null) { cache.waypoints = new ArrayList<cgWaypoint>(); } cache.waypoints.add(waypoint); } } } if (cache.coords != null) { cache.elevation = getElevation(cache.coords); } final cgRating rating = getRating(cache.guid, cache.geocode); if (rating != null) { cache.rating = rating.rating; cache.votes = rating.votes; cache.myVote = rating.myVote; } cache.updated = System.currentTimeMillis(); cache.detailedUpdate = System.currentTimeMillis(); cache.detailed = true; caches.cacheList.add(cache); return caches; }
From source file:carnero.cgeo.original.libs.Base.java
public String getMapUserToken(Handler noTokenHandler) { final Response response = request(false, "www.geocaching.com", "/map/default.aspx", "GET", "", 0, false); final String data = response.getData(); String usertoken = null;/*from ww w. j a v a 2 s . co m*/ if (data != null && data.length() > 0) { 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 && (usertoken == null || usertoken.length() == 0)) { noTokenHandler.sendEmptyMessage(0); } return usertoken; }
From source file:carnero.cgeo.original.libs.Base.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 va 2 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(Settings.tag, "cgBase.parseLatlon: Failed to parse coordinates."); } } return result; }
From source file:carnero.cgeo.original.libs.Base.java
public int parseFindCount(String page) { if (page == null || page.length() == 0) { return -1; }/*from ww w .j a va2 s .c om*/ 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(Settings.tag, "cgBase.parseFindCount: " + e.toString()); } return findCount; }
From source file:carnero.cgeo.original.libs.Base.java
public ArrayList<TrackableLog> parseTrackableLog(String page) { if (page == null || page.length() == 0) { return null; }//from ww w.j av a 2s. c o m final ArrayList<TrackableLog> trackables = new ArrayList<TrackableLog>(); int startPos = -1; int endPos = -1; startPos = page.indexOf("<table id=\"tblTravelBugs\""); if (startPos == -1) { Log.e(Settings.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(Settings.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(Settings.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(Settings.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 TrackableLog trackable = new TrackableLog(); 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(Settings.tag, "Trackable in inventory (#" + trackable.ctl + "/" + trackable.id + "): " + trackable.trackCode + " - " + trackable.name); trackables.add(trackable); } } return trackables; }
From source file:carnero.cgeo.original.libs.Base.java
public int postLog(App app, String geocode, String cacheid, String viewstate, String viewstate1, int logType, int year, int month, int day, String log, ArrayList<TrackableLog> trackables) { if (viewstate == null || viewstate.length() == 0) { Log.e(Settings.tag, "cgeoBase.postLog: No viewstate given"); return 1000; }//from w w w .j a va 2 s . c o m if (logTypes2.containsKey(logType) == false) { Log.e(Settings.tag, "cgeoBase.postLog: Unknown logtype"); return 1000; } if (log == null || log.length() == 0) { Log.e(Settings.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(Settings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + log + "; trackables: " + trackables.size()); } else { Log.i(Settings.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 (TrackableLog 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(Settings.tag, "cgeoBase.postLog: Can not log in geocaching (error: " + loginState + ")"); return loginState; } } if (page == null || page.length() == 0) { Log.e(Settings.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(Settings.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 (TrackableLog 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(Settings.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(Settings.tag, "Log successfully posted to cache #" + cacheid); if (app != null && geocode != null) { app.saveVisitDate(geocode); } return 1; } } catch (Exception e) { Log.e(Settings.tag, "cgeoBase.postLog.check: " + e.toString()); } Log.e(Settings.tag, "cgeoBase.postLog: Failed to post log because of unknown error"); return 1000; }
From source file:carnero.cgeo.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 w w w . j av a 2 s. c o m*/ if (data != null && data.length() > 0) { 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 && (usertoken == null || usertoken.length() == 0)) { noTokenHandler.sendEmptyMessage(0); } return usertoken; }