private void fetchTasks(TracksAction act) {
    final String server = _prefs.getString(PreferenceConstants.SERVER, null);
    final boolean badcert = _prefs.getBoolean(PreferenceConstants.BADCERT, false);
    final String username = _prefs.getString(PreferenceConstants.USERNAME, null);
    final String password = _prefs.getString(PreferenceConstants.PASSWORD, null);

    Log.d(TAG, "Fetching tasks");

    Handler replyTo = act.notify;

    if (server == null || username == null || password == null) {
      Message.obtain(replyTo, PREFS_FAIL_CODE).sendToTarget();
      return;
    }

    HttpResponse r;
    InputStream[] ret = new InputStream[3];

    Message.obtain(replyTo, FETCH_CODE).sendToTarget();

    try {
      r =
          HttpConnection.get(
              PreferenceUtils.getUri(_prefs, "contexts.xml"), username, password, badcert);
      ret[0] = r.getEntity().getContent();

      r =
          HttpConnection.get(
              PreferenceUtils.getUri(_prefs, "projects.xml"), username, password, badcert);
      ret[1] = r.getEntity().getContent();

      r =
          HttpConnection.get(
              PreferenceUtils.getUri(_prefs, "todos.xml"), username, password, badcert);
      ret[2] = r.getEntity().getContent();
    } catch (Exception e) {
      Log.w(TAG, "Failed to fetch tasks!", e);
      Message.obtain(replyTo, FETCH_FAIL_CODE).sendToTarget();
      return;
    }

    Message.obtain(replyTo, PARSE_CODE).sendToTarget();

    try {
      Xml.parse(ret[0], Xml.Encoding.UTF_8, new ContextXmlHandler());
      Xml.parse(ret[1], Xml.Encoding.UTF_8, new ProjectXmlHandler());
      Xml.parse(ret[2], Xml.Encoding.UTF_8, new TaskXmlHandler());
    } catch (IOException e) {
      Log.w(TAG, "Failed to read XML!", e);
      Message.obtain(replyTo, FETCH_FAIL_CODE).sendToTarget();
      return;
    } catch (SAXException e) {
      Log.w(TAG, "Failed to parse XML!", e);
      Message.obtain(replyTo, PARSE_FAIL_CODE).sendToTarget();
      return;
    }

    Message.obtain(replyTo, SUCCESS_CODE).sendToTarget();
  }
