List of usage examples for java.io File setWritable
public boolean setWritable(boolean writable, boolean ownerOnly)
From source file:org.docx4all.ui.menu.FileMenu.java
public void createInFileSystem(FileObject file) throws FileSystemException { FileObject parent = file.getParent(); String uri = UriParser.decode(parent.getName().getURI()); if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1 && parent.getName().getScheme().startsWith("file") && !parent.isWriteable() && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) { //TODO: Check whether we still need this workaround. //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819 //Re: File.canWrite() returns false for the "My Documents" directory (win) String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent); File f = new File(localpath); f.setWritable(true, true); }/*from www . j av a 2 s .co m*/ file.createFile(); }
From source file:hudson.plugins.project_inheritance.projects.view.InheritanceViewAction.java
private boolean dumpBuildSteps(List<Builder> builders, List<File> generatedScripts, File srcDir) throws IOException { boolean isLinux = true; int i = 0;/*from www . j a v a2 s . c o m*/ for (Builder builder : builders) { if (!(builder instanceof CommandInterpreter)) { continue; } CommandInterpreter ci = (CommandInterpreter) builder; File builderScript; if (builder instanceof BatchFile) { isLinux = false; builderScript = new File(srcDir, String.format("step_%d.bat", i++)); } else { builderScript = new File(srcDir, String.format("step_%d.sh", i++)); } BufferedWriter out = new BufferedWriter(new FileWriter(builderScript, true)); String cmd = ci.getCommand(); if (!isLinux) { //Ensure windows line-endings cmd = cmd.replaceAll("\r\n", "\n").replaceAll("\n", "\r\n"); } out.write(cmd); builderScript.setExecutable(true, false); builderScript.setReadable(true, false); builderScript.setWritable(true, false); out.close(); generatedScripts.add(builderScript); } return isLinux; }
From source file:com.buaa.cfs.utils.FileUtil.java
/** * Set permissions to the required value. Uses the java primitives instead of forking if group == other. * * @param f the file to change// www. j av a 2s. c o m * @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 or on Windows if (group != other || NativeIO.isAvailable() || Shell.WINDOWS) { 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)) { rv = 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)) { rv = 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)) { rv = f.setExecutable(user.implies(FsAction.EXECUTE), true); checkReturnValue(rv, f, permission); } }
From source file:org.docx4all.ui.menu.FileMenu.java
private RETURN_TYPE saveAsFile(String callerActionName, ActionEvent actionEvent, String fileType) { Preferences prefs = Preferences.userNodeForPackage(getClass()); WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class); ResourceMap rm = editor.getContext().getResourceMap(getClass()); JInternalFrame iframe = editor.getCurrentInternalFrame(); String oldFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY); VFSJFileChooser chooser = createFileChooser(rm, callerActionName, iframe, fileType); RETURN_TYPE returnVal = chooser.showSaveDialog((Component) actionEvent.getSource()); if (returnVal == RETURN_TYPE.APPROVE) { FileObject selectedFile = getSelectedFile(chooser, fileType); boolean error = false; boolean newlyCreatedFile = false; if (selectedFile == null) { // Should never happen, whether the file exists or not } else {// w w w . j av a 2 s .c o m //Check selectedFile's existence and ask user confirmation when needed. try { boolean selectedFileExists = selectedFile.exists(); if (!selectedFileExists) { FileObject parent = selectedFile.getParent(); String uri = UriParser.decode(parent.getName().getURI()); if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1 && parent.getName().getScheme().startsWith("file") && !parent.isWriteable() && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) { //TODO: Check whether we still need this workaround. //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819 //Re: File.canWrite() returns false for the "My Documents" directory (win) String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent); File f = new File(localpath); f.setWritable(true, true); } selectedFile.createFile(); newlyCreatedFile = true; } else if (!selectedFile.getName().getURI().equalsIgnoreCase(oldFilePath)) { String title = rm.getString(callerActionName + ".Action.text"); String message = VFSUtils.getFriendlyName(selectedFile.getName().getURI()) + "\n" + rm.getString(callerActionName + ".Action.confirmMessage"); int answer = editor.showConfirmDialog(title, message, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) { selectedFile = null; } } // if (!selectedFileExists) } catch (FileSystemException exc) { exc.printStackTrace();//ignore log.error("Couldn't create new file or assure file existence. File = " + selectedFile.getName().getURI()); selectedFile = null; error = true; } } //Check whether there has been an error, cancellation by user //or may proceed to saving file. if (selectedFile != null) { //Proceed to saving file String selectedPath = selectedFile.getName().getURI(); if (log.isDebugEnabled()) { log.debug("saveAsFile(): selectedFile = " + VFSUtils.getFriendlyName(selectedPath)); } prefs.put(Constants.LAST_OPENED_FILE, selectedPath); if (selectedFile.getName().getScheme().equals("file")) { prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath); } PreferenceUtil.flush(prefs); boolean success = false; if (EXPORT_AS_NON_SHARED_DOC_ACTION_NAME.equals(callerActionName)) { log.info("saveAsFile(): Exporting as non shared document to " + VFSUtils.getFriendlyName(selectedPath)); success = export(iframe, selectedPath, callerActionName); if (success) { prefs.put(Constants.LAST_OPENED_FILE, selectedPath); if (selectedPath.startsWith("file:")) { prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath); } PreferenceUtil.flush(prefs); log.info("saveAsFile(): Opening " + VFSUtils.getFriendlyName(selectedPath)); editor.createInternalFrame(selectedFile); } } else { success = save(iframe, selectedPath, callerActionName); if (success) { if (Constants.DOCX_STRING.equals(fileType) || Constants.FLAT_OPC_STRING.equals(fileType)) { //If saving as .docx then update the document dirty flag //of toolbar states as well as internal frame title. editor.getToolbarStates().setDocumentDirty(iframe, false); editor.getToolbarStates().setLocalEditsEnabled(iframe, false); FileObject file = null; try { file = VFSUtils.getFileSystemManager().resolveFile(oldFilePath); editor.updateInternalFrame(file, selectedFile); } catch (FileSystemException exc) { ;//ignore } } else { //Because document dirty flag is not cleared //and internal frame title is not changed, //we present a success message. String title = rm.getString(callerActionName + ".Action.text"); String message = VFSUtils.getFriendlyName(selectedPath) + "\n" + rm.getString(callerActionName + ".Action.successMessage"); editor.showMessageDialog(title, message, JOptionPane.INFORMATION_MESSAGE); } } } if (!success && newlyCreatedFile) { try { selectedFile.delete(); } catch (FileSystemException exc) { log.error("saveAsFile(): Saving failure and cannot remove the newly created file = " + selectedPath); exc.printStackTrace(); } } } else if (error) { log.error("saveAsFile(): selectedFile = NULL"); String title = rm.getString(callerActionName + ".Action.text"); String message = rm.getString(callerActionName + ".Action.errorMessage"); editor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE); } } //if (returnVal == JFileChooser.APPROVE_OPTION) return returnVal; }
From source file:com.pari.nm.utils.backup.BackupRestore.java
public boolean unzip(File zipFile) { ZipFile zf = null;//from w ww . j av a 2 s . c o m FileOutputStream fout = null; // File zipFile = new File(localDir, zipFileName); try { zf = new ZipFile(zipFile); Enumeration en = zf.entries(); while (en.hasMoreElements()) { ZipEntry ze = (ZipEntry) en.nextElement(); String currentEntry = ze.getName(); File destFile = new File(zipFile.getParent(), currentEntry); File destinationParent = destFile.getParentFile(); if (!destinationParent.exists()) { destinationParent.mkdirs(); destinationParent.setWritable(true, false); } System.err.println("ZIP ENTRY NAME:" + currentEntry); if (!ze.isDirectory()) { InputStream in = zf.getInputStream(ze); byte[] data = new byte[4096]; int read = 0; File extractFile = new File(zipFile.getParent(), ze.getName()); fout = new FileOutputStream(extractFile); while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); } } return true; } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (zf != null) { zf.close(); } } catch (Exception ex) { } try { if (fout != null) { fout.close(); } } catch (Exception ex) { } } return false; }
From source file:ezbake.protect.ezca.EzCABootstrap.java
public void ensureDirectory(String path) throws IOException { File directory = new File(path); if (directory.exists() && !directory.isDirectory()) { throw new IOException("Unable to create directory. " + path + " already exists and is not a directory"); }/* w w w. j a va2 s .c o m*/ if (!directory.mkdirs() && !directory.isDirectory()) { throw new IOException("Unable to make directories, mkdirs returned false"); } if (!directory.setExecutable(false, false) || !directory.setExecutable(true, true)) { throw new IOException("Created directory, but unable to set executable"); } if (!directory.setReadable(false, false) || !directory.setReadable(true, true)) { throw new IOException("Created directory, but unable to set readable"); } if (!directory.setWritable(false, false) || !directory.setWritable(true, true)) { throw new IOException("Created directory, but unable to set writable"); } }
From source file:edu.umd.cs.buildServer.BuildServer.java
/** * Makes a directory world-readable./*w w w . j a v a2 s. c o m*/ * <p> * This will not work on Windows! * * @param dirName * The directory to make world-readable. * @throws IOException */ private void makeDirectoryWorldReadable(File dir) throws IOException { // TODO Make sure that this is a non-Windows machine. if (dir.isDirectory()) { dir.setReadable(true, false); dir.setWritable(true, false); dir.setExecutable(true, false); } }
From source file:org.apache.flink.runtime.blob.BlobServerGetTest.java
/** * Retrieves a BLOB from the HA store to a {@link BlobServer} which cannot create incoming * files. File transfers should fail.// ww w . j av a 2s .c om */ @Test public void testGetFailsIncomingForJobHa() throws IOException { assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows. final JobID jobId = new JobID(); final Configuration config = new Configuration(); config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER"); config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath()); config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, temporaryFolder.newFolder().getPath()); BlobStoreService blobStore = null; try { blobStore = BlobUtils.createBlobStoreFromConfig(config); File tempFileDir = null; try (BlobServer server = new BlobServer(config, blobStore)) { server.start(); // store the data on the server (and blobStore), remove from local store byte[] data = new byte[2000000]; rnd.nextBytes(data); BlobKey blobKey = put(server, jobId, data, PERMANENT_BLOB); assertTrue(server.getStorageLocation(jobId, blobKey).delete()); // 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)); // request the file from the BlobStore exception.expect(IOException.class); exception.expectMessage("Permission denied"); try { get(server, jobId, blobKey); } finally { HashSet<String> expectedDirs = new HashSet<>(); expectedDirs.add("incoming"); expectedDirs.add(JOB_DIR_PREFIX + jobId); // only the incoming and job directory should exist (no job directory!) File storageDir = tempFileDir.getParentFile(); String[] actualDirs = storageDir.list(); assertNotNull(actualDirs); assertEquals(expectedDirs, new HashSet<>(Arrays.asList(actualDirs))); // job directory should be empty File jobDir = new File(tempFileDir.getParentFile(), JOB_DIR_PREFIX + jobId); assertArrayEquals(new String[] {}, jobDir.list()); } } finally { // set writable again to make sure we can remove the directory if (tempFileDir != null) { //noinspection ResultOfMethodCallIgnored tempFileDir.setWritable(true, false); } } } finally { if (blobStore != null) { blobStore.closeAndCleanupAllData(); } } }
From source file:org.apache.flink.runtime.blob.BlobServerGetTest.java
/** * Retrieves a BLOB from the HA store to a {@link BlobServer} which cannot create the final * storage file. File transfers should fail. *///from ww w .j a va 2 s .c o m @Test public void testGetFailsStoreForJobHa() throws IOException { assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows. final JobID jobId = new JobID(); final Configuration config = new Configuration(); config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER"); config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath()); config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, temporaryFolder.newFolder().getPath()); BlobStoreService blobStore = null; try { blobStore = BlobUtils.createBlobStoreFromConfig(config); File jobStoreDir = null; try (BlobServer server = new BlobServer(config, blobStore)) { server.start(); // store the data on the server (and blobStore), remove from local store byte[] data = new byte[2000000]; rnd.nextBytes(data); BlobKey blobKey = put(server, jobId, data, PERMANENT_BLOB); assertTrue(server.getStorageLocation(jobId, blobKey).delete()); // make sure the blob cache cannot create any files in its storage dir jobStoreDir = server.getStorageLocation(jobId, blobKey).getParentFile(); assertTrue(jobStoreDir.setExecutable(true, false)); assertTrue(jobStoreDir.setReadable(true, false)); assertTrue(jobStoreDir.setWritable(false, false)); // request the file from the BlobStore exception.expect(AccessDeniedException.class); try { get(server, jobId, blobKey); } finally { // there should be no remaining incoming files File incomingFileDir = new File(jobStoreDir.getParent(), "incoming"); assertArrayEquals(new String[] {}, incomingFileDir.list()); // there should be no files in the job directory assertArrayEquals(new String[] {}, jobStoreDir.list()); } } finally { // set writable again to make sure we can remove the directory if (jobStoreDir != null) { //noinspection ResultOfMethodCallIgnored jobStoreDir.setWritable(true, false); } } } finally { if (blobStore != null) { blobStore.closeAndCleanupAllData(); } } }
From source file:com.pari.nm.utils.backup.BackupRestore.java
public synchronized boolean doDBBackup(File backupDir, BackupRestoreJob statusIf) { try {/*w w w. j a v a2s . c o m*/ // First run the back to a dir DBOperations bup = new DBOperations(); if (!backupDir.exists()) { backupDir.mkdir(); backupDir.setWritable(true, false); } String fileName = ""; if (isPostgres()) { fileName = "paridb"; } else { fileName = "paridb.dmp"; } { if (bup.backup(backupDir, fileName)) { statusIf.logMsg("Database backedup successfully."); print("Database backedup successfully."); statusIf.statusUpdate("Database backedup successfully", true, 30, ""); File exportLog = new File(backupDir, "export.log"); if (exportLog.exists()) { exportLog.delete(); } } else { statusIf.setState(JobStatus.FAILED); statusIf.logMsg( "Failed to exported the database. Contact Pari Support (support@parinetworks.com)."); statusIf.executionComplete( "Failed to exported the database. Contact Pari Support (support@parinetworks.com).", false, ""); logger.debug( "Failed to exported the database. Contact Pari Support (support@parinetworks.com)."); return false; } } return true; } catch (Exception ex) { ex.printStackTrace(); statusIf.setState(JobStatus.FAILED); statusIf.logMsg("Failed to exported the database. Contact Pari Support (support@parinetworks.com)."); statusIf.executionComplete( "Failed to exported the database. Contact Pari Support (support@parinetworks.com).", false, ""); } return false; }