Пример #1
1
  /** Test copy from an input stream to a file */
  static void testCopyInputStreamToFile() throws IOException {
    testCopyInputStreamToFile(0);
    for (int i = 0; i < 100; i++) {
      testCopyInputStreamToFile(rand.nextInt(32000));
    }

    // FileAlreadyExistsException
    Path target = createTempFile("blah", null);
    try {
      InputStream in = new ByteArrayInputStream(new byte[0]);
      try {
        copy(in, target);
        throw new RuntimeException("FileAlreadyExistsException expected");
      } catch (FileAlreadyExistsException ignore) {
      }
    } finally {
      delete(target);
    }
    Path tmpdir = createTempDirectory("blah");
    try {
      if (TestUtil.supportsLinks(tmpdir)) {
        Path link = createSymbolicLink(tmpdir.resolve("link"), tmpdir.resolve("target"));
        try {
          InputStream in = new ByteArrayInputStream(new byte[0]);
          try {
            copy(in, link);
            throw new RuntimeException("FileAlreadyExistsException expected");
          } catch (FileAlreadyExistsException ignore) {
          }
        } finally {
          delete(link);
        }
      }
    } finally {
      delete(tmpdir);
    }

    // nulls
    try {
      copy((InputStream) null, target);
      throw new RuntimeException("NullPointerException expected");
    } catch (NullPointerException ignore) {
    }
    try {
      copy(new ByteArrayInputStream(new byte[0]), (Path) null);
      throw new RuntimeException("NullPointerException expected");
    } catch (NullPointerException ignore) {
    }
  }
