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

The following examples show how to use java.io.File#setReadOnly() . 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: BazelLibGenerator.java    From onos with Apache License 2.0 6 votes vote down vote up
void write(String outputFilePath) {
    DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));
    File outputFile = new File(outputFilePath);
    if (!outputFile.setWritable(true)) {
        error("Failed to make %s to writeable.", outputFilePath);
    }
    try (PrintWriter writer = new PrintWriter(outputFile)) {
        writer.write(String.format(
                "# ***** This file was auto-generated at %s. Do not edit this file manually. *****\n",
                formatter.format(Instant.now())));
        writer.write("# ***** Use onos-lib-gen *****\n");

        writer.write("\nload(\"//tools/build/bazel:variables.bzl\", \"ONOS_GROUP_ID\", \"ONOS_VERSION\")\n\n");
        writer.write("\nload(\"@bazel_tools//tools/build_defs/repo:java.bzl\", \"java_import_external\")\n\n");

        libraries.forEach(library -> writer.print(library.getFragment()));
        writer.print(generateArtifacts());
        writer.print(generateArtifactMap());
        writer.flush();
    } catch (FileNotFoundException e) {
        error("File not found: %s", outputFilePath);
    }
    if (!outputFile.setReadOnly()) {
        error("Failed to set %s to read-only.", outputFilePath);
    }
}
 
Example 2
Source File: TableWriter.java    From mph-table with Apache License 2.0 6 votes vote down vote up
private static <K, V> void rewriteShardsInOrder(
        final File outputPath,
        final TableMeta<K, V> meta,
        final List<File> shards,
        final MMapBuffer sizes,
        final MMapBuffer hashes) throws IOException {
    final long startMillis = System.currentTimeMillis();
    try (final DataOutputStream out = new DataOutputStream(new BufferedFileDataOutputStream(outputPath))) {
        final int numShards = shards.size();
        final long shardSize = Math.max(1L, (meta.numEntries() + numShards - 1) / numShards);
        for (int i = 0; i < numShards; ++i) {
            final long start = i * shardSize;
            final long end = Math.min((i + 1) * shardSize, meta.numEntries());
            try {
                rewriteShardInOrder(out, meta, shards.get(i), shardSize, sizes, hashes, start, end);
            } finally {
                shards.get(i).delete();
            }
        }
        out.flush();
    }
    outputPath.setReadOnly();
    LOGGER.info("rewrote shards in " + (System.currentTimeMillis() - startMillis) + " ms");
}
 
Example 3
Source File: AbstractAuthHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private static void updateReadBit(File file) throws IOException {
	if (file != null) {
		// The goal is to set the file permissions bits to only have owner
		// read set (-r-------- or 400) but currently
		// java.io.File.setReadOnly may leave the group and other read bits
		// set. Try to leverage the registered helper to clear the remaining
		// read bits.Document this in the release notes.
		file.setReadOnly();
		ISystemFileCommandsHelper helper = ServerFactory
				.getRpcFileSystemHelper();
		if (helper == null) {
			helper = SysFileHelperBridge.getSysFileCommands();
		}
		if (helper != null) {
			helper.setOwnerReadOnly(file.getAbsolutePath());
		}
	}
}
 
Example 4
Source File: BaseFileObjectTestHid.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCreateFolderOrDataFile_ReadOnly() throws Exception {
    clearWorkDir();
    final File wDir = getWorkDir();
    final File fold = new File(new File(new File(wDir,"a"), "b"), "c");
    final File data = new File(new File(new File(fold,"a"), "b"), "c.data");
    final boolean makeReadOnly = wDir.setReadOnly();
    if (!makeReadOnly && Utilities.isWindows()) {
        // According to bug 6728842: setReadOnly() only prevents the 
        // directory to be deleted on windows, does not prevent files
        // to be create in it. Thus the test cannot work on Windows.
        return;
    }
    assertTrue("Can change directory to read only: " + wDir, makeReadOnly);
    assertFalse("Cannot write", wDir.canWrite());
    try {
        implCreateFolderOrDataFile(fold, data);        
        fail("Creating folder or data should not be allowed: " + data);
    } catch (IOException ex) {            
    } finally {
        assertTrue(wDir.setWritable(true));
    }
}
 
