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

The following are Jave code examples for showing how to use setWritable() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: trellis-rosid-file-streaming   File: BeamProcessorTest.java   View Source Code Vote up 7 votes
@Test
@Category(NeedsRunner.class)
public void testUnwritableRemoveContainerPipeline() throws Exception {

    final Map<String, String> dataConfiguration = singletonMap("repository",
            getClass().getResource("/dataDirectory2").toURI().toString());

    final File root = new File(getClass().getResource("/dataDirectory2").toURI());

    assumeTrue(root.setReadOnly());

    final PCollection<KV<String, String>> pCollection = pipeline
        .apply("Create", Create.of(CONTAINER_KV))
        .apply(ParDo.of(new BeamProcessor(dataConfiguration, LDP.PreferContainment.getIRIString(), false)));

    PAssert.that(pCollection).empty();

    pipeline.run();
    root.setWritable(true);
}
 
Example 2
Project: trellis-rosid-file-streaming   File: BeamProcessorTest.java   View Source Code Vote up 7 votes
@Test
@Category(NeedsRunner.class)
public void testUnwritableAddContainerPipeline() throws Exception {

    final Map<String, String> dataConfiguration = singletonMap("repository",
            getClass().getResource("/dataDirectory2").toURI().toString());

    final File root = new File(getClass().getResource("/dataDirectory2").toURI());

    assumeTrue(root.setReadOnly());

    final PCollection<KV<String, String>> pCollection = pipeline
        .apply("Create", Create.of(CONTAINER_KV))
        .apply(ParDo.of(new BeamProcessor(dataConfiguration, LDP.PreferContainment.getIRIString(), true)));

    PAssert.that(pCollection).empty();

    pipeline.run();
    root.setWritable(true);
}
 
Example 3
Project: rskj   File: FileUtil.java   View Source Code Vote up 6 votes
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);
                }
            }
        }

        if (!file.setWritable(true)) {
            LOGGER.error("File is not writable");
        }

        boolean result = file.delete();
        return result;
    } else {
        return false;
    }
}
 
Example 4
Project: uavstack   File: UpgradeUtil.java   View Source Code Vote up 6 votes
/**
 * Change the permission of the file to --Readable, Writable, Executable--
 * 
 * @param fileName
 */
public static void changeFilePermisson4Win(String fileName) {

    File file = new File(fileName);
    if (!file.exists()) {
        return;
    }

    if (!file.canRead()) {
        file.setReadable(true);
    }

    if (!file.canWrite()) {
        file.setWritable(true);
    }

    if (!file.canExecute()) {
        file.setExecutable(true);
    }
}
 
