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

The following are Jave code examples for showing how to use setReadOnly() 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: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 6 votes
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 2
Project: incubator-netbeans   File: PanelSourceFoldersTest.java   View Source Code Vote up 6 votes
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 3
Project: athena   File: BuckLibGenerator.java   View Source Code Vote up 6 votes
void write(String outputFilePath) {
    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",
                new Date().toString()));
        libraries.forEach(library -> writer.print(library.getBuckFragment()));
        artifacts.forEach(artifact -> writer.print(artifact.getBuckFragment()));
        writer.flush();
    } catch (FileNotFoundException e) {
        error("File not found: %s", outputFilePath);
    }
    if (!outputFile.setReadOnly()) {
        error("Failed to set %s to read-only.", outputFilePath);
    }
}
 
Example 4
Project: openjdk-jdk10   File: TestIOException.java   View Source Code Vote up 6 votes
@Test
void testReadOnlyDirectory() {
    File outDir = new File("out1");
    if (!outDir.mkdir()) {
        throw new Error("Cannot create directory");
    }
    if (!outDir.setReadOnly()) {
        throw new Error("could not set directory read-only");
    }
    if (outDir.canWrite()) {
        throw new Error("directory is writable");
    }

    try {
        javadoc("-d", outDir.toString(),
                new File(testSrc, "TestIOException.java").getPath());
        checkExit(Exit.ERROR);
        checkOutput(Output.OUT, true,
            "Destination directory not writable: " + outDir);
    } finally {
        outDir.setWritable(true);
    }
}
 
Example 5
Project: incubator-netbeans   File: VCSInterceptorTest.java   View Source Code Vote up 5 votes
public void testIsMutable() throws IOException {
    File f = new File(dataRootDir, "workdir/root-test-versioned");
    FileObject fo = FileUtil.toFileObject(f);
    fo = fo.createData("checkme.txt");
    File file = FileUtil.toFile(fo);
    fo.canWrite();
    assertTrue(inteceptor.getBeforeCreateFiles().contains(file));
    assertTrue(inteceptor.getDoCreateFiles().contains(file));
    assertTrue(inteceptor.getCreatedFiles().contains(file));
    assertFalse(inteceptor.getIsMutableFiles().contains(file));
    
    file.setReadOnly();
    fo.canWrite();
    assertTrue(inteceptor.getIsMutableFiles().contains(file));
}
 
Example 6
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 5 votes
public void testCannotLockReadOnlyFile() throws Exception {
    clearWorkDir();
    final File wDir = getWorkDir();
    final File data = new File(wDir,"c.data");
    data.createNewFile();
    data.setReadOnly();
    FileObject fd = FileUtil.toFileObject(data);
    try {
        FileLock lock = fd.lock();
        fail("Shall not be possible to create a lock: " + lock);
    } catch (IOException ex) {
    }
}
 
Example 7
Project: incubator-netbeans   File: SourceGroupsTest.java   View Source Code Vote up 5 votes
public void testIsFolderWritable() throws Exception {
    SourceGroup[] javaSGs = SourceGroups.getJavaSourceGroups(javaApp);
    // existing folder
    assertTrue(SourceGroups.isFolderWritable(javaSGs[0], "javaapp"));
    // non-existing
    assertTrue(SourceGroups.isFolderWritable(javaSGs[0], "should.not.exist"));
    
    File notWritableRoot = new File(getWorkDir(), "cantwrite");
    notWritableRoot.mkdir();
    notWritableRoot.setReadOnly();
    SourceGroup notWritable = new SourceGroupImpl(notWritableRoot);
    assertFalse(SourceGroups.isFolderWritable(notWritable, ""));
    assertFalse(SourceGroups.isFolderWritable(notWritable, "should.not.exist"));
}
 
Example 8
Project: myfaces-trinidad   File: FileSystemStyleCache.java   View Source Code Vote up 5 votes
/**
 * Creates a new PrintWriter.  The caller is responsible for closing the Writer when done with it
 * @return
 */
public PrintWriter createWriter()
{
  File outputFile = _getOutputFile(_baseFilename, _files.size() + 1);
  
  // We never want to do anything other than read it or delete it:
  outputFile.setReadOnly();

  _files.add(outputFile);
  
  return _getWriter(outputFile);
}
 
