示例#1
0
  private void visitEntry(final Entry entry, DropboxEntryVisitor visitor) {
    if (null != entry.contents) {
      logger.debug(entry.path + "contents size: " + entry.contents.size());
      for (Entry child : entry.contents) {
        if (!child.isDeleted) {
          if (!child.isDir) {
            visitor.visitFile(child);
          } else {
            try {
              visitor.preVisitDirectory(child);
            } catch (IOException e) {
              logger.error(e.getMessage());
            }

            try {
              Entry childWithContents =
                  api.metadata(
                      child.path,
                      0,
                      MetaHandler.getHash(child.path),
                      true,
                      MetaHandler.getRev(child.path));
              visitEntry(childWithContents, visitor);
            } catch (DropboxException e) {
              logger.error(e.getMessage());
            }
            visitor.postVisitDirectory(child);
          }
        }
      }
    }
  }
示例#2
0
  public boolean push() {
    if (!isLinked()) return false;

    FileInputStream inputStream = null;
    try {
      app.getGui().setStatus("Uploading...");
      File[] files = new File(NoteManager.defaultPath).listFiles();
      for (int i = 0; i < files.length; i++) {
        inputStream = new FileInputStream(files[i]);
        mDBApi.putFileOverwrite(
            "/".concat(files[i].getName()), inputStream, files[i].length(), null);
        app.getGui().setStatus("Uploaded ".concat(files[i].getName()));
        inputStream.close();
      }
      return true;
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      app.getGui().setStatus("Files not found.");
    } catch (DropboxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      app.getGui().setStatus("Couldn't connect to server.");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      app.getGui().setStatus("IO errors.");
    }
    return false;
  }
示例#3
0
  public boolean pull() {
    // TODO Auto-generated method stub
    if (!isLinked()) return false;

    File file;
    FileOutputStream outputStream = null;
    try {
      Entry entry = mDBApi.metadata("/", 0, null, true, null);
      for (Entry e : entry.contents) {
        if (!e.isDir) {
          app.getGui().setStatus("Downloading...");
          file = new File(NoteManager.defaultPath.concat(e.fileName()));
          outputStream = new FileOutputStream(file);
          DropboxFileInfo info = mDBApi.getFile("/".concat(e.fileName()), null, outputStream, null);
          app.getGui().setStatus("Downloaded ".concat(info.getMetadata().fileName()));
          outputStream.close();
        }
      }
      return true;
    } catch (DropboxException e) {
      e.printStackTrace();
      app.getGui().setStatus("Couldn't connect to server.");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      app.getGui().setStatus("Files not found.");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      app.getGui().setStatus("IO errors.");
    }
    return false;
  }
  private void loadMetadata(DropboxFile file) {
    Log.d(TAG, "Loading metadata for " + file.getRemoteFile());

    DropboxAPI.Entry metadata = null;
    try {
      metadata = dropboxApi.metadata(file.getRemoteFile(), 0, null, false, null);
    } catch (DropboxServerException se) {
      if (se.error == DropboxServerException._404_NOT_FOUND) {
        Log.d(TAG, "metadata NOT found! Returning NOT_FOUND status.");
        file.setStatus(DropboxFileStatus.NOT_FOUND);
        return;
      }
      throw new RemoteException("Server Exception: " + se.error + " " + se.reason, se);
    } catch (DropboxException e) {
      throw new RemoteException("Dropbox Exception: " + e.getMessage(), e);
    }

    Log.d(TAG, "Metadata retrieved. rev on Dropbox = " + metadata.rev);
    Log.d(TAG, "local rev = " + file.getOriginalRev());

    file.setLoadedMetadata(metadata);

    if (metadata.rev.equals(file.getOriginalRev())) {
      // don't bother downloading if the rev is the same
      Log.d(TAG, "revs match. returning NOT_CHANGED status.");
      file.setStatus(DropboxFileStatus.NOT_CHANGED);
    } else if (metadata.isDeleted) {
      Log.d(TAG, "File marked as deleted on Dropbox! Returning NOT_FOUND status.");
      file.setStatus(DropboxFileStatus.NOT_FOUND);
    } else {
      Log.d(TAG, "revs don't match. returning FOUND status.");
      file.setStatus(DropboxFileStatus.FOUND);
    }
  }
