List of usage examples for java.io File setReadable
public boolean setReadable(boolean readable)
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 *//*from w w w. ja v a 2 s .c o m*/ 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; }
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 *//*from w w w . j a v a 2 s.com*/ 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:edu.stolaf.cs.wmrserver.TransformProcessor.java
private File writeTransformSource(String transformTypeString, File jobTransformDir, String scriptExtension, String transformSource) throws IOException { // Write the script to a temporary file File scriptFile = new File(jobTransformDir, "job-" + transformTypeString + scriptExtension); if (!scriptFile.createNewFile()) { throw new IOException("Could not create " + transformTypeString + " file."); }/* w w w . jav a 2 s . c om*/ try { FileUtils.writeStringToFile(scriptFile, transformSource); } catch (IOException ex) { throw new IOException("Could not write " + transformTypeString + " code to disk.", ex); } // Change file permissions on the new file to ensure it is accessible try { scriptFile.setReadable(true); scriptFile.setExecutable(true, false); } catch (SecurityException ex) { throw new IOException("Could not assign permissions to " + transformTypeString + " file.", ex); } return scriptFile; }
From source file:display.containers.FileManager.java
public static boolean copyFile(File from, File to) throws IOException { boolean created = to.createNewFile(); if (created) { FileChannel fromChannel = null; FileChannel toChannel = null; try {/*from ww w . j a v a 2 s .c o m*/ fromChannel = new FileInputStream(from).getChannel(); toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); // set the flags of the to the same as the from to.setReadable(from.canRead()); to.setWritable(from.canWrite()); to.setExecutable(from.canExecute()); } finally { if (fromChannel != null) { fromChannel.close(); } if (toChannel != null) { toChannel.close(); } return false; } } return created; }
From source file:org.rapidbeans.rapidenv.Unpacker.java
private void setOutFileMode(final File file, final FileMode fileMode) { switch (PlatformHelper.getOsfamily()) { case linux:/* ww w. j a va 2s.c om*/ final String smode = fileMode.toChmodStringFull(); final SystemCommand cmd = new SystemCommand(); cmd.setExecutable("chmod"); cmd.addArgument(new Argument(smode)); cmd.addArgument(new Argument(file.getAbsolutePath())); cmd.setSilent(true); final CommandExecutionResult result = cmd.execute(); if (result.getReturncode() != 0) { throw new RapidEnvException( "Error while trying to set mode \"" + smode + "\" for file: " + file.getAbsolutePath()); } break; default: file.setReadable(fileMode.isUr() || fileMode.isGr() || fileMode.isOr()); file.setWritable(fileMode.isUw() || fileMode.isGw() || fileMode.isOw()); file.setExecutable(fileMode.isUx() || fileMode.isGx() || fileMode.isOx()); break; } }
From source file:alluxio.shell.command.CpCommandIntegrationTest.java
@Test public void copyDirectoryFromLocalToExistingDirAtomic() throws Exception { File localDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir"); localDir.mkdir();/*from w ww .j av a 2 s. c o m*/ File testFile = generateFileContent("/localDir/testFile", BufferUtils.getIncreasingByteArray(10)); File testDir = testFile.getParentFile(); AlluxioURI alluxioDirPath = new AlluxioURI("/testDir"); // Create the destination directory before call command of 'copyFromLocal'. mFileSystem.createDirectory(alluxioDirPath); testFile.setReadable(false); String[] cmd = { "cp", "file://" + testDir.getPath(), alluxioDirPath.getPath() }; Assert.assertEquals(-1, mFsShell.run(cmd)); Assert.assertEquals(testFile.getPath() + " (Permission denied)\n", mOutput.toString()); // The destination directory should not be deleted. Assert.assertTrue(mFileSystem.exists(alluxioDirPath)); mOutput.reset(); // If we put a copyable file in the directory, we should be able to copy just that file generateFileContent("/localDir/testFile2", BufferUtils.getIncreasingByteArray(20)); Assert.assertEquals(-1, mFsShell.run(cmd)); Assert.assertEquals(testFile.getPath() + " (Permission denied)\n", mOutput.toString()); Assert.assertTrue(mFileSystem.exists(alluxioDirPath)); Assert.assertTrue(mFileSystem.exists(new AlluxioURI("/testDir/testFile2"))); Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/testFile"))); // The directory should also be deleted from Alluxio filesystem when all files in the // directory are failed. File innerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir/innerDir"); innerDir.mkdir(); File innerFile = generateFileContent("/localDir/innerDir/innerFile1", BufferUtils.getIncreasingByteArray(30)); innerFile.setReadable(false); Assert.assertEquals(-1, mFsShell.run(cmd)); Assert.assertTrue(mFileSystem.exists(alluxioDirPath)); Assert.assertTrue(mFileSystem.exists(new AlluxioURI("/testDir/testFile2"))); Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/testFile"))); Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/innerDir"))); Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/innerDir/innerFile1"))); }
From source file:alluxio.shell.command.CpCommandIntegrationTest.java
@Test public void copyFromLocalAtomic() throws Exception { // copyFromLocal should not leave around any empty file metadata if it fails in the middle of // copying a file File testFile1 = generateFileContent("/testFile1", BufferUtils.getIncreasingByteArray(10)); AlluxioURI alluxioFilePath = new AlluxioURI("/testFile"); // Set testFile1 to be not readable, so that when we try to open it, we fail. NOTE: for this to // test anything, we depend on the implementation of copyFromLocal creating the destination file // in Alluxio before it tries to open the source file testFile1.setReadable(false); String[] cmd = { "cp", "file://" + testFile1.getPath(), alluxioFilePath.getPath() }; Assert.assertEquals(-1, mFsShell.run(cmd)); Assert.assertEquals(testFile1.getPath() + " (Permission denied)\n", mOutput.toString()); // Make sure the alluxio file wasn't created anyways Assert.assertFalse(mFileSystem.exists(alluxioFilePath)); }
From source file:alluxio.shell.command.CpCommandIntegrationTest.java
@Test public void copyFromLocalDirNotReadableInnerDir() throws Exception { // Copy a directory from local to Alluxio filesystem, which the destination uri was not created // before./*ww w. j a v a 2 s . c o m*/ File srcOuterDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir"); File srcInnerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/innerDir"); File emptyDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir"); srcOuterDir.mkdir(); srcInnerDir.mkdir(); emptyDir.mkdir(); generateFileContent("/outerDir/srcFile1", BufferUtils.getIncreasingByteArray(10)); generateFileContent("/outerDir/innerDir/srcFile2", BufferUtils.getIncreasingByteArray(10)); srcInnerDir.setReadable(false); int ret = mFsShell.run("cp", "file://" + srcOuterDir.getPath() + "/", "/dstDir"); Assert.assertEquals(-1, ret); Assert.assertEquals("Failed to list files for directory " + srcInnerDir.getAbsolutePath() + "\n", mOutput.toString()); }
From source file:alluxio.shell.command.CpCommandTest.java
@Test public void copyFromLocalDirNotReadableInnerDir() throws IOException, AlluxioException { // Copy a directory from local to Alluxio filesystem, which the destination uri was not created // before.// w w w . j a va 2s . co m File srcOuterDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir"); File srcInnerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/innerDir"); File emptyDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir"); srcOuterDir.mkdir(); srcInnerDir.mkdir(); emptyDir.mkdir(); generateFileContent("/outerDir/srcFile1", BufferUtils.getIncreasingByteArray(10)); generateFileContent("/outerDir/innerDir/srcFile2", BufferUtils.getIncreasingByteArray(10)); srcInnerDir.setReadable(false); int ret = mFsShell.run("cp", "file://" + srcOuterDir.getPath() + "/", "/dstDir"); Assert.assertEquals(-1, ret); Assert.assertEquals("Failed to list files for directory " + srcInnerDir.getAbsolutePath() + "\n", mOutput.toString()); }
From source file:org.rhq.core.pc.drift.DriftDetectorTest.java
/** * Attempts to make a file non-readable. Windows does not support file permissions like * unix and linux platforms do.//from w w w . ja v a2 s . c o m * * @param file The file to update */ private void setNotReadable(File file) { boolean setToReadable = file.setReadable(false); // not every win os (maybe none) supports this call, perform the test anyway, as best as possible if (!setToReadable) { if (isWindows) { file.delete(); } else { assertTrue(setToReadable, "Failed to make " + file.getPath() + " write only"); } } }