Example #2
0
  /**
   * Execute this {@link HttpUriRequest}, passing a valid response through {@link
   * XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}.
   */
  private static void execute(
      HttpUriRequest request, HttpClient httpClient, ContentHandler handler, boolean isZipFile)
      throws SAXException {
    try {
      final HttpResponse resp = httpClient.execute(request);
      final int status = resp.getStatusLine().getStatusCode();
      if (status != HttpStatus.SC_OK) {
        throw new SAXException(
            "Unexpected server response "
                + resp.getStatusLine()
                + " for "
                + request.getRequestLine());
      }

      final InputStream input = resp.getEntity().getContent();
      if (isZipFile) {
        // We downloaded the compressed file from TheTVDB
        final ZipInputStream zipin = new ZipInputStream(input);
        zipin.getNextEntry();
        try {
          Xml.parse(zipin, Xml.Encoding.UTF_8, handler);
        } catch (SAXException e) {
          throw new SAXException("Malformed response for " + request.getRequestLine(), e);
        } catch (IOException ioe) {
          throw new SAXException(
              "Problem reading remote response for " + request.getRequestLine(), ioe);
        } finally {
          if (zipin != null) {
            zipin.close();
          }
        }
      } else {
        try {
          Xml.parse(input, Xml.Encoding.UTF_8, handler);
        } catch (SAXException e) {
          throw new SAXException("Malformed response for " + request.getRequestLine(), e);
        } catch (IOException ioe) {
          throw new SAXException(
              "Problem reading remote response for " + request.getRequestLine(), ioe);
        } finally {
          if (input != null) {
            input.close();
          }
        }
      }
    } catch (AssertionError ae) {
      // looks like Xml.parse is throwing AssertionErrors instead of
      // IOExceptions
      throw new SAXException("Problem reading remote response for " + request.getRequestLine());
    } catch (Exception e) {
      throw new SAXException("Problem reading remote response for " + request.getRequestLine(), e);
    }
  }
  public ArrayList<Bundle> parse() throws ParseException {
    final Bundle currentBundle = new Bundle();
    RootElement root = new RootElement("bundles");
    final ArrayList<Bundle> bundles = new ArrayList<Bundle>();

    root.getChild("bundle")
        .setStartElementListener(
            new StartElementListener() {
              public void start(Attributes attributes) {
                String tags = attributes.getValue("", "tags");
                String name = attributes.getValue("", "name");

                if (tags != null) {
                  currentBundle.setTagString(tags);
                }
                if (name != null) {
                  currentBundle.setName(name);
                }

                bundles.add(currentBundle.copy());
              }
            });
    try {
      Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (Exception e) {
      throw new ParseException(e.getMessage(), 0);
    }
    return bundles;
  }
  @Override
  public Object parseXml(String xmlString) {
    final ArrayList<ColourDAO> colours = new ArrayList<ColourDAO>();
    RootElement rootElement = new RootElement(Tags.COLOURS);
    Element modelElement = rootElement.getChild(Tags.COLOUR);
    modelElement.setStartElementListener(
        new StartElementListener() {
          @Override
          public void start(Attributes attributes) {
            colourDAO = new ColourDAO(attributes.getValue(Tags.ID), "");
          }
        });
    modelElement.setEndTextElementListener(
        new EndTextElementListener() {
          @Override
          public void end(String body) {
            if (!TextUtils.isEmpty(body)) {
              colourDAO.name = body;
              colours.add(colourDAO);
            }
          }
        });

    try {
      Xml.parse(xmlString, rootElement.getContentHandler());
    } catch (SAXException e) {
      e.printStackTrace();
    }
    return colours;
  }
Example #5
0
  public static void fillData2(final Story s) {
    URL storyURL;
    try {
      storyURL = new URL(mobileStoryUrlBase + s.url.substring(s.url.lastIndexOf('/')));
    } catch (MalformedURLException e) {
      throw new RuntimeException("Malformed story url");
    }

    RootElement html = new RootElement("http://www.w3.org/1999/xhtml", "html");
    Element body = html.getChild("body");

    body.setTextElementListener(
        new TextElementListener() {

          private ParseState state = ParseState.OTHER;
          /**
           * We don't know which element we are at in end(). So to know when the body div is ending,
           * keep track of how many elements have started and ended
           */
          private int depth = 0;

          @Override
          public void start(Attributes attributes) {
            if (attributes.getValue("class").equals(PHOTO_CLASS)) state = ParseState.PHOTO;
            else if (state == ParseState.PHOTO) s.imgUrl = attributes.getValue("src");
            else if (attributes.getValue("class").equals(BODY_CLASS)) {
              state = ParseState.BODY;
              s.text = "";
            } else if (state == ParseState.BODY) depth++;
          }

          @Override
          public void end(String body) {
            if (state == ParseState.BODY) {
              if (depth == 0) state = ParseState.OTHER;
              else {
                s.text = s.text + body;
                depth--;
              }
            }
          }
        });

    body.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attributes) {
            // Log.d("isd", "class2: " + attributes.getValue("class"));
          }
        });

    try {
      Xml.parse(
          storyURL.openConnection().getInputStream(), Xml.Encoding.UTF_8, html.getContentHandler());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public Links parse(InputStream xml) {
    try {
      Xml.parse(xml, Xml.Encoding.ISO_8859_1, this);
      xml.close();
    } catch (Exception e) {
      Log.d(Constants.TAG, e.toString());
    }

    return links;
  }
  /**
   * Parses the.
   *
   * @param xml the xml
   * @return the list´
   * @author RayBa
   * @throws SAXException
   * @date 07.04.2013
   */
  public List<Channel> parse(String xml) throws SAXException {
    RootElement channels = new RootElement("channels");
    Element rootElement = channels.getChild("root");
    Element groupElement = rootElement.getChild("group");
    Element channelElement = groupElement.getChild("channel");
    Element logoElement = channelElement.getChild("logo");
    Element subChanElement = channelElement.getChild("subchannel");

    channels.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attributes) {
            channelList = new ArrayList<Channel>();
          }
        });

    channelElement.setStartElementListener(
        new StartElementListener() {
          public void start(Attributes attributes) {
            currentChannel = new Channel();
            currentChannel.setChannelID(Long.valueOf(attributes.getValue("ID")));
            currentChannel.setPosition(Integer.valueOf(attributes.getValue("nr")));
            currentChannel.setName(attributes.getValue("name"));
            currentChannel.setEpgID(Long.valueOf(attributes.getValue("EPGID")));
            channelList.add(currentChannel);
          }
        });

    logoElement.setEndTextElementListener(
        new EndTextElementListener() {

          @Override
          public void end(String body) {
            currentChannel.setLogoUrl(body);
          }
        });

    subChanElement.setStartElementListener(
        new StartElementListener() {
          public void start(Attributes attributes) {
            Channel c = new Channel();
            c.setChannelID(Long.valueOf(attributes.getValue("ID")));
            c.setName(attributes.getValue("name"));
            c.setPosition(currentChannel.getPosition());
            c.setEpgID(currentChannel.getEpgID());
            c.setLogoUrl(currentChannel.getLogoUrl());
            c.setFlag(Channel.FLAG_ADDITIONAL_AUDIO);
            channelList.add(c);
          }
        });

    Xml.parse(xml, channels.getContentHandler());
    return channelList;
  }
 public List<Message> parse() {
   final Message currentMessage = new Message();
   RootElement root = new RootElement(RSS);
   final List<Message> messages = new ArrayList<Message>();
   Element channel = root.getChild(CHANNEL);
   Element item = channel.getChild(ITEM);
   item.setEndElementListener(
       new EndElementListener() {
         public void end() {
           messages.add(currentMessage.copy());
         }
       });
   item.getChild(TITLE)
       .setEndTextElementListener(
           new EndTextElementListener() {
             public void end(String body) {
               currentMessage.setTitle(body);
             }
           });
   item.getChild(LINK)
       .setEndTextElementListener(
           new EndTextElementListener() {
             public void end(String body) {
               currentMessage.setLink(body);
             }
           });
   item.getChild(DESCRIPTION)
       .setEndTextElementListener(
           new EndTextElementListener() {
             public void end(String body) {
               currentMessage.setDescription(body);
             }
           });
   item.getChild(PUB_DATE)
       .setEndTextElementListener(
           new EndTextElementListener() {
             public void end(String body) {
               currentMessage.setDate(body);
             }
           });
   try {
     Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   return messages;
 }
  @Override
  public Object parseXml(String xmlString) throws Exception {
    RootElement rootElement = new RootElement(Tags.submitBike);
    Element messageHeadingElement = rootElement.getChild(Tags.MessageHeading);
    Element messageBodyElement = rootElement.getChild(Tags.MessageBody);

    messageHeadingElement.setEndTextElementListener(
        new EndTextElementListener() {

          @Override
          public void end(String body) {
            messageHeading = body;
          }
        });
    Xml.parse(xmlString, rootElement.getContentHandler());
    return messageHeading;
  }
  /**
   * Parses the xml String favourites.xml
   *
   * @param context the context
   * @param xml the xml
   * @return the list´
   * @author RayBa
   * @throws SAXException
   * @date 05.07.2012
   */
  public List<Fav> parse(Context context, String xml) throws SAXException {
    RootElement root = new RootElement("settings");
    Element sectionElement = root.getChild("section");
    Element entryElement = sectionElement.getChild("entry");

    root.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attributes) {
            favourites = new ArrayList<Fav>();
          }
        });

    entryElement.setEndTextElementListener(
        new EndTextElementListener() {

          @Override
          public void end(String body) {
            String[] channelInfos = body.split("\\|");
            if (channelInfos.length > 1) {
              currentFav = new Fav();
              long id = Long.valueOf(channelInfos[0]);
              currentFav.id = id;
              currentFav.name = channelInfos[1];
              favourites.add(currentFav);
            }
          }
        });

    Xml.parse(xml, root.getContentHandler());
    for (int i = 0; i < favourites.size(); i++) {
      Fav fav = favourites.get(i);
      fav.position = i + 1;
    }
    return favourites;
  }
 public static synchronized HashMap<String, AppSupportFeature> getInstance(Context context) {
   if (features == null) {
     InputStream inputStream =
         context.getResources().openRawResource(R.raw.app_supported_feature_config);
     XML2Feature xml2Feature = new XML2Feature();
     try {
       android.util.Xml.parse(inputStream, Xml.Encoding.UTF_8, xml2Feature);
       List<AppSupportFeature> featuresList = xml2Feature.getFeatures();
       if (featuresList != null && featuresList.size() > 0) {
         features = new HashMap<String, AppSupportFeature>();
         for (AppSupportFeature appSupportFeature : featuresList) {
           features.put(appSupportFeature.getName(), appSupportFeature);
         }
       }
     } catch (IOException e) {
       LOG.error("Parse feature config error", e);
     } catch (SAXException e) {
       LOG.error("Parse feature config error", e);
     } finally {
       IOUtils.close(inputStream);
     }
   }
   return features;
 }
  public ArrayList<NewsStory> parseStories(InputStream in) throws IOException, SAXException {

    Xml.parse(in, Xml.Encoding.UTF_8, this);
    return stories;
  }
