List of usage examples for java.io File setWritable
public boolean setWritable(boolean writable, boolean ownerOnly)
From source file:com.cmart.PageControllers.SellItemImagesController.java
public void saveImages(String baseURL) { //System.out.println("sellitemimagecont: looking for image to upload!"); //System.out.println("saving images :" + baseURL); baseURL = baseURL + "/" + GV.REMOTE_IMAGE_DIR + "/"; // Special case for the thumbnail /*if(this.images.size()>1){ FileItem image = this.images.get(0); //from w w w. j a v a2s. c o m //TODO: compress an image String[] ext = image.getName().split("\\."); int extIndex = ext.length>0 ? ext.length-1 : 0; String filename = this.itemID + "_" + 0 + "." + ext[extIndex]; String URL = filename; // Setup the thumbnail file File file = new File(GlobalVars.localImageDir, filename); file.setReadable(true, false); file.setWritable(true, false); try { image.write(file); GlobalVars.db.insertThumbnail(this.itemID, URL); } catch (Exception e) { // TODO Auto-generated catch block this.errors.add(new Error("SellItemImagesController (saveImages): Could not save thumbnail", e)); e.printStackTrace(); } }*/ boolean thumbnail = true; // Loop through all the images for (int i = 0; i < this.images.size(); i++) { FileItem image = this.images.get(i); //TODO: make number start from one and only count real images if (image.getSize() > 0) { // Make the file name and path String[] ext = image.getName().split("\\."); int extIndex = ext.length > 0 ? ext.length - 1 : 0; String filename = this.itemID + "_" + (i + 1) + "." + ext[extIndex]; //String URL = filename; // Setup the image file //System.out.println("setting temp dir as the image"); File file = new File(GV.LOCAL_TEMP_DIR, filename + "tmp"); file.setReadable(true, false); file.setWritable(true, false); //System.out.println("URL :" + URL); //System.out.println("name :" + filename); //System.out.println("local :" + GV.LOCAL_IMAGE_DIR); //System.out.println("remote :" + GV.REMOTE_IMAGE_DIR); try { //System.out.println("doing db insert"); GV.DB.insertImage(this.itemID, i + 1, filename, ""); //System.out.println("saving image"); image.write(file); //System.out.println("mkaing file in img dir"); File file2 = new File(GV.LOCAL_IMAGE_DIR, filename); //System.out.println("doing the image resize"); BufferedImage originalImage2 = ImageIO.read(file); int type2 = originalImage2.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage2.getType(); //System.out.println("doing the image resize second step"); BufferedImage resizeImageHintJpg2 = resizeImageWithHint(originalImage2, type2, 500, 450); ImageIO.write(resizeImageHintJpg2, "jpg", file2); try { file.delete(); } catch (Exception e) { } //System.out.println("sellitemimagecont: inserted an image!"); if (thumbnail) { //TODO: some image compression String thumbName = this.itemID + "_" + 0 + "." + ext[extIndex]; GV.DB.insertThumbnail(this.itemID, thumbName); //System.out.println("doing thumbnail"); File thumbFile = new File(GV.LOCAL_IMAGE_DIR, thumbName); // Get a JPEG writer // TODO: other formats?? /*ImageWriter writer = null; Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter)iter.next(); } // Set the output file ImageOutputStream ios = ImageIO.createImageOutputStream(thumbFile); writer.setOutput(ios); // Set the compression level JPEGImageWriteParam imgparams = new JPEGImageWriteParam(Locale.getDefault()); imgparams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ; imgparams.setCompressionQuality(128); // Write the compressed file RenderedImage rendFile = ImageIO.read(file); writer.write(null, new IIOImage(rendFile, null, null), imgparams); // copy file InputStream fin = new FileInputStream(file); OutputStream fout = new FileOutputStream(thumbFile); byte[] buff = new byte[1024]; int len; while((len = fin.read(buff)) > 0) fout.write(buff, 0, len); fin.close(); fout.close(); */ BufferedImage originalImage = ImageIO.read(file2); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type, 100, 100); ImageIO.write(resizeImageHintJpg, "jpg", thumbFile); thumbnail = false; } } catch (Exception e) { // TODO Auto-generated catch block this.errors.add(new Error("SellItemImagesController (saveImages): Could not save image", e)); e.printStackTrace(); } } } if (this.errors.size() == 0 && !this.useHTML5()) { createRedirectURL(); } // Try to save the uploaded files /*try { while(images.hasNext()) { FileItem item = (FileItem) images.next(); System.out.println("doing item 1"); /* * Handle Form Fields. * if(item.isFormField()) { System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString()); } else { //Handle Uploaded files. System.out.println("Field Name = "+item.getFieldName()+ ", File Name = "+item.getName()+ ", Content type = "+item.getContentType()+ ", File Size = "+item.getSize()); /* * Write file to the ultimate location. * File file = new File(GlobalVars.imageDir,item.getName()); item.write(file); } //System.out.close(); } }catch(Exception ex) { System.out.println("Error encountered while uploading file"); }*/ }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.PeriodicResourceUpdater.java
protected synchronized void copyDatabase(final File existingDB, final String newDB) throws IOException { try (final StringReader in = new StringReader(newDB); final FileOutputStream out = new FileOutputStream(existingDB); final FileLock lock = out.getChannel().tryLock()) { if (lock == null) { LOGGER.error("Database " + existingDB.getAbsolutePath() + " locked by another process."); return; }/*from w w w. j av a 2 s . com*/ IOUtils.copy(in, out); existingDB.setReadable(true, false); existingDB.setWritable(true, true); lock.release(); } }
From source file:org.openbase.bco.ontology.lib.testing.Measurement.java
private void putIntoExcelFile(final String sheetName, final List<Long> simpleQuMeasuredValues, final List<Long> complexQuMeasuredValues, int daysCurCount) { // https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/ XSSFWorkbook workbook;//from w w w. j a v a2s.c o m XSSFSheet sheet; Row row; try { FileInputStream excelFile = new FileInputStream(new File(FILE_NAME)); workbook = new XSSFWorkbook(excelFile); sheet = workbook.getSheet(sheetName); } catch (IOException ex) { workbook = new XSSFWorkbook(); sheet = workbook.createSheet(sheetName); row = sheet.createRow(daysCurCount); row.createCell(0).setCellValue("Days"); row.createCell(1).setCellValue("Triple"); row.createCell(2).setCellValue("Mean of simple trigger"); row.createCell(3).setCellValue("Mean of complex trigger"); } row = sheet.createRow(daysCurCount + 1); System.out.println("simple: " + simpleQuMeasuredValues); System.out.println("simple count: " + simpleQuMeasuredValues.size()); System.out.println("complex: " + complexQuMeasuredValues); System.out.println("complex count: " + complexQuMeasuredValues.size()); long sumSimple = 0L; long sumComplex = 0L; for (final long valueSimple : simpleQuMeasuredValues) { sumSimple += valueSimple; } for (final long valueComplex : complexQuMeasuredValues) { sumComplex += valueComplex; } // number of days final Cell cellDay = row.createCell(0); cellDay.setCellValue(daysCurCount + 1); // number of triple final Cell cellTriple = row.createCell(1); cellTriple.setCellValue(numberOfTriple); // mean of simple trigger time final Cell cellMeanSimple = row.createCell(2); cellMeanSimple.setCellValue(sumSimple / simpleQuMeasuredValues.size()); // mean of complex trigger time final Cell cellMeanComplex = row.createCell(3); cellMeanComplex.setCellValue(sumComplex / complexQuMeasuredValues.size()); try { final File file = new File(FILE_NAME); file.setReadable(true, false); file.setExecutable(true, false); file.setWritable(true, false); System.out.println("Save data row ..."); final FileOutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); workbook.close(); } catch (IOException ex) { ExceptionPrinter.printHistory(ex, LOGGER); } }
From source file:org.openbase.bco.ontology.lib.testing.Measurement.java
private void saveMemoryTestValues(final String sheetName, final List<Long> simpleQuMeasuredValues, final List<Long> complexQuMeasuredValues, final DataVolume dataVolume) { XSSFWorkbook workbook;/*from ww w.j av a2 s .c o m*/ XSSFSheet sheet; Row rowSimple; Row rowComplex; try { FileInputStream excelFile = new FileInputStream(new File(FILE_NAME)); workbook = new XSSFWorkbook(excelFile); sheet = workbook.getSheet(sheetName); rowSimple = sheet.getRow(1); rowComplex = sheet.getRow(2); } catch (IOException ex) { workbook = new XSSFWorkbook(); sheet = workbook.createSheet(sheetName); final Row row = sheet.createRow(0); rowSimple = sheet.createRow(1); rowComplex = sheet.createRow(2); row.createCell(1).setCellValue("ConfigData only"); row.createCell(2).setCellValue("ConfigData and dayData"); row.createCell(3).setCellValue("ConfigData and 4x dayData"); } long sumSimple = 0L; long sumComplex = 0L; for (final long valueSimple : simpleQuMeasuredValues) { sumSimple += valueSimple; } for (final long valueComplex : complexQuMeasuredValues) { sumComplex += valueComplex; } int column = 0; switch (dataVolume) { case CONFIG: column = 1; break; case CONFIG_DAY: column = 2; break; case CONFIG_WEEK: column = 3; break; default: break; } System.out.println("Save date in column: " + column); // mean of simple trigger time final Cell cellMeanSimple = rowSimple.createCell(column); cellMeanSimple.setCellValue(sumSimple / simpleQuMeasuredValues.size()); // mean of complex trigger time final Cell cellMeanComplex = rowComplex.createCell(column); cellMeanComplex.setCellValue(sumComplex / complexQuMeasuredValues.size()); try { final File file = new File(FILE_NAME); file.setReadable(true, false); file.setExecutable(true, false); file.setWritable(true, false); System.out.println("Save data row ..."); final FileOutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); workbook.close(); } catch (IOException ex) { ExceptionPrinter.printHistory(ex, LOGGER); } }
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String) *///from w w w. ja va 2 s .c o m public synchronized boolean createKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#createKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } boolean isComplete = false; OutputStream publicStream = null; OutputStream privateStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { if (!(keyDirectory.mkdirs())) { throw new KeyManagementException( "Configured key directory does not exist and unable to create it"); } } keyDirectory.setExecutable(true, true); SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm()); keyGenerator.initialize(keyConfig.getKeySize(), random); KeyPair keyPair = keyGenerator.generateKeyPair(); if (keyPair != null) { File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (!(privateFile.createNewFile())) { throw new IOException("Failed to store private key file"); } if (!(publicFile.createNewFile())) { throw new IOException("Failed to store public key file"); } privateFile.setWritable(true, true); publicFile.setWritable(true, true); privateStream = new FileOutputStream(privateFile); publicStream = new FileOutputStream(publicFile); IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream); IOUtils.write(keyPair.getPublic().getEncoded(), publicStream); // assume success, as we'll get an IOException if the write failed isComplete = true; } else { throw new KeyManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (publicStream != null) { IOUtils.closeQuietly(publicStream); } if (privateStream != null) { IOUtils.closeQuietly(privateStream); } } return isComplete; }
From source file:org.eclipse.acute.OmnisharpStreamConnectionProvider.java
/** * * @return path to server, unzipping it if necessary. Can be null is fragment is missing. *///from w ww .j a va 2 s . c o m private @Nullable File getServer() throws IOException { File serverPath = new File(AcutePlugin.getDefault().getStateLocation().toFile(), "omnisharp-roslyn"); //$NON-NLS-1$ if (!serverPath.exists()) { serverPath.mkdirs(); try (InputStream stream = FileLocator.openStream(AcutePlugin.getDefault().getBundle(), new Path("omnisharp-roslyn.tar"), true); //$NON-NLS-1$ TarArchiveInputStream tarStream = new TarArchiveInputStream(stream);) { TarArchiveEntry entry = null; while ((entry = tarStream.getNextTarEntry()) != null) { if (!entry.isDirectory()) { File targetFile = new File(serverPath, entry.getName()); targetFile.getParentFile().mkdirs(); InputStream in = new BoundedInputStream(tarStream, entry.getSize()); // mustn't be closed try (FileOutputStream out = new FileOutputStream(targetFile);) { IOUtils.copy(in, out); if (!Platform.OS_WIN32.equals(Platform.getOS())) { int xDigit = entry.getMode() % 10; targetFile.setExecutable(xDigit > 0, (xDigit & 1) == 1); int wDigit = (entry.getMode() / 10) % 10; targetFile.setWritable(wDigit > 0, (wDigit & 1) == 1); int rDigit = (entry.getMode() / 100) % 10; targetFile.setReadable(rDigit > 0, (rDigit & 1) == 1); } } } } } } return serverPath; }
From source file:com.puppycrawl.tools.checkstyle.MainTest.java
@Test public void testExistingFilePlainOutputToFileWithoutReadAndRwPermissions() throws Exception { final File file = temporaryFolder.newFile("file.output"); // That works fine on Linux/Unix, but .... // It's not possible to make a file unreadable in Windows NTFS for owner. // http://stackoverflow.com/a/4354686 // https://github.com/google/google-oauth-java-client/issues/55#issuecomment-69403681 //assertTrue(file.setReadable(false, false)); assertTrue(file.setWritable(false, false)); exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(new Assertion() { @Override/*from ww w.j a v a 2s .c o m*/ public void checkAssertion() throws IOException { assertEquals("Permission denied : '" + file.getCanonicalPath() + "'." + System.lineSeparator(), systemOut.getLog()); assertEquals("", systemErr.getLog()); } }); Main.main("-c", "src/test/resources/com/puppycrawl/tools/checkstyle/config-classname.xml", "-f", "plain", "-o", file.getCanonicalPath(), "src/test/resources/com/puppycrawl/tools/checkstyle/InputMain.java"); }
From source file:com.oneops.inductor.AbstractOrderExecutor.java
/** * writes private key/*from www . jav a 2s .c om*/ * * @param key String */ protected String writePrivateKey(String key) { String uuid = UUID.randomUUID().toString(); String fileName = config.getDataDir() + "/" + uuid; try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(fileName))) { bw.write(key); bw.close(); File f = new File(fileName); f.setExecutable(false, false); f.setReadable(false, false); f.setWritable(false, false); f.setReadable(true, true); f.setWritable(true, true); logger.debug("file: " + fileName); } catch (IOException e) { logger.error("could not write file: " + fileName + " msg:" + e.getMessage()); } return fileName; }
From source file:com.oneops.inductor.AbstractOrderExecutor.java
/** * Creates a chef config file for unique lockfile by ci. * returns chef config full path./*from w ww . j a v a2 s . co m*/ * * @param ci * @param cookbookRelativePath chef config full path * @param logLevel * @return */ protected String writeChefConfig(String ci, String cookbookRelativePath, String logLevel) { String filename = "/tmp/chef-" + ci; String cookbookDir = config.getCircuitDir(); if (!cookbookRelativePath.equals("")) cookbookDir = config.getCircuitDir().replace("packer", cookbookRelativePath); cookbookDir += "/components/cookbooks"; String sharedDir = config.getCircuitDir().replace("packer", "shared/cookbooks"); String content = "cookbook_path [\"" + cookbookDir + "\",\"" + sharedDir + "\"]\n"; content += "lockfile \"" + filename + ".lock\"\n"; content += "file_cache_path \"/tmp\"\n"; content += "log_level :" + logLevel + "\n"; content += "verify_api_cert true\n"; FileWriter fstream; try { fstream = new FileWriter(filename); BufferedWriter bw = new BufferedWriter(fstream); bw.write(content); bw.close(); File f = new File(filename); f.setExecutable(false, false); f.setReadable(false, false); f.setWritable(false, false); f.setReadable(true, true); f.setWritable(true, true); logger.debug("file: " + filename); } catch (IOException e) { logger.error("could not write file: " + filename + " msg:" + e.getMessage()); } return filename; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java
protected boolean copyDatabaseIfDifferent(final File existingDB, final File newDB) throws IOException { if (filesEqual(existingDB, newDB)) { LOGGER.info("[" + getClass().getSimpleName() + "] database unchanged."); return false; }/*from w w w.j av a 2s.c o m*/ if (existingDB.isDirectory() && newDB.isDirectory()) { moveDirectory(existingDB, newDB); LOGGER.info("[" + getClass().getSimpleName() + "] Successfully updated database " + existingDB); return true; } if (existingDB != null && existingDB.exists()) { deleteDatabase(existingDB); } newDB.setReadable(true, true); newDB.setWritable(true, false); final boolean renamed = newDB.renameTo(existingDB); if (!renamed) { LOGGER.fatal("[" + getClass().getSimpleName() + "] Unable to rename " + newDB + " to " + existingDB.getAbsolutePath() + "; current working directory is " + System.getProperty("user.dir")); return false; } LOGGER.info("[" + getClass().getSimpleName() + "] Successfully updated database " + existingDB); return true; }