Java Code Examples for java.nio.file.Files#createFile()

The following examples show how to use java.nio.file.Files#createFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: D8DexMergerTest.java    From bundletool with Apache License 2.0 6 votes vote down vote up
@Test
public void outputDirectoryNotEmpty_throws() throws Exception {
  Path dexFile = writeTestDataToFile("testdata/dex/classes.dex");
  Files.createFile(outputDir.resolve("a-file.txt"));

  IllegalArgumentException exception =
      assertThrows(
          IllegalArgumentException.class,
          () ->
              new D8DexMerger()
                  .merge(
                      ImmutableList.of(dexFile),
                      outputDir,
                      NO_MAIN_DEX_LIST,
                      /* isDebuggable= */ false,
                      /* minSdkVersion= */ ANDROID_K_API_VERSION));

  assertThat(exception).hasMessageThat().contains("is not empty");
}
 
Example 2
Source File: TestPosixFilePermissions.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Simple test to check posix file permission on createFile().
 * 
 * @throws IOException
 */
@Test
public void testWriteBuffered() throws IOException {
	Path rootPath = Paths.get(clusterUri);

	Path pathToTest = rootPath.resolve("tmp/out6.txt");

	Path path = pathToTest;
	Set<PosixFilePermission> perms = EnumSet.of(
			PosixFilePermission.OWNER_READ,
			PosixFilePermission.OWNER_WRITE,
			PosixFilePermission.GROUP_READ,
			PosixFilePermission.GROUP_WRITE);
	Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));

	Set<PosixFilePermission> perms2 = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS);
	assertNotNull(perms2);
	
	assertTrue(perms2.contains(PosixFilePermission.OWNER_READ));
}
 
Example 3
Source File: EdenProjectFilesystemDelegateTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void computeSha1ViaXattrForFileOutsideMount() throws IOException {
  FileSystem fs =
      Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("user").build());
  Path root = fs.getPath(JIMFS_WORKING_DIRECTORY);
  ProjectFilesystemDelegate delegate = new DefaultProjectFilesystemDelegate(root);

  Path path = fs.getPath("/foo");
  Files.createFile(path);
  byte[] bytes = new byte[] {66, 85, 67, 75};
  Files.write(path, bytes);

  EdenMount mount = createMock(EdenMount.class);
  Config config = ConfigBuilder.createFromText("[eden]", "use_xattr = true");
  EdenProjectFilesystemDelegate edenDelegate =
      new EdenProjectFilesystemDelegate(mount, delegate, config);
  assertEquals(
      "EdenProjectFilesystemDelegate.computeSha1() should return the SHA-1 of a file that is "
          + "outside of the EdenFS root.",
      Sha1HashCode.fromHashCode(Hashing.sha1().hashBytes(bytes)),
      edenDelegate.computeSha1(path));
}
 
Example 4
Source File: MostFilesTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteRecursivelyIfExistsWithUndeletableFile() throws IOException {
  FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
  BuckFSProviderDeleteError bfsProvider = new BuckFSProviderDeleteError(vfs);
  BuckFileSystem bfs = new BuckFileSystem(bfsProvider, "/");
  Path fakeTmpDir = bfs.getPath("/tmp/fake-tmp-dir");
  Path dirToDelete = fakeTmpDir.resolve("delete-me");
  Path childDir = dirToDelete.resolve("child-dir");
  Files.createDirectories(childDir);
  Path readOnlyFile = dirToDelete.resolve("roFile");
  Files.createFile(readOnlyFile);
  Path deletableFile = childDir.resolve("deletableFile");
  Files.createFile(deletableFile);
  bfsProvider.setFileToErrorOnDeletion(readOnlyFile);

  MostFiles.deleteRecursivelyIfExists(dirToDelete);
  assertThat(Files.exists(childDir), is(false));
  assertThat(Files.exists(dirToDelete), is(true));
  assertThat(Files.exists(readOnlyFile), is(true));
}
 
Example 5
Source File: TestAppBundleGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testToPathStreamFromClassPath() throws MalformedURLException, IOException {
  Path mainFolder = temporaryFolder.newFolder().toPath();

  Files.createFile(mainFolder.resolve("a.jar"));
  Files.createFile(mainFolder.resolve("b.jar"));
  Files.createFile(mainFolder.resolve("xyz-dremio.jar"));
  Files.createDirectory(mainFolder.resolve("www-dremio"));
  Files.createFile(mainFolder.resolve("www-dremio/foo.jar"));

  assertThat(
      AppBundleGenerator
          .toPathStream(
              Arrays.asList(mainFolder.resolve("a.jar").toString(), mainFolder.resolve(".*-dremio").toString()))
          .collect(Collectors.toList()),
      is(equalTo(Arrays.asList(mainFolder.resolve("a.jar"), mainFolder.resolve("www-dremio")))));
}
 