Example #13
0
    @Override
    public void handleMessage(Message msg) {
      Intent intent = new Intent(BACKEND_UPDATE);
      intent.putExtra(BACKEND_UPDATE_RUNNING, true);
      sendBroadcast(intent);

      boolean hadNewPosts = false;

      // Copy the ArrayList to avoid surprises due to concurrent modifications
      // We don't need to synchronize or anything here, as that would induce delays
      // and we don't really care if we load something that wasn't really due.
      @SuppressWarnings("unchecked")
      ArrayList<String> boardsCopy = (ArrayList<String>) boards.clone();

      int count = boardsCopy.size();
      AndroidHttpClient httpClient =
          AndroidHttpClient.newInstance(
              preferences.getString("user_agent", getString(R.string.user_agent_default)));
      try {
        for (int i = 0; i < count; i++) {
          String board = boardsCopy.get(i);
          Uri lastIdUri = Uri.withAppendedPath(PostsProvider.Posts.CONTENT_LASTID_URI_BASE, board);
          String[] columns = {PostsProvider.Posts.COLUMN_NAME_ID};
          Cursor c = getContentResolver().query(lastIdUri, columns, null, null, null);
          long lastId = 0;
          if (c.moveToFirst()) {
            lastId = c.getLong(0);
          }
          c.close();

          try {
            List<NameValuePair> params = new LinkedList<NameValuePair>();
            params.add(new BasicNameValuePair("query", "id:[" + lastId + " TO *]"));
            String paramString = URLEncodedUtils.format(params, "utf-8");
            String url =
                preferences.getString("olccs_base_uri", getString(R.string.olccs_base_uri_default))
                    + board
                    + "/search?"
                    + paramString;
            HttpResponse res = httpClient.execute(new HttpGet(url));
            if (res.getStatusLine().getStatusCode() >= 300) {
              throw new IOException(
                  "Got HTTP response " + res.getStatusLine().toString() + " for URL " + url);
            }
            HttpEntity entity = res.getEntity();
            if (entity == null) {
              throw new IOException("Got empty response for URL " + url);
            }
            Xml.parse(entity.getContent(), Xml.Encoding.UTF_8, new XmlPostsHandler());
          } catch (IOException e) {
            Log.e("PostsUpdateMessageHandler", "Unable to fetch data for board " + board);
          } catch (SAXException e) {
            Log.e(
                "PostsUpdateMessageHandler",
                "Unable to parse XML content returned by server for board " + board);
          }

          if (lastId < curLastId) hadNewPosts = true;
        }
      } catch (Exception e) {
        Log.e("PostsUpdateMessageHandler", "Unhandled error " + e.getMessage());
        e.printStackTrace();
      } finally {
        httpClient.close();
      }

      if (msg.what == MSG_UPDATE_AUTO || msg.what == MSG_UPDATE_USER_REQUEST) {
        if (hadNewPosts) {
          delay = 3000;
        } else {
          delay = Math.min(delay + 3000, 60000);
        }
      }
      if (msg.what == MSG_UPDATE_AUTO) {
        Message newMsg = this.obtainMessage();
        newMsg.arg1 = msg.arg1;
        newMsg.what = msg.what;
        newMsg.obj = boards;
        if (!destroyCalled) {
          this.sendMessageDelayed(newMsg, delay);
        }
      }

      intent = new Intent(BACKEND_UPDATE);
      intent.putExtra(BACKEND_UPDATE_RUNNING, false);
      sendBroadcast(intent);
    }
