Example #1
0
 private static void switchToEnglish(String previousPage) {
   if (previousPage != null && previousPage.contains(ENGLISH)) {
     Log.i("Geocaching.com language already set to English");
     // get find count
     getLoginStatus(
         Network.getResponseData(Network.getRequest("http://www.geocaching.com/email/")));
   } else {
     final String page = Network.getResponseData(Network.getRequest(LANGUAGE_CHANGE_URI));
     getLoginStatus(page);
     if (page == null) {
       Log.e("Failed to read viewstates to set geocaching.com language");
     }
     final Parameters params =
         new Parameters(
             "__EVENTTARGET",
                 "ctl00$uxLocaleList$uxLocaleList$ctl00$uxLocaleItem", // switch to english
             "__EVENTARGUMENT", "");
     Login.transferViewstates(page, params);
     final HttpResponse response =
         Network.postRequest(
             LANGUAGE_CHANGE_URI, params, new Parameters("Referer", LANGUAGE_CHANGE_URI));
     if (Network.isSuccess(response)) {
       Log.i("changed language on geocaching.com to English");
     } else {
       Log.e("Failed to set geocaching.com language to English");
     }
   }
 }
Example #2
0
  public static BitmapDrawable downloadAvatarAndGetMemberStatus() {
    try {
      final String profile =
          BaseUtils.replaceWhitespace(
              Network.getResponseData(Network.getRequest("http://www.geocaching.com/my/")));

      Settings.setMemberStatus(
          BaseUtils.getMatch(profile, GCConstants.PATTERN_MEMBER_STATUS, true, null));
      if (profile.contains(GCConstants.MEMBER_STATUS_RENEW)) {
        Settings.setMemberStatus(GCConstants.MEMBER_STATUS_PM);
      }

      setActualCachesFound(
          Integer.parseInt(
              BaseUtils.getMatch(profile, GCConstants.PATTERN_CACHES_FOUND, true, "-1")
                  .replaceAll("[,.]", "")));

      final String avatarURL =
          BaseUtils.getMatch(profile, GCConstants.PATTERN_AVATAR_IMAGE_PROFILE_PAGE, false, null);
      if (null != avatarURL) {
        final HtmlImage imgGetter = new HtmlImage("", false, 0, false);
        return imgGetter.getDrawable(avatarURL);
      }
      // No match? There may be no avatar set by user.
      Log.d("No avatar set for user");
    } catch (Exception e) {
      Log.w("Error when retrieving user avatar", e);
    }
    return null;
  }
