List of usage examples for java.io File setWritable
public boolean setWritable(boolean writable)
From source file:org.duracloud.retrieval.config.RetrievalToolConfigParser.java
protected RetrievalToolConfig processOptions(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(cmdOptions, args); RetrievalToolConfig config = new RetrievalToolConfig(); config.setContext(DEFAULT_CONTEXT);/*from w w w .j a va 2 s .c o m*/ config.setHost(cmd.getOptionValue("h")); config.setUsername(cmd.getOptionValue("u")); if (null != cmd.getOptionValue("p")) { config.setPassword(cmd.getOptionValue("p")); } else if (null != getPasswordEnvVariable()) { config.setPassword(getPasswordEnvVariable()); } else { ConsolePrompt console = getConsole(); if (null == console) { printHelp("You must either specify a password in the command " + "line or specify the " + CommandLineToolUtil.PASSWORD_ENV_VARIABLE_NAME + " environmental variable."); } else { char[] password = console.readPassword("DuraCloud password: "); config.setPassword(new String(password)); } } if (cmd.hasOption("r")) { try { config.setPort(Integer.valueOf(cmd.getOptionValue("r"))); } catch (NumberFormatException e) { throw new ParseException("The value for port (-r) must be " + "a number."); } } else { config.setPort(DEFAULT_PORT); } if (cmd.hasOption("i")) { config.setStoreId(cmd.getOptionValue("i")); } if (!cmd.hasOption("s") && !cmd.hasOption("a")) { throw new ParseException("Either a list of spaces (-s) should be " + "provided or the all spaces flag (-a) must be set."); } if (cmd.hasOption("s")) { String[] spaces = cmd.getOptionValues("s"); List<String> spacesList = new ArrayList<String>(); for (String space : spaces) { if (space != null && !space.equals("")) { spacesList.add(space); } } config.setSpaces(spacesList); } if (cmd.hasOption("a")) { config.setAllSpaces(true); } else { config.setAllSpaces(false); } File contentDir = new File(cmd.getOptionValue("c")); if (contentDir.exists()) { if (!contentDir.isDirectory()) { throw new ParseException("Content Dir paramter must provide " + "the path to a directory."); } } else { contentDir.mkdirs(); } contentDir.setWritable(true); config.setContentDir(contentDir); if (cmd.hasOption("w")) { File workDir = new File(cmd.getOptionValue("w")); if (workDir.exists()) { if (!workDir.isDirectory()) { throw new ParseException("Work Dir parameter must provide " + "the path to a directory."); } } else { workDir.mkdirs(); } workDir.setWritable(true); config.setWorkDir(workDir); } else { config.setWorkDir(null); } if (cmd.hasOption("o")) { config.setOverwrite(true); } else { config.setOverwrite(false); } if (cmd.hasOption("t")) { try { config.setNumThreads(Integer.valueOf(cmd.getOptionValue("t"))); } catch (NumberFormatException e) { throw new ParseException("The value for threads (-t) must " + "be a number."); } } else { config.setNumThreads(DEFAULT_NUM_THREADS); } if (cmd.hasOption("d")) { config.setApplyTimestamps(false); } else { config.setApplyTimestamps(true); } if (cmd.hasOption("l")) { config.setListOnly(true); } else { config.setListOnly(false); } if (cmd.hasOption("f")) { if ((config.getSpaces() != null && config.getSpaces().size() > 1) || config.isAllSpaces()) { throw new ParseException( "The 'list-file' option (-f) can " + "only operate on one space at a time."); } else if (config.isListOnly()) { throw new ParseException("The 'list-file' option (-f) can " + "not be used at the same time with the 'list-only' option (-l)."); } else { File listFile = new File(cmd.getOptionValue("f")); if (listFile.exists()) { config.setListFile(listFile); } else { throw new ParseException( "The specified 'list-file' containing " + "content IDs to retrieve does not exist."); } } } return config; }
From source file:org.multibit.file.FileHandler.java
/** * Delete a file with an overwrite of all of the data. * //from w w w. java2 s. co m * Set bit patterns are used rather than random numbers to avoid a * futex_wait_queue_me error on Linux systems (related to /dev/random usage) * * @param file * @throws IOException */ public static void secureDelete(File file) throws IOException { log.debug("Start of secureDelete"); RandomAccessFile raf = null; if (file != null && file.exists()) { try { // Prep for file delete as this can be fiddly on windows. // Make sure it is writable and any references to it are garbage // collected and finalized. file.setWritable(true); System.gc(); long length = file.length(); raf = new RandomAccessFile(file, "rws"); raf.seek(0); raf.getFilePointer(); int pos = 0; while (pos < length) { raf.write(SECURE_DELETE_FILL_BYTES); pos += SECURE_DELETE_FILL_BYTES.length; } } finally { if (raf != null) { raf.close(); raf = null; } } boolean deleteSuccess = file.delete(); log.debug("Result of delete of file '" + file.getAbsolutePath() + "' was " + deleteSuccess); } log.debug("End of secureDelete"); }
From source file:sce.ProcessExecutor.java
/** * File Permissions using File and PosixFilePermission * * @throws IOException// w w w . j ava 2s.c o m */ public void setFilePermissions() throws IOException { File file = new File("/Users/temp.txt"); //set application user permissions to 455 file.setExecutable(false); file.setReadable(false); file.setWritable(true); //change permission to 777 for all the users //no option for group and others file.setExecutable(true, false); file.setReadable(true, false); file.setWritable(true, false); //using PosixFilePermission to set file permissions 777 Set<PosixFilePermission> perms = new HashSet<>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms); }
From source file:com.tela.pms.PatientController.java
/** * loadHomePage will also provide facility to load the application home for logged in users. *//*w ww.j ava 2s . c om*/ @RequestMapping(value = "/deletePatient", method = RequestMethod.POST) public String deletePatient(Model model, HttpServletRequest request) { String patientId = request.getParameter("patientId"); String patientPhoto = request.getParameter("patientPhoto"); int id = Integer.parseInt(patientId); String realName = "patient-" + patientId; if (patientPhoto.contains(realName)) { logger.info("Patient to be deleted has a photo in cloudinary " + id); String fileName = patientPhoto + ".jpg"; File catalinaBase = new File(System.getProperty("catalina.base")).getAbsoluteFile(); logger.info("catalinaBase:" + catalinaBase.getAbsolutePath()); File newFile = new File(catalinaBase, "webapps/pms/WEB-INF/views/images/Uploaded_images/Patients/" + fileName); newFile.setWritable(true); newFile.delete(); /* try { FileOutputStream to; String file = "/home/amila/patient/" + fileName; to = new FileOutputStream(file ); to.write(new String("blah blah").getBytes()); to.flush(); to.close(); File f = new File(file); System.out.print(f.delete()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } Patient patient = new Patient(); patient.setPatient_Id(id); patientService.deletePatient(patient); logger.info("Patient " + id + " deleted @ " + new Date()); /*deleting prescription for deleted user*/ List<Prescription> prescriptionList_todelete = prescriptionService.retrieveAllPrescriptionsByPatientId(id); for (Prescription prescription : prescriptionList_todelete) { prescriptionService.deletePrescription(prescription); } patientList = patientService.retrieveAllPatients(); model.addAttribute("patientList", patientList); return "home"; }
From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceDirectoryHandlerTest.java
@Test public void throwsExceptionWhenUploadDirectoryForWorkspaceCreationFails() throws WorkspaceFilesystemException { int workspaceID = 1; File workspaceDirectory = new File(this.workspaceBaseDirectory, "" + workspaceID); boolean isDirectoryCreated = workspaceDirectory.mkdirs(); assertTrue("Workspace directory was not successfuly created.", isDirectoryCreated); assertTrue("Workspace directory wasn't created", workspaceDirectory.exists()); workspaceDirectory.setWritable(false); File workspaceUploadDirectory = new File(workspaceDirectory, this.workspaceUploadDirectoryName); String errorMessage = "Upload directory for workspace " + workspaceID + " could not be created"; try {//from www . j a v a 2 s . c o m this.workspaceDirectoryHandler.createUploadDirectoryForWorkspace(workspaceID); fail("Exception was not thrown"); } catch (IOException ex) { assertEquals(errorMessage, ex.getMessage()); } assertFalse("Workspace upload directory shouldn't have been created," + " since there should be no permissions for that.", workspaceUploadDirectory.exists()); }
From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceDirectoryHandlerTest.java
@Test public void throwsExceptionWhenOrphansDirectoryInWorkspaceCreationFails() throws WorkspaceFilesystemException { int workspaceID = 1; File workspaceDirectory = new File(this.workspaceBaseDirectory, "" + workspaceID); boolean isDirectoryCreated = workspaceDirectory.mkdirs(); assertTrue("Workspace directory was not successfuly created.", isDirectoryCreated); assertTrue("Workspace directory wasn't created", workspaceDirectory.exists()); workspaceDirectory.setWritable(false); File workspaceOrphansDirectory = new File(workspaceDirectory, this.orphansDirectoryName); String errorMessage = "Orphans directory in workspace " + workspaceID + " could not be created"; try {//from w w w . j a v a 2s .c o m this.workspaceDirectoryHandler.createOrphansDirectoryInWorkspace(workspaceID); fail("Exception was not thrown"); } catch (IOException ex) { assertEquals(errorMessage, ex.getMessage()); } assertFalse("Workspace orphans directory shouldn't have been created," + " since there should be no permissions for that.", workspaceOrphansDirectory.exists()); }
From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java
/** * Dumps data provided the rows variable into the specified database. The location of the database * is in the form's media folder in ODK's SDCard's folder. * * Indexes in {@param rows} are expected to correspond to rows in {@param org.cgiar.ilri.odk.pull.backend.carriers.Form.DB_DATA_TABLE} for {@param fileName}. * Each JSONArray element should be a JSONObject with children being column values (with keys being column names). * Make sure all JSONObjects in the JSONArray have the same number of key-value pairs. * * @param fileName Then name to be given to the Database (without the .db suffix) * @param rows The {@link org.json.JSONArray} object containing the data * @return TRUE if database created successfully *//* w ww .ja va 2s .c o m*/ private boolean saveDataInDb(String fileName, JSONArray rows) { boolean result = false; //TODO: only do this if ODK Collect is not using this file String pathToFile = Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX; /*File existingDb = new File(pathToFile+File.separator+fileName+Form.SUFFIX_DB); existingDb.delete();*/ final DatabaseHelper databaseHelper = new DatabaseHelper(this, fileName, 1, pathToFile); SQLiteDatabase db = null; try { db = databaseHelper.getWritableDatabase(); } catch (SQLiteException e) {//probably because the existing .db file is corrupt e.printStackTrace(); Log.w(TAG, "Unable to open database in " + pathToFile + File.separator + fileName + Form.SUFFIX_DB + " most likely because the database is corrupt. Trying to recreate db file"); File existingDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB); existingDbFile.delete(); File existingDbJournalFile = new File( pathToFile + File.separator + fileName + Form.SUFFIX_DB + Form.SUFFIX_JOURNAL); existingDbJournalFile.delete(); try { db = databaseHelper.getWritableDatabase(); } catch (SQLiteException e1) { Log.e(TAG, "Unable to recreate " + pathToFile + File.separator + fileName + Form.SUFFIX_DB + " file"); e1.printStackTrace(); } } if (rows.length() > 0 && db != null) { try { List<String> columns = new ArrayList<String>(); List<String> indexes = new ArrayList<String>(); Iterator<String> iterator = rows.getJSONObject(0).keys(); //recreate the tables db.execSQL("drop table if exists " + Form.DB_METADATA_TABLE); String createMetaTableString = "create table " + Form.DB_METADATA_TABLE + " (" + Form.DB_META_LOCALE_FIELD + " " + Form.DB_META_LOCALE_FIELD_TYPE + ")"; db.execSQL(createMetaTableString); databaseHelper.runInsertQuery(Form.DB_METADATA_TABLE, new String[] { Form.DB_META_LOCALE_FIELD }, new String[] { Form.DB_DEFAULT_LOCALE }, -1, db); db.execSQL("drop table if exists " + Form.DB_DATA_TABLE); String createTableString = "create table " + Form.DB_DATA_TABLE + " ("; while (iterator.hasNext()) { String currKey = iterator.next(); if (columns.size() > 0) {//this is the first column createTableString = createTableString + ", "; } createTableString = createTableString + Form.DB_DATA_COLUMN_PREFIX + currKey + " " + Form.DB_DATA_COLUMN_TYPE; columns.add(currKey); if (currKey.endsWith(Form.SUFFIX_INDEX_FIELD)) { Log.d(TAG, fileName + " has an index column " + currKey); indexes.add(currKey); } } //only continue if we have at least one column if (columns.size() > 0) { createTableString = createTableString + ", " + Form.DB_DATA_SORT_FIELD + " " + Form.DB_DATA_SORT_COLUMN_TYPE + ")"; db.execSQL(createTableString); for (int index = 0; index < indexes.size(); index++) { db.execSQL("create index " + indexes.get(index) + Form.SUFFIX_INDEX + " on " + Form.DB_DATA_TABLE + "(" + Form.DB_DATA_COLUMN_PREFIX + indexes.get(index) + ")"); } for (int rowIndex = 0; rowIndex < rows.length(); rowIndex++) { JSONObject currRow = rows.getJSONObject(rowIndex); String[] currColumns = new String[columns.size() + 1]; String[] currValues = new String[columns.size() + 1]; for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) { currColumns[columnIndex] = Form.DB_DATA_COLUMN_PREFIX + columns.get(columnIndex); currValues[columnIndex] = currRow.getString(columns.get(columnIndex)); } currColumns[columns.size()] = Form.DB_DATA_SORT_FIELD; currValues[columns.size()] = String.valueOf((double) rowIndex);//TODO: not sure if should be float or double databaseHelper.runInsertQuery(Form.DB_DATA_TABLE, currColumns, currValues, -1, db);//do not add unique key field index in argument list. Will end up being an extra query } result = true; } } catch (JSONException e) { e.printStackTrace(); } } else { Log.w(TAG, "Provided jsonArray to be dumped into a db is empty"); } db.close(); //copy db to the ADB push directory File adbFormDir = new File( Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX); if (!adbFormDir.exists() || !adbFormDir.isDirectory()) { adbFormDir.setWritable(true); adbFormDir.setReadable(true); Log.i(TAG, "Trying to create dir " + adbFormDir.getPath()); } File sourceDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB); File destDbFile = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX + File.separator + fileName + Form.SUFFIX_DB); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(sourceDbFile); out = new FileOutputStream(destDbFile); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:com.streamsets.datacollector.cluster.TestShellClusterProvider.java
@Test public void testCopyDirectory() throws Exception { File copyTempDir = new File(tempDir, "copy"); File srcDir = new File(copyTempDir, "somedir"); File dstDir = new File(copyTempDir, "dst"); Assert.assertTrue(srcDir.mkdirs());/* ww w .j a v a2s.c o m*/ Assert.assertTrue(dstDir.mkdirs()); File link1 = new File(copyTempDir, "link1"); File link2 = new File(copyTempDir, "link2"); File dir1 = new File(copyTempDir, "dir1"); File file1 = new File(dir1, "f1"); File file2 = new File(dir1, "f2"); Assert.assertTrue(dir1.mkdirs()); Assert.assertTrue(file1.createNewFile()); Assert.assertTrue(file2.createNewFile()); file2.setReadable(false); file2.setWritable(false); file2.setExecutable(false); Files.createSymbolicLink(link1.toPath(), dir1.toPath()); Files.createSymbolicLink(link2.toPath(), link1.toPath()); Files.createSymbolicLink(new File(srcDir, "dir1").toPath(), link2.toPath()); File clone = ShellClusterProvider.createDirectoryClone(srcDir, srcDir.getName(), dstDir); File cloneF1 = new File(new File(clone, "dir1"), "f1"); Assert.assertTrue(cloneF1.isFile()); }
From source file:com.all.client.data.JAudioTaggerStrategy.java
@Override public Track createTrack(TrackFile trackFile) throws InvalidFileException { LocalTrack track = new LocalTrack(trackFile.getFileName(), trackFile.getHashcode()); File file = trackFile.getFile(); track.setFileFormat(file.getName().substring(file.getName().lastIndexOf('.') + 1, file.getName().length()) .toUpperCase());// w ww. j a va 2 s . co m track.setSize(file.length()); try { if (!file.canWrite()) { file.setWritable(true); } if (file.exists()) { audioFile = AudioFileIO.read(file); } metadataReader = new MetadataReader(audioFile); if (audioFile instanceof MP3File) { metadataReader = new Mp3MetadataReader(audioFile); } Tag tag = metadataReader.getTag(); readAudioHeader(track); readTag(track, file, tag); // TODO Model a Business Exception to propagate // low level exceptions to show an appropriate // message to the user } catch (Exception e) { log.error(e.getMessage()); } track.setFileName(trackFile.getFile().getName()); return track; }
From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java
/** * This method saves the CSV item set for the form that is currently being handled. File is saved * in the form's media directory in ODK's SDCard's directory. Saving is in two * * @param fileName The name to be given to the CSV file. Make sure the name also contains the * suffix to be given to the file * @param csv The CSV String to be saved * @return True if the save was successful *//* w w w. ja va 2 s. c om*/ private boolean saveCSVInFile(String fileName, String csv) { Log.d(TAG, "CSV string = " + csv); File directory = new File(Form.BASE_ODK_LOCATION); boolean dirCreated = false; if (!directory.exists() || !directory.isDirectory()) {//means that the base directory does not exist dirCreated = directory.mkdirs(); directory.setReadable(true); directory.setWritable(true); Log.i(TAG, "Trying to create dir " + directory.getPath()); } else { dirCreated = true; Log.i(TAG, directory.getPath() + " already existed"); } if (dirCreated) { //check if form specific directory is created /* One thing to note here is that Collect handles downloaded from aggregate and forms gotten from adb push differently - Forms downloaded from aggregate will expect the itemsets.csv file to be in a dir with a name that is exactly the form name - Forms gotten from adb push will expect the itemsets.csv file to be in a dir where non-alphanumeric characters in the form name are replaced with underscores Will put the itemsets.csv file in both these dirs */ File formDir = new File(Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX); dirCreated = false; if (!formDir.exists() || !formDir.isDirectory()) { dirCreated = formDir.mkdirs(); formDir.setWritable(true); formDir.setReadable(true); Log.i(TAG, "Trying to create dir " + formDir.getPath()); } else { Log.i(TAG, formDir.getPath() + " already existed"); dirCreated = true; } File adbFormDir = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX); if (dirCreated) { if (!adbFormDir.exists() || !adbFormDir.isDirectory()) { dirCreated = adbFormDir.mkdirs(); adbFormDir.setWritable(true); adbFormDir.setReadable(true); Log.i(TAG, "Trying to create dir " + adbFormDir.getPath()); } else { Log.i(TAG, adbFormDir.getPath() + " already existed"); dirCreated = true; } } else { Log.e(TAG, "Unable to create " + formDir.getPath() + " not attempting to create " + adbFormDir.getPath()); } if (dirCreated) { try { String adbFileName = Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX + "/" + fileName; fileName = Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX + "/" + fileName; File csvFile = new File(fileName); File adbCSVFile = new File(adbFileName); boolean fileCreated = false; if (!csvFile.exists()) { fileCreated = csvFile.createNewFile(); Log.i(TAG, "Trying to create dir " + csvFile.getPath()); } else { csvFile.delete(); fileCreated = csvFile.createNewFile(); Log.i(TAG, csvFile.getPath() + " already existed"); } if (fileCreated) { if (!adbCSVFile.exists()) { fileCreated = adbCSVFile.createNewFile(); Log.i(TAG, "Trying to create dir " + adbCSVFile.getPath()); } else { adbCSVFile.delete(); fileCreated = adbCSVFile.createNewFile(); Log.i(TAG, adbCSVFile.getPath() + " already existed"); } if (fileCreated) { csvFile.setReadable(true); csvFile.setWritable(true); adbCSVFile.setReadable(true); adbCSVFile.setWritable(true); //OutputStreamWriter outputStreamWriter1 = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE)); OutputStreamWriter outputStreamWriter1 = new OutputStreamWriter( new FileOutputStream(csvFile, false)); OutputStreamWriter outputStreamWriter2 = new OutputStreamWriter( new FileOutputStream(adbCSVFile, false)); outputStreamWriter1.write(csv); outputStreamWriter2.write(csv); outputStreamWriter1.close(); outputStreamWriter2.close(); return true; } else { Log.e(TAG, "Unable to create " + adbCSVFile.getPath()); } } else { Log.e(TAG, "Unable to create " + csvFile.getPath()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { Log.e(TAG, "Unable to create " + formDir.getPath()); } } else { Log.e(TAG, "Unable to create " + directory.getPath()); } return false; }