public void clearPersistentCache(Context ctx) {
   Log.w(TAG, "Deleting old Breadcrumbs cache files");
   synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) {
     ctx.deleteFile(BREADCRUMSB_ACTIVITY_CACHE_FILE);
     ctx.deleteFile(BREADCRUMSB_BUNDLES_CACHE_FILE);
   }
 }
Example #2
0
 /**
  * The entire purpose of this function is to recover the issues that were in the old version of
  * the library and then to delete the remaining file when we are done with it. A user should never
  * need to call this function, this gets automatically run for them in {@link
  * Api#init(android.app.Application)}.
  */
 public void recoverOldIssues() {
   Log.d(TAG, "Attempting to recover old feeback for the benefit of the user.");
   FileInputStream oldCacheFile = null;
   try {
     // Load the old data from a file
     oldCacheFile = context.openFileInput(OLD_ISSUES_CACHE_FILE);
     final String oldIssuesWithCommentsJSON = IOUtils.toString(oldCacheFile);
     // Parse the Data - The old json save contained IssuesWithComments
     final IssuesWithComments oldIssues =
         new IssueParser(TAG).parseIssues(oldIssuesWithCommentsJSON);
     // Save the data in the new database.
     for (Issue issue : oldIssues.issues()) {
       addCreatedIssue(issue);
     }
   } catch (FileNotFoundException e) {
     Log.i(
         TAG,
         "There was no old version of the issues cache lying around. Don't need to recover anything.");
   } catch (IOException e) {
     Log.i(TAG, "Encountered problems handling the old cache file", e);
   } finally {
     if (oldCacheFile != null) {
       try {
         oldCacheFile.close();
         oldCacheFile = null;
       } catch (IOException e) {
         Log.wtf(TAG, "Could not close a file that we already had opened.", e);
       }
       // Remove the file now that we are done with it.
       context.deleteFile(OLD_ISSUES_CACHE_FILE);
     }
   }
 }
Example #3
0
  public void downloadFile() {
    try {
      // get the URL
      URL url = new URL(URL_STRING);

      // get the input stream
      InputStream in = url.openStream();

      context.deleteFile(FILENAME);
      // get the output stream
      FileOutputStream out = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);

      // read input and write output
      byte[] buffer = new byte[1024];
      int bytesRead = in.read(buffer);
      while (bytesRead != -1) {
        out.write(buffer, 0, bytesRead);
        bytesRead = in.read(buffer);
      }
      out.close();
      in.close();
    } catch (IOException e) {
      Log.e("News reader", e.toString());
    }
  }
  /**
   * Delete the wishlist
   *
   * @param mCtx A context to open the file wish
   */
  public static void ResetCards(Context mCtx) {

    String[] files = mCtx.fileList();
    for (String fileName : files) {
      if (fileName.equals(WISHLIST_NAME)) {
        mCtx.deleteFile(fileName);
      }
    }
  }
Example #5
0
 /**
  * Remove a pre-loaded icon from the persistent icon cache.
  *
  * @param componentName the component that should own the icon
  */
 public void deletePreloadedIcon(ComponentName componentName, UserHandleCompat user) {
   // We don't keep icons for other profiles in persistent cache.
   if (!user.equals(UserHandleCompat.myUserHandle()) || componentName == null) {
     return;
   }
   remove(componentName, user);
   boolean success = mContext.deleteFile(getResourceFilename(componentName));
   if (DEBUG && success) Log.d(TAG, "removed pre-loaded icon from persistent cache");
 }
 public void remove() {
   String storageMode = getStorageMode();
   if (storageMode.equals("internal") || storageMode.equals("")) {
     context.deleteFile(this.fileName);
   } else if (storageMode.equals("sdcard")) {
     File root = Environment.getExternalStorageDirectory();
     File morgDir = new File(root, "mobileorg");
     File morgFile = new File(morgDir, this.fileName);
     morgFile.delete();
   }
 }
  /**
   * remove the auth token variables securely
   *
   * @param context
   */
  public static void clear(Context context) {
    try {
      String filename = getAccessTokenFilename(context.getApplicationContext());
      context.deleteFile(filename);

      Log.v(
          AppBlade.LogTag, String.format("RemoteAuthHelper.clear (delete file) path:%s", filename));

      AppBlade.setDeviceId(null);
    } catch (Exception ex) {
      Log.w(AppBlade.LogTag, "RemoteAuthHelper clear ", ex);
    }
  }