Example #3
0
  /**
   * Copy a file into another. The directory structure of target file will be created if needed.
   *
   * @param source the source file
   * @param destination the target file
   * @return true if the copy happened without error, false otherwise
   */
  public static boolean copy(final File source, final File destination) {
    FileUtils.mkdirs(destination.getParentFile());

    InputStream input = null;
    OutputStream output = null;
    boolean copyDone = false;

    try {
      input = new BufferedInputStream(new FileInputStream(source));
      output = new BufferedOutputStream(new FileOutputStream(destination));
      copyDone = copy(input, output);
      // close here already to catch any issue with closing
      input.close();
      output.close();
    } catch (final FileNotFoundException e) {
      Log.e("LocalStorage.copy: could not copy file", e);
      return false;
    } catch (final IOException e) {
      Log.e("LocalStorage.copy: could not copy file", e);
      return false;
    } finally {
      // close here quietly to clean up in all situations
      IOUtils.closeQuietly(input);
      IOUtils.closeQuietly(output);
    }

    return copyDone;
  }
        @Override
        public void handleMessage(final Message msg) {
          try {
            if (waypoint == null) {
              Log.d("No waypoint loaded to edit. id= " + waypointId);
              waypointId = -1;
            } else {
              geocode = waypoint.getGeocode();
              prefix = waypoint.getPrefix();
              lookup = waypoint.getLookup();
              own = waypoint.isUserDefined();

              if (initViews) {
                visitedCheckBox.setChecked(waypoint.isVisited());
                if (waypoint.getCoords() != null) {
                  buttonLat.setText(
                      waypoint.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE));
                  buttonLon.setText(
                      waypoint.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE));
                }
                waypointName.setText(
                    Html.fromHtml(StringUtils.trimToEmpty(waypoint.getName())).toString());
                Dialogs.moveCursorToEnd(waypointName);
                if (TextUtils.containsHtml(waypoint.getNote())) {
                  note.setText(
                      Html.fromHtml(StringUtils.trimToEmpty(waypoint.getNote())).toString());
                } else {
                  note.setText(StringUtils.trimToEmpty(waypoint.getNote()));
                }
                Dialogs.moveCursorToEnd(note);
              }
              new AsyncTask<Void, Void, Geocache>() {
                @Override
                protected Geocache doInBackground(final Void... params) {
                  return DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_ONLY);
                }

                @Override
                protected void onPostExecute(final Geocache cache) {
                  setCoordsModificationVisibility(ConnectorFactory.getConnector(geocode), cache);
                }
              }.execute();
            }

            if (own) {
              initializeWaypointTypeSelector();
            }
          } catch (final RuntimeException e) {
            Log.e("EditWaypointActivity.loadWaypointHandler", e);
          } finally {
            if (waitDialog != null) {
              waitDialog.dismiss();
              waitDialog = null;
            }
          }
        }
  private void requestToken() {

    final Parameters params = new Parameters();
    params.put("oauth_callback", callback);
    final String method = "GET";
    OAuth.signOAuth(
        host, pathRequest, method, https, params, null, null, consumerKey, consumerSecret);
    final HttpResponse response = Network.getRequest(getUrlPrefix() + host + pathRequest, params);

    if (Network.isSuccess(response)) {
      final String line = Network.getResponseData(response);

      int status = STATUS_ERROR;
      if (StringUtils.isNotBlank(line)) {
        assert line != null;
        final MatcherWrapper paramsMatcher1 = new MatcherWrapper(paramsPattern1, line);
        if (paramsMatcher1.find()) {
          OAtoken = paramsMatcher1.group(1);
        }
        final MatcherWrapper paramsMatcher2 = new MatcherWrapper(paramsPattern2, line);
        if (paramsMatcher2.find()) {
          OAtokenSecret = paramsMatcher2.group(1);
        }

        if (StringUtils.isNotBlank(OAtoken) && StringUtils.isNotBlank(OAtokenSecret)) {
          setTempTokens(OAtoken, OAtokenSecret);
          try {
            final Parameters paramsBrowser = new Parameters();
            paramsBrowser.put("oauth_token", OAtoken);
            final String encodedParams =
                EntityUtils.toString(new UrlEncodedFormEntity(paramsBrowser));
            startActivity(
                new Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse(getUrlPrefix() + host + pathAuthorize + "?" + encodedParams)));
            status = STATUS_SUCCESS;
          } catch (ParseException e) {
            Log.e("OAuthAuthorizationActivity.requestToken", e);
          } catch (IOException e) {
            Log.e("OAuthAuthorizationActivity.requestToken", e);
          }
        }
      }

      requestTokenHandler.sendEmptyMessage(status);
    } else {
      final String extErrMsg = getExtendedErrorMsg(response);
      if (StringUtils.isNotBlank(extErrMsg)) {
        final Message msg = requestTokenHandler.obtainMessage(STATUS_ERROR_EXT_MSG, extErrMsg);
        requestTokenHandler.sendMessage(msg);
      } else {
        requestTokenHandler.sendEmptyMessage(STATUS_ERROR);
      }
    }
  }
Example #6
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_CANCELED) {
      // User cancelled the image capture
      showToast(getResources().getString(R.string.info_select_logimage_cancelled));
      return;
    }

    if (resultCode != RESULT_OK) {
      // Image capture failed, advise user
      showFailure();
      return;
    }

    if (data != null) {
      Uri selectedImage = data.getData();
      String[] filePathColumn = {MediaColumns.DATA};

      Cursor cursor = null;
      try {
        cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor == null) {
          showFailure();
          return;
        }
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        if (StringUtils.isBlank(filePath)) {
          showFailure();
          return;
        }
        imageUri = Uri.parse(filePath);
      } catch (Exception e) {
        Log.e("ImageSelectActivity.onActivityResult", e);
        showFailure();
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }

      Log.d("SELECT IMAGE data = " + data.toString());
    } else {
      Log.d("SELECT IMAGE data is null");
    }

    if (requestCode == SELECT_NEW_IMAGE) {
      showToast(getResources().getString(R.string.info_stored_image) + "\n" + imageUri);
    }

    loadImagePreview();
  }
