Java Code Examples for java.io.File#setWritable()

The following examples show how to use java.io.File#setWritable() . 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: FileUtil.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
public static boolean recursiveDelete(String fileName) {
    File file = new File(fileName);
    if (file.exists()) {
        //check if the file is a directory
        if (file.isDirectory()) {
            if ((file.list()).length > 0) {
                for(String s:file.list()){
                    //call deletion of file individually
                    recursiveDelete(fileName + System.getProperty("file.separator") + s);
                }
            }
        }

        file.setWritable(true);
        boolean result = file.delete();
        return result;
    } else {
        return false;
    }
}
 
Example 2
Source File: TenantPopulator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 *
 * Create the landing zone directory for a tenant.
 *
 * @param tenant
 *            , the tenant for which to create landing zone directories
 *
 */
private void createTenantLzDirectory(TenantRecord tenant) {
    List<LandingZoneRecord> landingZones = tenant.getLandingZone();
    for (LandingZoneRecord lz : landingZones) {
        String lzPath = lz.getPath();
        File lzDirectory = new File(lzPath);
        if (!lzDirectory.mkdir()) {
            LOG.debug("Failed to mkdir: {}", lzDirectory.getPath());
        }
        if (!lzDirectory.setReadable(true, false)) {
            LOG.debug("Failed to setReadable: {}", lzDirectory.getPath());
        }
        if (!lzDirectory.setWritable(true, false)) {
            LOG.debug("Failed to setWritable: {}", lzDirectory.getPath());
        }
    }
}
 
Example 3
Source File: Builder.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
public static File getPersistenceFile() throws IOException {

        final File file = File.createTempFile("chm-test-", "map");

        //Not Guaranteed to work on Windows, since OS file-lock takes precedence
        if (System.getProperty("os.name").indexOf(WIN_OS) > 0) {
            /*Windows will lock a file that are currently in use. You cannot delete it, however,
              using setwritable() and then releasing RandomRW lock adds the file to JVM exit cleanup.
    		  This will only work if the user is an admin on windows.
    		*/
            file.setWritable(true);//just in case relative path was used.
            try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
                //allows closing the file access on windows. forcing to close access. Only works for admin-access.
            }
        }

        //file.delete(); //isnt guaranteed on windows.
        file.deleteOnExit();//isnt guaranteed on windows.

        return file;
    }
 
Example 4
Source File: Application.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Map<String, String> env = System.getenv();
    for (String envName : env.keySet()) {
        System.out.format("%s=%s%n", envName, env.get(envName));
    }
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources("resources/*");
    for (Resource resource : resources) {
        File resourceFile = new File(resource.getFilename());
        try (FileOutputStream fos = new FileOutputStream(resourceFile)) {
            IOUtils.copyLarge(resource.getInputStream(), fos);
        }
        resourceFile.setExecutable(true);
        resourceFile.setReadable(true);
        resourceFile.setWritable(true);
    }
    SpringApplication.run(Application.class, args);
}
 
Example 5
Source File: Utils.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void copyFile(File src, File dst) throws IOException {
    Path parent = dst.toPath().getParent();
    if (parent != null) {
        Files.createDirectories(parent);
    }
    Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING);
    if (dst.isDirectory() && !dst.canWrite()) {
        dst.setWritable(true);
    }
}
 
Example 6
Source File: ModulesService.java    From InviZible with GNU General Public License v3.0 5 votes vote down vote up
private void cleanLogFileNoRootMethod(String logFilePath, String text) {
    try {
        File f = new File(pathVars.getAppDataDir() + "/logs");

        if (f.mkdirs() && f.setReadable(true) && f.setWritable(true))
            Log.i(LOG_TAG, "log dir created");

        PrintWriter writer = new PrintWriter(logFilePath, "UTF-8");
        writer.println(text);
        writer.close();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Unable to create dnsCrypt log file " + e.getMessage());
    }
}
 