Example 6
Source File: AarGeneratorActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testCheckFlags_MissingClasses() throws IOException, OptionsParsingException {
  Path manifest = tempDir.resolve("AndroidManifest.xml");
  Files.createFile(manifest);
  Path rtxt = tempDir.resolve("R.txt");
  Files.createFile(rtxt);

  String[] args = new String[] {"--manifest", manifest.toString(), "--rtxt", rtxt.toString()};
  OptionsParser optionsParser =
      OptionsParser.builder().optionsClasses(AarGeneratorOptions.class).build();
  optionsParser.parse(args);
  AarGeneratorOptions options = optionsParser.getOptions(AarGeneratorOptions.class);
  thrown.expect(IllegalArgumentException.class);
  thrown.expectMessage("classes must be specified. Building an .aar without"
        + " classes is unsupported.");
  AarGeneratorAction.checkFlags(options);
}
 
Example 7
Source File: TestBundleFileSystem.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
@Test
public void setLastModifiedTime() throws Exception {
	Path root = fs.getRootDirectories().iterator().next();

	Path folder = root.resolve("folder");
	Files.createDirectory(folder);

	Path file = root.resolve("file");
	Files.createFile(file);

	int manyDays = 365 * 12;
	FileTime someTimeAgo = FileTime.from(manyDays, TimeUnit.DAYS);
	Files.setLastModifiedTime(folder, someTimeAgo);
	Files.setLastModifiedTime(file, someTimeAgo);
	Files.setLastModifiedTime(root, someTimeAgo);

	// Should be equal, +/- 2 seconds (allowing precision loss)
	assertEquals((double) someTimeAgo.toMillis(), Files
			.getLastModifiedTime(folder).toMillis(), 2001);
	assertEquals((double) someTimeAgo.toMillis(), Files
			.getLastModifiedTime(file).toMillis(), 2001);

	// Fails as we'll get back -1 instead
	// assertEquals((double)someTimeAgo.toMillis(),
	// Files.getLastModifiedTime(root).toMillis(), 2001);
}
 
Example 8
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testSymbolicLinks_lookupOfAbsoluteSymlinkPathFromRelativePath() throws IOException {
  // relative path lookups are in the FileSystemView for the working directory
  // this tests that when an absolute path is encountered, the lookup handles it correctly

  Files.createDirectories(path("/foo/bar/baz"));
  Files.createFile(path("/foo/bar/baz/file"));
  Files.createDirectories(path("one/two/three"));
  Files.createSymbolicLink(path("/work/one/two/three/link"), path("/foo/bar"));

  assertThatPath("one/two/three/link/baz/file").isSameFileAs("/foo/bar/baz/file");
}
 
Example 9
Source File: TestVerboseFS.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** Test copy */
public void testCopy() throws IOException {
  InfoStreamListener stream = new InfoStreamListener("copy");
  Path dir = wrap(createTempDir(), stream);
  Files.createFile(dir.resolve("foobar"));
  Files.copy(dir.resolve("foobar"), dir.resolve("baz"));
  assertTrue(stream.sawMessage());

  expectThrows(IOException.class, () -> Files.copy(dir.resolve("nonexistent"), dir.resolve("something")));
}
 
Example 10
Source File: CleanupReleasedSnapshotsRepositoryPurgeTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonArtifactFile()
    throws Exception
{

    RepositoryRegistry repositoryRegistry = applicationContext.getBean( ArchivaRepositoryRegistry.class);
    ManagedRepository managedRepository = repositoryRegistry.getManagedRepository( TEST_REPO_ID );
    repositoryRegistry.removeRepository( managedRepository );
    repositoryRegistry.putRepository(
        getRepoConfiguration( TEST_REPO_ID, TEST_REPO_NAME ));

    String repoRoot = prepareTestRepos();

    // test listeners for the correct artifacts
    listenerControl.replay();

    Path file = Paths.get(repoRoot, INDEX_PATH );
    if ( !Files.exists(file) )
    {
        // help windauze to create directory with .
        Files.createDirectories( file.getParent() );
        Files.createFile( file );
    }
    assertTrue( Files.exists(file) );

    repoPurge.process( INDEX_PATH );

    listenerControl.verify();

    assertTrue( Files.exists(file) );
}
 