Example #14
0
 public HashMap<String, Object> a(String paramString) {
   n.a locala = new n.a();
   Xml.parse(paramString, locala);
   return locala.a();
 }
Example #15
0
  @Override
  public Collection<cgCache> parse(
      final InputStream stream, final CancellableHandler progressHandler)
      throws IOException, ParserException {
    resetCache();
    final RootElement root = new RootElement(namespace, "gpx");
    final Element waypoint = root.getChild(namespace, "wpt");

    // waypoint - attributes
    waypoint.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attrs) {
            try {
              if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
                final String latitude = attrs.getValue("lat");
                final String longitude = attrs.getValue("lon");
                // latitude and longitude are required attributes, but we export them empty for
                // waypoints without coordinates
                if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
                  cache.setCoords(
                      new Geopoint(Double.valueOf(latitude), Double.valueOf(longitude)));
                }
              }
            } catch (Exception e) {
              Log.w("Failed to parse waypoint's latitude and/or longitude.");
            }
          }
        });

    // waypoint
    waypoint.setEndElementListener(
        new EndElementListener() {

          @Override
          public void end() {
            // try to find geocode somewhere else
            if (StringUtils.isBlank(cache.getGeocode())) {
              findGeoCode(name);
              findGeoCode(desc);
              findGeoCode(cmt);
            }
            // take the name as code, if nothing else is available
            if (StringUtils.isBlank(cache.getGeocode())) {
              if (StringUtils.isNotBlank(name)) {
                cache.setGeocode(name.trim());
              }
            }

            if (StringUtils.isNotBlank(cache.getGeocode())
                && cache.getCoords() != null
                && ((type == null && sym == null)
                    || StringUtils.contains(type, "geocache")
                    || StringUtils.contains(sym, "geocache"))) {
              fixCache(cache);
              cache.setListId(listId);
              cache.setDetailed(true);

              createNoteFromGSAKUserdata();

              final String geocode = cache.getGeocode();
              if (result.contains(geocode)) {
                Log.w("Duplicate geocode during GPX import: " + geocode);
              }
              // modify cache depending on the use case/connector
              afterParsing(cache);

              // finally store the cache in the database
              result.add(geocode);
              cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
              cgData.removeAllFromCache();
              showProgressMessage(progressHandler, progressStream.getProgress());
            } else if (StringUtils.isNotBlank(cache.getName())
                && StringUtils.containsIgnoreCase(type, "waypoint")) {
              addWaypointToCache();
            }

            resetCache();
          }

          private void addWaypointToCache() {
            fixCache(cache);

            if (cache.getName().length() > 2) {
              final String cacheGeocodeForWaypoint =
                  "GC" + cache.getName().substring(2).toUpperCase(Locale.US);
              // lookup cache for waypoint in already parsed caches
              final cgCache cacheForWaypoint =
                  cgData.loadCache(cacheGeocodeForWaypoint, LoadFlags.LOAD_CACHE_OR_DB);
              if (cacheForWaypoint != null) {
                final Waypoint waypoint =
                    new Waypoint(cache.getShortdesc(), convertWaypointSym2Type(sym), false);
                waypoint.setId(-1);
                waypoint.setGeocode(cacheGeocodeForWaypoint);
                waypoint.setPrefix(cache.getName().substring(0, 2));
                waypoint.setLookup("---");
                // there is no lookup code in gpx file
                waypoint.setCoords(cache.getCoords());
                waypoint.setNote(cache.getDescription());

                final ArrayList<Waypoint> mergedWayPoints = new ArrayList<Waypoint>();
                mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());

                final ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>();
                newPoints.add(waypoint);
                Waypoint.mergeWayPoints(newPoints, mergedWayPoints, true);
                cacheForWaypoint.setWaypoints(newPoints, false);
                cgData.saveCache(cacheForWaypoint, EnumSet.of(SaveFlag.SAVE_DB));
                showProgressMessage(progressHandler, progressStream.getProgress());
              }
            }
          }
        });

    // waypoint.time
    waypoint
        .getChild(namespace, "time")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                try {
                  cache.setHidden(parseDate(body));
                } catch (Exception e) {
                  Log.w("Failed to parse cache date", e);
                }
              }
            });

    // waypoint.getName()
    waypoint
        .getChild(namespace, "name")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                name = body;

                final String content = body.trim();
                cache.setName(content);

                findGeoCode(cache.getName());
              }
            });

    // waypoint.desc
    waypoint
        .getChild(namespace, "desc")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                desc = body;

                cache.setShortdesc(validate(body));
              }
            });

    // waypoint.cmt
    waypoint
        .getChild(namespace, "cmt")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                cmt = body;

                cache.setDescription(validate(body));
              }
            });

    // waypoint.getType()
    waypoint
        .getChild(namespace, "type")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                final String[] content = body.split("\\|");
                if (content.length > 0) {
                  type = content[0].toLowerCase(Locale.US).trim();
                }
              }
            });

    // waypoint.sym
    waypoint
        .getChild(namespace, "sym")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(final String body) {
                sym = body.toLowerCase(Locale.US);
                if (sym.contains("geocache") && sym.contains("found")) {
                  cache.setFound(true);
                }
              }
            });

    // waypoint.url
    waypoint
        .getChild(namespace, "url")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String url) {
                final MatcherWrapper matcher = new MatcherWrapper(patternGuid, url);
                if (matcher.matches()) {
                  final String guid = matcher.group(1);
                  if (StringUtils.isNotBlank(guid)) {
                    cache.setGuid(guid);
                  }
                }
                final MatcherWrapper matcherCode = new MatcherWrapper(patternUrlGeocode, url);
                if (matcherCode.matches()) {
                  String geocode = matcherCode.group(1);
                  cache.setGeocode(geocode);
                }
              }
            });

    // for GPX 1.0, cache info comes from waypoint node (so called private children,
    // for GPX 1.1 from extensions node
    final Element cacheParent = getCacheParent(waypoint);

    // GSAK extensions
    for (String gsakNamespace : GSAK_NS) {
      final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
      gsak.getChild(gsakNamespace, "Watch")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String watchList) {
                  cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
                }
              });

      gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));

      for (int i = 2; i <= 4; i++) {
        gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
      }
    }

    // 3 different versions of the GC schema
    for (String nsGC : nsGCList) {
      // waypoints.cache
      final Element gcCache = cacheParent.getChild(nsGC, "cache");

      gcCache.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1) {
                  cache.setCacheId(attrs.getValue("id"));
                }
                if (attrs.getIndex("archived") > -1) {
                  cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
                }
                if (attrs.getIndex("available") > -1) {
                  cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
                }
              } catch (Exception e) {
                Log.w("Failed to parse cache attributes.");
              }
            }
          });

      // waypoint.cache.getName()
      gcCache
          .getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheName) {
                  cache.setName(validate(cacheName));
                }
              });

      // waypoint.cache.getOwner()
      gcCache
          .getChild(nsGC, "owner")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String ownerUserId) {
                  cache.setOwnerUserId(validate(ownerUserId));
                }
              });

      // waypoint.cache.getOwner()
      gcCache
          .getChild(nsGC, "placed_by")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String ownerDisplayName) {
                  cache.setOwnerDisplayName(validate(ownerDisplayName));
                }
              });

      // waypoint.cache.getType()
      gcCache
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  cache.setType(CacheType.getByPattern(validate(body)));
                }
              });

      // waypoint.cache.container
      gcCache
          .getChild(nsGC, "container")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  cache.setSize(CacheSize.getById(validate(body)));
                }
              });

      // waypoint.cache.getAttributes()
      // @see issue #299

      // <groundspeak:attributes>
      //   <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
      //   <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
      // where inc = 0 => _no, inc = 1 => _yes
      // IDs see array CACHE_ATTRIBUTES
      final Element gcAttributes = gcCache.getChild(nsGC, "attributes");

      // waypoint.cache.attribute
      final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");

      gcAttribute.setStartElementListener(
          new StartElementListener() {
            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
                  int attributeId = Integer.parseInt(attrs.getValue("id"));
                  boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
                  String internalId =
                      CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
                  if (internalId != null) {
                    cache.getAttributes().add(internalId);
                  }
                }
              } catch (NumberFormatException e) {
                // nothing
              }
            }
          });

      // waypoint.cache.getDifficulty()
      gcCache
          .getChild(nsGC, "difficulty")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.setDifficulty(Float.parseFloat(body));
                  } catch (NumberFormatException e) {
                    Log.w("Failed to parse difficulty", e);
                  }
                }
              });

      // waypoint.cache.getTerrain()
      gcCache
          .getChild(nsGC, "terrain")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.setTerrain(Float.parseFloat(body));
                  } catch (NumberFormatException e) {
                    Log.w("Failed to parse terrain", e);
                  }
                }
              });

      // waypoint.cache.country
      gcCache
          .getChild(nsGC, "country")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String country) {
                  if (StringUtils.isBlank(cache.getLocation())) {
                    cache.setLocation(validate(country));
                  } else {
                    cache.setLocation(cache.getLocation() + ", " + country.trim());
                  }
                }
              });

      // waypoint.cache.state
      gcCache
          .getChild(nsGC, "state")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String state) {
                  String trimmedState = state.trim();
                  if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
                    if (StringUtils.isBlank(cache.getLocation())) {
                      cache.setLocation(validate(state));
                    } else {
                      cache.setLocation(trimmedState + ", " + cache.getLocation());
                    }
                  }
                }
              });

      // waypoint.cache.encoded_hints
      gcCache
          .getChild(nsGC, "encoded_hints")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String encoded) {
                  cache.setHint(validate(encoded));
                }
              });

      gcCache
          .getChild(nsGC, "short_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String shortDesc) {
                  cache.setShortdesc(validate(shortDesc));
                }
              });

      gcCache
          .getChild(nsGC, "long_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String desc) {
                  cache.setDescription(validate(desc));
                }
              });

      // waypoint.cache.travelbugs
      final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");

      // waypoint.cache.travelbug
      final Element gcTB = gcTBs.getChild(nsGC, "travelbug");

      // waypoint.cache.travelbugs.travelbug
      gcTB.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              trackable = new Trackable();

              try {
                if (attrs.getIndex("ref") > -1) {
                  trackable.setGeocode(attrs.getValue("ref"));
                }
              } catch (Exception e) {
                // nothing
              }
            }
          });

      gcTB.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (StringUtils.isNotBlank(trackable.getGeocode())
                  && StringUtils.isNotBlank(trackable.getName())) {
                if (cache.getInventory() == null) {
                  cache.setInventory(new ArrayList<Trackable>());
                }
                cache.getInventory().add(trackable);
              }
            }
          });

      // waypoint.cache.travelbugs.travelbug.getName()
      gcTB.getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String tbName) {
                  trackable.setName(validate(tbName));
                }
              });

      // waypoint.cache.logs
      final Element gcLogs = gcCache.getChild(nsGC, "logs");

      // waypoint.cache.log
      final Element gcLog = gcLogs.getChild(nsGC, "log");

      gcLog.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              log = new LogEntry("", 0, LogType.UNKNOWN, "");

              try {
                if (attrs.getIndex("id") > -1) {
                  log.id = Integer.parseInt(attrs.getValue("id"));
                }
              } catch (Exception e) {
                // nothing
              }
            }
          });

      gcLog.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (log.type != LogType.UNKNOWN) {
                cache.getLogs().add(log);
              }
            }
          });

      // waypoint.cache.logs.log.date
      gcLog
          .getChild(nsGC, "date")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    log.date = parseDate(body).getTime();
                  } catch (Exception e) {
                    Log.w("Failed to parse log date", e);
                  }
                }
              });

      // waypoint.cache.logs.log.getType()
      gcLog
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  final String logType = validate(body);
                  log.type = LogType.getByType(logType);
                }
              });

      // waypoint.cache.logs.log.finder
      gcLog
          .getChild(nsGC, "finder")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String finderName) {
                  log.author = validate(finderName);
                }
              });

      // waypoint.cache.logs.log.text
      gcLog
          .getChild(nsGC, "text")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String logText) {
                  log.log = validate(logText);
                }
              });
    }

    try {
      progressStream = new ProgressInputStream(stream);
      Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
      return cgData.loadCaches(result, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL));
    } catch (SAXException e) {
      Log.w("Cannot parse .gpx file as GPX " + version + ": could not parse XML - ", e);
      throw new ParserException(
          "Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
    }
  }