Example 7
Source File: LibSvmRecordWriterTest.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testNDArrayWritables() throws Exception {
    INDArray arr2 = Nd4j.zeros(2);
    arr2.putScalar(0, 11);
    arr2.putScalar(1, 12);
    INDArray arr3 = Nd4j.zeros(3);
    arr3.putScalar(0, 13);
    arr3.putScalar(1, 14);
    arr3.putScalar(2, 15);
    List<Writable> record = Arrays.asList((Writable) new DoubleWritable(1),
                                        new NDArrayWritable(arr2),
                                        new IntWritable(2),
                                        new DoubleWritable(3),
                                        new NDArrayWritable(arr3),
                                        new IntWritable(4));
    File tempFile = File.createTempFile("LibSvmRecordWriter", ".txt");
    tempFile.setWritable(true);
    tempFile.deleteOnExit();
    if (tempFile.exists())
        tempFile.delete();

    String lineOriginal = "13.0,14.0,15.0,4 1:1.0 2:11.0 3:12.0 4:2.0 5:3.0";

    try (LibSvmRecordWriter writer = new LibSvmRecordWriter()) {
        Configuration configWriter = new Configuration();
        configWriter.setInt(LibSvmRecordWriter.FEATURE_FIRST_COLUMN, 0);
        configWriter.setInt(LibSvmRecordWriter.FEATURE_LAST_COLUMN, 3);
        FileSplit outputSplit = new FileSplit(tempFile);
        writer.initialize(configWriter,outputSplit,new NumberOfRecordsPartitioner());
        writer.write(record);
    }

    String lineNew = FileUtils.readFileToString(tempFile).trim();
    assertEquals(lineOriginal, lineNew);
}
 
Example 8
Source File: FileUtilsTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteDirectory() throws Exception {

	// deleting a non-existent file should not cause an error

	File doesNotExist = new File(tmp.newFolder(), "abc");
	FileUtils.deleteDirectory(doesNotExist);

	// deleting a write protected file should throw an error

	File cannotDeleteParent = tmp.newFolder();
	File cannotDeleteChild = new File(cannotDeleteParent, "child");

	try {
		assumeTrue(cannotDeleteChild.createNewFile());
		assumeTrue(cannotDeleteParent.setWritable(false));
		assumeTrue(cannotDeleteChild.setWritable(false));

		FileUtils.deleteDirectory(cannotDeleteParent);
		fail("this should fail with an exception");
	}
	catch (AccessDeniedException ignored) {
		// this is expected
	}
	finally {
		//noinspection ResultOfMethodCallIgnored
		cannotDeleteParent.setWritable(true);
		//noinspection ResultOfMethodCallIgnored
		cannotDeleteChild.setWritable(true);
	}
}
 
Example 9
Source File: NativeErrors.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Throwable {
    // Execute command in another vm. Verify stdout for expected err msg.

    // Test with no input file given.
    checkResult(executeCmd("-encoding"), "err.bad.arg");

    File f0 = new File(System.getProperty("test.src", "."), "test123");
    String path0 = f0.getPath();
    if ( f0.exists() ) {
        throw new Error("Input file should not exist: " + path0);
    }
    checkResult(executeCmd(path0), "err.cannot.read");

    File f1 = new File(System.getProperty("test.src", "."), "test1");
    File f2 = File.createTempFile("test2", ".tmp");
    String path1 = f1.getPath();
    String path2 = f2.getPath();
    if ( !f1.exists() ) {
        throw new Error("Missing input file: " + path1);
    }
    if ( !f2.setWritable(false) ) {
        throw new Error("Output file cannot be made read only: " + path2);
    }
    f2.deleteOnExit();
    if ( f2.canWrite() ) {
        String msg = "Output file is still writable. " +
                "Probably because test is run as root. Read-only test skipped.";
        System.out.println(msg);
    } else {
        // Test write to a read-only file.
        checkResult(executeCmd(path1, path2), "err.cannot.write");
    }
}
 
Example 10
Source File: Utils.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void copyFile(File src, File dst) throws IOException {
    Path parent = dst.toPath().getParent();
    if (parent != null) {
        Files.createDirectories(parent);
    }
    Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING);
    if (dst.isDirectory() && !dst.canWrite()) {
        dst.setWritable(true);
    }
}
 