Example 11
Source File: DeleteInterference.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void deleteAndRecreateDirectory(Path dir) {
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        try {
            deleteFileTree(dir);
            Path subdir = Files.createDirectories(dir.resolve("subdir"));
            Files.createFile(subdir.resolve("test"));
        } catch (IOException ioe) {
            // ignore
        }
    }
}
 
Example 12
Source File: SearchFilterFilesTest.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
@ClearSystemProperty( key = RETEST_PROJECT_ROOT )
void getFilterByName_should_return_user_filter_with_given_name_over_default_filter() throws IOException {
	System.setProperty( RETEST_PROJECT_ROOT, filterFolder.toString() );
	final Path positioningFilter = filterFolder.resolve( "content.filter" );
	Files.createFile( positioningFilter );

	final Filter result = SearchFilterFiles.getFilterByName( "content.filter" );
	assertThat( result ).isNotNull();
	assertThat( result.toString() ).isEqualTo( "CompoundFilter(filters=[])" );
}
 
Example 13
Source File: BleachFileMang.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
/** Creates a file, doesn't do anything if the file already exists. **/
public static void createFile(String... file) {
	try { 
		if (fileExists(file)) return;
		dir.toFile().mkdirs();
		Files.createFile(stringsToPath(file));
	} catch (IOException e) { System.out.println("Error Creating File: " + file); e.printStackTrace(); } 
}
 
Example 14
Source File: ScratchPad.java    From EWItool with GNU General Public License v3.0 5 votes vote down vote up
public boolean store() {
  Path spPath = Paths.get( userPrefs.getLibraryLocation(), SCRATCHPAD_NAME );
  try {
    Files.deleteIfExists( spPath );
    Files.createFile( spPath );
    for (int p = 0; p < patchList.size(); p++){
      Files.write( spPath, patchList.get( p ).patchBlob, StandardOpenOption.APPEND );
    }
     Platform.runLater( () -> sharedData.setScratchPadCount( patchList.size() ) );
  } catch( IOException e ) {
    e.printStackTrace();
    return false;
  }
  return true;
}
 
Example 15
Source File: ShutdownFileSystemDeploymentServiceUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testUncleanShutdown() throws Exception {
    File deployment = new File(tmpDir, "foo.war");
    final DiscardTaskExecutor myExecutor = new DiscardTaskExecutor();
    MockServerController sc = new MockServerController(myExecutor);
    final BlockingDeploymentOperations ops = new BlockingDeploymentOperations(sc.create());
    final FileSystemDeploymentService testee = new FileSystemDeploymentService(resourceAddress, null, tmpDir, null, sc, myExecutor);
    testee.setAutoDeployZippedContent(true);
    sc.addCompositeSuccessResponse(1);
    testSupport.createZip(deployment, 0, false, false, true, true);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    try {
        Future<Boolean> lockDone = executorService.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try {
                    synchronized (ops.lock) {
                        logger.info("Executor service should be locked");
                        while (!ops.ready) {//Waiting for deployment to start.
                            Thread.sleep(100);
                        }
                        logger.info("About to stop the scanner");
                        testee.stopScanner();
                        logger.info("Closing executor service " + myExecutor);
                        myExecutor.shutdown();
                        logger.info("Executor service should be closed");
                    }
                    return true;
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        });
        final File dodeploy = new File(tmpDir, "foo.war" + FileSystemDeploymentService.DO_DEPLOY);
        Files.createFile(dodeploy.toPath());
        testee.startScanner(ops);
        testee.scan();
        lockDone.get(100000, TimeUnit.MILLISECONDS);
    } finally {
        executorService.shutdownNow();
    }
}
 
Example 16
Source File: ExportersTest.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
@Test
public void createDataSource1() throws IOException {
    Files.createFile(fileSystem.getPath(WORK_FOO_TST));
    DataSource dataSource = Exporters.createDataSource(fileSystem.getPath("/work/"), "foo", null);
    assertTrue(dataSource.exists(FOO_TST));
}
 