Example #8
0
  /**
   * Creates a empty database on the system and rewrites it with your own database.
   *
   * @throws java.io.IOException io exception
   */
  private void createDataBase() throws IOException {

    try {
      if (!isDatabaseUpdated()) {
        if (mDataBase != null) close();
        context.deleteFile(DB_NAME);
        copyDataBase();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    openDataBase();
  }
 /**
  * Remove Firefox account persisted to disk.
  *
  * @param context Android context.
  * @param filename name of persisted pickle file; must not contain path separators.
  * @return <code>true</code> if given pickle existed and was successfully deleted.
  */
 public static boolean deletePickle(final Context context, final String filename) {
   return context.deleteFile(filename);
 }
  // Do an update from the given repo. All applications found, and their
  // APKs, are added to 'apps'. (If 'apps' already contains an app, its
  // APKs are merged into the existing one).
  // Returns null if successful, otherwise an error message to be displayed
  // to the user (if there is an interactive user!)
  // 'newetag' should be passed empty. On success, it may contain an etag
  // value for the index that was successfully processed, or it may contain
  // null if none was available.
  public static String doUpdate(
      Context ctx,
      DB.Repo repo,
      List<DB.App> apps,
      StringBuilder newetag,
      List<Integer> keeprepos,
      ProgressListener progressListener) {
    try {

      int code = 0;
      if (repo.pubkey != null) {

        // This is a signed repo - we download the jar file,
        // check the signature, and extract the index...
        Log.d(
            "FDroid",
            "Getting signed index from "
                + repo.address
                + " at "
                + logDateFormat.format(new Date(System.currentTimeMillis())));
        String address = repo.address + "/index.jar";
        PackageManager pm = ctx.getPackageManager();
        try {
          PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), 0);
          address += "?" + pi.versionName;
        } catch (Exception e) {
        }
        Bundle progressData = createProgressData(repo.address);
        ProgressListener.Event event =
            new ProgressListener.Event(RepoXMLHandler.PROGRESS_TYPE_DOWNLOAD, progressData);
        code =
            getRemoteFile(
                ctx, address, "tempindex.jar", repo.lastetag, newetag, progressListener, event);
        if (code == 200) {
          String jarpath = ctx.getFilesDir() + "/tempindex.jar";
          JarFile jar = null;
          JarEntry je;
          Certificate[] certs;
          try {
            jar = new JarFile(jarpath, true);
            je = (JarEntry) jar.getEntry("index.xml");
            File efile = new File(ctx.getFilesDir(), "/tempindex.xml");
            InputStream input = null;
            OutputStream output = null;
            try {
              input = jar.getInputStream(je);
              output = new FileOutputStream(efile);
              Utils.copy(input, output);
            } finally {
              Utils.closeQuietly(output);
              Utils.closeQuietly(input);
            }
            certs = je.getCertificates();
          } catch (SecurityException e) {
            Log.e("FDroid", "Invalid hash for index file");
            return "Invalid hash for index file";
          } finally {
            if (jar != null) {
              jar.close();
            }
          }
          if (certs == null) {
            Log.d("FDroid", "No signature found in index");
            return "No signature found in index";
          }
          Log.d(
              "FDroid",
              "Index has " + certs.length + " signature" + (certs.length > 1 ? "s." : "."));

          boolean match = false;
          for (Certificate cert : certs) {
            String certdata = Hasher.hex(cert.getEncoded());
            if (repo.pubkey.equals(certdata)) {
              match = true;
              break;
            }
          }
          if (!match) {
            Log.d("FDroid", "Index signature mismatch");
            return "Index signature mismatch";
          }
        }

      } else {

        // It's an old-fashioned unsigned repo...
        Log.d("FDroid", "Getting unsigned index from " + repo.address);
        Bundle eventData = createProgressData(repo.address);
        ProgressListener.Event event =
            new ProgressListener.Event(RepoXMLHandler.PROGRESS_TYPE_DOWNLOAD, eventData);
        code =
            getRemoteFile(
                ctx,
                repo.address + "/index.xml",
                "tempindex.xml",
                repo.lastetag,
                newetag,
                progressListener,
                event);
      }

      if (code == 200) {
        // Process the index...
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        RepoXMLHandler handler = new RepoXMLHandler(repo, apps, progressListener);
        xr.setContentHandler(handler);

        File tempIndex = new File(ctx.getFilesDir() + "/tempindex.xml");
        BufferedReader r = new BufferedReader(new FileReader(tempIndex));

        // A bit of a hack, this might return false positives if an apps description
        // or some other part of the XML file contains this, but it is a pretty good
        // estimate and makes the progress counter more informative.
        // As with asking the server about the size of the index before downloading,
        // this also has a time tradeoff. It takes about three seconds to iterate
        // through the file and count 600 apps on a slow emulator (v17), but if it is
        // taking two minutes to update, the three second wait may be worth it.
        final String APPLICATION = "<application";
        handler.setTotalAppCount(Utils.countSubstringOccurrence(tempIndex, APPLICATION));

        InputSource is = new InputSource(r);
        xr.parse(is);

        if (handler.pubkey != null && repo.pubkey == null) {
          // We read an unsigned index, but that indicates that
          // a signed version is now available...
          Log.d("FDroid", "Public key found - switching to signed repo for future updates");
          repo.pubkey = handler.pubkey;
          try {
            DB db = DB.getDB();
            db.updateRepoByAddress(repo);
          } finally {
            DB.releaseDB();
          }
        }

      } else if (code == 304) {
        // The index is unchanged since we last read it. We just mark
        // everything that came from this repo as being updated.
        Log.d("FDroid", "Repo index for " + repo.address + " is up to date (by etag)");
        keeprepos.add(repo.id);
        // Make sure we give back the same etag. (The 200 route will
        // have supplied a new one.
        newetag.append(repo.lastetag);

      } else {
        return "Failed to read index - HTTP response " + Integer.toString(code);
      }

    } catch (SSLHandshakeException sslex) {
      Log.e(
          "FDroid",
          "SSLHandShakeException updating from "
              + repo.address
              + ":\n"
              + Log.getStackTraceString(sslex));
      return "A problem occurred while establishing an SSL connection. If this problem persists, AND you have a very old device, you could try using http instead of https for the repo URL.";
    } catch (Exception e) {
      Log.e(
          "FDroid", "Exception updating from " + repo.address + ":\n" + Log.getStackTraceString(e));
      return "Failed to update - " + e.getMessage();
    } finally {
      ctx.deleteFile("tempindex.xml");
      ctx.deleteFile("tempindex.jar");
    }

    return null;
  }
 private void removeFileFromDisk(BLASTQuery query) {
   if (context.deleteFile(query.getJobIdentifier() + ".xml")) {
     Log.i(TAG, "BLAST hits file deleted");
   }
 }
 public void tearDown() {
   context.deleteFile(db_file);
 }
 public void delete() {
   mContext.deleteFile(FILE_NAME);
 }
