示例#1
0
    @Override
    public void trayEventOccurred(TrayEvent event) {
      switch (event.getType()) {
        case OPEN_FOLDER:
          File folder = new File((String) event.getArgs().get(0));
          FileUtil.openFile(folder);

          break;

        case PREFERENCES:
          settingsDialog.setVisible(true);
          break;

        case DONATE:
          FileUtil.browsePage(Constants.APPLICATION_DONATE_URL);
          break;

        case WEBSITE:
          FileUtil.browsePage(Constants.APPLICATION_URL);
          break;

        case QUIT:
          doShutdown();
          break;

        default:
          logger.log(Level.WARNING, "Unknown tray event type: {0}", event);
          // Fressen.
      }
    }
  @Override
  public void execute() throws Exception {
    if (!FileUtil.symlinksSupported()) {
      return; // no symbolic links on Windows
    }

    File inFolder = pickFolder(3121);
    File symlinkFile = new File(inFolder + "/newFile-" + Math.random());

    log(this, symlinkFile.getAbsolutePath());

    FileUtil.createSymlink("/does/not/exist", symlinkFile);
  }
示例#3
0
  private static List<File> getRecursiveFileListNoSort(
      File root, boolean includeDirectories, boolean followSymlinkDirectories) {
    List<File> result = new ArrayList<File>();
    List<File> filesDirs = Arrays.asList(root.listFiles());

    for (File file : filesDirs) {
      boolean isDirectory = file.isDirectory();
      boolean isSymlinkDirectory = isDirectory && FileUtil.isSymlink(file);
      boolean includeFile = !isDirectory || includeDirectories;
      boolean followDirectory =
          (isSymlinkDirectory && followSymlinkDirectories) || (isDirectory && !isSymlinkDirectory);

      if (includeFile) {
        result.add(file);
      }

      if (followDirectory) {
        List<File> deeperList =
            getRecursiveFileListNoSort(file, includeDirectories, followSymlinkDirectories);
        result.addAll(deeperList);
      }
    }

    return result;
  }
示例#4
0
  /*     pictures/
   *       some/
   *         folder/
   *           file.jpg
   *       some\\folder/
   * ->       file.jpg
   *
   *  relativeNormalizedPath = pictures/some\\folder/file.jpg
   *
   *  -> createable: pictures/somefolder (filename conflict)/file.jpg
   *
   *  http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx
   */
  public NormalizedPath toCreatable(String filenameSuffix, boolean canExist) throws Exception {
    if (canExist) {
      return toCreatable(filenameSuffix, 0);
    } else {
      NormalizedPath creatableNormalizedPath = null;
      int attempt = 0;

      do {
        creatableNormalizedPath = toCreatable(filenameSuffix, attempt);
        boolean exists = FileUtil.exists(creatableNormalizedPath.toFile());

        // TODO [medium] The exists-check should be in the pathPart-loop, b/c what if fileB is a
        // FILE in this path: folderA/fileB/folderC/file1.jpg

        if (!exists) {
          return creatableNormalizedPath;
        }

        logger.log(
            Level.WARNING, " - File exists, trying new file: " + creatableNormalizedPath.toFile());
      } while (attempt++ < 10);

      throw new Exception(
          "Cannot create creatable path; " + creatableNormalizedPath + " attempts: " + attempt);
    }
  }
示例#5
0
    private PartialFileHistory guessLastFileHistoryForFileWithMatchingChecksum(
        FileProperties fileProperties,
        Collection<PartialFileHistory> fileHistoriesWithSameChecksum) {
      PartialFileHistory lastFileHistory = null;

      // Check if they do not exist anymore --> assume it has moved!
      // We choose the best fileHistory to base on as follows:

      // 1. Ensure that it was modified at the same time and is the same size
      // 2. Check the fileHistory was deleted and the file does not actually exists
      // 3. Choose the one with the longest matching tail of the path to the new path

      for (PartialFileHistory fileHistoryWithSameChecksum : fileHistoriesWithSameChecksum) {
        FileVersion lastVersion = fileHistoryWithSameChecksum.getLastVersion();

        if (fileProperties.getLastModified() != lastVersion.getLastModified().getTime()
            || fileProperties.getSize() != lastVersion.getSize()) {
          continue;
        }

        File lastVersionOnLocalDisk =
            new File(config.getLocalDir() + File.separator + lastVersion.getPath());

        if (lastVersion.getStatus() != FileStatus.DELETED
            && !FileUtil.exists(lastVersionOnLocalDisk)) {
          if (lastFileHistory == null) {
            lastFileHistory = fileHistoryWithSameChecksum;
          } else {
            String filePath = fileProperties.getRelativePath();
            String currentPreviousPath = lastFileHistory.getLastVersion().getPath();
            String candidatePreviousPath = fileHistoryWithSameChecksum.getLastVersion().getPath();

            for (int i = 0; i < filePath.length(); i++) {
              if (!filePath.regionMatches(
                  filePath.length() - i,
                  candidatePreviousPath,
                  candidatePreviousPath.length() - i,
                  i)) {
                // The candidate no longer matches, take the current path.
                break;
              }
              if (!filePath.regionMatches(
                  filePath.length() - i,
                  currentPreviousPath,
                  currentPreviousPath.length() - i,
                  i)) {
                // The current previous path no longer matches, take the new candidate
                lastFileHistory = fileHistoryWithSameChecksum;
                break;
              }
            }
          }
        }
      }

      return lastFileHistory;
    }