Example #7
0
  public static String sha1(String text) {
    try {
      final MessageDigest digest = MessageDigest.getInstance("SHA-1");
      digest.update(text.getBytes(CharEncoding.UTF_8), 0, text.length());
      return new BigInteger(1, digest.digest()).toString(16);
    } catch (NoSuchAlgorithmException e) {
      Log.e("CryptUtils.sha1", e);
    } catch (UnsupportedEncodingException e) {
      Log.e("CryptUtils.sha1", e);
    }

    return StringUtils.EMPTY;
  }
Example #8
0
  public static void dumpOnOutOfMemory(final boolean enable) {

    if (enable) {

      if (!OOMDumpingUncaughtExceptionHandler.activateHandler()) {
        Log.e(
            "OOM dumping handler not activated (either a problem occured or it was already active)");
      }
    } else {
      if (!OOMDumpingUncaughtExceptionHandler.resetToDefault()) {
        Log.e("OOM dumping handler not resetted (either a problem occured or it was not active)");
      }
    }
  }
Example #9
0
 /**
  * Deletes all files from directory geocode with the given prefix.
  *
  * @param geocode The geocode identifying the cache directory
  * @param prefix The filename prefix
  */
 public static void deleteFilesWithPrefix(final String geocode, final String prefix) {
   final File[] filesToDelete = getFilesWithPrefix(geocode, prefix);
   if (filesToDelete == null) {
     return;
   }
   for (final File file : filesToDelete) {
     try {
       if (!FileUtils.delete(file)) {
         Log.w("LocalStorage.deleteFilesPrefix: Can't delete file " + file.getName());
       }
     } catch (final Exception e) {
       Log.e("LocalStorage.deleteFilesPrefix", e);
     }
   }
 }
Example #10
0
  @Override
  public void onCreate(final Bundle savedInstanceState) {
    // don't call the super implementation with the layout argument, as that would set the wrong
    // theme
    super.onCreate(savedInstanceState);

    // Disable the up navigation for this activity
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    setContentView(R.layout.main_activity);
    ButterKnife.inject(this);

    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
      // If we had been open already, start from the last used activity.
      finish();
      return;
    }

    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); // type to search

    version = Version.getVersionCode(this);
    Log.i(
        "Starting " + getPackageName() + ' ' + version + " a.k.a " + Version.getVersionName(this));

    init();

    checkShowChangelog();
  }
Example #11
0
 private static CacheSize getCacheSizeDeprecated(final ObjectNode response) {
   if (!response.has(CACHE_SIZE_DEPRECATED)) {
     return CacheSize.NOT_CHOSEN;
   }
   double size = 0;
   try {
     size = response.get(CACHE_SIZE_DEPRECATED).asDouble();
   } catch (final NullPointerException e) {
     Log.e("OkapiClient.getCacheSize", e);
   }
   switch ((int) Math.round(size)) {
     case 1:
       return CacheSize.MICRO;
     case 2:
       return CacheSize.SMALL;
     case 3:
       return CacheSize.REGULAR;
     case 4:
       return CacheSize.LARGE;
     case 5:
       return CacheSize.VERY_LARGE;
     default:
       break;
   }
   return CacheSize.NOT_CHOSEN;
 }
Example #12
0
 private static List<Waypoint> parseWaypoints(final JSONArray wptsJson) {
   List<Waypoint> result = null;
   for (int i = 0; i < wptsJson.length(); i++) {
     try {
       final JSONObject wptResponse = wptsJson.getJSONObject(i);
       final Waypoint wpt =
           new Waypoint(
               wptResponse.getString(WPT_NAME),
               parseWptType(wptResponse.getString(WPT_TYPE)),
               false);
       wpt.setNote(wptResponse.getString(WPT_DESCRIPTION));
       final Geopoint pt = parseCoords(wptResponse.getString(WPT_LOCATION));
       if (pt != null) {
         wpt.setCoords(pt);
       }
       if (result == null) {
         result = new ArrayList<Waypoint>();
       }
       result.add(wpt);
     } catch (final JSONException e) {
       Log.e("OkapiClient.parseWaypoints", e);
     }
   }
   return result;
 }