Example 11
Source File: TestDiskError.java    From RDFS with Apache License 2.0 5 votes vote down vote up
public void testShutdown() throws Exception {
  if (System.getProperty("os.name").startsWith("Windows")) {
    /**
     * This test depends on OS not allowing file creations on a directory
     * that does not have write permissions for the user. Apparently it is
     * not the case on Windows (at least under Cygwin), and possibly AIX.
     * This is disabled on Windows.
     */
    return;
  }
  // bring up a cluster of 3
  Configuration conf = new Configuration();
  conf.setLong("dfs.block.size", 512L);
  MiniDFSCluster cluster = new MiniDFSCluster(conf, 3, true, null);
  cluster.waitActive();
  FileSystem fs = cluster.getFileSystem();
  final int dnIndex = 0;
  File dir1 = new File(cluster.getBlockDirectory("data"+(2*dnIndex+1)).getParent(), "rbw");
  File dir2 = new File(cluster.getBlockDirectory("data"+(2*dnIndex+2)).getParent(), "rbw");
  try {
    // make the data directory of the first datanode to be readonly
    assertTrue(dir1.setReadOnly());
    assertTrue(dir2.setReadOnly());

    // create files and make sure that first datanode will be down
    DataNode dn = cluster.getDataNodes().get(dnIndex);
    for (int i=0; DataNode.isDatanodeUp(dn); i++) {
      Path fileName = new Path("/test.txt"+i);
      DFSTestUtil.createFile(fs, fileName, 1024, (short)2, 1L);
      DFSTestUtil.waitReplication(fs, fileName, (short)2);
      fs.delete(fileName, true);
    }
  } finally {
    // restore its old permission
    dir1.setWritable(true);
    dir2.setWritable(true);
    cluster.shutdown();
  }
}
 
Example 12
Source File: DeletingFileVisitor.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored") // Best effort only
private static void delete(Path p) {
    final File f = p.toFile();
    f.delete();
    f.setWritable(true, true);
}
 
Example 13
Source File: ForceInsertTest.java    From sync-android with Apache License 2.0 4 votes vote down vote up
@Test
public void notification_forceinsertWithAttachmentsError() throws Exception {

    // this test only makes sense if the data is inline base64 (there's no remote server to
    // pull the attachment from)
    boolean pullAttachmentsInline = true;

    // try and force an IOException when setting the attachment, and check everything is OK:

    // create a read only zero-length file where the extensions dir would go, to cause an IO
    // exception
    File extensions = new File(datastore.datastoreDir + "/extensions");
    extensions.createNewFile();
    extensions.setWritable(false);

    DocumentRevision doc1_rev1Mut = new DocumentRevision();
    doc1_rev1Mut.setBody(bodyOne);
    DocumentRevision doc1_rev1 = datastore.create(doc1_rev1Mut);
    Map<String, Object> atts = new HashMap<String, Object>();
    Map<String, Object> att1 = new HashMap<String, Object>();

    atts.put("att1", att1);
    att1.put("data", new String(new Base64().encode("this is some data".getBytes())));
    att1.put("content_type", "text/plain");

    ArrayList<String> revisionHistory = new ArrayList<String>();
    revisionHistory.add(doc1_rev1.getRevision());
    InternalDocumentRevision rev2 = new DocumentRevisionBuilder().setDocId(doc1_rev1.getId())
            .setRevId("2-blah").setBody(bodyOne).build();
    revisionHistory.add("2-blah");
    // now do a force insert
    //catch the exception thrown se we can look into the database
    try {
        ForceInsertItem fii = new ForceInsertItem(rev2, revisionHistory, atts, null,
                pullAttachmentsInline);
        datastore.forceInsert(Collections.singletonList(fii));
    } catch (DocumentException e) {
        //do nothing.
    }

    // Check that the attachment is not associated with the original rev
    Attachment storedAtt = datastore.getAttachment(doc1_rev1.getId(), doc1_rev1.getRevision()
            , "att1");
    Assert.assertNull(storedAtt);

    // adding the attachment should have failed transactionally, so the rev should not exist
    // as well
    Assert.assertFalse(datastore.contains(rev2.getId(), rev2.getRevision()));

}
 