示例#6
0
  @Test
  public void testIsEncryptedFileFalse() throws Exception {
    File tempDirectory = TestFileUtil.createTempDirectoryInSystemTemp();
    File testFile = new File(tempDirectory + "/somefile");

    FileUtil.writeToFile(new byte[] {1, 2, 3}, testFile);
    assertFalse(CipherUtil.isEncrypted(testFile));

    TestFileUtil.deleteDirectory(tempDirectory);
  }
  @Override
  public void execute() throws Exception {
    if (!FileUtil.symlinksSupported()) {
      return; // no symbolic links on Windows
    }

    File symlinkFile =
        pickFileOrFolder(
            2121,
            new FileFilter() {
              @Override
              public boolean accept(File file) {
                return FileUtil.isSymlink(file);
              }
            });

    log(this, symlinkFile.getAbsolutePath());

    symlinkFile.delete();
    FileUtil.createSymlink("/does/not/exist/" + Math.random(), symlinkFile);
  }
  @Override
  public void execute() throws Exception {
    if (!EnvironmentUtil.symlinksSupported()) {
      return; // no symbolic links on Windows
    }

    File file = pickFile(1782);

    log(this, file.getAbsolutePath());

    file.delete();
    FileUtil.createSymlink("/etc/init.d", file);
  }
示例#9
0
  public static byte[] decrypt(InputStream fromInputStream, String password) throws IOException {
    CipherSession cipherSession = new CipherSession(password);
    MultiCipherInputStream cipherInputStream =
        new MultiCipherInputStream(fromInputStream, cipherSession);
    ByteArrayOutputStream plaintextOutputStream = new ByteArrayOutputStream();

    FileUtil.appendToOutputStream(cipherInputStream, plaintextOutputStream);

    cipherInputStream.close();
    plaintextOutputStream.close();

    return plaintextOutputStream.toByteArray();
  }
示例#10
0
  public static void encrypt(
      InputStream plaintextInputStream,
      OutputStream ciphertextOutputStream,
      List<CipherSpec> cipherSuites,
      String password)
      throws IOException {
    CipherSession cipherSession = new CipherSession(password);
    OutputStream multiCipherOutputStream =
        new MultiCipherOutputStream(ciphertextOutputStream, cipherSuites, cipherSession);

    FileUtil.appendToOutputStream(plaintextInputStream, multiCipherOutputStream);

    multiCipherOutputStream.close();
    ciphertextOutputStream.close();
  }
示例#11
0
  private void downloadAndDecryptMultiChunks(Set<MultiChunkEntry> unknownMultiChunks)
      throws StorageException, IOException {
    logger.log(Level.INFO, "- Downloading and extracting multichunks ...");
    TransferManager transferManager = config.getConnection().createTransferManager();

    // TODO [medium] Check existing files by checksum and do NOT download them if they exist
    // locally, or copy them

    for (MultiChunkEntry multiChunkEntry : unknownMultiChunks) {
      File localEncryptedMultiChunkFile =
          config.getCache().getEncryptedMultiChunkFile(multiChunkEntry.getId());
      File localDecryptedMultiChunkFile =
          config.getCache().getDecryptedMultiChunkFile(multiChunkEntry.getId());
      MultiChunkRemoteFile remoteMultiChunkFile =
          new MultiChunkRemoteFile(
              localEncryptedMultiChunkFile
                  .getName()); // TODO [low] Make MultiChunkRemoteFile class, or something like that

      logger.log(
          Level.INFO,
          "  + Downloading multichunk " + StringUtil.toHex(multiChunkEntry.getId()) + " ...");
      transferManager.download(remoteMultiChunkFile, localEncryptedMultiChunkFile);
      result.downloadedMultiChunks.add(multiChunkEntry);

      logger.log(
          Level.INFO,
          "  + Decrypting multichunk " + StringUtil.toHex(multiChunkEntry.getId()) + " ...");
      InputStream multiChunkInputStream =
          config
              .getTransformer()
              .createInputStream(new FileInputStream(localEncryptedMultiChunkFile));
      OutputStream decryptedMultiChunkOutputStream =
          new FileOutputStream(localDecryptedMultiChunkFile);

      // TODO [medium] Calculate checksum while writing file, to verify correct content
      FileUtil.appendToOutputStream(multiChunkInputStream, decryptedMultiChunkOutputStream);

      decryptedMultiChunkOutputStream.close();
      multiChunkInputStream.close();

      logger.log(
          Level.FINE,
          "  + Locally deleting multichunk " + StringUtil.toHex(multiChunkEntry.getId()) + " ...");
      localEncryptedMultiChunkFile.delete();
    }

    transferManager.disconnect();
  }