Example #14
0
  /**
   * This method can be used to unpack a binary from the raw resources folder and store it in
   * /data/data/app.package/files/ This is typically useful if you provide your own C- or C++-based
   * binary. This binary can then be executed using sendShell() and its full path.
   *
   * @param sourceId resource id; typically <code>R.raw.id</code>
   * @param destName destination file name; appended to /data/data/app.package/files/
   * @param mode chmod value for this file
   * @return a <code>boolean</code> which indicates whether or not we were able to create the new
   *     file.
   */
  protected boolean installBinary(int sourceId, String destName, String mode) {
    File mf = new File(filesPath + File.separator + destName);
    if (!mf.exists()) {
      // First, does our files/ directory even exist?
      // We cannot wait for android to lazily create it as we will soon
      // need it.
      try {
        FileInputStream fis = context.openFileInput(BOGUS_FILE_NAME);
        fis.close();
      } catch (FileNotFoundException e) {
        FileOutputStream fos = null;
        try {
          fos = context.openFileOutput("bogus", Context.MODE_PRIVATE);
          fos.write("justcreatedfilesdirectory".getBytes());
        } catch (Exception ex) {
          if (RootTools.debugMode) {
            Log.e(LOG_TAG, ex.toString());
          }
          return false;
        } finally {
          if (null != fos) {
            try {
              fos.close();
              context.deleteFile(BOGUS_FILE_NAME);
            } catch (IOException e1) {
            }
          }
        }
      } catch (IOException ex) {
        if (RootTools.debugMode) {
          Log.e(LOG_TAG, ex.toString());
        }
        return false;
      }

      // Only now can we start creating our actual file
      InputStream iss = context.getResources().openRawResource(sourceId);
      FileOutputStream oss = null;
      try {
        oss = new FileOutputStream(mf);
        byte[] buffer = new byte[4096];
        int len;
        try {
          while (-1 != (len = iss.read(buffer))) {
            oss.write(buffer, 0, len);
          }
        } catch (IOException ex) {
          if (RootTools.debugMode) {
            Log.e(LOG_TAG, ex.toString());
          }
          return false;
        }
      } catch (FileNotFoundException ex) {
        if (RootTools.debugMode) {
          Log.e(LOG_TAG, ex.toString());
        }
        return false;
      } finally {
        if (oss != null) {
          try {
            oss.close();
          } catch (IOException e) {
          }
        }
      }
      try {
        iss.close();
      } catch (IOException ex) {
        if (RootTools.debugMode) {
          Log.e(LOG_TAG, ex.toString());
        }
        return false;
      }

      try {
        CommandCapture command =
            new CommandCapture(0, "chmod " + mode + " " + filesPath + File.separator + destName);
        Shell.startRootShell().add(command);
        command.waitForFinish();
      } catch (Exception e) {
      }
    }
    return true;
  }
Example #15
0
 public static boolean deletePlan(Context c, String name) {
   return c.deleteFile(name);
 }