Esempio n. 1
0
  @Override
  public void call(final Subscriber<? super FileEvent> subscriber) {
    final FileObserver observer =
        new FileObserver(pathToWatch) {
          @Override
          public void onEvent(int event, String file) {
            if (subscriber.isUnsubscribed()) {
              return;
            }

            FileEvent fileEvent = FileEvent.create(event, file);
            subscriber.onNext(fileEvent);

            if (fileEvent.isDeleteSelf()) {
              subscriber.onCompleted();
            }
          }
        };
    observer.startWatching(); // START OBSERVING

    subscriber.add(
        Subscriptions.create(
            new Action0() {
              @Override
              public void call() {
                observer.stopWatching();
              }
            }));
  }
Esempio n. 2
0
 public void stopObservers() {
   synchronized (observers) {
     for (final FileObserver o : observers.values()) {
       o.stopWatching();
     }
     observers.clear();
   }
 }
Esempio n. 3
0
 @Override
 public boolean deleteFile(String path, boolean notify) {
   File file = new File(path);
   boolean ret = false;
   if (!notify) {
     m_FileObserver.stopWatching();
     ret = file.delete();
     m_FileObserver.startWatching();
   } else {
     ret = file.delete();
   }
   Log.d(TAG, "deleteFile: " + ret + " path: " + path);
   return ret;
 }
Esempio n. 4
0
  protected void onReleaseResources(List<File> data) {

    if (mFileObserver != null) {
      mFileObserver.stopWatching();
      mFileObserver = null;
    }
  }
Esempio n. 5
0
 /** Called when deinitializing component. */
 protected void onDeinitialize() {
   super.onDeinitialize();
   m_FileThread.quitSafely();
   m_DecodeBitmapThread.quitSafely();
   m_FileThread = null;
   m_FileHandler = null;
   m_FileList.clear();
   m_FileObserver.stopWatching();
   m_FileObserver = null;
 }
Esempio n. 6
0
  public static void addThumbnailObserver(Context context, WeakReference<Observer> observer) {
    final List<WeakReference<Observer>> observers = mObservers;
    if (mFileObserver == null) {
      final Handler handler = new Handler();
      final File pathToObserve = getThumbnailDir(context);
      final int mask =
          FileObserver.CLOSE_WRITE
              | FileObserver.DELETE
              | FileObserver.MOVED_TO
              | FileObserver.MOVED_FROM;
      mFileObserver =
          new FileObserver(pathToObserve.getPath(), mask) {
            @Override
            public void onEvent(int event, final String path) {
              final boolean small;
              final String idString;
              if (path.endsWith(SUFFIX_SMALL)) {
                small = true;
                idString = path.subSequence(0, path.length() - SUFFIX_SMALL.length()).toString();
              } else if (path.endsWith(SUFFIX_LARGE)) {
                small = false;
                idString = path.subSequence(0, path.length() - SUFFIX_LARGE.length()).toString();
              } else return;

              long id = -1;
              try {
                id = Long.parseLong(idString);
              } catch (final Exception e) {
                // do nothing
              }
              final long bookId = id;

              // occurs in file observer thread, post to main
              handler.post(
                  new Runnable() {
                    @Override
                    public void run() {
                      for (final Observer o : WeakListIterator.from(observers)) {
                        o.onThumbnailChanged(bookId, small, new File(pathToObserve, path));
                      }
                      if (observers.size() == 0) stopWatching();
                    }
                  });
            }
          };
    }

    observers.add(observer);
    mFileObserver.startWatching();
  }