Example 14
Source File: BlobCachePutTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Uploads a byte array to a server which cannot create incoming files via the {@link
 * BlobCacheService}. File transfers should fail.
 *
 * @param jobId
 * 		job id
 * @param blobType
 * 		whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsIncoming(@Nullable final JobID jobId, BlobKey.BlobType blobType)
		throws IOException {
	assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

	final Configuration config = new Configuration();
	config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

	File tempFileDir = null;
	try (
		BlobServer server = new BlobServer(config, new VoidBlobStore());
		BlobCacheService cache = new BlobCacheService(config, new VoidBlobStore(), new InetSocketAddress("localhost", server.getPort())
		)) {

		server.start();

		// make sure the blob server cannot create any files in its storage dir
		tempFileDir = server.createTemporaryFilename().getParentFile();
		assertTrue(tempFileDir.setExecutable(true, false));
		assertTrue(tempFileDir.setReadable(true, false));
		assertTrue(tempFileDir.setWritable(false, false));

		byte[] data = new byte[2000000];
		rnd.nextBytes(data);

		// upload the file to the server via the cache
		exception.expect(IOException.class);
		exception.expectMessage("PUT operation failed: ");

		try {
			put(cache, jobId, data, blobType);
		} finally {
			File storageDir = tempFileDir.getParentFile();
			// only the incoming directory should exist (no job directory!)
			assertArrayEquals(new String[] {"incoming"}, storageDir.list());
		}
	} finally {
		// set writable again to make sure we can remove the directory
		if (tempFileDir != null) {
			//noinspection ResultOfMethodCallIgnored
			tempFileDir.setWritable(true, false);
		}
	}
}
 
Example 15
Source File: InstallActivity.java    From PMCADemo with MIT License 4 votes vote down vote up
protected void setPermissions(File file) {
    file.setReadable(true, false);
    file.setWritable(true, false);
    file.setExecutable(true, false);
}
 
Example 16
Source File: DirectorySynchronizeController.java    From MyBox with Apache License 2.0 4 votes vote down vote up
protected boolean initAttributes() {
    try {
        sourcePath = new File(sourcePathInput.getText());
        if (!paused || lastFileName == null) {
            copyAttr = new FileSynchronizeAttributes();
            copyAttr.setContinueWhenError(continueCheck.isSelected());
            copyAttr.setCopyAttrinutes(copyAttrCheck.isSelected());
            copyAttr.setCopyEmpty(copyEmptyCheck.isSelected());
            copyAttr.setConditionalCopy(isConditional);
            copyAttr.setCopyExisted(copyExistedCheck.isSelected());
            copyAttr.setCopyHidden(copyHiddenCheck.isSelected());
            copyAttr.setCopyNew(copyNewCheck.isSelected());
            copyAttr.setCopySubdir(copySubdirCheck.isSelected());
            copyAttr.setNotCopySome(notCopyCheck.isSelected());
            copyAttr.setOnlyCopyReadonly(copyReadonlyCheck.isSelected());
            List<String> notCopy = new ArrayList<>();
            if (copyAttr.isNotCopySome() && notCopyInput.getText() != null && !notCopyInput.getText().trim().isEmpty()) {
                String[] s = notCopyInput.getText().split(",");
                notCopy.addAll(Arrays.asList(s));
            }
            copyAttr.setNotCopyNames(notCopy);
            copyAttr.setOnlyCopyModified(copyModifiedCheck.isSelected());
            copyAttr.setModifyAfter(0);
            if (copyAttr.isOnlyCopyModified() && modifyAfterInput.getValue() != null) {
                copyAttr.setModifyAfter(DateTools.localDate2Date(modifyAfterInput.getValue()).getTime());
            }
            copyAttr.setDeleteNotExisteds(deleteNonExistedCheck.isSelected());

            if (!copyAttr.isCopyNew() && !copyAttr.isCopyExisted() && !copyAttr.isCopySubdir()) {
                alertInformation(message("NothingCopy"));
                return false;
            }
            // In case that the source path itself is in blacklist
            if (copyAttr.isNotCopySome()) {
                List<String> keys = copyAttr.getNotCopyNames();
                String srcName = sourcePath.getName();
                for (String key : keys) {
                    if (srcName.contains(key)) {
                        alertInformation(message("NothingCopy"));
                        return false;
                    }
                }
            }
            initLogs();
            logsTextArea.setText(AppVariables.message("SourcePath") + ": " + sourcePathInput.getText() + "\n");
            logsTextArea.appendText(AppVariables.message("TargetPath") + ": " + targetPathInput.getText() + "\n");

            strFailedCopy = AppVariables.message("FailedCopy") + ": ";
            strCreatedSuccessfully = AppVariables.message("CreatedSuccessfully") + ": ";
            strCopySuccessfully = AppVariables.message("CopySuccessfully") + ": ";
            strDeleteSuccessfully = AppVariables.message("DeletedSuccessfully") + ": ";
            strFailedDelete = AppVariables.message("FailedDelete") + ": ";
            strFileDeleteSuccessfully = AppVariables.message("FileDeletedSuccessfully") + ": ";
            strDirectoryDeleteSuccessfully = AppVariables.message("DirectoryDeletedSuccessfully") + ": ";

            targetPath = new File(targetPathInput.getText());
            if (!targetPath.exists()) {
                targetPath.mkdirs();
                updateLogs(strCreatedSuccessfully + targetPath.getAbsolutePath(), true);
            }
            targetPath.setWritable(true);
            targetPath.setExecutable(true);
            startHandle = true;
            lastFileName = null;

        } else {
            startHandle = false;
            updateLogs(message("LastHanldedFile") + " " + lastFileName, true);
        }

        processStartTime = new Date();

        return true;

    } catch (Exception e) {
        logger.error(e.toString());
        return false;
    }
}
 