Example #13
0
 @Override
 public void onTrimMemory(final int level) {
   if (level >= TRIM_MEMORY_MODERATE) {
     Log.i("Cleaning applications cache to trim memory");
     DataStore.removeAllFromCache();
   }
 }
Example #14
0
 private void writeWaypoints(final cgCache cache) throws IOException {
   List<cgWaypoint> waypoints = cache.getWaypoints();
   List<cgWaypoint> ownWaypoints = new ArrayList<cgWaypoint>(waypoints.size());
   List<cgWaypoint> originWaypoints = new ArrayList<cgWaypoint>(waypoints.size());
   for (cgWaypoint wp : cache.getWaypoints()) {
     if (wp.isUserDefined()) {
       ownWaypoints.add(wp);
     } else {
       originWaypoints.add(wp);
     }
   }
   int maxPrefix = 0;
   for (cgWaypoint wp : originWaypoints) {
     String prefix = wp.getPrefix();
     try {
       maxPrefix = Math.max(Integer.parseInt(prefix), maxPrefix);
     } catch (NumberFormatException ex) {
       Log.e("Unexpected origin waypoint prefix='" + prefix + "'", ex);
     }
     writeCacheWaypoint(wp, prefix);
   }
   for (cgWaypoint wp : ownWaypoints) {
     maxPrefix++;
     String prefix = StringUtils.leftPad(String.valueOf(maxPrefix), 2, '0');
     writeCacheWaypoint(wp, prefix);
   }
 }
 private static List<cgCache> parseCaches(final JSONObject response) {
   try {
     final JSONArray cachesResponse = response.getJSONArray("results");
     if (cachesResponse != null) {
       ArrayList<String> geocodes = new ArrayList<String>(cachesResponse.length());
       for (int i = 0; i < cachesResponse.length(); i++) {
         String geocode = cachesResponse.getString(i);
         if (StringUtils.isNotBlank(geocode)) {
           geocodes.add(geocode);
         }
       }
       List<cgCache> caches = new ArrayList<cgCache>(geocodes.size());
       for (String geocode : geocodes) {
         cgCache cache = getCache(geocode);
         if (cache != null) {
           caches.add(cache);
         }
       }
       return caches;
     }
   } catch (JSONException e) {
     Log.e("OkapiClient.parseCaches", e);
   }
   return null;
 }
 private static CacheSize getCacheSize(final JSONObject response) {
   if (response.isNull(CACHE_SIZE)) {
     return CacheSize.NOT_CHOSEN;
   }
   double size = 0;
   try {
     size = response.getDouble(CACHE_SIZE);
   } catch (JSONException e) {
     Log.e("OkapiClient.getCacheSize", e);
   }
   switch ((int) Math.round(size)) {
     case 1:
       return CacheSize.MICRO;
     case 2:
       return CacheSize.SMALL;
     case 3:
       return CacheSize.REGULAR;
     case 4:
       return CacheSize.LARGE;
     case 5:
       return CacheSize.LARGE;
     default:
       break;
   }
   return CacheSize.NOT_CHOSEN;
 }
Example #17
0
  private static List<Geocache> requestCaches(
      final OCApiConnector connector,
      final Parameters params,
      final Map<String, String> valueMap,
      final boolean my) {
    // if a global type filter is set, and OKAPI does not know that type, then return an empty list
    // instead of all caches
    if (Settings.getCacheType() != CacheType.ALL && StringUtils.isBlank(getFilterFromType())) {
      return Collections.emptyList();
    }

    addFilterParams(valueMap, connector, my);
    try {
      params.add("search_params", JsonUtils.writer.writeValueAsString(valueMap));
    } catch (final JsonProcessingException e) {
      Log.e("requestCaches", e);
      return Collections.emptyList();
    }
    addRetrieveParams(params, connector);

    final ObjectNode data =
        request(connector, OkapiService.SERVICE_SEARCH_AND_RETRIEVE, params).data;

    if (data == null) {
      return Collections.emptyList();
    }

    return parseCaches(data);
  }