Example 5
Source File: PanelSourceFoldersTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCheckValidity () throws Exception {

        File root = getWorkDir();
        File projectDir = new File (root, "project");
        File test = new File (root,  "tests");
        test.mkdir();
        File src = new File (root, "src");
        src.mkdir();
        File badSrcDir = new File (root, "badSrc");
        File badSrcDir2 = new File (test, "src");
        badSrcDir2.mkdir();
        File badProjectDir = new File (root, "badPrjDir");
        badProjectDir.mkdir();
        badProjectDir.setReadOnly();
        
        assertNotNull("Empty name", PanelProjectLocationExtSrc.checkValidity ("",projectDir.getAbsolutePath(),"build.xml", true));
        assertNotNull("Read Only WorkDir", PanelProjectLocationExtSrc.checkValidity ("",badProjectDir.getAbsolutePath(),"build.xml", true));
        assertNotNull("Non Existent Sources", PanelSourceFolders.checkValidity (projectDir, new File[] {badSrcDir} , new File[] {test}));
        assertFalse("Sources == Tests",  FolderList.isValidRoot (src, new File[] {src},projectDir));
        assertFalse("Tests under Sources", FolderList.isValidRoot (new File (src, "Tests"),new File[] {src},projectDir));
        assertFalse("Sources under Tests", FolderList.isValidRoot (badSrcDir2, new File[] {test},projectDir));
        assertNull ("Valid data", PanelSourceFolders.checkValidity (projectDir, new File[]{src}, new File[]{test}));
    }
 
Example 6
Source File: Base64MD5PasswordFilePrincipalDatabaseTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetPasswordFileWithReadOnlyFile()
{

    File testFile = createPasswordFile(0, 0);

    testFile.setReadOnly();

    try
    {
        _database.open(testFile);
    }
    catch (FileNotFoundException fnfe)
    {
        assertTrue(fnfe.getMessage().startsWith("Cannot read password file "));
    }
    catch (IOException e)
    {
        fail("Password File was not created." + e.getMessage());
    }
}
 
Example 7
Source File: AbstractAuthHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private static void updateReadBit(@Nullable final File file) throws IOException {
	if (nonNull(file)) {
		// The goal is to set the file permissions bits to only have owner
		// read set (-r-------- or 400) but currently
		// java.io.File.setReadOnly may leave the group and other read bits
		// set. Try to leverage the registered helper to clear the remaining
		// read bits.Document this in the release notes.
		file.setReadOnly();
		ISystemFileCommandsHelper helper = ServerFactory.getRpcFileSystemHelper();
		if (isNull(helper)) {
			helper = SysFileHelperBridge.getSysFileCommands();
		}
		if (nonNull(helper)) {
			helper.setOwnerReadOnly(file.getAbsolutePath());
		}
	}
}
 
Example 8
Source File: AbstractAuthHelper.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private static void updateReadBit(File file) throws IOException {
	if (file != null) {
		// The goal is to set the file permissions bits to only have owner
		// read set (-r-------- or 400) but currently
		// java.io.File.setReadOnly may leave the group and other read bits
		// set. Try to leverage the registered helper to clear the remaining
		// read bits.Document this in the release notes.
		file.setReadOnly();
		ISystemFileCommandsHelper helper = ServerFactory
				.getRpcFileSystemHelper();
		if (helper == null) {
			helper = SysFileHelperBridge.getSysFileCommands();
		}
		if (helper != null) {
			helper.setOwnerReadOnly(file.getAbsolutePath());
		}
	}
}
 
Example 9
Source File: JsonWorkspaceServiceTest.java    From pdfsam with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void saveWorkspaceReadOnly() throws IOException {
    File file = folder.newFile();
    file.setReadOnly();
    Map<String, Map<String, String>> data = new HashMap<>();
    Map<String, String> moduleData = new HashMap<>();
    moduleData.put("key", "value");
    data.put("module", moduleData);
    victim.saveWorkspace(data, file);
}
 
Example 10
Source File: ExtractIlluminaBarcodesTest.java    From picard with MIT License 5 votes vote down vote up
@Test
public void testNonWritableOutputFile() throws Exception {
    final File existingFile = new File(basecallsDir, "s_1_1101_barcode.txt.gz");
    try {
        existingFile.setReadOnly();
        final String readStructure = "25T8B25T";
        final int lane = 1;

        final File metricsFile = File.createTempFile("eib.", ".metrics");
        metricsFile.deleteOnExit();

        final List<String> args = new ArrayList<>(Arrays.asList(
                "BASECALLS_DIR=" + basecallsDir.getPath(),
                "LANE=" + lane,
                "READ_STRUCTURE=" + readStructure,
                "METRICS_FILE=" + metricsFile.getPath(),
                "COMPRESS_OUTPUTS=true"
        ));
        for (final String barcode : BARCODES) {
            args.add("BARCODE=" + barcode);
        }
        Assert.assertEquals(runPicardCommandLine(args), 4);
    } finally {
        existingFile.setWritable(true);
    }

}
 