Example 17
Source File: HiveEmbeddedServer2.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
private HiveConf configure() throws Exception {
    String scratchDir = NTFSLocalFileSystem.SCRATCH_DIR;


    File scratchDirFile = new File(scratchDir);
    TestUtils.delete(scratchDirFile);

    Configuration cfg = new Configuration();
    HiveConf conf = new HiveConf(cfg, HiveConf.class);
    conf.addToRestrictList("columns.comments");
    refreshConfig(conf);

    HdpBootstrap.hackHadoopStagingOnWin();

    // work-around for NTFS FS
    // set permissive permissions since otherwise, on some OS it fails
    if (TestUtils.isWindows()) {
        conf.set("fs.file.impl", NTFSLocalFileSystem.class.getName());
        conf.set("hive.scratch.dir.permission", "650");
        conf.setVar(ConfVars.SCRATCHDIRPERMISSION, "650");
        conf.set("hive.server2.enable.doAs", "false");
        conf.set("hive.execution.engine", "mr");
        //conf.set("hadoop.bin.path", getClass().getClassLoader().getResource("hadoop.cmd").getPath());
        System.setProperty("path.separator", ";");
        conf.setVar(HiveConf.ConfVars.HIVE_AUTHENTICATOR_MANAGER,
                DummyHiveAuthenticationProvider.class.getName());
    }
    else {
        conf.set("hive.scratch.dir.permission", "777");
        conf.setVar(ConfVars.SCRATCHDIRPERMISSION, "777");
        scratchDirFile.mkdirs();
        // also set the permissions manually since Hive doesn't do it...
        scratchDirFile.setWritable(true, false);
    }

    int random = new Random().nextInt();

    conf.set("hive.metastore.warehouse.dir", scratchDir + "/warehouse" + random);
    conf.set("hive.metastore.metadb.dir", scratchDir + "/metastore_db" + random);
    conf.set("hive.exec.scratchdir", scratchDir);
    conf.set("fs.permissions.umask-mode", "022");
    conf.set("javax.jdo.option.ConnectionURL", "jdbc:derby:;databaseName=" + scratchDir + "/metastore_db" + random + ";create=true");
    conf.set("hive.metastore.local", "true");
    conf.set("hive.aux.jars.path", "");
    conf.set("hive.added.jars.path", "");
    conf.set("hive.added.files.path", "");
    conf.set("hive.added.archives.path", "");
    conf.set("fs.default.name", "file:///");

    // clear mapred.job.tracker - Hadoop defaults to 'local' if not defined. Hive however expects this to be set to 'local' - if it's not, it does a remote execution (i.e. no child JVM)
    Field field = Configuration.class.getDeclaredField("properties");
    field.setAccessible(true);
    Properties props = (Properties) field.get(conf);
    props.remove("mapred.job.tracker");
    props.remove("mapreduce.framework.name");
    props.setProperty("fs.default.name", "file:///");

    // intercept SessionState to clean the threadlocal
    Field tss = SessionState.class.getDeclaredField("tss");
    tss.setAccessible(true);
    //tss.set(null, new InterceptingThreadLocal());

    return new HiveConf(conf);
}
 
