List of usage examples for org.apache.commons.vfs2 FileObject delete
boolean delete() throws FileSystemException;
From source file:org.eobjects.datacleaner.actions.DownloadFilesActionListener.java
@Override protected FileObject[] doInBackground() throws Exception { for (int i = 0; i < _urls.length; i++) { final String url = _urls[i]; final FileObject file = _files[i]; InputStream inputStream = null; OutputStream outputStream = null; try {//from ww w.j a v a 2s . co m byte[] buffer = new byte[1024]; final HttpGet method = new HttpGet(url); if (!_cancelled) { final HttpResponse response = _httpClient.execute(method); if (response.getStatusLine().getStatusCode() != 200) { throw new InvalidHttpResponseException(url, response); } final HttpEntity responseEntity = response.getEntity(); final long expectedSize = responseEntity.getContentLength(); if (expectedSize > 0) { publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize); } }); } inputStream = responseEntity.getContent(); if (!file.exists()) { file.createFile(); } outputStream = file.getContent().getOutputStream(); long bytes = 0; for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream .read(buffer)) { if (_cancelled) { break; } outputStream.write(buffer, 0, numBytes); bytes += numBytes; final long totalBytes = bytes; publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes); } }); } if (!_cancelled) { publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setFinished(file.getName().getBaseName()); } }); } } } catch (IOException e) { logger.debug("IOException occurred while downloading files", e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.warn("Could not close input stream: " + e.getMessage(), e); } } if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.warn("Could not flush & close output stream: " + e.getMessage(), e); } } } if (_cancelled) { logger.info("Deleting non-finished download-file '{}'", file); file.delete(); } } return _files; }
From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java
@Override public boolean remove(String path, SharedUserPortletParameters userParameters) { boolean success = false; FileObject file; try {//from w ww . ja va 2 s .c om file = cd(path, userParameters); success = file.delete(); } catch (FileSystemException e) { log.info("can't delete file because of FileSystemException : " + e.getMessage(), e); } log.debug("remove file " + path + ": " + success); return success; }
From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java
@Override public boolean putFile(String dir, String filename, InputStream inputStream, SharedUserPortletParameters userParameters, UploadActionType uploadOption) { boolean success = false; FileObject newFile = null; try {//from w w w .j a v a 2 s . com FileObject folder = cd(dir, userParameters); newFile = folder.resolveFile(filename); if (newFile.exists()) { switch (uploadOption) { case ERROR: throw new EsupStockFileExistException(); case OVERRIDE: newFile.delete(); break; case RENAME_NEW: newFile = folder.resolveFile(this.getUniqueFilename(filename, "-new-")); break; case RENAME_OLD: newFile.moveTo(folder.resolveFile(this.getUniqueFilename(filename, "-old-"))); break; } } newFile.createFile(); OutputStream outstr = newFile.getContent().getOutputStream(); FileCopyUtils.copy(inputStream, outstr); success = true; } catch (FileSystemException e) { log.info("can't upload file : " + e.getMessage(), e); } catch (IOException e) { log.warn("can't upload file : " + e.getMessage(), e); } if (!success && newFile != null) { // problem when uploading the file -> the file uploaded is corrupted // best is to delete it try { newFile.delete(); log.debug("delete corrupted file after bad upload ok ..."); } catch (Exception e) { log.debug("can't delete corrupted file after bad upload " + e.getMessage()); } } return success; }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private void saveProperties(ExternalData data) throws RepositoryException { OutputStream outputStream = null; try {// w w w . ja va 2 s . co m ExtendedNodeType propertiesType = NodeTypeRegistry.getInstance() .getNodeType(Constants.JAHIAMIX_VIEWPROPERTIES); Map<String, ExtendedPropertyDefinition> propertyDefinitionMap = propertiesType .getDeclaredPropertyDefinitionsAsMap(); Properties properties = new SortedProperties(); for (Map.Entry<String, String[]> property : data.getProperties().entrySet()) { if (propertyDefinitionMap.containsKey(property.getKey())) { String[] v = property.getValue(); if (v != null) { String propertyValue = StringUtils.join(v, ","); if (propertyDefinitionMap.get(property.getKey()).getRequiredType() != PropertyType.BOOLEAN || !propertyValue.equals("false")) { properties.put(property.getKey(), propertyValue); } } } } FileObject file = getFile(StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION); Properties original = new Properties(); if (file.exists()) { original.load(file.getContent().getInputStream()); for (String s : propertyDefinitionMap.keySet()) { original.remove(s); } } properties.putAll(original); if (!properties.isEmpty()) { outputStream = file.getContent().getOutputStream(); properties.store(outputStream, data.getPath()); } else { if (file.exists()) { file.delete(); } } ResourceBundle.clearCache(); } catch (FileSystemException e) { logger.error(e.getMessage(), e); throw new RepositoryException("Failed to write source code", e); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RepositoryException("Failed to write source code", e); } catch (NoSuchNodeTypeException e) { logger.error("Unable to find type : " + data.getType() + " for node " + data.getPath(), e); throw e; } finally { IOUtils.closeQuietly(outputStream); } }
From source file:org.kalypso.kalypsomodel1d2d.sim.SWANKalypsoSimulation.java
private void copyFilesToWorkDir(final FileObject tmpDir, final FileObject targetDir) throws FileSystemException, IOException { final List<FileObject> lListFilesToRemove = new ArrayList<>(); final Set<String> exclusionFileNamesToMove = new HashSet<>(); exclusionFileNamesToMove.add(EXECUTE_RESPONSE_XML); // copy input files for (int i = 0; i < tmpDir.getChildren().length; i++) { final FileObject actFile = tmpDir.getChildren()[i]; if (!exclusionFileNamesToMove.contains(actFile.getName().getBaseName().toLowerCase().trim())) { VFSUtilities.copyFileTo(actFile, targetDir); lListFilesToRemove.add(actFile); }/* w w w .ja v a 2 s .c o m*/ } for (final FileObject actFile : lListFilesToRemove) { actFile.delete(); } }
From source file:org.kalypso.kalypsomodel1d2d.sim.TelemacKalypsoSimulation.java
private void copyFilesToWorkDir(final FileObject tmpDir, final FileObject targetDir) throws FileSystemException, IOException { List<FileObject> lListFilesToRemove = new ArrayList<FileObject>(); Set<String> exclusionFileNamesToMove = new HashSet<String>(); exclusionFileNamesToMove.add(EXECUTE_RESPONSE_XML); // copy input files for (int i = 0; i < tmpDir.getChildren().length; i++) { FileObject actFile = tmpDir.getChildren()[i]; if (!exclusionFileNamesToMove.contains(actFile.getName().getBaseName().toLowerCase().trim())) { VFSUtilities.copyFileTo(actFile, targetDir); lListFilesToRemove.add(actFile); }//ww w .j a va2 s. com } for (Iterator<FileObject> iterator = lListFilesToRemove.iterator(); iterator.hasNext();) { FileObject actFile = iterator.next(); actFile.delete(); } }
From source file:org.kalypso.project.database.client.core.base.worker.UpdateProjectWorker.java
/** * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor) */// w ww .j av a 2 s . c om @Override public IStatus execute(final IProgressMonitor monitor) throws CoreException { monitor.beginTask( Messages.getString("org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.0"), //$NON-NLS-1$ 4); // remove local project lock final IRemoteProjectPreferences preferences = m_handler.getRemotePreferences(); final String ticket = preferences.getEditTicket(); preferences.setEditTicket(""); //$NON-NLS-1$ final File urlTempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$ final File src = new File(urlTempDir, "update.zip"); //$NON-NLS-1$ monitor.worked(1); try { monitor.subTask(Messages .getString("org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.4")); //$NON-NLS-1$ final ProjectExportWorker worker = new ProjectExportWorker(m_handler.getProject(), src, false); final IStatus status = worker.execute(monitor); monitor.worked(1); if (!status.isOK()) throw new CoreException( new Status(IStatus.ERROR, KalypsoProjectDatabaseClient.PLUGIN_ID, Messages.getString( "org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.5"))); //$NON-NLS-1$ final FileSystemManager manager = VFSUtilities.getManager(); final FileObject source = manager.resolveFile(src.getAbsolutePath()); final String fileName = String.format("%s.zip", m_handler.getName()); //$NON-NLS-1$ final String urlDestination = ProjectModelUrlResolver .getUrlAsFtp(new ProjectModelUrlResolver.IResolverInterface() { @Override public String getPath() { return System.getProperty(IProjectDataBaseClientConstant.SERVER_INCOMING_PATH); } }, fileName); //$NON-NLS-1$ monitor.subTask(Messages .getString("org.kalypso.project.database.client.core.project.commit.UpdateProjectWorker.7")); //$NON-NLS-1$ final FileObject destination = manager.resolveFile(urlDestination); VFSUtilities.copy(source, destination); final IProjectDatabase service = KalypsoProjectDatabaseClient.getService(); final KalypsoProjectBean bean = service.udpateProject(m_handler.getBean(), new URL(urlDestination)); preferences.setVersion(bean.getProjectVersion()); destination.close(); destination.delete(); } catch (final Exception e) { throw new CoreException(StatusUtilities.statusFromThrowable(e)); } finally { try { // add local project lock preferences.setEditTicket(ticket); } catch (final Throwable t) { t.printStackTrace(); } src.delete(); monitor.done(); } return Status.OK_STATUS; }
From source file:org.kalypso.project.database.server.ProjectDatabaseHelper.java
protected static Boolean removeBean(final Session session, final KalypsoProjectBean bean) { try {//from w w w . j a va 2 s. c o m final FileSystemManager manager = VFSUtilities.getManager(); /* remove file from server */ // destination webdav url of bean final String urlBean = ProjectDatabaseHelper.resolveDestinationUrl(bean); final FileObject fileBean = manager.resolveFile(urlBean); if (fileBean.exists()) { fileBean.delete(); } final FileObject parentFolder = fileBean.getParent(); if (parentFolder.exists()) { parentFolder.delete(); } /* delete database entry */ final Transaction tx = session.beginTransaction(); session.delete(bean); tx.commit(); return true; } catch (final FileSystemException e) { KalypsoProjectDatabase.getDefault().getLog().log(StatusUtilities.statusFromThrowable(e)); } return false; }
From source file:org.kalypso.ui.wizards.results.ReevaluateResultOperation.java
private IStatus processStepResult(final IStepResultMeta stepResult, final IProgressMonitor monitor) { /* delete map theme, if any */ if (m_modell != null && m_commandTarget != null) ResultMeta1d2dHelper.deleteResultThemeFromMap(stepResult, m_modell, m_commandTarget); final ProcessResultsBean bean = new ProcessResultsBean(); bean.deleteAll = false;/* w w w . j av a 2 s . c o m*/ bean.deleteFollowers = false; bean.evaluateFullResults = true; if (stepResult.getFullPath().toOSString().contains(ResultManager.STEADY_PREFIX)) bean.userCalculatedSteps = new Date[] { ResultManager.STEADY_DATE }; else if (stepResult.getFullPath().toOSString().contains(ResultManager.MAXI_PREFIX)) bean.userCalculatedSteps = new Date[] { ResultManager.MAXI_DATE }; else bean.userCalculatedSteps = new Date[] { stepResult.getStepTime() }; FileObject actResult = null; ResultManager resultManager = null; // FIXME: ugly, local try/catches are a sign of bad code! try { actResult = m_vfsManager.resolveFile( m_scenarioFolder.getFolder(stepResult.getFullPath()).getLocationURI().toURL().toExternalForm()); if (stepResult.getOwner() instanceof ICalcUnitResultMeta) { resultManager = new ResultManager(actResult, m_fileObjSWANResult, m_modelProvider, m_geoLog, (ICalcUnitResultMeta) stepResult.getOwner()); } else { resultManager = new ResultManager(actResult, m_fileObjSWANResult, m_modelProvider, m_geoLog); } resultManager.setStepsToProcess(bean.userCalculatedSteps); } catch (final CoreException | IOException e) { final IStatus status = new Status(IStatus.ERROR, Kalypso1d2dProjectPlugin.PLUGIN_ID, Messages.getString("ReevaluateResultOperation.9")); //$NON-NLS-1$ m_geoLog.log(status); return status; } // FIXME: dangerous: that operation also handles what results will be deleted etc. This should be separated, because that functionality is probably only needed // directly after calculation. Better abstraction is needed. final ResultProcessingOperation processingOperation = new ResultProcessingOperation(resultManager, bean); final IStatus resultStatus = processingOperation.execute(monitor); m_geoLog.log(resultStatus); // FIXME: this is not the right place to do delete these file! (and why is this not necessary for the other result types?) // FIXME: better: the code that creates the files should be responsible to delete them // the files are unzipped ones for all evaluated steps and only after finishing the complete reevaluation we can delete them, // so here we remove temporary unzipped swan data try { final FileObject unzippedSwanFile = m_vfsManager.resolveFile(processingOperation.getOutputDir(), ISimulation1D2DConstants.SIM_SWAN_TRIANGLE_FILE + "." //$NON-NLS-1$ + ISimulation1D2DConstants.SIM_SWAN_MAT_RESULT_EXT); final FileObject unzippedShiftFile = m_vfsManager.resolveFile(processingOperation.getOutputDir(), ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_FILE); final FileObject unzippedTabFile = m_vfsManager.resolveFile(processingOperation.getOutputDir(), ISimulation1D2DConstants.SIM_SWAN_TRIANGLE_FILE + "_out.tab"); //$NON-NLS-1$ unzippedSwanFile.delete(); unzippedShiftFile.delete(); unzippedTabFile.delete(); unzippedSwanFile.close(); unzippedShiftFile.close(); unzippedTabFile.close(); } catch (final FileSystemException e) { m_geoLog.log(StatusUtilities.statusFromThrowable(e)); } if (!resultStatus.isOK()) { return resultStatus; } // if OK move the new results data to the results folder // this operation is not cancelable // processing finished without problems, prepare the data-operation // this is where the name of the result folder is actually set final ICalcUnitResultMeta calcUnitMeta = processingOperation.getCalcUnitMeta(); final String calcUnitId = calcUnitMeta.getCalcUnit(); List<String> lListResultsToRemove = new ArrayList<>(); lListResultsToRemove.addAll(Arrays.asList(processingOperation.getOriginalStepsToDelete())); if (lListResultsToRemove.size() == 0) { lListResultsToRemove.add(stepResult.getId()); } lListResultsToRemove = removeAllOthersStepWithDate(lListResultsToRemove, stepResult.getId()); final String[] lResultsToRemove = lListResultsToRemove.toArray(new String[lListResultsToRemove.size()]); final Path unitFolderRelativePath = new Path("results/" + calcUnitId); //$NON-NLS-1$ final IFolder unitFolder = m_scenarioFolder.getFolder(unitFolderRelativePath); final ResultManagerOperation dataOperation = new ResultManagerOperation(resultManager, unitFolder.getLocation().toFile(), Status.OK_STATUS, processingOperation.getOutputDir(), calcUnitMeta, lResultsToRemove); dataOperation.setBoolRemoveRawResult(false); return dataOperation.execute(monitor); }
From source file:org.mycore.backend.filesystem.MCRCStoreVFS.java
@Override protected void doDeleteContent(String storageId) throws Exception { FileObject targetObject = fsManager.resolveFile(getBase(), storageId); LOGGER.debug("Delete fired on: " + targetObject); LOGGER.debug("targetObject.class = " + targetObject.getClass().getName()); if (targetObject.delete()) { LOGGER.debug("Delete of " + targetObject + " was successful."); } else {/*from ww w .java 2 s . c o m*/ LOGGER.warn("Delete of " + targetObject + " was NOT successful (w/o errors given)."); } }