Пример #2
0
 public void drop() throws Exception {
   for (int i = 0; i < 16; i++) {
     File subDir = new File(mainDir, String.valueOf(i) + ".dir");
     for (int j = 0; j < 16; j++) {
       if (databases[i][j] != null) {
         File dbFile = new File(subDir, String.valueOf(j) + ".dat");
         if (dbFile.exists()) {
           try {
             Files.delete(dbFile.toPath());
           } catch (SecurityException | IOException e) {
             throw new Exception("Access violation: cannon delete database file");
           }
         }
       }
     }
     if (subDir.exists()) {
       try {
         Files.delete(subDir.toPath());
       } catch (DirectoryNotEmptyException e) {
         throw new Exception("Cannot remove table subdirectory. Redundant files");
       } catch (SecurityException | IOException e) {
         throw new Exception("Access violation: cannot delete database subdirectory");
       }
     }
   }
   try {
     Files.delete(mainDir.toPath());
   } catch (DirectoryNotEmptyException e) {
     throw new Exception("Cannot remove main table directory. Redundant files");
   } catch (SecurityException | IOException e) {
     throw new Exception("Access violation: cannot delete main database directory");
   }
 }
  private Toolbox loadToolbox() throws IOException, URISyntaxException {

    Path foundPath = findToolsDir();

    Toolbox box;
    if (Files.isDirectory(foundPath)) {
      box = new Toolbox(foundPath);

      Path tempDir = Files.createTempDirectory(TOOLS_DIR_NAME);
      Path tempZipFile = tempDir.resolve(TOOLS_ZIP_NAME);

      dirToZip(foundPath, tempZipFile);
      byte[] zipContents = Files.readAllBytes(tempZipFile);
      box.setZipContents(zipContents);
      Files.delete(tempZipFile);
      Files.delete(tempDir);
    }

    // found tools zip
    else {
      FileSystem fs = FileSystems.newFileSystem(foundPath, null);
      Path toolsPath = fs.getPath(TOOLS_DIR_NAME);
      box = new Toolbox(toolsPath);

      byte[] zipContents = Files.readAllBytes(foundPath);
      box.setZipContents(zipContents);
    }

    return box;
  }
  /**
   * Check uploading files and create attachments
   *
   * @throws Exception
   */
  @Test
  public void testCreateAttachment() throws Exception {

    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Files.delete(Paths.get(storagePath + attachment.getPreviewPath()));
    Files.delete(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(
        attachment.getMimeType().equals("image/png")
            && messageResponse.getCode() == 0
            && isExistPreview
            && isExistImage);
  }
  /* Function Name: decryptSplitFileHandler
  // Description: Handles the decryption of split files
  // Calling Function: decryptFileHandler
  // Parameters: File parent - file to be decrypted
  //             String indent - indentation for log file
  */
  private void decryptSplitFileHandler(File parent, String indent) {

    try {

      log.write(indent.concat(parent.getName()).concat("\n"));

      String dePath = fileOne.getAbsolutePath();
      String deName = fileOne.getName().substring(2, (fileOne.getName().length() - 1));

      dePath = dePath.substring(0, (dePath.length() - fileOne.getName().length()));
      dePath = dePath.concat(deName);

      StatusGuiBuilder.updateStatusGui(fname);

      crypto.doSplitDecrypt(fileOne, fileTwo, new File(dePath));

      decryptSplitFileHandlerHelper(dePath);

      Files.delete(fileOne.toPath());
      Files.delete(fileTwo.toPath());

    } catch (IOException ex) {
      Logger.getLogger(DirectoryStructureDecryptionHandler.class.getName())
          .log(Level.SEVERE, null, ex);
    }
  }
Пример #6
0
 public void deleteOld(String fileName) throws IOException {
   if (fileName == null || fileName.isEmpty()) return;
   Path pathToFile = Paths.get(getRoot());
   if (Files.exists(pathToFile.resolve(fileName))) {
     Files.delete(pathToFile.resolve(fileName));
   }
   if (Files.exists(pathToFile.resolve(thumb_pre.concat(fileName)))) {
     Files.delete(pathToFile.resolve(thumb_pre.concat(fileName)));
   }
 }
Пример #7
0
 private void rmDir(Path path) throws IOException {
   try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
     for (Path file : newDirectoryStream) {
       if (Files.isDirectory(file)) {
         rmDir(file);
       } else {
         Files.delete(file);
       }
     }
     Files.delete(path);
   }
 }
  @Test
  public void compilationDatabaseFetchedFromCacheAlsoFetchesSymlinkTreeOrHeaderMap()
      throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "compilation_database", tmp);
    workspace.setUp();
    ProjectFilesystem filesystem = new FakeProjectFilesystem();

    // This test only fails if the directory cache is enabled and we don't update
    // the header map/symlink tree correctly when fetching from the cache.
    workspace.enableDirCache();

    addLibraryHeaderFiles(workspace);

    BuildTarget target =
        BuildTargetFactory.newInstance("//:library_with_header#default,compilation-database");

    // Populate the cache with the built rule
    workspace.buildAndReturnOutput(target.getFullyQualifiedName());

    Path headerSymlinkTreeFolder =
        BuildTargets.getGenPath(
            filesystem,
            target.withFlavors(
                ImmutableFlavor.of("default"), CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR),
            "%s");
    Path exportedHeaderSymlinkTreeFolder =
        BuildTargets.getGenPath(
            filesystem,
            target.withFlavors(
                ImmutableFlavor.of("default"),
                CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR),
            "%s");

    // Validate the symlink tree/header maps
    verifyHeaders(workspace, headerSymlinkTreeFolder, "bar.h", "baz.h", "blech_private.h");
    verifyHeaders(workspace, exportedHeaderSymlinkTreeFolder, "bar.h", "baz.h");

    // Delete the newly-added files and build again
    Files.delete(workspace.getPath("baz.h"));
    Files.delete(workspace.getPath("blech_private.h"));
    workspace.buildAndReturnOutput(target.getFullyQualifiedName());
    verifyHeaders(workspace, headerSymlinkTreeFolder, "bar.h");
    verifyHeaders(workspace, exportedHeaderSymlinkTreeFolder, "bar.h");

    // Restore the headers, build again, and check the symlink tree/header maps
    addLibraryHeaderFiles(workspace);
    workspace.buildAndReturnOutput(target.getFullyQualifiedName());
    verifyHeaders(workspace, headerSymlinkTreeFolder, "bar.h", "baz.h", "blech_private.h");
    verifyHeaders(workspace, exportedHeaderSymlinkTreeFolder, "bar.h", "baz.h");
  }
Пример #9
0
 public void delete() throws IOException {
   if (Files.exists(fileTmp)) {
     Files.delete(fileTmp);
   }
   if (Files.exists(fileOld)) {
     Files.delete(fileOld);
   }
   if (Files.exists(fileNew)) {
     Files.delete(fileNew);
   }
   if (Files.exists(file)) {
     Files.delete(file);
   }
 }
Пример #10
0
 private void closeResources() throws IOException {
   if (out != null) {
     out.close();
   }
   if (in != null) {
     in.close();
   }
   if (socket != null) {
     socket.close();
   }
   if (fileName != null) {
     Files.delete(Paths.get(fileName));
     Files.delete(Paths.get("edited_" + fileName));
   }
 }
Пример #11
0
  @Test
  public void test() throws Exception {
    Module module =
        new Module(
            "test",
            new Version("1.0.0", new LiquibaseMigration(), new AntMigration("test-ant_1.0.0.xml")));

    Connection conn = DriverManager.getConnection("jdbc:h2:mem:test", "sa", "sa");
    Path path = Paths.get("solidbase-test-dir");

    try {
      Solidbase solidbase = new Solidbase();
      solidbase.migrate(
          conn, Thread.currentThread().getContextClassLoader(), new H2Database(), module);

      Integer count = selectIntFromDatabase(conn, "SELECT COUNT(*) FROM PERSON");
      assertEquals(0, count.intValue());

      String version =
          selectStringFromDatabase(conn, "SELECT VERSION FROM VERSIONS WHERE MODULE_ID='test'");
      assertEquals("1.0.0", version);

      assertTrue(Files.exists(path));
      assertTrue(Files.isDirectory(path));

    } finally {
      ignoreException(() -> conn.close());
      ignoreException(() -> Files.delete(path));
    }
  }