Example 18
Source File: BlobServerPutTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Uploads a byte array to a server which cannot create incoming files via the {@link
 * BlobServer}. File transfers should fail.
 *
 * @param jobId
 * 		job id
 * @param blobType
 * 		whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsIncoming(@Nullable final JobID jobId, BlobKey.BlobType blobType)
		throws IOException {
	assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

	final Configuration config = new Configuration();
	config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

	File tempFileDir = null;
	try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

		server.start();

		// make sure the blob server cannot create any files in its storage dir
		tempFileDir = server.createTemporaryFilename().getParentFile();
		assertTrue(tempFileDir.setExecutable(true, false));
		assertTrue(tempFileDir.setReadable(true, false));
		assertTrue(tempFileDir.setWritable(false, false));

		byte[] data = new byte[2000000];
		rnd.nextBytes(data);

		// upload the file to the server directly
		exception.expect(IOException.class);
		exception.expectMessage(" (Permission denied)");

		try {
			put(server, jobId, data, blobType);
		} finally {
			File storageDir = tempFileDir.getParentFile();
			// only the incoming directory should exist (no job directory!)
			assertArrayEquals(new String[] {"incoming"}, storageDir.list());
		}
	} finally {
		// set writable again to make sure we can remove the directory
		if (tempFileDir != null) {
			//noinspection ResultOfMethodCallIgnored
			tempFileDir.setWritable(true, false);
		}
	}
}
 
Example 19
Source File: CheckLockLocationTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }
    // writableDirectory and its contents will be deleted after the test
    // that uses it

    // Create a plain file which we will attempt to use as a directory
    // (%t/not-a-dir)
    File notAdir = new File(tmpOrHomeDir, NOT_A_DIR);
    if (!createFile(notAdir, false)) {
        throw new RuntimeException("Test setup failed: unable to a plain"
                + " working file " + notAdir.getAbsolutePath() );
    }
    notAdir.deleteOnExit();

    // Create a non-writable directory (%t/non-writable-dir)
    File nonWritableDir = new File(tmpOrHomeDir, NON_WRITABLE_DIR);
    if (!createFile(nonWritableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " a non-"
                + "writable working directory "
                + nonWritableDir.getAbsolutePath() );
    }
    nonWritableDir.deleteOnExit();

    // make it non-writable
    Path path = nonWritableDir.toPath();
    final boolean nonWritable = nonWritableDir.setWritable(false);
    final boolean isWritable = Files.isWritable(path);
    if (nonWritable && !isWritable) {
        runNonWritableDirTest = true;
        System.out.println("Created non writable dir for "
                + getOwner(path) + " at: " + path.toString());
    } else {
        runNonWritableDirTest = false;
        System.out.println( "Test Setup WARNING: unable to make"
                + " working directory " + nonWritableDir.getAbsolutePath()
                + "\n\t non-writable for " + getOwner(path)
                +  " on platform " + System.getProperty("os.name"));
    }

    // make sure non-existent directory really doesn't exist
    File nonExistentDir = new File(tmpOrHomeDir, NON_EXISTENT_DIR);
    if (nonExistentDir.exists()) {
        nonExistentDir.delete();
    }
    System.out.println("Setup completed - writableDir is: " + writableDir.getPath());
    return writableDir;
}
 
Example 20
Source File: BlobServerPutTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Uploads a byte array to a server which cannot create incoming files via the {@link
 * BlobServer}. File transfers should fail.
 *
 * @param jobId
 * 		job id
 * @param blobType
 * 		whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsIncoming(@Nullable final JobID jobId, BlobKey.BlobType blobType)
		throws IOException {
	assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

	final Configuration config = new Configuration();
	config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

	File tempFileDir = null;
	try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

		server.start();

		// make sure the blob server cannot create any files in its storage dir
		tempFileDir = server.createTemporaryFilename().getParentFile();
		assertTrue(tempFileDir.setExecutable(true, false));
		assertTrue(tempFileDir.setReadable(true, false));
		assertTrue(tempFileDir.setWritable(false, false));

		byte[] data = new byte[2000000];
		rnd.nextBytes(data);

		// upload the file to the server directly
		exception.expect(IOException.class);
		exception.expectMessage(" (Permission denied)");

		try {
			put(server, jobId, data, blobType);
		} finally {
			File storageDir = tempFileDir.getParentFile();
			// only the incoming directory should exist (no job directory!)
			assertArrayEquals(new String[] {"incoming"}, storageDir.list());
		}
	} finally {
		// set writable again to make sure we can remove the directory
		if (tempFileDir != null) {
			//noinspection ResultOfMethodCallIgnored
			tempFileDir.setWritable(true, false);
		}
	}
}