Example 9
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 10
Project: openjdk-jdk10   File: TestIOException.java   View Source Code Vote up 5 votes
@Test
void testReadOnlySubdirectory() throws Exception {
    // init source file
    File srcDir = new File("src4");
    File src_p = new File(srcDir, "p");
    src_p.mkdirs();
    File src_p_C = new File(src_p, "C.java");
    try (FileWriter fw = new FileWriter(src_p_C)) {
        fw.write("package p; public class C { }");
    }

    // create an unwritable package output directory
    File outDir = new File("out3");
    File pkgOutDir = new File(outDir, "p");
    if (!pkgOutDir.mkdirs()) {
        throw new Error("Cannot create directory");
    }
    if (!pkgOutDir.setReadOnly()) {
        throw new Error("could not set directory read-only");
    }
    if (pkgOutDir.canWrite()) {
        throw new Error("directory is writable");
    }

    // run javadoc and check results
    try {
        setOutputDirectoryCheck(DirectoryCheck.NONE);
        javadoc("-d", outDir.toString(),
                src_p_C.getPath());
        checkExit(Exit.ERROR);
        checkOutput(Output.OUT, true,
            "Error writing file: " + new File(pkgOutDir, "C.html"));
    } finally {
        setOutputDirectoryCheck(DirectoryCheck.EMPTY);
        pkgOutDir.setWritable(true);
    }
}
 
Example 11
Project: incubator-netbeans   File: DataFolderTest.java   View Source Code Vote up 4 votes
public void testMoveFolderWithReadOnlyFile () throws Exception {
        String fsstruct [] = new String [] {
            "AA/A.txt",
            "AA/B.txt",
            "AA/C.txt",
            "AA/D.txt",
            "target/",
        };
        
        FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);

        FileObject fo = lfs.findResource ("AA");
        DataFolder folder = DataFolder.findFolder(fo);
        
        FileObject c = lfs.findResource("AA/C.txt");
        File cFile = FileUtil.toFile(c);
        assertNotNull(cFile);
        
        cFile.setReadOnly();
        
        assertFalse("Read only", c.canWrite());
        
        
        DataFolder target = DataFolder.findFolder(lfs.findResource("target"));

        CharSequence log = Log.enable("org.openide.loaders.DataFolder", Level.INFO);
        folder.move(target);
//        if (log.toString().indexOf("C.txt") == -1) {
//            fail("There should be warning about C.txt:\n" + log);
//        }
        FileObject newFO = lfs.findResource("target/AA");
        assertNotNull("New folder created", newFO);
        DataFolder newFolder = DataFolder.findFolder(newFO);
        assertEquals("New folder has three DO", 3, newFolder.getChildren().length);
        
        
        assertEquals("Folder keeps pointing to old file", "AA", folder.getPrimaryFile().getPath());
        assertEquals("It has one DO", 1, folder.getChildren().length);
        
        DataFolder original = DataFolder.findFolder(lfs.findResource("AA"));
        assertSame("Old folder retains identity", original, folder);
        
        if (newFolder == folder) {
            fail("newFolder should be created");
        }
        
        Node[] oldNodes = folder.getNodeDelegate().getChildren().getNodes(true);
        assertEquals("One node remains", 1, oldNodes.length);
        
        
        Node[] newNodes = newFolder.getNodeDelegate().getChildren().getNodes(true);
        assertEquals("Three nodes created", 3, newNodes.length);
    }
 
Example 12
Project: incubator-netbeans   File: FileVCSTest.java   View Source Code Vote up 4 votes
@Override
protected void setReadOnly(String path) throws IOException {
    File f = new File(workDirPath, path);
    assertNotNull(f);
    f.setReadOnly();
}
 
Example 13
Project: javaide   File: FileOp.java   View Source Code Vote up 4 votes
@Override
public void setReadOnly(@NonNull File file) {
    file.setReadOnly();
}
 
Example 14
Project: OpenJSharp   File: FileCodeWriter.java   View Source Code Vote up 4 votes
public void close() throws IOException {
    // mark files as read-onnly if necessary
    for (File f : readonlyFiles)
        f.setReadOnly();
}
 