Пример #12
0
 public void delete(String dir, String fileName) {
   try {
     Files.delete(Paths.get(dir, fileName));
   } catch (IOException e) {
     // TODO:: throw an appropriate exception
   }
 }
Пример #13
0
  /** Check that a cancelled key will never be queued */
  static void testCancel(Path dir) throws IOException {
    System.out.println("-- Cancel --");

    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {

      System.out.format("register %s for events\n", dir);
      WatchKey myKey = dir.register(watcher, new WatchEvent.Kind<?>[] {ENTRY_CREATE});
      checkKey(myKey, dir);

      System.out.println("cancel key");
      myKey.cancel();

      // create a file in the directory
      Path file = dir.resolve("mars");
      System.out.format("create: %s\n", file);
      Files.createFile(file);

      // poll for keys - there will be none
      System.out.println("poll...");
      try {
        WatchKey key = watcher.poll(3000, TimeUnit.MILLISECONDS);
        if (key != null) throw new RuntimeException("key should not be queued");
      } catch (InterruptedException x) {
        throw new RuntimeException(x);
      }

      // done
      Files.delete(file);

      System.out.println("OKAY");
    }
  }
 private void cleanupTmpFile(Path filePath) {
   try {
     Files.delete(filePath);
   } catch (Exception e) {
     _log.warn("Failed to delete tmp file {}", filePath);
   }
 }
Пример #15
0
  @Test
  public void executeTests() throws IOException {
    String testBase = server.whereIs("/selenium-server/tests");
    Path outputFile =
        Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value())
            .resolve("core-test-suite" + browser.replace('*', '-') + ".html");
    if (Files.exists(outputFile)) {
      Files.delete(outputFile);
    }
    Files.createDirectories(outputFile.getParent());

    String result =
        new HTMLLauncher()
            .runHTMLSuite(
                browser,
                // We need to do this because the path relativizing code in java.net.URL is
                // clearly having a bad day. "/selenium-server/tests" appended to "../tests/"
                // ends up as "/tests" rather than "/selenium-server/tests" as you'd expect.
                testBase + "/TestSuite.html",
                testBase + "/TestSuite.html",
                outputFile.toFile(),
                TimeUnit.MINUTES.toSeconds(5),
                null);

    assertEquals("PASSED", result);
  }
Пример #16
0
  /**
   * Aborts a temp block.
   *
   * @param sessionId the id of session
   * @param blockId the id of block
   * @throws BlockDoesNotExistException if block id can not be found in temporary blocks
   * @throws BlockAlreadyExistsException if block id already exists in committed blocks
   * @throws InvalidWorkerStateException if block id is not owned by session id
   * @throws IOException if I/O errors occur when deleting the block file
   */
  private void abortBlockInternal(long sessionId, long blockId)
      throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException,
          IOException {
    long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE);
    try {
      String path;
      TempBlockMeta tempBlockMeta;
      mMetadataReadLock.lock();
      try {
        checkTempBlockOwnedBySession(sessionId, blockId);
        tempBlockMeta = mMetaManager.getTempBlockMeta(blockId);
        path = tempBlockMeta.getPath();
      } finally {
        mMetadataReadLock.unlock();
      }

      // Heavy IO is guarded by block lock but not metadata lock. This may throw IOException.
      Files.delete(Paths.get(path));

      mMetadataWriteLock.lock();
      try {
        mMetaManager.abortTempBlockMeta(tempBlockMeta);
      } catch (BlockDoesNotExistException e) {
        throw Throwables.propagate(e); // We shall never reach here
      } finally {
        mMetadataWriteLock.unlock();
      }
    } finally {
      mLockManager.unlockBlock(lockId);
    }
  }
  @Test
  public void testAutoWriterStartsAndStops() throws Exception {
    MetricsLimiterStateManager manager = null;
    try {
      manager =
          new MetricsLimiterStateManager.Builder()
              .setStateFile(STATE_FILE)
              .setStateFileFlushInterval(Duration.millis(1)) // There is a 500ms sleep in the loop.
              .build(_marks);

      manager.startAutoWriter();
      Thread.yield();

      Assert.assertTrue(manager.isAlive());

      // Give the file a chance to be written
      assertStateFileAppears();

      Files.delete(STATE_FILE);
      manager.stopAutoWriter(true);

      // Final write
      assertStateFileAppears();
    } finally {
      if (manager != null) {
        manager.stopAutoWriter(true);
      }
    }
  }
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes atts) throws IOException {

        file.toFile().setWritable(true);
        Files.delete(file);
        return FileVisitResult.CONTINUE;
      }
