List of usage examples for java.io File setWritable
public boolean setWritable(boolean writable, boolean ownerOnly)
From source file:hdfs.FileUtil.java
/** * Set permissions to the required value. Uses the java primitives instead * of forking if group == other./*from www . ja v a 2 s . c o m*/ * @param f the file to change * @param permission the new permissions * @throws IOException */ public static void setPermission(File f, FsPermission permission) throws IOException { FsAction user = permission.getUserAction(); FsAction group = permission.getGroupAction(); FsAction other = permission.getOtherAction(); // use the native/fork if the group/other permissions are different // or if the native is available if (group != other || NativeIO.isAvailable()) { execSetPermission(f, permission); return; } boolean rv = true; // read perms rv = f.setReadable(group.implies(FsAction.READ), false); checkReturnValue(rv, f, permission); if (group.implies(FsAction.READ) != user.implies(FsAction.READ)) { f.setReadable(user.implies(FsAction.READ), true); checkReturnValue(rv, f, permission); } // write perms rv = f.setWritable(group.implies(FsAction.WRITE), false); checkReturnValue(rv, f, permission); if (group.implies(FsAction.WRITE) != user.implies(FsAction.WRITE)) { f.setWritable(user.implies(FsAction.WRITE), true); checkReturnValue(rv, f, permission); } // exec perms rv = f.setExecutable(group.implies(FsAction.EXECUTE), false); checkReturnValue(rv, f, permission); if (group.implies(FsAction.EXECUTE) != user.implies(FsAction.EXECUTE)) { f.setExecutable(user.implies(FsAction.EXECUTE), true); checkReturnValue(rv, f, permission); } }
From source file:com.anthemengineering.mojo.infer.InferMojo.java
/** * Extracts a given infer.tar.xz file to the given directory. * * @param tarXzToExtract the file to extract * @param inferDownloadDir the directory to extract the file to */// www . ja va 2 s . co m private static void extract(File tarXzToExtract, File inferDownloadDir) throws IOException { FileInputStream fin = null; BufferedInputStream in = null; XZCompressorInputStream xzIn = null; TarArchiveInputStream tarIn = null; try { fin = new FileInputStream(tarXzToExtract); in = new BufferedInputStream(fin); xzIn = new XZCompressorInputStream(in); tarIn = new TarArchiveInputStream(xzIn); TarArchiveEntry entry; while ((entry = tarIn.getNextTarEntry()) != null) { final File fileToWrite = new File(inferDownloadDir, entry.getName()); if (entry.isDirectory()) { FileUtils.forceMkdir(fileToWrite); } else { BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(fileToWrite)); final byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = tarIn.read(buffer))) { out.write(buffer, 0, n); } } finally { if (out != null) { out.close(); } } } // assign file permissions final int mode = entry.getMode(); fileToWrite.setReadable((mode & 0004) != 0, false); fileToWrite.setReadable((mode & 0400) != 0, true); fileToWrite.setWritable((mode & 0002) != 0, false); fileToWrite.setWritable((mode & 0200) != 0, true); fileToWrite.setExecutable((mode & 0001) != 0, false); fileToWrite.setExecutable((mode & 0100) != 0, true); } } finally { if (tarIn != null) { tarIn.close(); } } }
From source file:com.puppycrawl.tools.checkstyle.MainTest.java
@Test public void testExistingTargetFilePlainOutputToFileWithoutRwPermissions() throws Exception { final File file = temporaryFolder.newFile("file.output"); assertTrue(file.setReadable(true, true)); assertTrue(file.setWritable(false, false)); exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(new Assertion() { @Override/*from w w w . j av a2 s. c o m*/ public void checkAssertion() throws IOException { assertEquals("Permission denied : '" + file.getCanonicalPath() + "'." + System.lineSeparator(), systemOut.getLog()); assertEquals("", systemErr.getLog()); } }); Main.main("-c", "src/test/resources/com/puppycrawl/tools/checkstyle/config-classname.xml", "-f", "plain", "-o", file.getCanonicalPath(), "src/test/resources/com/puppycrawl/tools/checkstyle/InputMain.java"); }
From source file:org.apache.flink.contrib.streaming.state.RocksDBStateBackendConfigTest.java
@Test public void testContinueOnSomeDbDirectoriesMissing() throws Exception { File targetDir1 = tempFolder.newFolder(); File targetDir2 = tempFolder.newFolder(); String checkpointPath = tempFolder.newFolder().toURI().toString(); RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(checkpointPath); try {//from w ww . ja v a 2 s . co m if (!targetDir1.setWritable(false, false)) { System.err.println( "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable"); return; } rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath()); try { Environment env = getMockEnvironment(); rocksDbBackend.createKeyedStateBackend(env, env.getJobID(), "foobar", IntSerializer.INSTANCE, 1, new KeyGroupRange(0, 0), new KvStateRegistry().createTaskRegistry(env.getJobID(), new JobVertexID())); } catch (Exception e) { e.printStackTrace(); fail("Backend initialization failed even though some paths were available"); } } finally { //noinspection ResultOfMethodCallIgnored targetDir1.setWritable(true, false); FileUtils.deleteDirectory(targetDir1); FileUtils.deleteDirectory(targetDir2); } }
From source file:org.apache.carbondata.hive.server.HiveEmbeddedServer2.java
private HiveConf configure() throws Exception { log.info("Setting The Hive Conf Variables"); String scratchDir = 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"); conf.set("hive.scratch.dir.permission", "777"); conf.setVar(ConfVars.SCRATCHDIRPERMISSION, "777"); scratchDirFile.mkdirs();//from www.ja va 2 s. co m // 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); return new HiveConf(conf); }
From source file:org.neo4j.server.web.logging.HTTPLoggingDocIT.java
private File createUnwritableDirectory() { File file; if (osIsWindows()) { file = new File("\\\\" + UUID.randomUUID().toString() + "\\http.log"); } else {/*from ww w. j a v a2 s . c om*/ TargetDirectory targetDirectory = TargetDirectory.forTest(this.getClass()); file = targetDirectory.file("unwritable-" + System.currentTimeMillis()); assertTrue("create directory to be unwritable", file.mkdirs()); assertTrue("mark directory as unwritable", file.setWritable(false, false)); } return file; }
From source file:org.apache.ambari.server.serveraction.kerberos.CreateKeytabFilesServerAction.java
/** * Ensures that the owner of the Ambari server process is the only local user account able to * read and write to the specified file or read, write to, and execute the specified directory. * * @param file the file or directory for which to modify access *//* w w w . j a v a 2 s . c om*/ private void ensureAmbariOnlyAccess(File file) { if (file.exists()) { if (!file.setReadable(false, false) || !file.setReadable(true, true)) { LOG.warn(String.format("Failed to set %s readable only by Ambari", file.getAbsolutePath())); } if (!file.setWritable(false, false) || !file.setWritable(true, true)) { LOG.warn(String.format("Failed to set %s writable only by Ambari", file.getAbsolutePath())); } if (file.isDirectory()) { if (!file.setExecutable(false, false) && !file.setExecutable(true, true)) { LOG.warn(String.format("Failed to set %s executable by Ambari", file.getAbsolutePath())); } } else { if (!file.setExecutable(false, false)) { LOG.warn(String.format("Failed to set %s not executable", file.getAbsolutePath())); } } } }
From source file:gov.jgi.meta.MetaUtils.java
public static File createTempDir(String prefix, String tmpDir) throws IOException { final File sysTempDir = new File(tmpDir); File newTempDir; final int maxAttempts = 9; int attemptCount = 0; do {//from w ww . j a v a2 s . c o m attemptCount++; if (attemptCount > maxAttempts) { throw new IOException( "The highly improbable has occurred! Failed to create a unique temporary directory after " + maxAttempts + " attempts."); } String dirName = prefix + UUID.randomUUID().toString(); newTempDir = new File(sysTempDir, dirName); } while (newTempDir.exists()); try { FileUtils.forceMkdir(newTempDir); } catch (Exception e) { throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath() + ". Reason: " + e.getMessage(), e); } if (!(newTempDir.setExecutable(true, false) && newTempDir.setReadable(true, false) && newTempDir.setWritable(true, false))) { throw new IOException("unable to set RWX bits to 777"); } return (newTempDir); }
From source file:org.springframework.integration.file.FileWritingMessageHandler.java
private void renameTo(File tempFile, File resultFile) throws IOException { Assert.notNull(resultFile, "'resultFile' must not be null"); Assert.notNull(tempFile, "'tempFile' must not be null"); if (resultFile.exists()) { if (resultFile.setWritable(true, false) && resultFile.delete()) { if (!tempFile.renameTo(resultFile)) { throw new IOException("Failed to rename file '" + tempFile.getAbsolutePath() + "' to '" + resultFile.getAbsolutePath() + "'"); }//from w w w .j a va 2 s . c o m } else { throw new IOException("Failed to rename file '" + tempFile.getAbsolutePath() + "' to '" + resultFile.getAbsolutePath() + "' since '" + resultFile.getName() + "' is not writable or can not be deleted"); } } else { if (!tempFile.renameTo(resultFile)) { throw new IOException("Failed to rename file '" + tempFile.getAbsolutePath() + "' to '" + resultFile.getAbsolutePath() + "'"); } } }
From source file:org.ngrinder.common.util.CompressionUtils.java
/** * Untar an input file into an output file. * The output file is created in the output folder, having the same name as * the input file, minus the '.tar' extension. * * @param inFile the input .tar file//from w w w. ja va 2 s . c o m * @param outputDir the output directory file. * @return The {@link List} of {@link File}s with the untared content. */ @SuppressWarnings("resource") public static List<File> untar(final File inFile, final File outputDir) { final List<File> untaredFiles = new LinkedList<File>(); InputStream is = null; TarArchiveInputStream debInputStream = null; try { is = new FileInputStream(inFile); debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException( String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { File parentFile = outputFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } final OutputStream outputFileStream = new FileOutputStream(outputFile); try { IOUtils.copy(debInputStream, outputFileStream); } finally { IOUtils.closeQuietly(outputFileStream); } if (FilenameUtils.isExtension(outputFile.getName(), EXECUTABLE_EXTENSION)) { outputFile.setExecutable(true, true); } outputFile.setReadable(true); outputFile.setWritable(true, true); } untaredFiles.add(outputFile); } } catch (Exception e) { throw processException("Error while untar file", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(debInputStream); } return untaredFiles; }