示例#5
0
  private void syncStorage() {
    try {
      logger.debug("Synching storage.");
      final String rootDir = "/";
      Entry folderEntry =
          api.metadata(rootDir, 0, MetaHandler.getHash(rootDir), true, MetaHandler.getRev(rootDir));

      // TODO handle removed entries

      visitEntry(
          folderEntry,
          new DropboxEntryVisitor() {
            @Override
            public void preVisitDirectory(Entry entry) throws IOException {
              if (!MetaHandler.isStored(entry.path)) {
                logger.debug("Creating local dir: " + entry.path);
                Path filePath =
                    FileSystems.getDefault().getPath(startDir.toString(), entry.path.substring(1));
                WatchKey key =
                    filePath
                        .getParent()
                        .register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
                keys.remove(key);
                key.cancel();

                filePath.toFile().mkdir();

                key =
                    filePath
                        .getParent()
                        .register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
                keys.put(key, filePath.getParent());

                MetaHandler.setFile(entry.path, filePath.toFile(), entry.rev);
              }
            }

            @Override
            public void visitFile(Entry entry) {
              if (!MetaHandler.isStored(entry.path)) downloadFile(entry.path);
              else if (!MetaHandler.isCurrent(entry.path, entry.rev)) {
                Path fullPath =
                    FileSystems.getDefault().getPath(startDir.toString(), entry.path.substring(1));
                try {
                  logger.debug("Uploading file " + entry.path);
                  uploadFile(entry.path, fullPath);
                } catch (Exception e) {
                  logger.error("Error uploading file: " + e.getMessage());
                }
              }
            }
          });

    } catch (DropboxException ex) {
      logger.error("Error syching root dir: " + ex.getMessage());
    }
  }
 public BufferedReader getRemoteFile(String filename) throws IOException {
   String filePath = this.remotePath + filename;
   try {
     DropboxInputStream is = dropboxApi.getFileStream(filePath, null);
     BufferedReader fileReader = new BufferedReader(new InputStreamReader(is));
     return fileReader;
   } catch (DropboxUnlinkedException e) {
     throw new IOException("Dropbox Authentication Failed, re-run setup wizard");
   } catch (DropboxException e) {
     throw new IOException("Fetching " + filename + ": " + e.toString());
   }
 }
  @Override
  protected Void doInBackground(Void... params) {
    try {
      inputStream = new FileInputStream(file);
      DropboxAPI.Entry response =
          mDBApi.putFile(file.getName(), inputStream, file.length(), null, null);
      Log.d(log, "doInBackground() The uploaded file's rev is: " + response.rev);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      Log.d(log, "doInBackground() FileNotFoundException " + e.toString());
    } catch (DropboxException e) {
      e.printStackTrace();
      Log.d(log, "doInBackground() DropboxException " + e.toString());
    }

    return null;
  }
示例#8
0
  public String accountInfo() {
    // TODO Auto-generated method stub
    if (!isLinked()) return "You haven't been logged yet.\nPress Dropbox -> Login.";

    try {
      Account account = mDBApi.accountInfo();
      StringBuilder user = new StringBuilder(account.displayName);
      user.append("\nCountry : ");
      user.append(account.country);
      user.append("\nUsage   : ");
      user.append(account.quota);
      return user.toString();
    } catch (DropboxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
  public void putRemoteFile(String filename, String contents) throws IOException {
    FileUtils orgFile = new FileUtils(filename, context);
    BufferedWriter writer = orgFile.getWriter();
    writer.write(contents);
    writer.close();

    File uploadFile = orgFile.getFile();
    FileInputStream fis = new FileInputStream(uploadFile);
    try {
      this.dropboxApi.putFileOverwrite(this.remotePath + filename, fis, uploadFile.length(), null);
    } catch (DropboxUnlinkedException e) {
      throw new IOException("Dropbox Authentication Failed, re-run setup wizard");
    } catch (DropboxException e) {
      throw new IOException("Uploading " + filename + " because: " + e.toString());
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
        }
      }
    }
  }