Esempio n. 7
0
  @Override
  protected void onStartLoading() {
    if (mData != null) deliverResult(mData);

    if (mFileObserver == null) {
      mFileObserver =
          new FileObserver(mPath, FILE_OBSERVER_MASK) {
            @Override
            public void onEvent(int event, String path) {
              onContentChanged();
            }
          };
    }
    mFileObserver.startWatching();

    if (takeContentChanged() || mData == null) forceLoad();
  }
 public LockPasswordUtils(Context context) {
   mSharedPreferences =
       context.getSharedPreferences(LOCK_PASSWORD_SALT_FILE, Context.MODE_PRIVATE);
   mEditor = mSharedPreferences.edit();
   if (sLockPasswordFilename == null) {
     String dataSystemDirectory = context.getCacheDir().getAbsolutePath();
     sLockPasswordFilename = new File(dataSystemDirectory, LOCK_PASSWORD_FILE);
     sHaveNonZeroPasswordFile.set(sLockPasswordFilename.length() > 0);
     int fileObserverMask =
         FileObserver.CLOSE_WRITE
             | FileObserver.DELETE
             | FileObserver.MOVED_TO
             | FileObserver.CREATE;
     sPasswordObserver = new PasswordFileObserver(dataSystemDirectory, fileObserverMask);
     sPasswordObserver.startWatching();
   }
 }
 public void a_()
 {
   if (B != null) {
     B.a(true);
   }
   if (I != null)
   {
     I.d();
     I.c();
     I = null;
   }
   O = true;
   if (aj) {
     com.estrongs.fs.a.b.a().b(Y);
   }
   if (W != null) {
     W.stopWatching();
   }
 }
Esempio n. 10
0
  /** @param contentResolver Used to look up and save settings. */
  public LockPatternUtils(Context context) {
    mContext = context;
    mContentResolver = context.getContentResolver();

    // Initialize the location of gesture & PIN lock files
    if (sLockPatternFilename == null) {
      String dataSystemDirectory =
          android.os.Environment.getDataDirectory().getAbsolutePath() + SYSTEM_DIRECTORY;
      sLockPatternFilename = dataSystemDirectory + LOCK_PATTERN_FILE;
      sLockPasswordFilename = dataSystemDirectory + LOCK_PASSWORD_FILE;
      sHaveNonZeroPatternFile.set(new File(sLockPatternFilename).length() > 0);
      sHaveNonZeroPasswordFile.set(new File(sLockPasswordFilename).length() > 0);
      int fileObserverMask =
          FileObserver.CLOSE_WRITE
              | FileObserver.DELETE
              | FileObserver.MOVED_TO
              | FileObserver.CREATE;
      sPasswordObserver = new PasswordFileObserver(dataSystemDirectory, fileObserverMask);
      sPasswordObserver.startWatching();
    }
  }