Example 5
Project: web3j-maven-plugin   File: SolC.java   View Source Code Vote up 6 votes
private void initBundled() throws IOException {
    File tmpDir = new File(System.getProperty("java.io.tmpdir"), "solc");
    tmpDir.setReadable(true);
    tmpDir.setWritable(true);
    tmpDir.setExecutable(true);
    tmpDir.mkdirs();

    String solcPath = "/native/" + getOS() + "/solc/";
    InputStream is = getClass().getResourceAsStream(solcPath + "file.list");
    Scanner scanner = new Scanner(is);
    while (scanner.hasNext()) {
        String s = scanner.next();
        File targetFile = new File(tmpDir, s);
        InputStream fis = getClass().getResourceAsStream(solcPath + s);
        Files.copy(fis, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        if (solc == null) {
            // first file in the list denotes executable
            solc = targetFile;
            solc.setExecutable(true);
        }
        targetFile.deleteOnExit();
    }
    tmpDir.deleteOnExit();
}
 
Example 6
Project: DICE-Fault-Injection-GUI   File: BandwidthView.java   View Source Code Vote up 6 votes
public void upload() throws IOException {
    
	try (InputStream input = file.getInputstream()) {
        Date date = new Date();
        long datetime = date.getTime();

		//Files.copy(input, new File("/Users/darrenw/Downloads/PrimeTest/Uploads/"+ datetime + file.getFileName()).toPath())
	  //  File fileper = new File("/Users/darrenw/Downloads/PrimeTest/Uploads/"+ datetime + file.getFileName());
        Files.copy(input, new File("/home/ubuntu/Uploads/"+ datetime + file.getFileName()).toPath());
	    File fileper = new File("/home/ubuntu/Uploads/"+ datetime + file.getFileName());
	    fileper.setReadable(true, false);
	    fileper.setWritable(true, false);
	  //  setSshkeypath("/Users/darrenw/Downloads/PrimeTest/Uploads/"+ datetime + file.getFileName());
 	  setSshkeypath("/home/ubuntu/Uploads/"+ datetime + file.getFileName());

	    System.out.println(sshkeypath.toString());
	}     
}
 
Example 7
Project: oneops   File: AbstractOrderExecutor.java   View Source Code Vote up 6 votes
/**
 * writes private key
 *
 * @param key String
 */
protected String writePrivateKey(String key) {
  String uuid = UUID.randomUUID().toString();
  String fileName = config.getDataDir() + "/" + uuid;
  try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(fileName))) {
    bw.write(key);
    bw.close();
    File f = new File(fileName);
    f.setExecutable(false, false);
    f.setReadable(false, false);
    f.setWritable(false, false);
    f.setReadable(true, true);
    f.setWritable(true, true);
    logger.debug("file: " + fileName);
  } catch (IOException e) {
    logger.error("could not write file: " + fileName + " msg:"
        + e.getMessage());
  }
  return fileName;
}
 
Example 8
Project: JAVA-   File: UploadUtil.java   View Source Code Vote up 5 votes
/** 上传文件处理(支持批量) */
public static List<String> uploadFile(HttpServletRequest request) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    List<String> fileNames = InstanceUtil.newArrayList();
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        String pathDir = getUploadDir(request);
        File dirFile = new File(pathDir);
        if (!dirFile.isDirectory()) {
            dirFile.mkdirs();
        }
        for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
            String key = iterator.next();
            MultipartFile multipartFile = multiRequest.getFile(key);
            if (multipartFile != null) {
                String name = multipartFile.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                String postFix = name.substring(name.lastIndexOf(".")).toLowerCase();
                String fileName = uuid + postFix;
                String filePath = pathDir + File.separator + fileName;
                File file = new File(filePath);
                file.setWritable(true, false);
                try {
                    multipartFile.transferTo(file);
                    fileNames.add(fileName);
                } catch (Exception e) {
                    logger.error(name + "保存失败", e);
                }
            }
        }
    }
    return fileNames;
}
 
Example 9
Project: FuzzDroid   File: FileBasedTracingUtils.java   View Source Code Vote up 5 votes
public static File getFuzzerDirectory() {
	File storageDir = new File(Environment.getExternalStorageDirectory(),
			"evoFuzzDumps/");
	if (!storageDir.exists() && !storageDir.mkdirs())
		Log.e(SharedClassesSettings.TAG, "Could not create communication directory for watchdog: " + storageDir);
	storageDir.setWritable(true, false);
	Log.i(SharedClassesSettings.TAG, "Communication directory for watchdog: " + storageDir);
	return storageDir;
}
 
Example 10
Project: osquery-java   File: PluginManager.java   View Source Code Vote up 5 votes
/**
 * Start extension by communicating with osquery core and starting thrift
 * server
 * 
 * @param name
 *            name of extension
 * @param version
 *            version of extension
 * @param sdkVersion
 *            version of the osquery SDK used to build this extension
 * @param minSdkVersion
 *            minimum version of the osquery SDK that you can use
 * @throws IOException
 * @throws ExtensionException
 */