Example #18
0
 private static List<Waypoint> parseWaypoints(final ArrayNode wptsJson) {
   List<Waypoint> result = null;
   for (final JsonNode wptResponse : wptsJson) {
     try {
       final Waypoint wpt =
           new Waypoint(
               wptResponse.get(WPT_NAME).asText(),
               parseWptType(wptResponse.get(WPT_TYPE).asText()),
               false);
       wpt.setNote(wptResponse.get(WPT_DESCRIPTION).asText());
       final Geopoint pt = parseCoords(wptResponse.get(WPT_LOCATION).asText());
       if (pt != null) {
         wpt.setCoords(pt);
       }
       if (result == null) {
         result = new ArrayList<>();
       }
       wpt.setPrefix(wpt.getName());
       result.add(wpt);
     } catch (final NullPointerException e) {
       Log.e("OkapiClient.parseWaypoints", e);
     }
   }
   return result;
 }
Example #19
0
  /**
   * Check if the user has been logged in when he retrieved the data.
   *
   * @param page
   * @return <code>true</code> if user is logged in, <code>false</code> otherwise
   */
  public static boolean getLoginStatus(final String page) {
    if (StringUtils.isBlank(page)) {
      Log.e("Login.checkLogin: No page given");
      return false;
    }

    setActualStatus(cgeoapplication.getInstance().getString(R.string.init_login_popup_ok));

    // on every page except login page
    setActualLoginStatus(BaseUtils.matches(page, GCConstants.PATTERN_LOGIN_NAME));
    if (isActualLoginStatus()) {
      setActualUserName(BaseUtils.getMatch(page, GCConstants.PATTERN_LOGIN_NAME, true, "???"));
      setActualCachesFound(
          Integer.parseInt(
              BaseUtils.getMatch(page, GCConstants.PATTERN_CACHES_FOUND, true, "0")
                  .replaceAll("[,.]", "")));
      Settings.setMemberStatus(
          BaseUtils.getMatch(page, GCConstants.PATTERN_MEMBER_STATUS, true, null));
      if (page.contains(GCConstants.MEMBER_STATUS_RENEW)) {
        Settings.setMemberStatus(GCConstants.MEMBER_STATUS_PM);
      }
      return true;
    }

    // login page
    setActualLoginStatus(BaseUtils.matches(page, GCConstants.PATTERN_LOGIN_NAME_LOGIN_PAGE));
    if (isActualLoginStatus()) {
      setActualUserName(Settings.getUsername());
      // number of caches found is not part of this page
      return true;
    }

    setActualStatus(cgeoapplication.getInstance().getString(R.string.init_login_popup_failed));
    return false;
  }
Example #20
0
    @Override
    public void run() {
      if (app == null) {
        return;
      }
      if (cleanupRunning) {
        return;
      }

      boolean more = false;
      if (version != Settings.getVersion()) {
        Log.i(
            "Initializing hard cleanup - version changed from "
                + Settings.getVersion()
                + " to "
                + version
                + ".");

        more = true;
      }

      cleanupRunning = true;
      DataStore.clean(more);
      cleanupRunning = false;

      if (version > 0) {
        Settings.setVersion(version);
      }
    }