Esempio n. 11
0
  /** Called when initializing component. */
  protected void onInitialize() {
    // start file thread
    m_FileThread = new FileManageerThread("save media thread");
    m_FileThread.start();
    m_FileHandler = m_FileThread.getHandler();
    // start image thread
    m_DecodeBitmapThread = new DecodeBitmapThread("decode bitmap thread");
    m_DecodeBitmapThread.start();
    m_DecodeBitmapHandler = m_DecodeBitmapThread.getHandler();
    // observe file change
    m_FileHandler.sendMessage(Message.obtain(m_FileHandler, MESSAGE_LOAD_IMAGES));
    m_FileObserver =
        new FileObserver(m_DefaultFolder.getAbsolutePath()) {

          @Override
          public void onEvent(int event, String file) {
            if (event == FileObserver.DELETE) {
              m_FileHandler.sendMessage(Message.obtain(m_FileHandler, MESSAGE_LOAD_IMAGES, 1, 0));
            }
          }
        };
    m_FileObserver.startWatching(); // START OBSERVING

    /*
     * Creates a work queue for the pool of Thread objects used for
     * decoding, using a linked list queue that blocks when the queue is
     * empty.
     */
    m_DecodeWorkQueue = new LinkedBlockingQueue<Runnable>();
    m_DecodeThreadPool =
        new ThreadPoolExecutor(
            NUMBER_OF_CORES,
            NUMBER_OF_CORES,
            KEEP_ALIVE_TIME,
            KEEP_ALIVE_TIME_UNIT,
            m_DecodeWorkQueue);
  }
  private void logBootEvents(Context ctx) throws IOException {
    final DropBoxManager db = (DropBoxManager) ctx.getSystemService(Context.DROPBOX_SERVICE);
    final SharedPreferences prefs = ctx.getSharedPreferences("log_files", Context.MODE_PRIVATE);
    final String headers =
        new StringBuilder(512)
            .append("Build: ")
            .append(Build.FINGERPRINT)
            .append("\n")
            .append("Hardware: ")
            .append(Build.BOARD)
            .append("\n")
            .append("Bootloader: ")
            .append(Build.BOOTLOADER)
            .append("\n")
            .append("Radio: ")
            .append(Build.RADIO)
            .append("\n")
            .append("Kernel: ")
            .append(FileUtils.readTextFile(new File("/proc/version"), 1024, "...\n"))
            .append("\n")
            .toString();

    String recovery = RecoverySystem.handleAftermath();
    if (recovery != null && db != null) {
      db.addText("SYSTEM_RECOVERY_LOG", headers + recovery);
    }

    if (SystemProperties.getLong("ro.runtime.firstboot", 0) == 0) {
      String now = Long.toString(System.currentTimeMillis());
      SystemProperties.set("ro.runtime.firstboot", now);
      if (db != null) db.addText("SYSTEM_BOOT", headers);

      // Negative sizes mean to take the *tail* of the file (see FileUtils.readTextFile())
      addFileToDropBox(db, prefs, headers, "/proc/last_kmsg", -LOG_SIZE, "SYSTEM_LAST_KMSG");
      addFileToDropBox(db, prefs, headers, "/cache/recovery/log", -LOG_SIZE, "SYSTEM_RECOVERY_LOG");
      addFileToDropBox(
          db, prefs, headers, "/data/dontpanic/apanic_console", -LOG_SIZE, "APANIC_CONSOLE");
      addFileToDropBox(
          db, prefs, headers, "/data/dontpanic/apanic_threads", -LOG_SIZE, "APANIC_THREADS");
    } else {
      if (db != null) db.addText("SYSTEM_RESTART", headers);
    }

    // Scan existing tombstones (in case any new ones appeared)
    File[] tombstoneFiles = TOMBSTONE_DIR.listFiles();
    for (int i = 0; tombstoneFiles != null && i < tombstoneFiles.length; i++) {
      addFileToDropBox(
          db, prefs, headers, tombstoneFiles[i].getPath(), LOG_SIZE, "SYSTEM_TOMBSTONE");
    }

    // Start watching for new tombstone files; will record them as they occur.
    // This gets registered with the singleton file observer thread.
    sTombstoneObserver =
        new FileObserver(TOMBSTONE_DIR.getPath(), FileObserver.CLOSE_WRITE) {
          @Override
          public void onEvent(int event, String path) {
            try {
              String filename = new File(TOMBSTONE_DIR, path).getPath();
              addFileToDropBox(db, prefs, headers, filename, LOG_SIZE, "SYSTEM_TOMBSTONE");
            } catch (IOException e) {
              Slog.e(TAG, "Can't log tombstone", e);
            }
          }
        };

    sTombstoneObserver.startWatching();
  }