示例#12
0
  private void removeDeletedFiles(
      DatabaseVersion newDatabaseVersion, List<PartialFileHistory> fileHistoriesWithLastVersion) {
    logger.log(Level.FINER, "- Looking for deleted files ...");

    for (PartialFileHistory fileHistory : fileHistoriesWithLastVersion) {
      // Ignore this file history if it has been updated in this database version before (file
      // probably renamed!)
      if (newDatabaseVersion.getFileHistory(fileHistory.getFileHistoryId()) != null) {
        continue;
      }

      // Check if file exists, remove if it doesn't
      FileVersion lastLocalVersion = fileHistory.getLastVersion();
      File lastLocalVersionOnDisk =
          new File(config.getLocalDir() + File.separator + lastLocalVersion.getPath());

      // Ignore this file history if the last version is marked "DELETED"
      if (lastLocalVersion.getStatus() == FileStatus.DELETED) {
        continue;
      }

      // Add this file history if a new file with this name has been added (file type change)
      PartialFileHistory newFileWithSameName =
          getFileHistoryByPathFromDatabaseVersion(
              newDatabaseVersion, fileHistory.getLastVersion().getPath());

      // If file has VANISHED, mark as DELETED
      if (!FileUtil.exists(lastLocalVersionOnDisk) || newFileWithSameName != null) {
        PartialFileHistory deletedFileHistory =
            new PartialFileHistory(fileHistory.getFileHistoryId());
        FileVersion deletedVersion = lastLocalVersion.clone();

        deletedVersion.setStatus(FileStatus.DELETED);
        deletedVersion.setVersion(fileHistory.getLastVersion().getVersion() + 1);
        deletedVersion.setUpdated(new Date());

        logger.log(Level.FINER, "  + Deleted: Adding DELETED version: {0}", deletedVersion);
        logger.log(Level.FINER, "                           based on: {0}", lastLocalVersion);

        deletedFileHistory.addFileVersion(deletedVersion);
        newDatabaseVersion.addFileHistory(deletedFileHistory);
      }
    }
  }
  private void updateTable(LsFolderRequest lsRequest, LsFolderResponse lsResponse) {
    logger.log(
        Level.INFO,
        "Detail panel: Updating table with "
            + lsResponse.getResult().getFileVersions().size()
            + " file versions ...");

    // Add new file version items
    List<PartialFileHistory> fileVersions =
        new ArrayList<>(lsResponse.getResult().getFileVersions().values());
    selectedFileHistory = fileVersions.get(0);

    for (FileVersion fileVersion : selectedFileHistory.getFileVersions().values()) {
      String checksumStr =
          (fileVersion.getChecksum() != null) ? fileVersion.getChecksum().toString() : "";

      TableItem tableItem = new TableItem(historyTable, SWT.NONE);

      tableItem.setData(fileVersion);
      tableItem.setImage(COLUMN_INDEX_STATUS, getStatusImage(fileVersion.getStatus()));
      tableItem.setText(COLUMN_INDEX_PATH, fileVersion.getPath());
      tableItem.setText(COLUMN_INDEX_VERSION, Long.toString(fileVersion.getVersion()));
      tableItem.setText(COLUMN_INDEX_TYPE, fileVersion.getType().toString());
      tableItem.setText(COLUMN_INDEX_SIZE, FileUtil.formatFileSize(fileVersion.getSize()));
      tableItem.setText(COLUMN_INDEX_POSIX_PERMS, fileVersion.getPosixPermissions());
      tableItem.setText(COLUMN_INDEX_DOS_ATTRS, fileVersion.getDosAttributes());
      tableItem.setText(COLUMN_INDEX_CHECKSUM, checksumStr);
      tableItem.setText(COLUMN_INDEX_LAST_MODIFIED, "" + fileVersion.getLastModified());
      tableItem.setText(COLUMN_INDEX_UPDATED, "" + fileVersion.getUpdated());
    }

    if (historyTable.getItemCount() > 0) {
      restoreButton.setEnabled(false);
      historyTable.select(historyTable.getItemCount() - 1);
    }

    resizeColumns();
  }