Example #21
0
  public static void loadRatings(final @NonNull ArrayList<Geocache> caches) {
    if (!Settings.isRatingWanted()) {
      return;
    }

    final ArrayList<String> geocodes = getVotableGeocodes(caches);
    if (geocodes.isEmpty()) {
      return;
    }

    try {
      final Map<String, GCVoteRating> ratings = GCVote.getRating(null, geocodes);

      // save found cache coordinates
      for (Geocache cache : caches) {
        if (ratings.containsKey(cache.getGeocode())) {
          GCVoteRating rating = ratings.get(cache.getGeocode());

          cache.setRating(rating.getRating());
          cache.setVotes(rating.getVotes());
          cache.setMyVote(rating.getMyVote());
        }
      }
    } catch (Exception e) {
      Log.e("GCvote.loadRatings", e);
    }
  }
  @Override
  public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) {
    super.onCreateContextMenu(menu, view, info);
    final int viewId = view.getId();

    if (viewId == R.id.type) {
      for (final LogType typeOne : possibleLogTypes) {
        menu.add(viewId, typeOne.id, 0, typeOne.getL10n());
        Log.w("Adding " + typeOne + " " + typeOne.getL10n());
      }
    } else if (viewId == R.id.changebutton) {
      final int textId = ((TextView) findViewById(viewId)).getId();

      menu.setHeaderTitle(res.getString(R.string.log_tb_changeall));
      for (LogTypeTrackable logType : LogTypeTrackable.values()) {
        menu.add(textId, logType.id, 0, res.getString(logType.resourceId));
      }
    } else {
      final int realViewId = ((LinearLayout) findViewById(viewId)).getId();

      for (final cgTrackableLog tb : trackables) {
        if (tb.id == realViewId) {
          menu.setHeaderTitle(tb.name);
        }
      }
      for (LogTypeTrackable logType : LogTypeTrackable.values()) {
        menu.add(realViewId, logType.id, 0, res.getString(logType.resourceId));
      }
    }
  }
Example #23
0
  private static List<Geocache> parseCaches(final JSONObject response) {
    try {
      // Check for empty result
      final String result = response.getString("results");
      if (StringUtils.isBlank(result) || StringUtils.equals(result, "[]")) {
        return Collections.emptyList();
      }

      // Get and iterate result list
      final JSONObject cachesResponse = response.getJSONObject("results");
      if (cachesResponse != null) {
        final List<Geocache> caches = new ArrayList<Geocache>(cachesResponse.length());
        @SuppressWarnings("unchecked")
        final Iterator<String> keys = cachesResponse.keys();
        while (keys.hasNext()) {
          final String key = keys.next();
          final Geocache cache = parseSmallCache(cachesResponse.getJSONObject(key));
          if (cache != null) {
            caches.add(cache);
          }
        }
        return caches;
      }
    } catch (final JSONException e) {
      Log.e("OkapiClient.parseCachesResult", e);
    }
    return Collections.emptyList();
  }
Example #24
0
  private static List<String> parseAttributes(final ArrayNode nameList, final ArrayNode acodeList) {

    final List<String> result = new ArrayList<>();

    for (int i = 0; i < nameList.size(); i++) {
      try {
        final String name = nameList.get(i).asText();
        final int acode =
            acodeList != null
                ? Integer.parseInt(acodeList.get(i).asText().substring(1))
                : CacheAttribute.NO_ID;
        final CacheAttribute attr = CacheAttribute.getByOcACode(acode);

        if (attr != null) {
          result.add(attr.rawName);
        } else {
          result.add(name);
        }
      } catch (final NullPointerException e) {
        Log.e("OkapiClient.parseAttributes", e);
      }
    }

    return result;
  }
Example #25
0
  /**
   * Save a stream to a file.
   *
   * <p>If the response could not be saved to the file due, for example, to a network error, the
   * file will not exist when this method returns.
   *
   * @param inputStream the stream whose content will be saved
   * @param targetFile the target file, which will be created if necessary
   * @return true if the operation was successful, false otherwise
   */
  public static boolean saveToFile(final InputStream inputStream, final File targetFile) {
    if (inputStream == null) {
      return false;
    }

    try {
      try {
        final File tempFile = File.createTempFile("download", null, targetFile.getParentFile());
        final FileOutputStream fos = new FileOutputStream(tempFile);
        final boolean written = copy(inputStream, fos);
        fos.close();
        if (written) {
          return tempFile.renameTo(targetFile);
        }
        FileUtils.deleteIgnoringFailure(tempFile);
        return false;
      } finally {
        IOUtils.closeQuietly(inputStream);
      }
    } catch (final IOException e) {
      Log.e("LocalStorage.saveToFile", e);
      FileUtils.deleteIgnoringFailure(targetFile);
    }
    return false;
  }