Esempio n. 13
0
 protected void a(com.estrongs.fs.h paramh, TypedMap paramTypedMap)
 {
   if ((w != null) && (w.equals(paramh)) && (!am.aW(w.getPath()))) {}
   while ((z.n) && (paramh != null) && (paramh.getPath().equals("/"))) {
     return;
   }
   if (W != null)
   {
     W.stopWatching();
     W = null;
   }
   if ((!M) && (k(paramh.getAbsolutePath()))) {}
   for (;;)
   {
     synchronized (N)
     {
       if ((v != null) && (w != null) && ((N.isEmpty()) || (!am.e(paramh.getAbsolutePath(), w.getAbsolutePath()))))
       {
         N.push(w);
         TypedMap localTypedMap = new TypedMap(U);
         b.put(w, localTypedMap);
       }
       U.clear();
       if (paramTypedMap != null) {
         U.putAll(paramTypedMap);
       }
       R();
       if (v == null)
       {
         F.put(paramh.getPath(), g.onSaveInstanceState());
         w = paramh;
         v = paramh.getPath();
         if ((am.ba(v)) && (am.bW(v)) && (paramh.getName().equals("es_recycle_content")))
         {
           w = com.estrongs.fs.d.m("recycle://");
           v = "recycle://";
         }
         if (am.ba(w.getAbsolutePath()))
         {
           W = new bz(this, w.getAbsolutePath());
           W.startWatching();
         }
         V = true;
         U.put("back", Boolean.valueOf(M));
         if ((U == null) || (!U.getBoolean("refresh")) || (M)) {
           break;
         }
         b(true);
         return;
       }
     }
     if (ak)
     {
       F.put(v, null);
       ak = false;
     }
     else
     {
       F.put(v, g.onSaveInstanceState());
     }
   }
   g();
 }
Esempio n. 14
0
    void scanDir(final File dir) {
      // Checks if scan should be continued
      if (!inScan.get()) {
        return;
      }

      if (dir == null || !dir.isDirectory()) {
        return;
      }

      if (dir.getAbsolutePath().startsWith("/sys")) {
        LCTX.d("Skip system dir: " + dir);
        return;
      }

      try {
        final File cd = CacheManager.getCacheDir();
        if (dir.getCanonicalPath().equals(cd.getCanonicalPath())) {
          LCTX.d("Skip file cache: " + dir);
          return;
        }
      } catch (final IOException ex) {
        ex.printStackTrace();
      }

      if (LCTX.isDebugEnabled()) {
        LCTX.d("Scan dir: " + dir);
      }

      // Retrieves file observer for scanning folder
      final FileObserver observer = getObserver(dir);
      // Stop watching
      observer.stopWatching();

      // Retrieves listener
      final Listener l = listeners.getListener();

      // Retrieves file list
      final File[] files = dir.listFiles((FilenameFilter) filter);
      // Sort file list
      if (LengthUtils.isNotEmpty(files)) {
        Arrays.sort(files, StringUtils.NFC);
      }
      // Call the file scan callback
      l.onFileScan(dir, files);

      // Retrieves files from current directory
      final File[] childDirs = dir.listFiles(DirectoryFilter.ALL);
      // Immediately starts folder watching
      getObserver(dir).startWatching();

      if (LengthUtils.isNotEmpty(childDirs)) {
        // Sort child dir list
        Arrays.sort(childDirs, StringUtils.NFC);
        // Add children for deep ordered scanning
        synchronized (this) {
          for (int i = childDirs.length - 1; i >= 0; i--) {
            this.paths.addFirst(childDirs[i]);
          }
        }
      }
    }
Esempio n. 15
0
 public void stop() {
   if (mFileObserver != null) {
     mFileObserver.stopWatching();
   }
 }