Example 15
Project: hadoop   File: TestDataNodeVolumeFailure.java   View Source Code Vote up 4 votes
@Test
public void testVolumeFailure() throws Exception {
  System.out.println("Data dir: is " +  dataDir.getPath());
 
  
  // Data dir structure is dataDir/data[1-4]/[current,tmp...]
  // data1,2 is for datanode 1, data2,3 - datanode2 
  String filename = "/test.txt";
  Path filePath = new Path(filename);
  
  // we use only small number of blocks to avoid creating subdirs in the data dir..
  int filesize = block_size*blocks_num;
  DFSTestUtil.createFile(fs, filePath, filesize, repl, 1L);
  DFSTestUtil.waitReplication(fs, filePath, repl);
  System.out.println("file " + filename + "(size " +
      filesize + ") is created and replicated");
 
  // fail the volume
  // delete/make non-writable one of the directories (failed volume)
  data_fail = new File(dataDir, "data3");
  failedDir = MiniDFSCluster.getFinalizedDir(dataDir, 
      cluster.getNamesystem().getBlockPoolId());
  if (failedDir.exists() &&
      //!FileUtil.fullyDelete(failedDir)
      !deteteBlocks(failedDir)
      ) {
    throw new IOException("Could not delete hdfs directory '" + failedDir + "'");
  }
  data_fail.setReadOnly();
  failedDir.setReadOnly();
  System.out.println("Deleteing " + failedDir.getPath() + "; exist=" + failedDir.exists());
  
  // access all the blocks on the "failed" DataNode, 
  // we need to make sure that the "failed" volume is being accessed - 
  // and that will cause failure, blocks removal, "emergency" block report
  triggerFailure(filename, filesize);
  
  // make sure a block report is sent 
  DataNode dn = cluster.getDataNodes().get(1); //corresponds to dir data3
  String bpid = cluster.getNamesystem().getBlockPoolId();
  DatanodeRegistration dnR = dn.getDNRegistrationForBP(bpid);
  
  Map<DatanodeStorage, BlockListAsLongs> perVolumeBlockLists =
      dn.getFSDataset().getBlockReports(bpid);

  // Send block report
  StorageBlockReport[] reports =
      new StorageBlockReport[perVolumeBlockLists.size()];

  int reportIndex = 0;
  for(Map.Entry<DatanodeStorage, BlockListAsLongs> kvPair : perVolumeBlockLists.entrySet()) {
      DatanodeStorage dnStorage = kvPair.getKey();
      BlockListAsLongs blockList = kvPair.getValue();
      reports[reportIndex++] =
          new StorageBlockReport(dnStorage, blockList);
  }
  
  cluster.getNameNodeRpc().blockReport(dnR, bpid, reports, null);

  // verify number of blocks and files...
  verify(filename, filesize);
  
  // create another file (with one volume failed).
  System.out.println("creating file test1.txt");
  Path fileName1 = new Path("/test1.txt");
  DFSTestUtil.createFile(fs, fileName1, filesize, repl, 1L);
  
  // should be able to replicate to both nodes (2 DN, repl=2)
  DFSTestUtil.waitReplication(fs, fileName1, repl);
  System.out.println("file " + fileName1.getName() + 
      " is created and replicated");
}
 
Example 16
Project: openjdk-jdk10   File: TestIOException.java   View Source Code Vote up 4 votes
@Test
void testReadOnlyDocFilesDir() throws Exception {
    // init source files
    File srcDir = new File("src4");
    File src_p = new File(srcDir, "p");
    src_p.mkdirs();
    File src_p_C = new File(src_p, "C.java");
    try (FileWriter fw = new FileWriter(src_p_C)) {
        fw.write("package p; public class C { }");
    }
    File src_p_docfiles = new File(src_p, "doc-files");
    src_p_docfiles.mkdir();
    try (FileWriter fw = new FileWriter(new File(src_p_docfiles, "info.txt"))) {
        fw.write("info");
    }

    // create an unwritable doc-files output directory
    File outDir = new File("out4");
    File pkgOutDir = new File(outDir, "p");
    File docFilesOutDir = new File(pkgOutDir, "doc-files");
    if (!docFilesOutDir.mkdirs()) {
        throw new Error("Cannot create directory");
    }
    if (!docFilesOutDir.setReadOnly()) {
        throw new Error("could not set directory read-only");
    }
    if (docFilesOutDir.canWrite()) {
        throw new Error("directory is writable");
    }

    try {
        setOutputDirectoryCheck(DirectoryCheck.NONE);
        javadoc("-d", outDir.toString(),
                "-sourcepath", srcDir.getPath(),
                "p");
        checkExit(Exit.ERROR);
        checkOutput(Output.OUT, true,
            "Error writing file: " + new File(docFilesOutDir, "info.txt"));
    } finally {
        setOutputDirectoryCheck(DirectoryCheck.EMPTY);
        docFilesOutDir.setWritable(true);
    }
}
 
Example 17
Project: openjdk-jdk10   File: FileCodeWriter.java   View Source Code Vote up 4 votes
@Override
public void close() throws IOException {
    // mark files as read-onnly if necessary
    for (File f : readonlyFiles)
        f.setReadOnly();
}