Example #26
0
  @Override
  public void onCreate() {
    try {
      final ViewConfiguration config = ViewConfiguration.get(this);
      final Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
      menuKeyField.setAccessible(true);
      menuKeyField.setBoolean(config, false);
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException ignored) {
    }

    // Set language to English if the user decided so.
    initApplicationLocale(Settings.useEnglish());

    // ensure initialization of lists
    DataStore.getLists();

    // Check if Google Play services is available
    if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)
        == ConnectionResult.SUCCESS) {
      isGooglePlayServicesAvailable = true;
    }
    Log.i(
        "Google Play services are " + (isGooglePlayServicesAvailable ? "" : "not ") + "available");
    final Sensors sensors = Sensors.getInstance();
    sensors.setupGeoDataObservables(Settings.useGooglePlayServices(), Settings.useLowPowerMode());
    sensors.setupDirectionObservable(Settings.useLowPowerMode());

    // Attempt to acquire an initial location before any real activity happens.
    sensors
        .geoDataObservable(true)
        .subscribeOn(RxUtils.looperCallbacksScheduler)
        .first()
        .subscribe();
  }
Example #27
0
  /**
   * read all viewstates from page
   *
   * @return String[] with all view states
   */
  public static String[] getViewstates(String page) {
    // Get the number of viewstates.
    // If there is only one viewstate, __VIEWSTATEFIELDCOUNT is not present

    if (page == null) { // no network access
      return null;
    }

    int count = 1;
    final MatcherWrapper matcherViewstateCount =
        new MatcherWrapper(GCConstants.PATTERN_VIEWSTATEFIELDCOUNT, page);
    if (matcherViewstateCount.find()) {
      try {
        count = Integer.parseInt(matcherViewstateCount.group(1));
      } catch (NumberFormatException e) {
        Log.e("getViewStates", e);
      }
    }

    String[] viewstates = new String[count];

    // Get the viewstates
    final MatcherWrapper matcherViewstates =
        new MatcherWrapper(GCConstants.PATTERN_VIEWSTATES, page);
    while (matcherViewstates.find()) {
      String sno = matcherViewstates.group(1); // number of viewstate
      int no;
      if (StringUtils.isEmpty(sno)) {
        no = 0;
      } else {
        try {
          no = Integer.parseInt(sno);
        } catch (NumberFormatException e) {
          Log.e("getViewStates", e);
          no = 0;
        }
      }
      viewstates[no] = matcherViewstates.group(2);
    }

    if (viewstates.length != 1 || viewstates[0] != null) {
      return viewstates;
    }
    // no viewstates were present
    return null;
  }
Example #28
0
  public static byte[] hashHmac(String text, String salt) {
    byte[] macBytes = {};

    try {
      final SecretKeySpec secretKeySpec =
          new SecretKeySpec(salt.getBytes(CharEncoding.UTF_8), "HmacSHA1");
      final Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(secretKeySpec);
      macBytes = mac.doFinal(text.getBytes(CharEncoding.UTF_8));
    } catch (GeneralSecurityException e) {
      Log.e("CryptUtils.hashHmac", e);
    } catch (UnsupportedEncodingException e) {
      Log.e("CryptUtils.hashHmac", e);
    }

    return macBytes;
  }
Example #29
0
 /**
  * Make a fresh copy of the file to reset its timestamp. On some storage, it is impossible to
  * modify the modified time after the fact, in which case a brand new file must be created if we
  * want to be able to use the time as validity hint.
  *
  * <p>See Android issue 1699.
  *
  * @param file the file to refresh
  */
 private static void makeFreshCopy(final File file) {
   final File tempFile = new File(file.getParentFile(), file.getName() + "-temp");
   if (file.renameTo(tempFile)) {
     LocalStorage.copy(tempFile, file);
     FileUtils.deleteIgnoringFailure(tempFile);
   } else {
     Log.e("Could not reset timestamp of file " + file.getAbsolutePath());
   }
 }
Example #30
0
 @Override
 public void updateGeoData(final GeoData geo) {
   try {
     buttonLat.setHint(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW));
     buttonLon.setHint(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE_RAW));
   } catch (final Exception e) {
     Log.e("failed to update location", e);
   }
 }