Esempio n. 16
0
 public void start() {
   if (mFileObserver == null) {
     mFileObserver = new MyFileObserver(mPath, FileObserver.DELETE);
   }
   mFileObserver.startWatching();
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String storageState = Environment.getExternalStorageState();

    if (!Environment.MEDIA_MOUNTED.equals(storageState)
        && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(storageState)) {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setTitle(R.string.no_media_warning);
      builder.setMessage(R.string.no_media_hint);
      AlertDialog alert = builder.create();
      alert.setButton(
          AlertDialog.BUTTON_POSITIVE,
          getString(R.string.dismiss),
          new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              finish();
            }
          });
      alert.show();
      return;
    }

    if (mDirectory == null)
      mDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

    // Create a list adapter...
    adapter = new ChoosePDFAdapter(getLayoutInflater());
    setListAdapter(adapter);

    this.getListView().setBackgroundColor(Color.WHITE);
    this.getListView().setFooterDividersEnabled(true);
    // this.getListView().setDividerHeight(20);
    this.getListView().setDivider(new ColorDrawable(Color.BLUE));

    // ...that is updated dynamically when files are scanned
    mHandler = new Handler();
    mUpdateFiles =
        new Runnable() {
          public void run() {
            Resources res = getResources();
            String appName = res.getString(R.string.app_name);
            String version = res.getString(R.string.version);
            String title = res.getString(R.string.picker_title_App_Ver_Dir);
            setTitle(String.format(title, appName, version, mDirectory));

            mParent = mDirectory.getParentFile();

            mDirs =
                mDirectory.listFiles(
                    new FileFilter() {

                      public boolean accept(File file) {
                        return file.isDirectory();
                      }
                    });
            if (mDirs == null) mDirs = new File[0];

            mFiles =
                mDirectory.listFiles(
                    new FileFilter() {

                      public boolean accept(File file) {
                        if (file.isDirectory()) return false;
                        String fname = file.getName().toLowerCase();
                        if (fname.endsWith(".pdf")) return true;
                        if (fname.endsWith(".xps")) return true;
                        if (fname.endsWith(".cbz")) return true;
                        if (fname.endsWith(".png")) return true;
                        if (fname.endsWith(".jpe")) return true;
                        if (fname.endsWith(".jpeg")) return true;
                        if (fname.endsWith(".jpg")) return true;
                        if (fname.endsWith(".jfif")) return true;
                        if (fname.endsWith(".jfif-tbnl")) return true;
                        if (fname.endsWith(".tif")) return true;
                        if (fname.endsWith(".tiff")) return true;
                        return false;
                      }
                    });
            if (mFiles == null) mFiles = new File[0];

            Arrays.sort(
                mFiles,
                new Comparator<File>() {
                  public int compare(File arg0, File arg1) {
                    return arg0.getName().compareToIgnoreCase(arg1.getName());
                  }
                });

            Arrays.sort(
                mDirs,
                new Comparator<File>() {
                  public int compare(File arg0, File arg1) {
                    return arg0.getName().compareToIgnoreCase(arg1.getName());
                  }
                });

            adapter.clear();
            if (mParent != null)
              adapter.add(
                  new ChoosePDFItem(
                      ChoosePDFItem.Type.PARENT, getString(R.string.parent_directory)));
            for (File f : mDirs)
              adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.DIR, f.getName()));
            for (File f : mFiles)
              adapter.add(new ChoosePDFItem(ChoosePDFItem.Type.DOC, f.getName()));

            lastPosition();
          }
        };

    // Start initial file scan...
    mHandler.post(mUpdateFiles);

    // ...and observe the directory and scan files upon changes.
    FileObserver observer =
        new FileObserver(mDirectory.getPath(), FileObserver.CREATE | FileObserver.DELETE) {
          public void onEvent(int event, String path) {
            mHandler.post(mUpdateFiles);
          }
        };
    observer.startWatching();
  }
  private void logBootEvents(Context ctx) throws IOException {
    final DropBoxManager db = (DropBoxManager) ctx.getSystemService(Context.DROPBOX_SERVICE);
    final SharedPreferences prefs = ctx.getSharedPreferences("log_files", Context.MODE_PRIVATE);
    final String headers =
        new StringBuilder(512)
            .append("Build: ")
            .append(Build.FINGERPRINT)
            .append("\n")
            .append("Hardware: ")
            .append(Build.BOARD)
            .append("\n")
            .append("Revision: ")
            .append(SystemProperties.get("ro.revision", ""))
            .append("\n")
            .append("Bootloader: ")
            .append(Build.BOOTLOADER)
            .append("\n")
            .append("Radio: ")
            .append(Build.RADIO)
            .append("\n")
            .append("Kernel: ")
            .append(FileUtils.readTextFile(new File("/proc/version"), 1024, "...\n"))
            .append("\n")
            .toString();
    final String bootReason = SystemProperties.get("ro.boot.bootreason", null);

    String recovery = RecoverySystem.handleAftermath();
    if (recovery != null && db != null) {
      db.addText("SYSTEM_RECOVERY_LOG", headers + recovery);
    }

    String lastKmsgFooter = "";
    if (bootReason != null) {
      lastKmsgFooter =
          new StringBuilder(512)
              .append("\n")
              .append("Boot info:\n")
              .append("Last boot reason: ")
              .append(bootReason)
              .append("\n")
              .toString();
    }

    if (SystemProperties.getLong("ro.runtime.firstboot", 0) == 0) {
      if ("encrypted".equals(SystemProperties.get("ro.crypto.state"))
          && "trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt"))) {
        // Encrypted, first boot to get PIN/pattern/password so data is tmpfs
        // Don't set ro.runtime.firstboot so that we will do this again
        // when data is properly mounted
      } else {
        String now = Long.toString(System.currentTimeMillis());
        SystemProperties.set("ro.runtime.firstboot", now);
      }
      if (db != null) db.addText("SYSTEM_BOOT", headers);

      // Negative sizes mean to take the *tail* of the file (see FileUtils.readTextFile())
      addFileWithFootersToDropBox(
          db, prefs, headers, lastKmsgFooter, "/proc/last_kmsg", -LOG_SIZE, "SYSTEM_LAST_KMSG");
      addFileWithFootersToDropBox(
          db,
          prefs,
          headers,
          lastKmsgFooter,
          "/sys/fs/pstore/console-ramoops",
          -LOG_SIZE,
          "SYSTEM_LAST_KMSG");
      addFileToDropBox(db, prefs, headers, "/cache/recovery/log", -LOG_SIZE, "SYSTEM_RECOVERY_LOG");
      addFileToDropBox(
          db, prefs, headers, "/cache/recovery/last_kmsg", -LOG_SIZE, "SYSTEM_RECOVERY_KMSG");
      addFileToDropBox(
          db, prefs, headers, "/data/dontpanic/apanic_console", -LOG_SIZE, "APANIC_CONSOLE");
      addFileToDropBox(
          db, prefs, headers, "/data/dontpanic/apanic_threads", -LOG_SIZE, "APANIC_THREADS");
      addAuditErrorsToDropBox(db, prefs, headers, -LOG_SIZE, "SYSTEM_AUDIT");
      addFsckErrorsToDropBox(db, prefs, headers, -LOG_SIZE, "SYSTEM_FSCK");
    } else {
      if (db != null) db.addText("SYSTEM_RESTART", headers);
    }

    // Scan existing tombstones (in case any new ones appeared)
    File[] tombstoneFiles = TOMBSTONE_DIR.listFiles();
    for (int i = 0; tombstoneFiles != null && i < tombstoneFiles.length; i++) {
      if (tombstoneFiles[i].isFile()) {
        addFileToDropBox(
            db, prefs, headers, tombstoneFiles[i].getPath(), LOG_SIZE, "SYSTEM_TOMBSTONE");
      }
    }

    // Start watching for new tombstone files; will record them as they occur.
    // This gets registered with the singleton file observer thread.
    sTombstoneObserver =
        new FileObserver(TOMBSTONE_DIR.getPath(), FileObserver.CLOSE_WRITE) {
          @Override
          public void onEvent(int event, String path) {
            try {
              File file = new File(TOMBSTONE_DIR, path);
              if (file.isFile()) {
                addFileToDropBox(db, prefs, headers, file.getPath(), LOG_SIZE, "SYSTEM_TOMBSTONE");
              }
            } catch (IOException e) {
              Slog.e(TAG, "Can't log tombstone", e);
            }
          }
        };

    sTombstoneObserver.startWatching();
  }