List of usage examples for java.io File canWrite
public boolean canWrite()
From source file:ee.pri.rl.blog.service.BlogServiceImpl.java
/** * @see BlogService#deleteFile(String, String) *///w w w . j a v a 2 s . c o m @Override public void deleteFile(String entryName, String fileName) throws IOException { log.info("Deleting file " + fileName + " from " + entryName); File uploadPath = new File(getSetting(SettingName.UPLOAD_PATH).getValue()); File directory = new File(uploadPath, entryName); File file = new File(directory, fileName); if (file.exists() && file.canWrite()) { if (file.delete()) { log.info("File deleted"); } else { throw new IOException("Could not delete file"); } } else { throw new IOException("File does not exist or cannot be deleted"); } }
From source file:org.dataone.proto.trove.mn.domain.v1.ResourceNode.java
private void saveFile() { try {// ww w . j a v a 2 s . c o m File resourceFile = myRourceNodeResource.getFile(); if (resourceFile.canWrite()) { FileOutputStream fileOutputStream = new FileOutputStream(resourceFile); TypeMarshaller.marshalTypeToOutputStream(node, fileOutputStream); } } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } catch (JiBXException ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } }
From source file:at.diamonddogs.net.WebClient.java
private void saveData(InputStream i) throws IOException { if (i == null) { return;// w w w . j ava2 s . c o m } TempFile tmp = webRequest.getTmpFile().second; FileOutputStream fos = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(i, md); File file = new File(tmp.getPath()); Log.d(TAG, file.getAbsolutePath() + "can write: " + file.canWrite()); if (file.exists() && !tmp.isAppend()) { file.delete(); } byte buffer[] = new byte[READ_BUFFER_SIZE]; fos = new FileOutputStream(file, tmp.isAppend()); int bytesRead = 0; while ((bytesRead = dis.read(buffer)) != -1) { if (!webRequest.isCancelled()) { fos.write(buffer, 0, bytesRead); publishDownloadProgress(bytesRead); } else { Log.i(TAG, "Cancelled Download"); break; } } fos.flush(); fos.close(); if (webRequest.isCancelled()) { Log.i(TAG, "delete file due to canclled download: " + file.getName()); file.delete(); } else { if (tmp.isUseChecksum()) { String md5 = new String(Hex.encodeHex(md.digest())); Log.d(TAG, "md5 check, original: " + tmp.getChecksum() + " file: " + md5); if (!md5.equalsIgnoreCase(tmp.getChecksum())) { throw new IOException("Error while downloading File.\nOriginal Checksum: " + tmp.getChecksum() + "\nChecksum: " + md5); } } } } catch (Exception e) { if (fos != null && tmp.isAppend()) { fos.flush(); fos.close(); } Log.e(TAG, "Failed download", e); // Please do not do that - that hides the original error! throw new IOException(e.getMessage()); // Who ever changed this... new IOException(e) is API level 9!!! and // gives a nice NoSuchMethodException :) // throw new IOException(e); } }
From source file:com.adaptris.fs.StandardWorkerTest.java
@Test public void testCheckExists() throws Exception { File nonExistent = Mockito.mock(File.class); Mockito.when(nonExistent.exists()).thenReturn(false); try {/*from w w w . j a va 2 s . c o m*/ FsWorker.checkExists(nonExistent); fail(); } catch (FsException expected) { } File exists = Mockito.mock(File.class); Mockito.when(exists.canRead()).thenReturn(false); Mockito.when(exists.exists()).thenReturn(true); Mockito.when(exists.canWrite()).thenReturn(true); FsWorker.checkExists(exists); }
From source file:com.wudaosoft.net.httpclient.FileResponseHandler.java
@Override public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new ClientProtocolException("Unexpected response status: " + status); }//from w ww. j a v a 2 s.c o m HttpEntity entity = response.getEntity(); if (entity == null || !entity.isStreaming()) { throw new ClientProtocolException("Response contains no content"); } File tempFile = null; if (this.file != null) { tempFile = this.file; } else if (this.dir != null) { Header contentDisposition = response.getLastHeader("Content-disposition"); String filename = contentDisposition.getValue().split(";")[1].split("=")[1].replace("\"", ""); tempFile = new File(this.dir, filename); } Args.notNull(tempFile, "file"); Args.check(tempFile.canWrite(), "file must be writeable"); InputStream inputStream = entity.getContent(); FileOutputStream outputStream = new FileOutputStream(tempFile); try { byte[] buff = new byte[4096]; int size = -1; while ((size = inputStream.read(buff)) != -1) { outputStream.write(buff, 0, size); } outputStream.flush(); return tempFile; } finally { try { outputStream.close(); } catch (IOException e) { } } }
From source file:org.powertac.tournament.services.TournamentProperties.java
/** * Make sure filelocation exists, fall back to catalina dir, we know that exists *//*from www . j a va 2 s . c o m*/ private void checkFileLocation(String name, String catalinaBase) { String directory = properties.getProperty(name); if (!directory.endsWith(File.separator)) { directory += File.separator; properties.setProperty(name, directory); } File test = new File(directory); if (!test.exists()) { String msg = String.format("%s '%s' doesn't exist<br/>falling back on : %s", name, directory, catalinaBase); log.error(msg); messages.add(msg); properties.setProperty(name, catalinaBase); } else if (!test.canWrite()) { String msg = String.format("%s '%s' isn't writeable<br/>falling back on : %s", name, directory, catalinaBase); log.error(msg); messages.add(msg); properties.setProperty(name, catalinaBase); } }
From source file:org.springsource.ide.eclipse.commons.internal.configurator.ui.ConfiguratorPreferencesPage.java
protected void doInstall(final ConfigurableExtension extension) { // FIXME use directory where extension is installed final File installDirectory = new File(userLocationText.getText()); if (!installDirectory.canWrite()) { UiStatusHandler.logAndDisplay(new Status(IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind( "Installation failed. The directory ''{0}'' is not writeable.", userLocationText.getText()))); return;/*from ww w . ja v a2 s . com*/ } try { final IStatus[] status = new IStatus[1]; UiUtil.busyCursorWhile(new ICoreRunnable() { public void run(IProgressMonitor monitor) throws CoreException { status[0] = extension.install(installDirectory, monitor); if (status[0].getSeverity() != IStatus.ERROR) { IStatus configurationStatus = extension.configure(monitor); if (status[0].getSeverity() != IStatus.OK) { MultiStatus result = new MultiStatus(Activator.PLUGIN_ID, 0, NLS.bind( "The installation of {0} generated warning. See error log for details.", extension.getLabel()), null); result.add(status[0]); result.add(configurationStatus); status[0] = result; } else { status[0] = configurationStatus; } } } }); handleResult(extension, status); doRefresh(); } catch (OperationCanceledException ignored) { // cancelled } catch (CoreException e) { UiStatusHandler.logAndDisplay(e.getStatus()); } }
From source file:net.sf.jasperreports.customvisualization.export.CVElementPhantomJSImageDataProvider.java
/** * Returns the location of a newly created image, * //from ww w . j a v a2 s.co m * @param jasperReportsContext * @param element * @return image byte array * @throws Exception */ @Override public byte[] getImageData(JasperReportsContext jasperReportsContext, JRGenericPrintElement element) throws Exception { if (element.getParameterValue(CVPrintElement.CONFIGURATION) == null) { throw new JRRuntimeException("Configuration object is null."); } String phantomjsExecutablePath = jasperReportsContext .getProperty(CVElementPhantomJSImageDataProvider.PROPERTY_PHANTOMJS_EXECUTABLE_PATH); if (phantomjsExecutablePath == null) { phantomjsExecutablePath = "phantomjs"; } int phantomjsTimeout; String timeoutProperty = jasperReportsContext .getProperty(CVElementPhantomJSImageDataProvider.PROPERTY_PHANTOMJS_EXECUTABLE_TIMEOUT); if (timeoutProperty != null) { phantomjsTimeout = Integer.parseInt(timeoutProperty); } else { phantomjsTimeout = 60000; } String phantomjsTempFolderPath = jasperReportsContext .getProperty(CVElementPhantomJSImageDataProvider.PROPERTY_PHANTOMJS_TEMPDIR_PATH); if (phantomjsTempFolderPath == null) { phantomjsTempFolderPath = System.getProperty("java.io.tmpdir"); } File tempFolder = new File(phantomjsTempFolderPath); if (tempFolder.exists()) { // Collect the files that must be deleted as we finish to render everything List<File> cleanableResourcePaths = new ArrayList<>(); try { List<String> scripts = new ArrayList<>(); RepositoryUtil repositoryUtil = RepositoryUtil.getInstance(jasperReportsContext); for (String scriptLocation : scriptResourceLocations) { scripts.add(copyResourceToTempFolder(scriptLocation, tempFolder, cleanableResourcePaths, true, repositoryUtil)); } scripts.add(copyResourceToTempFolder((String) element.getParameterValue(CVPrintElement.SCRIPT_URI), tempFolder, cleanableResourcePaths, true, repositoryUtil)); String cssUriParameter = (String) element.getParameterValue(CVPrintElement.CSS_URI); String cssUri = null; if (cssUriParameter != null) { cssUri = copyResourceToTempFolder(cssUriParameter, tempFolder, cleanableResourcePaths, true, repositoryUtil); } String htmlPage = getHtmlPage(jasperReportsContext, element, scripts.subList(1, scripts.size()), cssUri); File htmlPageFile = createTempFile("in.html", tempFolder, cleanableResourcePaths, false); try (InputStream is = new ByteArrayInputStream(htmlPage.getBytes()); OutputStream os = new FileOutputStream(htmlPageFile)) { CVUtils.byteStreamCopy(is, os); } File outputSvgFile = createTempFile("out.svg", tempFolder, cleanableResourcePaths, false); boolean renderAsPng = CVUtils.isRenderAsPng(element); try { runCommand(new String[] { phantomjsExecutablePath, scripts.get(0), "--output-format=" + (renderAsPng ? "png" : "svg"), "--timeout=" + CVUtils.getTimeout(element), "--zoom-factor=" + CVUtils.getZoomFactor(element), htmlPageFile.getName(), outputSvgFile.getName() }, tempFolder, phantomjsTimeout); } catch (Exception ex) { throw new JRRuntimeException( "Error while executing the javascript file to generate the SVG image: " + ex.getMessage()); } if (!outputSvgFile.exists() || outputSvgFile.length() <= 0) { throw new JRRuntimeException( "Error while executing the javascript file to generate the SVG image."); } try (InputStream is = new FileInputStream(outputSvgFile); ByteArrayOutputStream os = new ByteArrayOutputStream()) { CVUtils.byteStreamCopy(is, os); return os.toByteArray(); } } finally { for (File cleanableResource : cleanableResourcePaths) { if (cleanableResource.exists() && cleanableResource.canWrite()) { JRPropertiesUtil propertiesUtil = JRPropertiesUtil.getInstance(jasperReportsContext); boolean isPhantomJSinDebugMode = propertiesUtil.getBooleanProperty( CVElementPhantomJSImageDataProvider.PROPERTY_PHANTOMJS_DEBUG, false); String keepTempFilesProperty = element.getPropertiesMap() .getProperty("cv.keepTemporaryFiles"); boolean keepTempFiles = keepTempFilesProperty != null && keepTempFilesProperty.equals("true"); if (!(isPhantomJSinDebugMode && keepTempFiles)) { if (log.isDebugEnabled()) { log.debug("Cleaning up resource after rendering of element " + CVUtils.getElementId(element) + ": " + cleanableResource.getAbsolutePath()); } cleanableResource.delete(); } } } } } else { throw new JRRuntimeException("Temp folder '" + tempFolder + "' does not exist!"); } }
From source file:com.xpn.xwiki.plugin.fileupload.FileUploadPlugin.java
/** * Loads the list of uploaded files in the context if there are any uploaded files. * //w w w . j a v a 2 s. com * @param uploadMaxSize Maximum size of the uploaded files. * @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory. * @param tempdir Temporary directory to store the uploaded files that are not kept in memory. * @param context Context of the request. * @throws XWikiException if the request could not be parsed, or the maximum file size was reached. * @see FileUploadPluginApi#loadFileList(long, int, String) */ public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException { LOGGER.debug("Loading uploaded files"); // If we already have a file list then loadFileList was already called // Continuing would empty the list.. We need to stop. if (context.get(FILE_LIST_KEY) != null) { LOGGER.debug("Called loadFileList twice"); return; } // Get the FileUpload Data // Make sure the factory only ever creates file items which will be deleted when the jvm is stopped. DiskFileItemFactory factory = new DiskFileItemFactory() { public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) { try { final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName); // Needed to make sure the File object is created. item.getOutputStream(); item.getStoreLocation().deleteOnExit(); return item; } catch (IOException e) { String path = System.getProperty("java.io.tmpdir"); if (super.getRepository() != null) { path = super.getRepository().getPath(); } throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?"); } } }; factory.setSizeThreshold(uploadSizeThreashold); if (tempdir != null) { File tempdirFile = new File(tempdir); if (tempdirFile.mkdirs() && tempdirFile.canWrite()) { factory.setRepository(tempdirFile); } } // TODO: Does this work in portlet mode, or we must use PortletFileUpload? FileUpload fileupload = new ServletFileUpload(factory); RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest()); fileupload.setSizeMax(uploadMaxSize); // context.put("fileupload", fileupload); try { @SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext); if (list.size() > 0) { LOGGER.info("Loaded " + list.size() + " uploaded files"); } // We store the file list in the context context.put(FILE_LIST_KEY, list); } catch (FileUploadBase.SizeLimitExceededException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file"); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e); } }
From source file:org.springsource.ide.eclipse.commons.internal.configurator.ConfiguratorImporter.java
public File getDefaultInstallLocation() { List<File> locations = getSearchLocations(); for (File location : locations) { if (location.exists() && location.canWrite()) { return location; }//from w w w.j a v a2s . co m } return null; }