Example #16
0
  /**
   * Search for shows which include a certain keyword in their title. Dependent on the TheTVDB
   * search algorithms.
   *
   * @param title
   * @return a List with SearchResult objects, max 100
   * @throws SAXException
   * @throws IOException
   */
  public static List<SearchResult> searchShow(String title, Context context)
      throws IOException, SAXException {
    String language = getTheTVDBLanguage(context);

    URL url;
    try {
      url =
          new URL(
              xmlMirror
                  + "GetSeries.php?seriesname="
                  + URLEncoder.encode(title, "UTF-8")
                  + (language != null ? "&language=" + language : ""));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    final List<SearchResult> series = new ArrayList<SearchResult>();
    final SearchResult currentShow = new SearchResult();

    RootElement root = new RootElement("Data");
    Element item = root.getChild("Series");
    // set handlers for elements we want to react to
    item.setEndElementListener(
        new EndElementListener() {
          public void end() {
            series.add(currentShow.copy());
          }
        });
    item.getChild("id")
        .setEndTextElementListener(
            new EndTextElementListener() {
              public void end(String body) {
                currentShow.tvdbid = body;
              }
            });
    item.getChild("SeriesName")
        .setEndTextElementListener(
            new EndTextElementListener() {
              public void end(String body) {
                currentShow.title = body.trim();
              }
            });
    item.getChild("Overview")
        .setEndTextElementListener(
            new EndTextElementListener() {
              public void end(String body) {
                currentShow.overview = body.trim();
              }
            });

    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(25000);
    connection.setReadTimeout(90000);
    InputStream in = connection.getInputStream();
    try {
      Xml.parse(in, Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (Exception e) {
      throw new IOException();
    }
    in.close();

    return series;
  }
Example #17
0
  public long parse(final InputStream stream, Handler handlerIn) {
    handler = handlerIn;

    final RootElement root = new RootElement(namespace, "gpx");
    final Element waypoint = root.getChild(namespace, "wpt");

    // waypoint - attributes
    waypoint.setStartElementListener(
        new StartElementListener() {

          @Override
          public void start(Attributes attrs) {
            try {
              if (attrs.getIndex("lat") > -1) {
                cache.latitude = new Double(attrs.getValue("lat"));
              }
              if (attrs.getIndex("lon") > -1) {
                cache.longitude = new Double(attrs.getValue("lon"));
              }
            } catch (Exception e) {
              Log.w(cgSettings.tag, "Failed to parse waypoint's latitude and/or longitude.");
            }
          }
        });

    // waypoint
    waypoint.setEndElementListener(
        new EndElementListener() {

          @Override
          public void end() {
            if (cache.geocode == null || cache.geocode.length() == 0) {
              // try to find geocode somewhere else
              findGeoCode(name);
              findGeoCode(desc);
              findGeoCode(cmt);
            }

            if (cache.geocode != null
                && cache.geocode.length() > 0
                && cache.latitude != null
                && cache.longitude != null
                && ((type == null && sym == null)
                    || (type != null && type.indexOf("geocache") > -1)
                    || (sym != null && sym.indexOf("geocache") > -1))) {
              fixCache(cache);
              cache.reason = listId;
              cache.detailed = true;

              app.addCacheToSearch(search, cache);
            }

            showFinishedMessage(handler, search);

            type = null;
            sym = null;
            name = null;
            desc = null;
            cmt = null;

            cache = null;
            cache = new cgCache();
          }
        });

    // waypoint.time
    waypoint
        .getChild(namespace, "time")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                try {
                  cache.hidden = parseDate(body);
                } catch (Exception e) {
                  Log.w(cgSettings.tag, "Failed to parse cache date: " + e.toString());
                }
              }
            });

    // waypoint.name
    waypoint
        .getChild(namespace, "name")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                name = body;

                final String content = body.trim();
                cache.name = content;

                findGeoCode(cache.name);
                findGeoCode(cache.description);
              }
            });

    // waypoint.desc
    waypoint
        .getChild(namespace, "desc")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                desc = body;

                cache.shortdesc = validate(body);
              }
            });

    // waypoint.cmt
    waypoint
        .getChild(namespace, "cmt")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                cmt = body;

                cache.description = validate(body);
              }
            });

    // waypoint.type
    waypoint
        .getChild(namespace, "type")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                final String[] content = body.split("\\|");
                if (content.length > 0) {
                  type = content[0].toLowerCase().trim();
                }
              }
            });

    // waypoint.sym
    waypoint
        .getChild(namespace, "sym")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String body) {
                body = body.toLowerCase();
                sym = body;
                if (body.indexOf("geocache") != -1 && body.indexOf("found") != -1) {
                  cache.found = true;
                }
              }
            });

    // waypoint.url
    waypoint
        .getChild(namespace, "url")
        .setEndTextElementListener(
            new EndTextElementListener() {

              @Override
              public void end(String url) {
                final Matcher matcher = patternGuid.matcher(url);
                if (matcher.matches()) {
                  String guid = matcher.group(1);
                  if (guid.length() > 0) {
                    cache.guid = guid;
                  }
                }
              }
            });

    // for GPX 1.0, cache info comes from waypoint node (so called private children,
    // for GPX 1.1 from extensions node
    final Element cacheParent = getCacheParent(waypoint);

    for (String nsGC : nsGCList) {
      // waypoints.cache
      final Element gcCache = cacheParent.getChild(nsGC, "cache");

      gcCache.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1) {
                  cache.cacheid = attrs.getValue("id");
                }
                if (attrs.getIndex("archived") > -1) {
                  cache.archived = attrs.getValue("archived").equalsIgnoreCase("true");
                }
                if (attrs.getIndex("available") > -1) {
                  cache.disabled = !attrs.getValue("available").equalsIgnoreCase("true");
                }
              } catch (Exception e) {
                Log.w(cgSettings.tag, "Failed to parse cache attributes.");
              }
            }
          });

      // waypoint.cache.name
      gcCache
          .getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheName) {
                  cache.name = validate(cacheName);
                }
              });

      // waypoint.cache.owner
      gcCache
          .getChild(nsGC, "owner")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String cacheOwner) {
                  cache.owner = validate(cacheOwner);
                }
              });

      // waypoint.cache.type
      gcCache
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  setType(validate(body.toLowerCase()));
                }
              });

      // waypoint.cache.container
      gcCache
          .getChild(nsGC, "container")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  cache.size = validate(body.toLowerCase());
                }
              });

      // waypoint.cache.attributes
      // @see issue #299

      // <groundspeak:attributes>
      //   <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
      //   <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
      // where inc = 0 => _no, inc = 1 => _yes
      // IDs see array CACHE_ATTRIBUTES
      final Element gcAttributes = gcCache.getChild(nsGC, "attributes");

      // waypoint.cache.attribute
      final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");

      gcAttribute.setStartElementListener(
          new StartElementListener() {
            @Override
            public void start(Attributes attrs) {
              try {
                if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
                  int attributeId = Integer.parseInt(attrs.getValue("id"));
                  boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
                  String internalId =
                      CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
                  if (internalId != null) {
                    if (cache.attributes == null) {
                      cache.attributes = new ArrayList<String>();
                    }
                    cache.attributes.add(internalId);
                  }
                }
              } catch (NumberFormatException e) {
                // nothing
              }
            }
          });

      // waypoint.cache.difficulty
      gcCache
          .getChild(nsGC, "difficulty")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.difficulty = new Float(body);
                  } catch (Exception e) {
                    Log.w(cgSettings.tag, "Failed to parse difficulty: " + e.toString());
                  }
                }
              });

      // waypoint.cache.terrain
      gcCache
          .getChild(nsGC, "terrain")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    cache.terrain = new Float(body);
                  } catch (Exception e) {
                    Log.w(cgSettings.tag, "Failed to parse terrain: " + e.toString());
                  }
                }
              });

      // waypoint.cache.country
      gcCache
          .getChild(nsGC, "country")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String country) {
                  if (cache.location == null || cache.location.length() == 0) {
                    cache.location = validate(country);
                  } else {
                    cache.location = cache.location + ", " + country.trim();
                  }
                }
              });

      // waypoint.cache.state
      gcCache
          .getChild(nsGC, "state")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String state) {
                  if (cache.location == null || cache.location.length() == 0) {
                    cache.location = validate(state);
                  } else {
                    cache.location = state.trim() + ", " + cache.location;
                  }
                }
              });

      // waypoint.cache.encoded_hints
      gcCache
          .getChild(nsGC, "encoded_hints")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String encoded) {
                  cache.hint = validate(encoded);
                }
              });

      gcCache
          .getChild(nsGC, "short_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String shortDesc) {
                  cache.shortdesc = validate(shortDesc);
                }
              });

      gcCache
          .getChild(nsGC, "long_description")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String desc) {
                  cache.description = validate(desc);
                }
              });

      // waypoint.cache.travelbugs
      final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");

      // waypoint.cache.travelbugs.travelbug
      gcTBs
          .getChild(nsGC, "travelbug")
          .setStartElementListener(
              new StartElementListener() {

                @Override
                public void start(Attributes attrs) {
                  trackable = new cgTrackable();

                  try {
                    if (attrs.getIndex("ref") > -1) {
                      trackable.geocode = attrs.getValue("ref").toUpperCase();
                    }
                  } catch (Exception e) {
                    // nothing
                  }
                }
              });

      // waypoint.cache.travelbug
      final Element gcTB = gcTBs.getChild(nsGC, "travelbug");

      gcTB.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (trackable.geocode != null
                  && trackable.geocode.length() > 0
                  && trackable.name != null
                  && trackable.name.length() > 0) {
                if (cache.inventory == null) {
                  cache.inventory = new ArrayList<cgTrackable>();
                }
                cache.inventory.add(trackable);
              }
            }
          });

      // waypoint.cache.travelbugs.travelbug.name
      gcTB.getChild(nsGC, "name")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String tbName) {
                  trackable.name = validate(tbName);
                }
              });

      // waypoint.cache.logs
      final Element gcLogs = gcCache.getChild(nsGC, "logs");

      // waypoint.cache.log
      final Element gcLog = gcLogs.getChild(nsGC, "log");

      gcLog.setStartElementListener(
          new StartElementListener() {

            @Override
            public void start(Attributes attrs) {
              log = new cgLog();

              try {
                if (attrs.getIndex("id") > -1) {
                  log.id = Integer.parseInt(attrs.getValue("id"));
                }
              } catch (Exception e) {
                // nothing
              }
            }
          });

      gcLog.setEndElementListener(
          new EndElementListener() {

            @Override
            public void end() {
              if (log.log != null && log.log.length() > 0) {
                if (cache.logs == null) {
                  cache.logs = new ArrayList<cgLog>();
                }
                cache.logs.add(log);
              }
            }
          });

      // waypoint.cache.logs.log.date
      gcLog
          .getChild(nsGC, "date")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  try {
                    log.date = parseDate(body).getTime();
                  } catch (Exception e) {
                    Log.w(cgSettings.tag, "Failed to parse log date: " + e.toString());
                  }
                }
              });

      // waypoint.cache.logs.log.type
      gcLog
          .getChild(nsGC, "type")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String body) {
                  final String logType = validate(body).toLowerCase();
                  if (cgBase.logTypes0.containsKey(logType)) {
                    log.type = cgBase.logTypes0.get(logType);
                  } else {
                    log.type = cgBase.LOG_NOTE;
                  }
                }
              });

      // waypoint.cache.logs.log.finder
      gcLog
          .getChild(nsGC, "finder")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String finderName) {
                  log.author = validate(finderName);
                }
              });

      // waypoint.cache.logs.log.text
      gcLog
          .getChild(nsGC, "text")
          .setEndTextElementListener(
              new EndTextElementListener() {

                @Override
                public void end(String logText) {
                  log.log = validate(logText);
                }
              });
    }
    boolean parsed = false;
    try {
      Xml.parse(stream, Xml.Encoding.UTF_8, root.getContentHandler());
      parsed = true;
    } catch (IOException e) {
      Log.e(cgSettings.tag, "Cannot parse .gpx file as GPX " + version + ": could not read file!");
    } catch (SAXException e) {
      Log.e(
          cgSettings.tag,
          "Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
    }
    return parsed ? search.getCurrentId() : 0L;
  }