public void startExtension(String name, String version, String sdkVersion, String minSdkVersion)
		throws IOException, ExtensionException {
	ExtensionManager.Client client = new ClientManager(EXTENSION_SOCKET).getClient();
	InternalExtensionInfo info = new InternalExtensionInfo(name, version, sdkVersion, minSdkVersion);
	try {
		ExtensionStatus status = client.registerExtension(info, registry);
		if (status.getCode() == 0) {
			this.uuid = status.uuid;
			Processor<PluginManager> processor = new Processor<PluginManager>(this);
			String serverSocketPath = EXTENSION_SOCKET + "." + String.valueOf(uuid);
			File socketFile = new File(serverSocketPath);
			if (socketFile.exists()) {
				socketFile.delete();
			}
			AFUNIXServerSocket socket = AFUNIXServerSocket.bindOn(new AFUNIXSocketAddress(socketFile));
			socketFile.setExecutable(true, false);
			socketFile.setWritable(true, false);
			socketFile.setReadable(true, false);
			TServerSocket transport = new TServerSocket(socket);
			TTransportFactory transportFactory = new TTransportFactory();
			TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
			TServer server = new TSimpleServer(new Args(transport).processor(processor)
					.transportFactory(transportFactory).protocolFactory(protocolFactory));

			// Run it
			System.out.println("Starting the server...");
			server.serve();
		} else {
			throw new ExtensionException(1, status.getMessage(), uuid);
		}
	} catch (TException e) {
		throw new ExtensionException(1, "Could not connect to socket", uuid);
	}
}
 
Example 11
Project: ZooKeeper   File: ZooKeeperServerMainTest.java   View Source Code Vote up 5 votes
/**
 * Tests that the ZooKeeper server will fail to start if the
 * snapshot directory is read only.
 *
 * This test will fail if it is executed as root user.
 */
@Test(timeout = 30000)
public void testReadOnlySnapshotDir() throws Exception {
    ClientBase.setupTestEnv();
    final int CLIENT_PORT = PortAssignment.unique();

    // Start up the ZK server to automatically create the necessary directories
    // and capture the directory where data is stored
    MainThread main = new MainThread(CLIENT_PORT, true);
    File tmpDir = main.tmpDir;
    main.start();
    Assert.assertTrue("waiting for server being up", ClientBase
            .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
                    CONNECTION_TIMEOUT / 2));
    main.shutdown();

    // Make the snapshot directory read only
    File snapDir = new File(main.dataDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
    snapDir.setWritable(false);

    // Restart ZK and observe a failure
    main = new MainThread(CLIENT_PORT, false, tmpDir);
    main.start();

    Assert.assertFalse("waiting for server being up", ClientBase
            .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
                    CONNECTION_TIMEOUT / 2));

    main.shutdown();

    snapDir.setWritable(true);

    main.deleteDirs();
}
 
Example 12
Project: secondbase   File: FlagsTest.java   View Source Code Vote up 5 votes
@Test
public void testSecretInPropertiesFile() throws Exception {
    final String secretValue = "secretValue";

    final SecretHandler secretHandler = args -> {
        args[1] = secretValue;
        return args;
    };

    final class TestFlags {
        @Flag(name = "secret")
        private String secret;
    }

    final File propertiesFile = File.createTempFile("test", "properties");
    propertiesFile.setWritable(true);
    final FileOutputStream fio = new FileOutputStream(propertiesFile);
    final String properties = "secret=valueToBeExchanged\n";
    fio.write(properties.getBytes());
    fio.close();

    final TestFlags testFlags = new TestFlags();
    new Flags(new SecretHandler[]{secretHandler})
            .loadOpts(testFlags)
            .parse(new String[]{"--properties-file", propertiesFile.getAbsolutePath()});

    assertEquals(secretValue, testFlags.secret);
}
 
Example 13
Project: trellis-rosid-file   File: RDFPatchTest.java   View Source Code Vote up 5 votes
@Test
public void testWriteErrors() throws Exception {
    final File file = new File(getClass().getResource("/readonly/resource.rdfp").toURI());
    assumeTrue(file.setWritable(false));
    assertFalse(RDFPatch.write(file, empty(), empty(), now()));
    file.setWritable(true);
}
 