Example 11
Source File: ClientIntegrationE2ETest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private void modifyFileAttribs(String filePath, int modType) throws Exception{
    //create file object
    File modFile = new File(filePath);

    if (modFile.exists()) {
        switch (modType) {
            //future ref touch command touch -d 2001-01-31 bindetmi2.dll
            case P4JTEST_MODIFYFILE_MAKENEWER:
                modFile.setLastModified(1);
                debugPrint("File: " + filePath, "Now Modified: " + modFile.lastModified());
                break;
            case P4JTEST_MODIFYFILE_MAKEOLDER:
                modFile.setLastModified(0);
                debugPrint("File: " + filePath, "Now Modified: " + modFile.lastModified());
                break;
            case P4JTEST_MODIFYFILE_MAKEWRITABLE:
                SysFileHelperBridge.getSysFileCommands().setWritable(modFile.getCanonicalPath(), true);
                //modFile.setWritable(true);
                debugPrint("File: " + filePath, "Writable?: " + modFile.canWrite());
                break;
            case P4JTEST_MODIFYFILE_MAKEREADONLY:
                modFile.setReadOnly();
                debugPrint("File: " + filePath, "ReadOnly?: " + modFile.canRead());
                break;
            default: //P4JTEST_TIMESTAMP_MAKEOLD

        }
    }
}
 
Example 12
Source File: RealSourceFilesTest.java    From RADL with Apache License 2.0 5 votes vote down vote up
@Test
public void preparesReadOnlyFileForUpdate() throws Exception {
  File file = randomFile(aSourceSetDir(), codeDir, "");
  Code code = new Code();
  code.add("public class C { }");
  SourceFile sourceFile = new SourceFile(file.getCanonicalPath(), code);
  file.setReadOnly();

  reality.add(file.getPath(), sourceFile);

  verify(scm).prepareForUpdate(eq(file));
}
 
Example 13
Source File: Bug1779315.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testFilesMethods() throws IOException {
    File f = new File("blah.txt");
    File f2 = new File("blah2.txt");

    // All of these should generate a warning
    f.mkdir();
    f.mkdirs();
    f.delete();
    f.createNewFile();
    f.setLastModified(1L);
    f.setReadOnly();
    f.renameTo(f2);
}
 
Example 14
Source File: DatabaseManagerTest.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Test(expected = DocumentStoreNotOpenedException.class)
public void nonWritableDatastoreManagerPathThrows() throws DocumentStoreNotOpenedException, IOException {
    File f = new File(TEST_PATH, "c_root_test");
    try {
        f.mkdirs();
        f.setReadOnly();
        DocumentStore ds = DocumentStore.getInstance(f);
        ds.close();
    } finally {
        f.setWritable(true);
        f.delete();
    }
}
 
Example 15
Source File: TestIOException.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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 16
Source File: ClientIntegrationE2ETest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private void modifyFileAttribs(String filePath, int modType) throws Exception{
    //create file object
    File modFile = new File(filePath);

    if (modFile.exists()) {
        switch (modType) {
            //future ref touch command touch -d 2001-01-31 bindetmi2.dll
            case P4JTEST_MODIFYFILE_MAKENEWER:
                modFile.setLastModified(1);
                debugPrint("File: " + filePath, "Now Modified: " + modFile.lastModified());
                break;
            case P4JTEST_MODIFYFILE_MAKEOLDER:
                modFile.setLastModified(0);
                debugPrint("File: " + filePath, "Now Modified: " + modFile.lastModified());
                break;
            case P4JTEST_MODIFYFILE_MAKEWRITABLE:
                SysFileHelperBridge.getSysFileCommands().setWritable(modFile.getCanonicalPath(), true);
                //modFile.setWritable(true);
                debugPrint("File: " + filePath, "Writable?: " + modFile.canWrite());
                break;
            case P4JTEST_MODIFYFILE_MAKEREADONLY:
                modFile.setReadOnly();
                debugPrint("File: " + filePath, "ReadOnly?: " + modFile.canRead());
                break;
            default: //P4JTEST_TIMESTAMP_MAKEOLD

        }
    }
}
 
Example 17
Source File: FileCodeWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void close() throws IOException {
    // mark files as read-onnly if necessary
    for (File f : readonlyFiles)
        f.setReadOnly();
}
 
Example 18
Source File: FileCodeWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void close() throws IOException {
    // mark files as read-onnly if necessary
    for (File f : readonlyFiles)
        f.setReadOnly();
}
 
Example 19
Source File: FileCodeWriter.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public void close() throws IOException {
    // mark files as read-onnly if necessary
    for (File f : readonlyFiles)
        f.setReadOnly();
}
 
Example 20
Source File: FileCodeWriter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void close() throws IOException {
    // mark files as read-onnly if necessary
    for (File f : readonlyFiles)
        f.setReadOnly();
}