public static void moveToDirectory(File src, File destDir, boolean createDestDir) {
   try {
     FileUtils.moveToDirectory(src, destDir, createDestDir);
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
  private void cleanupBeforeRestore() {
    stopWalletService();

    // clear files directory (by moving everything to an archive folder)

    File filesDir = getActivity().getFilesDir();
    File archiveDir = new File(filesDir, "archive_" + System.currentTimeMillis());
    File[] filesInFilesDir =
        filesDir.listFiles(
            new FilenameFilter() {
              @Override
              public boolean accept(File dir, String filename) {
                // exclude archive dirs
                return !filename.startsWith("archive_");
              }
            });
    for (File file : filesInFilesDir) {
      try {
        FileUtils.moveToDirectory(file, archiveDir, true);
        Log.d(TAG, "Moved file '" + file + "' to '" + archiveDir + "'");
      } catch (IOException e) {
        Log.w(TAG, "Could not move file: " + file.toString());
      }
    }
  }
Exemple #3
0
  private void moveBuildToExistingBranchDir(final File sourceBranchDir, final File targetBranchDir)
      throws MoveBuildDataException {
    LOGGER.info("Moving build to existing branch folder. Target: " + targetBranchDir);
    try {
      File[] filesToMove =
          sourceBranchDir.listFiles(
              new FilenameFilter() {
                @Override
                public boolean accept(final File dir, final String name) {
                  // we don't want to copy branch.xml, it should already exist.
                  return !"branch.xml".equals(name);
                }
              });

      if (filesToMove.length != 1 || !filesToMove[0].isDirectory()) {
        throw new MoveBuildDataException(
            "The branch directory must only contain one build directory.");
      }

      if (targetBuildAlreadyExists(filesToMove[0].getName(), targetBranchDir)) {
        throw new MoveBuildDataException("The target build directory already exists");
      }

      FileUtils.moveToDirectory(filesToMove[0], targetBranchDir, false);
    } catch (IOException e) {
      throw new MoveBuildDataException("Problem while moving build data.", e);
    }
  }
  public void moveErrorFile(String dataFileName, String creditCardDataFileErrorDirectory) {
    File dataFile = new File(dataFileName);

    if (!dataFile.exists() || !dataFile.canRead()) {
      LOG.error("Cannot find/read data file " + dataFileName);

    } else {

      try {
        FileUtils.moveToDirectory(dataFile, new File(creditCardDataFileErrorDirectory), true);
      } catch (IOException ex) {
        LOG.error(
            "Cannot move the file:"
                + dataFile
                + " to the directory: "
                + creditCardDataFileErrorDirectory,
            ex);
      }
    }
  }
Exemple #5
0
  @Override
  public Bag makeBagInPlace(
      Version version,
      boolean retainBaseDirectory,
      boolean keepEmptyDirectories,
      Completer completer) {
    log.info(MessageFormat.format("Making a bag in place at {0}", this.dir));
    File dataDir = new File(this.dir, this.bagFactory.getBagConstants(version).getDataDirectory());
    log.trace("Data directory is " + dataDir);
    try {
      // If there is no data direct
      if (!dataDir.exists()) {
        log.trace("Data directory does not exist");
        // If retainBaseDirectory
        File moveToDir = dataDir;
        if (retainBaseDirectory) {
          log.trace("Retaining base directory");
          // Create new base directory in data directory
          moveToDir = new File(dataDir, this.dir.getName());
          // Move contents of base directory to new base directory
        }
        log.debug(
            MessageFormat.format(
                "Data directory does not exist so moving files to {0}", moveToDir));
        for (File file : FileHelper.normalizeForm(this.dir.listFiles())) {
          if (!(file.equals(dataDir)
              || (file.isDirectory() && this.ignoreDirs.contains(file.getName())))) {
            log.trace(MessageFormat.format("Moving {0} to {1}", file, moveToDir));
            FileUtils.moveToDirectory(file, moveToDir, true);
          } else {
            log.trace(MessageFormat.format("Not moving {0}", file));
          }
        }

      } else {
        if (!dataDir.isDirectory())
          throw new RuntimeException(MessageFormat.format("{0} is not a directory", dataDir));
        // Look for additional, non-ignored files
        for (File file : FileHelper.normalizeForm(this.dir.listFiles())) {
          // If there is a directory that isn't the data dir and isn't ignored and pre v0.97 then
          // exception
          if (file.isDirectory()
              && (!file.equals(dataDir))
              && !this.ignoreDirs.contains(file.getName())
              && (Version.V0_93 == version
                  || Version.V0_94 == version
                  || Version.V0_95 == version
                  || Version.V0_96 == version)) {
            throw new RuntimeException(
                "Found additional directories in addition to existing data directory.");
          }
        }
      }
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }

    // Handle empty directories
    if (keepEmptyDirectories) {
      log.debug("Adding .keep files to empty directories");
      this.addKeep(dataDir);
    } else {
      log.trace("Not adding .keep files to empty directories");
    }

    // Copy the tags
    log.debug("Copying tag files");
    for (File tagFile : this.tagFiles) {
      log.trace(MessageFormat.format("Copying tag file {0} to {1}", tagFile, this.dir));
      try {
        FileUtils.copyFileToDirectory(tagFile, this.dir);
      } catch (IOException ex) {
        throw new RuntimeException(ex);
      }
    }

    // Create a bag
    log.debug(MessageFormat.format("Creating bag by payload files at {0}", this.dir));
    Bag bag = this.bagFactory.createBagByPayloadFiles(this.dir, version, this.ignoreDirs);
    // Complete the bag
    log.debug("Making complete");
    bag = bag.makeComplete(completer);
    // Write the bag
    log.debug("Writing");
    return bag.write(new FileSystemWriter(this.bagFactory), this.dir);
  }
  private void doMigrateFrom_v1_0_262(Context context, NetworkParameters migrationParams)
      throws IOException {
    Log.d(TAG, "********* MIGRATION FROM v1.0.262 - " + migrationParams.getId() + "*********");

    final File rootDir = context.getFilesDir();
    final File storageDir;
    final File archiveDir = new File(rootDir, "archive_" + System.currentTimeMillis());
    final File walletFile;
    final File chainFile;

    final File newWalletFile;
    final File newChainFile;

    if (ClientUtils.isMainNet(migrationParams)) {
      String walletFilesPrefix = AppConfig.MainNetConfig.get().getWalletFilesPrefix();
      storageDir = new File(rootDir, "mainnet_wallet__uuid_object_storage");
      walletFile = new File(rootDir, "mainnet_wallet_.wallet");
      newWalletFile = new File(rootDir, walletFilesPrefix + ".wallet");
      chainFile = new File(rootDir, "mainnet_wallet_.spvchain");
      newChainFile = new File(rootDir, walletFilesPrefix + ".spvchain");
    } else if (ClientUtils.isTestNet(migrationParams)) {
      String walletFilesPrefix = AppConfig.TestNetConfig.get().getWalletFilesPrefix();
      storageDir = new File(rootDir, "testnet_wallet__uuid_object_storage");
      walletFile = new File(rootDir, "testnet_wallet_.wallet");
      newWalletFile = new File(rootDir, walletFilesPrefix + ".wallet");
      chainFile = new File(rootDir, "testnet_wallet_.spvchain");
      newChainFile = new File(rootDir, walletFilesPrefix + ".spvchain");
    } else {
      throw new RuntimeException(
          "Network params not supported (unknown): " + migrationParams.toString());
    }

    final File keyFile = new File(storageDir, "ECKeyWrapper.json");

    if (keyFile.exists() && walletFile.exists()) {

      // Keys: stored in ECKeyWrapper.json
      /* Key format (JSON):
        {
          "...uuid1...": {
              "isPublicOnly": true,
              "keyPayload": [...bytes (integers)...],
              "name": "remote_server_public_key",
              "uuid": "...uuid1..."
          },
          "...uuid2...": {
              "isPublicOnly": false,
              "keyPayload": [...bytes (integers)...],
              "name": "remote_client_public_key",
              "uuid": "...uuid2..."
          }
        }
      */

      Log.d(TAG, "Key file found: " + keyFile);
      String keyFileJson = FileUtils.readFileToString(keyFile);
      Type type = new TypeToken<Map<String, ECKeyWrapper>>() {}.getType();
      // Note: do not use gson from serializeutils (key is not stored in base64).
      Map<String, ECKeyWrapper> keys = new Gson().fromJson(keyFileJson, type);
      ECKey serverKey = null;
      ECKey clientKey = null;
      for (ECKeyWrapper key : keys.values()) {
        if (key.isPublicOnly && key.name.equals("remote_server_public_key")) {
          serverKey = ECKey.fromPublicOnly(key.keyPayload);
        } else if (!key.isPublicOnly && key.name.equals("remote_client_public_key")) {
          clientKey = ECKey.fromPrivate(key.keyPayload);
        } else {
          Log.d(TAG, "Unknown key name: " + key.name);
        }
      }

      if (clientKey != null && serverKey != null) {
        Log.d(TAG, "Found client and server keys - store in shared preferences.");
        try {

          /** ******** Actual Migration Code ********* */
          SharedPrefUtils.setClientKey(context, migrationParams, clientKey);
          SharedPrefUtils.setServerKey(context, migrationParams, serverKey, "n/a - migration");
          Log.d(
              TAG,
              "Migrated keys:"
                  + " clientPubKey="
                  + clientKey.getPublicKeyAsHex()
                  + ", serverPubKey="
                  + serverKey.getPublicKeyAsHex());

          // move wallet file
          Log.d(
              TAG,
              "Migrate wallet file: " + walletFile.toString() + " -> " + newWalletFile.toString());
          FileUtils.copyFile(walletFile, newWalletFile);
          Log.d(
              TAG,
              "Migrate chain file: " + chainFile.toString() + " -> " + newChainFile.toString());
          FileUtils.copyFile(chainFile, newChainFile);

          SharedPrefUtils.enableMultisig2of2ToCltvForwarder(context);

          // move everything to an archive file.
          Log.d(TAG, "Move old files to archive dir: " + archiveDir.toString());
          FileUtils.moveToDirectory(storageDir, archiveDir, true);
          FileUtils.moveToDirectory(walletFile, archiveDir, true);
          FileUtils.moveToDirectory(chainFile, archiveDir, true);

        } catch (Exception e) {
          Log.d(TAG, "Exception: ", e);
          // clear the changes made.
          SharedPrefUtils.setClientKey(context, migrationParams, null);
          SharedPrefUtils.setServerKey(context, migrationParams, null, "");
          if (newWalletFile.exists()) {
            newWalletFile.delete();
          }
        }
      }
    } else {
      Log.d(
          TAG,
          "Key file or wallet file not found - no migration required - "
              + String.format(
                  "keyFile: %s (exists: %s), walletFile: %s (exists: %s)",
                  keyFile.toString(),
                  keyFile.exists(),
                  walletFile.toString(),
                  walletFile.exists()));
    }

    Log.d(TAG, "********* MIGRATION FROM v1.0.262 FINISHED *********");
  }