Example 14
Project: automat   File: UploadUtil.java   View Source Code Vote up 5 votes
/** 上传文件处理(支持批量) */
public static List<String> uploadFile(HttpServletRequest request) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    List<String> fileNames = InstanceUtil.newArrayList();
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        String pathDir = getUploadDir(request);
        File dirFile = new File(pathDir);
        if (!dirFile.isDirectory()) {
            dirFile.mkdirs();
        }
        for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
            String key = iterator.next();
            MultipartFile multipartFile = multiRequest.getFile(key);
            if (multipartFile != null) {
                String name = multipartFile.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                String postFix = name.substring(name.lastIndexOf(".")).toLowerCase();
                String fileName = uuid + postFix;
                String filePath = pathDir + File.separator + fileName;
                File file = new File(filePath);
                file.setWritable(true, false);
                try {
                    multipartFile.transferTo(file);
                    fileNames.add(fileName);
                } catch (Exception e) {
                    logger.error(name + "保存失败", e);
                }
            }
        }
    }
    return fileNames;
}
 
Example 15
Project: https-github.com-apache-zookeeper   File: ZooKeeperServerMainTest.java   View Source Code Vote up 5 votes
/**
 * Tests that the ZooKeeper server will fail to start if the
 * snapshot directory is read only.
 *
 * This test will fail if it is executed as root user.
 */
@Test(timeout = 30000)
public void testReadOnlySnapshotDir() throws Exception {
    ClientBase.setupTestEnv();
    final int CLIENT_PORT = PortAssignment.unique();

    // Start up the ZK server to automatically create the necessary directories
    // and capture the directory where data is stored
    MainThread main = new MainThread(CLIENT_PORT, true, null);
    File tmpDir = main.tmpDir;
    main.start();
    Assert.assertTrue("waiting for server being up", ClientBase
            .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
                    CONNECTION_TIMEOUT / 2));
    main.shutdown();

    // Make the snapshot directory read only
    File snapDir = new File(main.dataDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
    snapDir.setWritable(false);

    // Restart ZK and observe a failure
    main = new MainThread(CLIENT_PORT, false, tmpDir, null);
    main.start();

    Assert.assertFalse("waiting for server being up", ClientBase
            .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
                    CONNECTION_TIMEOUT / 2));

    main.shutdown();

    snapDir.setWritable(true);

    main.deleteDirs();
}
 
Example 16
Project: mumu-core   File: UploadUtil.java   View Source Code Vote up 5 votes
/**
    * 上传文件处理(支持批量)
    * @param request
    * @param pathDir 上传文件保存路径
    * @return
    * @throws IllegalStateException
    * @throws IOException
    */
public static List<String> uploadFile(HttpServletRequest request,String pathDir) throws IllegalStateException, IOException {
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
			request.getSession().getServletContext());
	List<String> fileNames = new ArrayList<String>();
	if (multipartResolver.isMultipart(request)) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multiRequest.getFileNames();
		if(pathDir==null|| pathDir.equals("")){
			pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtils.currentTime());
		}
           File dirFile = new File(pathDir);
           if (!dirFile.isDirectory()) {
               dirFile.mkdirs();
           }
		while (iterator.hasNext()) {
			String key = iterator.next();
			MultipartFile multipartFile = multiRequest.getFile(key);
			if (multipartFile != null) {
				String uuid = UUID.randomUUID().toString().replace("-", "");
				String name = multipartFile.getOriginalFilename();
				int lastIndexOf = name.lastIndexOf(".");
				String postFix="";
				if(lastIndexOf!=-1){
					postFix = name.substring(lastIndexOf).toLowerCase();
				}
				String fileName = uuid + postFix;
				String filePath = pathDir + File.separator + fileName;
				File file = new File(filePath);
				file.setWritable(true, false);

				multipartFile.transferTo(file);
				fileNames.add(file.getAbsolutePath());
			}
		}
	}
	return fileNames;
}
 
