public EntityInfo loadNode(Node n) {
    long nodeId = n.getId(); // >> 1;
    try {
      String res =
          sendRequest(
              SITE_API + "api/0.6/node/" + nodeId,
              "GET",
              null,
              ctx.getString(R.string.loading_poi_obj) + nodeId,
              false); //$NON-NLS-1$ //$NON-NLS-2$
      if (res != null) {
        OsmBaseStorage st = new OsmBaseStorage();
        st.parseOSM(
            new ByteArrayInputStream(res.getBytes("UTF-8")), null, null, true); // $NON-NLS-1$
        EntityId id = new Entity.EntityId(EntityType.NODE, nodeId);
        //				Node entity = (Node) st.getRegisteredEntities().get(id);
        entityInfo = st.getRegisteredEntityInfo().get(id);
        return entityInfo;
      }

    } catch (IOException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    } catch (SAXException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    }
    return null;
  }
Beispiel #2
0
    public void update(OsmandApplication ctx, boolean night) {
      if (nightMode == night && !f) {
        return;
      }
      f = false;
      nightMode = night;
      if (bgDark != 0 && bgLight != 0) {
        iv.setBackgroundDrawable(ctx.getResources().getDrawable(night ? bgDark : bgLight));
      }
      Drawable d = null;
      if (resDarkId != 0 && nightMode) {
        d = ctx.getIconsCache().getIcon(resDarkId);
      } else if (resLightId != 0 && !nightMode) {
        d = ctx.getIconsCache().getIcon(resLightId);
      } else if (resId != 0) {
        d = ctx.getIconsCache().getIcon(resId, nightMode ? resClrDark : resClrLight);
      }

      if (iv instanceof ImageView) {
        if (compass) {
          ((ImageView) iv).setImageDrawable(new CompassDrawable(d));
        } else {
          ((ImageView) iv).setImageDrawable(d);
        }
      } else if (iv instanceof TextView) {
        ((TextView) iv).setCompoundDrawablesWithIntrinsicBounds(d, null, null, null);
      }
    }
  @Override
  public Node loadNode(Amenity n) {
    if (n.getId() % 2 == 1) {
      // that's way id
      return null;
    }
    long nodeId = n.getId() >> 1;
    try {
      String res =
          sendRequest(
              SITE_API + "api/0.6/node/" + nodeId,
              "GET",
              null,
              ctx.getString(R.string.loading_poi_obj) + nodeId,
              false); //$NON-NLS-1$ //$NON-NLS-2$
      if (res != null) {
        OsmBaseStorage st = new OsmBaseStorage();
        st.parseOSM(
            new ByteArrayInputStream(res.getBytes("UTF-8")), null, null, true); // $NON-NLS-1$
        EntityId id = new Entity.EntityId(EntityType.NODE, nodeId);
        Node entity = (Node) st.getRegisteredEntities().get(id);
        entityInfo = st.getRegisteredEntityInfo().get(id);
        // check whether this is node (because id of node could be the same as relation)
        if (entity != null && MapUtils.getDistance(entity.getLatLon(), n.getLocation()) < 50) {
          return entity;
        }
        return null;
      }

    } catch (IOException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    } catch (SAXException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    }
    return null;
  }