Example 17
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
Example 18
Source File: LocalFileHandler.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public UploadResult upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");

    // Get current time
    Calendar current = Calendar.getInstance(optionService.getLocale());
    // Get month and day of month
    int year = current.get(Calendar.YEAR);
    int month = current.get(Calendar.MONTH) + 1;

    String monthString = month < 10 ? "0" + month : String.valueOf(month);

    // Build directory
    String subDir = UPLOAD_SUB_DIR + year + FILE_SEPARATOR + monthString + FILE_SEPARATOR;

    String originalBasename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));

    // Get basename
    String basename = originalBasename + '-' + HaloUtils.randomUUIDWithoutDash();

    // Get extension
    String extension = FilenameUtils.getExtension(file.getOriginalFilename());

    log.debug("Base name: [{}], extension: [{}] of original filename: [{}]", basename, extension, file.getOriginalFilename());

    // Build sub file path
    String subFilePath = subDir + basename + '.' + extension;

    // Get upload path
    Path uploadPath = Paths.get(workDir, subFilePath);

    log.info("Uploading file: [{}]to directory: [{}]", file.getOriginalFilename(), uploadPath.toString());

    try {
        // TODO Synchronize here
        // Create directory
        Files.createDirectories(uploadPath.getParent());
        Files.createFile(uploadPath);

        // Upload this file
        file.transferTo(uploadPath);

        // Build upload result
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFilename(originalBasename);
        uploadResult.setFilePath(subFilePath);
        uploadResult.setKey(subFilePath);
        uploadResult.setSuffix(extension);
        uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
        uploadResult.setSize(file.getSize());

        // TODO refactor this: if image is svg ext. extension
        boolean isSvg = "svg".equals(extension);

        // Check file type
        if (FileHandler.isImageType(uploadResult.getMediaType()) && !isSvg) {
            lock.lock();
            try (InputStream uploadFileInputStream = new FileInputStream(uploadPath.toFile())) {
                // Upload a thumbnail
                String thumbnailBasename = basename + THUMBNAIL_SUFFIX;
                String thumbnailSubFilePath = subDir + thumbnailBasename + '.' + extension;
                Path thumbnailPath = Paths.get(workDir + thumbnailSubFilePath);

                // Read as image
                BufferedImage originalImage = ImageUtils.getImageFromFile(uploadFileInputStream, extension);
                // Set width and height
                uploadResult.setWidth(originalImage.getWidth());
                uploadResult.setHeight(originalImage.getHeight());

                // Generate thumbnail
                boolean result = generateThumbnail(originalImage, thumbnailPath, extension);
                if (result) {
                    // Set thumb path
                    uploadResult.setThumbPath(thumbnailSubFilePath);
                } else {
                    // If generate error
                    uploadResult.setThumbPath(subFilePath);
                }
            } finally {
                lock.unlock();
            }
        } else {
            uploadResult.setThumbPath(subFilePath);
        }

        log.info("Uploaded file: [{}] to directory: [{}] successfully", file.getOriginalFilename(), uploadPath.toString());
        return uploadResult;
    } catch (IOException e) {
        throw new FileOperationException("上传附件失败").setErrorData(uploadPath);
    }
}
 
Example 19
Source File: Documenter.java    From moduliths with Apache License 2.0 4 votes vote down vote up
private static Path recreateFile(String name) {

		try {

			Files.createDirectories(Paths.get(DEFAULT_LOCATION));

			Path filePath = Paths.get(DEFAULT_LOCATION, name);

			Files.deleteIfExists(filePath);

			return Files.createFile(filePath);

		} catch (IOException o_O) {
			throw new RuntimeException(o_O);
		}
	}
 
Example 20
Source File: StdPDPGroup.java    From XACML with MIT License 4 votes vote down vote up
public PDPPolicy publishPolicy(String id, String name, boolean isRoot, InputStream policy) throws PAPException {
	//
	// Does it exist already?
	//
	if (this.getPolicy(id) != null) {
		throw new PAPException("Policy with id " + id + " already exists - unpublish it first.");
	}
	Path tempFile = null;
	try {
		//
		// Copy the policy over
		//
		tempFile = Files.createFile(Paths.get(this.directory.toAbsolutePath().toString(), id));
		long num;
		try (OutputStream os = Files.newOutputStream(tempFile)) {
			num = ByteStreams.copy(policy, os);
		}
		logger.info("Copied " + num + " bytes for policy " + name);
		
		StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, isRoot, name, tempFile.toUri());
		if (tempRootPolicy.isValid() == false) {
			try {
				Files.delete(tempFile);
			} catch(Exception ee) {
				logger.error("Policy was invalid, could NOT delete it.", ee);
			}
			throw new PAPException("Policy is invalid");
		}
		//
		// Add it in
		//
		this.policies.add(tempRootPolicy);
		//
		// We are changed
		//
		this.firePDPGroupChanged(this);
		//
		// Return our new object.
		//
		return tempRootPolicy;
	} catch (IOException e) {
		logger.error("Failed to publishPolicy: ", e);
	}
	return null;
}