示例#10
0
  public boolean login() {
    try {
      AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
      WebAuthSession was = new WebAuthSession(appKeyPair, ACCESS_TYPE);
      WebAuthSession.WebAuthInfo info = was.getAuthInfo();

      if (Desktop.isDesktopSupported()) {
        try {
          Desktop.getDesktop().browse(URI.create(info.url));
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      JOptionPane.showMessageDialog(
          app.getGui().getContainer(),
          "Log in to your dropbox account and approve Myn on the opened page.\nAfter you done it, press OK.",
          "Auth",
          JOptionPane.PLAIN_MESSAGE);

      app.getGui().setStatus("Checking...");
      was.retrieveWebAccessToken(info.requestTokenPair);
      AccessTokenPair accessToken = was.getAccessTokenPair();
      authData = new AuthData(appKeyPair, accessToken);
      authData.persist();
      app.getGui().setStatus("Logged In.");
      return true;
    } catch (HeadlessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (DropboxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      app.getGui().setStatus("Couldn't connect to server.");
    }
    return false;
  }
示例#11
0
  public void downloadFile(String relPath) {
    VOSync.debug("Downloading file from storage: " + relPath);
    Path filePath = FileSystems.getDefault().getPath(startDir.toString(), relPath.substring(1));
    try {
      WatchKey key =
          filePath.getParent().register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.remove(key);
      key.cancel();

      FileOutputStream outp = new FileOutputStream(filePath.toFile());
      DropboxFileInfo info = api.getFile(relPath, null, outp, null);
      outp.close();

      key = filePath.getParent().register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.put(key, filePath.getParent());

      MetaHandler.setFile(relPath, filePath.toFile(), info.getMetadata().rev);
    } catch (IOException ex) {
      logger.error("Error downloading file " + relPath + ": " + ex.getMessage());
    } catch (DropboxException ex) {
      ex.printStackTrace();
      logger.error("Error downloading file " + relPath + ": " + ex.getMessage());
    }
  }
示例#12
0
  @Override
  public void run() {
    logger.debug("Register root " + startDir.toString());

    try {
      registerAll(startDir);
    } catch (IOException ex) {
      logger.error(ex.getMessage());
      return;
    }

    if (isInterrupted()) return;

    VOSync.debug("Sync local db with drive");

    DbPool.goSql(
        "Synching the local db with drive",
        "select NAME from FILES",
        new SqlWorker<Boolean>() {
          @Override
          public Boolean go(Connection conn, PreparedStatement stmt) throws SQLException {
            ResultSet resSet = stmt.executeQuery();
            while (resSet.next()) {
              try {
                String fileName = resSet.getString(1);
                Path filePath =
                    FileSystems.getDefault().getPath(startDir.toString(), fileName.substring(1));
                if (!filePath.toFile().exists()) {
                  logger.debug(
                      "Deleting file " + fileName + " existing in DB and not present on disk");
                  api.delete(fileName);
                  MetaHandler.delete(fileName);
                }
              } catch (DropboxException ex) {
              }
            }
            resSet.close();
            return true;
          }
        });

    if (isInterrupted()) return;

    VOSync.debug("Sync storage");

    syncStorage();

    logger.debug("Start watching");

    while (!isInterrupted()) {
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        System.err.println("WatchKey " + key.toString() + " not recognized!");
        continue;
      }

      for (WatchEvent<?> event : key.pollEvents()) {
        Kind<?> kind = event.kind();

        // TBD - provide example of how OVERFLOW event is handled
        if (kind == OVERFLOW) {
          continue;
        }

        // Context for directory entry event is the file name of entry
        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();
        Path child = dir.resolve(name);
        Path relativeDir = startDir.relativize(child);
        String fileRelPath = "/" + fixPath(relativeDir.toString());

        // print out event
        logger.debug(event.kind().name() + ":" + child + " " + name + " " + key);

        try {
          if (Files.exists(child, new LinkOption[] {}) && Files.isHidden(child)) {
            logger.error(
                "Skipping hidden file " + child.getFileName()); // skip OS generated catalog files
          } else {
            if (event.kind() == ENTRY_CREATE) {
              if (Files.isRegularFile(child, NOFOLLOW_LINKS)) { // file modified
                uploadFile(fileRelPath, child);
              } else if (Files.isDirectory(child, NOFOLLOW_LINKS)) { // directory contents changed
                registerAll(child);
              }
            } else if (event.kind() == ENTRY_DELETE) {
              logger.debug("Deleting " + fileRelPath);
              api.delete(fileRelPath);
              MetaHandler.delete(fileRelPath);
              logger.debug("Deleted!");
            } else if (event.kind() == ENTRY_MODIFY) {
              if (Files.isRegularFile(child, NOFOLLOW_LINKS)) { // file modified
                uploadFile(fileRelPath, child);
              } else if (Files.isDirectory(child, NOFOLLOW_LINKS)) { // directory contents changed
                // logger.debug("Renewing dir: "+relativeDir.toString());
                // TODO update folder date
                // MetaHandler.setFile(fileRelPath, child, rev);
              }
            }
          }
        } catch (IOException ex) {
          ex.printStackTrace();
          logger.error(ex.getMessage());
        } catch (DropboxException ex) {
          ex.printStackTrace();
          logger.error(ex.getMessage());
        }
      }

      boolean valid = key.reset();

      if (!valid) keys.remove(key);
    }
  }
示例#13
0
  /**
   * First of all create a backup of Money and Categories Database on the SD card. After that, get
   * those backups from the SD card and upload it to the DropBox after the app checks if it already
   * exist. If the backup already exists then delete the old and create the new one.
   *
   * @param params
   * @return
   */
  @Override
  protected String doInBackground(String... params) {

    String MoneyDBpath = "/data/" + context.getPackageName() + "/databases/MoneyDatabase";
    String MoneyOutputName = "/TransactionsBackup";
    BackupRestoreSD backupRestoreSD = new BackupRestoreSD(MoneyDBpath, MoneyOutputName, context);
    backupRestoreSD.backup();

    File MoneyBackup = new File(backupRestoreSD.getSDPath() + "/Pocket-Wallet/TransactionsBackup");

    String CategoriesDBpath = "/data/" + context.getPackageName() + "/databases/categories";
    String CategoriesOutputName = "/CategoriesBackup";
    backupRestoreSD = new BackupRestoreSD(CategoriesDBpath, CategoriesOutputName, context);
    backupRestoreSD.backup();

    File CategoryBackup = new File(backupRestoreSD.getSDPath() + "/Pocket-Wallet/CategoriesBackup");

    try {

      InputStream Mis = new FileInputStream(MoneyBackup);
      InputStream Cis = new FileInputStream(CategoryBackup);

      DropboxAPI.Entry metadata = api.metadata("/", 1000, null, true, null);

      boolean flag = false, cflag = false;
      List<DropboxAPI.Entry> CFolder = metadata.contents;

      for (DropboxAPI.Entry entry : CFolder) {
        if (entry.fileName().equals("TransactionsBackup")) {
          flag = true;
        } else if (entry.fileName().equals("CategoriesBackup")) {
          cflag = true;
        }

        if (flag && cflag) {
          break;
        }
      }

      if (!flag) {
        api.putFile("TransactionsBackup", Mis, MoneyBackup.length(), null, null);

      } else {
        api.delete("/TransactionsBackup");
        api.putFile("TransactionsBackup", Mis, MoneyBackup.length(), null, null);
      }

      if (!cflag) {
        api.putFile("CategoriesBackup", Cis, CategoryBackup.length(), null, null);
      } else {
        api.delete("/CategoriesBackup");
        api.putFile("CategoriesBackup", Cis, CategoryBackup.length(), null, null);
      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DropboxException e) {
      e.printStackTrace();
    }

    return null;
  }