示例#14
0
  public NormalizedPath withSuffix(String filenameSuffix, boolean canExist) throws Exception {
    if (canExist) {
      return toCreatable(filenameSuffix, 0);
    } else {
      NormalizedPath creatableNormalizedPath = null;
      int attempt = 0;

      do {
        String aFilenameSuffix = (attempt > 0) ? filenameSuffix + " " + attempt : filenameSuffix;
        creatableNormalizedPath =
            new NormalizedPath(
                root, addFilenameConflictSuffix(normalizedPath.toString(), aFilenameSuffix));
        boolean exists = FileUtil.exists(creatableNormalizedPath.toFile());

        if (!exists) {
          return creatableNormalizedPath;
        }
      } while (attempt++ < 200);

      throw new Exception(
          "Cannot create path with suffix; " + attempt + " attempts: " + creatableNormalizedPath);
    }
  }
  public static void assertFileEquals(
      File expectedFile, File actualFile, FileChange... allowedChanges)
      throws ArrayComparisonFailure, Exception {
    if (expectedFile == null && actualFile == null) {
      return;
    }

    assertNotNull(
        "Files are not equal: Actual file is " + actualFile + ", expected file is null.",
        expectedFile);
    assertNotNull(
        "Files are not equal: Expected file is " + expectedFile + ", actual file is null.",
        actualFile);

    Path root = Paths.get(actualFile.getAbsolutePath()).getRoot();
    FileVersionComparator fileVersionComparator = new FileVersionComparator(root.toFile(), "SHA1");

    if (!FileUtil.exists(expectedFile)) {
      fail("Files are not equal: Expected file " + expectedFile + " does not exist.");
    }

    if (!FileUtil.exists(actualFile)) {
      fail("Files are not equal: Actual file " + actualFile + " does not exist.");
    }

    if (FileUtil.isSymlink(actualFile) && FileUtil.isSymlink(expectedFile)) {
      return;
    }

    if (actualFile.isDirectory() != expectedFile.isDirectory()) {
      fail(
          "Files are not equal: Comparing a directory with a file (actual is dir = "
              + actualFile.isDirectory()
              + ", expected is dir = "
              + expectedFile.isDirectory()
              + ")");
    }

    if (actualFile.isDirectory() && expectedFile.isDirectory()) {
      return;
    }

    if (actualFile.length() != expectedFile.length()) {
      fail(
          "Files are not equal: Actual file size ("
              + actualFile
              + " = "
              + actualFile.length()
              + ") does not match expected file size ("
              + expectedFile
              + " = "
              + expectedFile.length()
              + ")");
    }

    byte[] expectedFileChecksum = TestFileUtil.createChecksum(expectedFile);
    byte[] actualFileChecksum = TestFileUtil.createChecksum(actualFile);

    assertArrayEquals(
        "Files are not equal: Actual file checksum ("
            + StringUtil.toHex(actualFileChecksum)
            + ") and expected file checksum ("
            + StringUtil.toHex(expectedFileChecksum)
            + ") do not match.",
        expectedFileChecksum,
        actualFileChecksum);

    FileProperties actualFileProperties =
        fileVersionComparator.captureFileProperties(actualFile, null, true);
    FileProperties expectedFileProperties =
        fileVersionComparator.captureFileProperties(expectedFile, null, true);

    FileVersionComparison fileVersionComparison =
        fileVersionComparator.compare(expectedFileProperties, actualFileProperties, true);

    List<FileChange> allowedChangesList = new ArrayList<FileChange>(Arrays.asList(allowedChanges));
    allowedChangesList.add(FileChange.CHANGED_PATH);

    if (!CollectionUtil.containsOnly(fileVersionComparison.getFileChanges(), allowedChangesList)) {
      fail(
          "Files are not equal: Actual file differs from expected file: "
              + fileVersionComparison.getFileChanges());
    }
  }