Пример #19
0
  public void run() throws Throwable {
    if (Files.notExists(jdkMods)) {
      return;
    }

    if (!CompilerUtils.compile(src, classes)) {
      throw new AssertionError("Compilation failure. See log.");
    }

    String modName = "test";
    Files.createDirectories(jmods);
    Files.createDirectories(jars);
    Path jarfile = jars.resolve("test.jar");
    JarUtils.createJarFile(jarfile, classes);

    Path image = Paths.get("mysmallimage");
    runJmod(jarfile.toString(), modName);
    runJlink(image, modName, "--compress", "2");
    execute(image, modName);

    Files.delete(jmods.resolve(modName + ".jmod"));

    image = Paths.get("myimage");
    runJmod(classes.toString(), modName);
    runJlink(image, modName);
    execute(image, modName);
  }
  public void unloadAndDelete(SmallModuleEntry sme) {
    UploaderPlugin up;
    synchronized (this) {
      up = sme.up;
      sme.up = null; // deactivate initiated here
      if (up == null) {
        Path zipPath = UploaderPlugin.getLocalPath(updateLocation, sme);
        if (Files.exists(zipPath)) {
          try {
            Files.delete(zipPath);
          } catch (Exception a) {
            System.out.println("could not delete unactive plugin " + sme.getName());
          }
        }
        return;
      }
    }

    try {
      up.destroy();
    } catch (Exception a) {
      System.out.println("could not destory plugin " + sme.getName());
      a.printStackTrace();
    }
  }
  @After
  public void tearDown() throws Exception {

    // Удаляем тестовый фаил
    Files.delete(Paths.get(pathTempFile));

    // Удаляем тестовые папки и файлы
    Files.walkFileTree(
        Paths.get(storagePath),
        new SimpleFileVisitor<Path>() {

          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
          }
        });
  }
Пример #22
0
  @Test
  public void testCreate_NonEmpty() throws IOException {
    final Path root = random();
    final Path txt = root.resolve("test.txt");
    try {
      Files.createDirectory(root);
      Files.createFile(txt);

      final SitePaths site = new SitePaths(root);
      assertFalse(site.isNew);
      assertEquals(root, site.site_path);
    } finally {
      Files.delete(txt);
      Files.delete(root);
    }
  }
Пример #23
0
 public void delete() {
   try {
     Files.delete(file);
   } catch (IOException e) {
     throw New.unchecked(e);
   }
 }
Пример #24
0
 public static boolean delete(File file) throws IOException {
   try {
     Files.delete(file.toPath());
     return true;
   } catch (NoSuchFileException | DirectoryNotEmptyException e) {
     return false;
   }
 }
Пример #25
0
 // Needed to remove the file once the Stream object is no more used.
 // @checkstyle NoFinalizerCheck (2 lines)
 // @checkstyle ProtectedMethodInFinalClassCheck (3 lines)
 @Override
 protected void finalize() throws Throwable {
   try {
     Files.delete(Paths.get(this.file.getAbsolutePath()));
   } finally {
     super.finalize();
   }
 }
Пример #26
0
 public static java.io.IOException deleteFile(java.nio.file.Path fh) {
   try {
     java.nio.file.Files.delete(fh);
   } catch (java.io.IOException ex) {
     if (java.nio.file.Files.exists(fh, LINKOPTS_NONE)) return ex; // genuine error
   }
   return null;
 }
Пример #27
0
 public static void deleteFile(String filename) {
   try {
     Path path = FileSystems.getDefault().getPath(filename);
     Files.delete(path);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Пример #28
0
 /*
  * Deletes the jaxp.properties.
  */
 static void deleteJAXPProps() throws IOException {
   Path filePath = getJAXPPropsPath();
   Files.delete(filePath);
   Path bakFilePath = filePath.resolveSibling(JAXP_PROPS_BAK);
   if (Files.exists(bakFilePath)) {
     Files.move(bakFilePath, filePath);
   }
 }
Пример #29
0
 public final void tearDown() throws IOException {
   try {
     java.nio.file.Files.delete(fileThreadLocal.get());
   } catch (IOException e) {
     logger.log(Level.WARNING, "Unable to delete file: " + fileThreadLocal.get(), e);
   }
   fileThreadLocal.remove();
 }
      @Override
      public FileVisitResult postVisitDirectory(Path directory, IOException ex) throws IOException {

        if (ex != null) throw ex;

        Files.delete(directory);
        return FileVisitResult.CONTINUE;
      }