Beispiel #4
0
  public void loadWorldRegions(OsmandApplication app) {
    OsmandRegions osmandRegions = app.getRegions();

    Map<String, String> loadedItems = osmandRegions.getFullNamesToLowercaseCopy();
    if (loadedItems.size() == 0) {
      return;
    }

    HashMap<String, WorldRegion> regionsLookupTable = new HashMap<>(loadedItems.size());

    // Create main regions
    Resources res = app.getResources();

    WorldRegion africaRegion =
        createRegionAs(
            AFRICA_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_africa));
    addSubregion(africaRegion);
    regionsLookupTable.put(africaRegion.regionId, africaRegion);

    WorldRegion asiaRegion =
        createRegionAs(
            ASIA_REGION_ID, loadedItems, osmandRegions, res.getString(R.string.index_name_asia));
    addSubregion(asiaRegion);
    regionsLookupTable.put(asiaRegion.regionId, asiaRegion);

    WorldRegion australiaAndOceaniaRegion =
        createRegionAs(
            AUSTRALIA_AND_OCEANIA_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_oceania));
    addSubregion(australiaAndOceaniaRegion);
    regionsLookupTable.put(australiaAndOceaniaRegion.regionId, australiaAndOceaniaRegion);

    WorldRegion centralAmericaRegion =
        createRegionAs(
            CENTRAL_AMERICA_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_central_america));
    addSubregion(centralAmericaRegion);
    regionsLookupTable.put(centralAmericaRegion.regionId, centralAmericaRegion);

    WorldRegion europeRegion =
        createRegionAs(
            EUROPE_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_europe));
    addSubregion(europeRegion);
    regionsLookupTable.put(europeRegion.regionId, europeRegion);

    WorldRegion northAmericaRegion =
        createRegionAs(
            NORTH_AMERICA_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_north_america));
    addSubregion(northAmericaRegion);
    regionsLookupTable.put(northAmericaRegion.regionId, northAmericaRegion);

    WorldRegion russiaRegion =
        createRegionAs(
            RUSSIA_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_russia));
    addSubregion(russiaRegion);
    regionsLookupTable.put(russiaRegion.regionId, russiaRegion);

    WorldRegion southAmericaRegion =
        createRegionAs(
            SOUTH_AMERICA_REGION_ID,
            loadedItems,
            osmandRegions,
            res.getString(R.string.index_name_south_america));
    addSubregion(southAmericaRegion);
    regionsLookupTable.put(southAmericaRegion.regionId, southAmericaRegion);

    // Process remaining regions
    for (; ; ) {
      int processedRegions = 0;

      Iterator<Entry<String, String>> iterator = loadedItems.entrySet().iterator();
      while (iterator.hasNext()) {
        String regionId = iterator.next().getKey();
        String parentRegionId = osmandRegions.getParentFullName(regionId);
        if (parentRegionId == null) {
          continue;
        }

        // Try to find parent of this region
        WorldRegion parentRegion = regionsLookupTable.get(parentRegionId);
        if (parentRegion == null) {
          continue;
        }

        WorldRegion newRegion = new WorldRegion().init(regionId, osmandRegions);
        parentRegion.addSubregion(newRegion);
        regionsLookupTable.put(newRegion.regionId, newRegion);

        // Remove
        processedRegions++;
        iterator.remove();
      }

      // If all remaining are orphans, that's all
      if (processedRegions == 0) break;
    }

    LOG.warn("Found orphaned regions: " + loadedItems.size());
    for (String regionId : loadedItems.keySet()) {
      LOG.warn("FullName = " + regionId + " parent=" + osmandRegions.getParentFullName(regionId));
    }
  }
  private String sendRequest(
      String url,
      String requestMethod,
      String requestBody,
      String userOperation,
      boolean doAuthenticate) {
    log.info("Sending request " + url); // $NON-NLS-1$
    //		if(true){
    //			return sendRequsetThroughHttpClient(url, requestMethod, requestBody, userOperation,
    // doAuthenticate);
    //		}

    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

      connection.setConnectTimeout(15000);
      connection.setRequestMethod(requestMethod);
      StringBuilder responseBody = new StringBuilder();
      if (doAuthenticate) {
        String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); // $NON-NLS-1$
        connection.addRequestProperty(
            "Authorization",
            "Basic "
                + Base64.encode(
                    token.getBytes("UTF-8"))); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      }
      connection.setDoInput(true);
      if (requestMethod.equals("PUT")
          || requestMethod.equals("POST")
          || requestMethod.equals("DELETE")) { // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-type", "text/xml"); // $NON-NLS-1$ //$NON-NLS-2$
        OutputStream out = connection.getOutputStream();
        if (requestBody != null) {
          BufferedWriter bwr =
              new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 1024); // $NON-NLS-1$
          bwr.write(requestBody);
          bwr.flush();
        }
        out.close();
      }
      connection.connect();
      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        String msg =
            userOperation
                + " "
                + ctx.getString(R.string.failed_op)
                + " : "
                + connection.getResponseMessage(); // $NON-NLS-1$//$NON-NLS-2$
        log.error(msg);
        showWarning(msg);
      } else {
        log.info("Response : " + connection.getResponseMessage()); // $NON-NLS-1$
        // populate return fields.
        responseBody.setLength(0);
        InputStream i = connection.getInputStream();
        if (i != null) {
          BufferedReader in =
              new BufferedReader(new InputStreamReader(i, "UTF-8"), 256); // $NON-NLS-1$
          String s;
          boolean f = true;
          while ((s = in.readLine()) != null) {
            if (!f) {
              responseBody.append("\n"); // $NON-NLS-1$
            } else {
              f = false;
            }
            responseBody.append(s);
          }
        }
        return responseBody.toString();
      }
    } catch (NullPointerException e) {
      // that's tricky case why NPE is thrown to fix that problem httpClient could be used
      String msg = ctx.getString(R.string.auth_failed);
      log.error(msg, e);
      showWarning(msg);
    } catch (MalformedURLException e) {
      log.error(userOperation + " " + ctx.getString(R.string.failed_op), e); // $NON-NLS-1$
      showWarning(
          MessageFormat.format(
              ctx.getResources().getString(R.string.poi_error_unexpected_template), userOperation));
    } catch (IOException e) {
      log.error(userOperation + " " + ctx.getString(R.string.failed_op), e); // $NON-NLS-1$
      showWarning(
          MessageFormat.format(
              ctx.getResources().getString(R.string.poi_error_io_error_template), userOperation));
    }

    return null;
  }
  protected String sendRequsetThroughHttpClient(
      String url,
      String requestMethod,
      String requestBody,
      String userOperation,
      boolean doAuthenticate) {
    StringBuilder responseBody = new StringBuilder();
    try {

      HttpParams params = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(params, 15000);
      DefaultHttpClient httpclient = new DefaultHttpClient(params);
      if (doAuthenticate) {
        UsernamePasswordCredentials credentials =
            new UsernamePasswordCredentials(
                settings.USER_NAME.get()
                    + ":" //$NON-NLS-1$
                    + settings.USER_PASSWORD.get());
        httpclient
            .getCredentialsProvider()
            .setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials);
      }
      HttpRequestBase method = null;
      if (requestMethod.equals("GET")) { // $NON-NLS-1$
        method = new HttpGet(url);
      } else if (requestMethod.equals("POST")) { // $NON-NLS-1$
        method = new HttpPost(url);
      } else if (requestMethod.equals("PUT")) { // $NON-NLS-1$
        method = new HttpPut(url);
      } else if (requestMethod.equals("DELETE")) { // $NON-NLS-1$
        method = new HttpDelete(url);

      } else {
        throw new IllegalArgumentException(requestMethod + " is invalid method"); // $NON-NLS-1$
      }
      if (requestMethod.equals("PUT")
          || requestMethod.equals("POST")
          || requestMethod.equals("DELETE")) { // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        // TODO add when needed
        //				connection.setDoOutput(true);
        //				connection.setRequestProperty("Content-type", "text/xml");
        //				OutputStream out = connection.getOutputStream();
        //				if (requestBody != null) {
        //					BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        //					bwr.write(requestBody);
        //					bwr.flush();
        //				}
        //				out.close();
      }

      HttpResponse response = httpclient.execute(method);
      if (response.getStatusLine() == null || response.getStatusLine().getStatusCode() != 200) {

        String msg;
        if (response.getStatusLine() != null) {
          msg = userOperation + " " + ctx.getString(R.string.failed_op); // $NON-NLS-1$
        } else {
          msg =
              userOperation
                  + " "
                  + ctx.getString(R.string.failed_op)
                  + response.getStatusLine().getStatusCode()
                  + " : "
                  + //$NON-NLS-1$//$NON-NLS-2$
                  response.getStatusLine().getReasonPhrase();
        }
        log.error(msg);
        showWarning(msg);
      } else {
        InputStream is = response.getEntity().getContent();
        if (is != null) {
          BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); // $NON-NLS-1$
          String s;
          while ((s = in.readLine()) != null) {
            responseBody.append(s);
            responseBody.append("\n"); // $NON-NLS-1$
          }
          is.close();
        }
        httpclient.getConnectionManager().shutdown();
        return responseBody.toString();
      }
    } catch (MalformedURLException e) {
      log.error(userOperation + " failed", e); // $NON-NLS-1$
      showWarning(
          MessageFormat.format(
              ctx.getResources().getString(R.string.poi_error_unexpected_template), userOperation));
    } catch (IOException e) {
      log.error(userOperation + " failed", e); // $NON-NLS-1$
      showWarning(
          MessageFormat.format(
              ctx.getResources().getString(R.string.poi_error_unexpected_template), userOperation));
    }
    return null;
  }