Example 17
Project: openjdk-jdk10   File: TestIOException.java   View Source Code Vote up 5 votes
@Test
void testReadOnlyFile() throws Exception {
    File outDir = new File("out2");
    if (!outDir.mkdir()) {
        throw new Error("Cannot create directory");
    }
    File index = new File(outDir, "index.html");
    try (FileWriter fw = new FileWriter(index)) { }
    if (!index.setReadOnly()) {
        throw new Error("could not set index read-only");
    }
    if (index.canWrite()) {
        throw new Error("index is writable");
    }

    try {
        setOutputDirectoryCheck(DirectoryCheck.NONE);
        javadoc("-d", outDir.toString(),
                new File(testSrc, "TestIOException.java").getPath());

        checkExit(Exit.ERROR);
        checkOutput(Output.OUT, true,
            "Error writing file: " + index);
    } finally {
        setOutputDirectoryCheck(DirectoryCheck.EMPTY);
        index.setWritable(true);
    }
}
 
Example 18
Project: trellis-rosid   File: BeamProcessorTest.java   View Source Code Vote up 4 votes
@Test
@Category(NeedsRunner.class)
public void testUnwritableAddContainerPipeline() throws Exception {

    final String dataConfiguration = getClass().getResource("/dataDirectory2").toURI().toString();

    final File root = new File(getClass().getResource("/dataDirectory2").toURI());

    assumeTrue(root.setReadOnly());

    final PCollection<KV<String, String>> pCollection = pipeline
        .apply("Create", Create.of(CONTAINER_KV))
        .apply(ParDo.of(new BeamProcessor(dataConfiguration, LDP.PreferContainment.getIRIString(), true)));

    PAssert.that(pCollection).empty();

    pipeline.run();
    root.setWritable(true);
}
 
Example 19
Project: trellis-rosid   File: CacheWriterTest.java   View Source Code Vote up 4 votes
@Test
@Category(NeedsRunner.class)
public void testUnwritablePipeline() throws Exception {

    final KV<String, String> kv = KV.of("trellis:repository/resource", null);

    final String dataConfiguration = getClass().getResource("/dataDirectory2").toURI().toString();

    final File root = new File(getClass().getResource("/dataDirectory2").toURI());

    assumeTrue(root.setReadOnly());

    final PCollection<KV<String, String>> pCollection = pipeline
        .apply("Create", Create.of(kv))
        .apply(ParDo.of(new CacheWriter(dataConfiguration)));

    PAssert.that(pCollection).empty();

    pipeline.run();
    root.setWritable(true);
}
 
Example 20
Project: mumu-core   File: UploadUtil.java   View Source Code Vote up 4 votes
/** 上传文件处理(支持批量)
 * @throws IOException
 * @throws IllegalStateException */
public static List<String> uploadImage(HttpServletRequest request) throws IllegalStateException, IOException {
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
			request.getSession().getServletContext());
	List<String> fileNames = new ArrayList<String>();
	if (multipartResolver.isMultipart(request)) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multiRequest.getFileNames();
		String pathDir = request.getSession().getServletContext()
				.getRealPath(uploadFileDir + DateUtils.currentTime());
		File dirFile = new File(pathDir);
		if (!dirFile.isDirectory()) {
			dirFile.mkdirs();
		}
		while (iterator.hasNext()) {
			String key = iterator.next();
			MultipartFile multipartFile = multiRequest.getFile(key);
			if (multipartFile != null) {
				String name = multipartFile.getOriginalFilename();
				// 默认文件格式为png图片
				if (name.indexOf(".") == -1 && "blob".equals(name)) {
					name = name + ".png";
				}
				String uuid = UUID.randomUUID().toString().replace("-", "");
				int lastIndexOf = name.lastIndexOf(".");
				if(lastIndexOf==-1){
					name=name + ".png";
				}
				lastIndexOf = name.lastIndexOf(".");
				String postFix=name.substring(lastIndexOf).toLowerCase();
				String fileName = uuid + postFix;
				String filePath = pathDir + File.separator + fileName;
				File file = new File(filePath);
				file.setWritable(true, false);

				multipartFile.transferTo(file);
				fileNames.add(file.getAbsolutePath());
			}
		}
	}
	return fileNames;
}