List of usage examples for org.apache.commons.vfs2 FileObject close
@Override void close() throws FileSystemException;
From source file:org.kalypso.service.wps.refactoring.DefaultWPSProcess.java
/** * @see org.kalypso.service.wps.client.IWPSProcess#startProcess(java.util.Map, java.util.List, * org.eclipse.core.runtime.IProgressMonitor) *//*from w ww. ja v a 2s . c o m*/ @Override public synchronized void startProcess(final Map<String, Object> inputs, final List<String> outputs, IProgressMonitor monitor) throws CoreException { Assert.isTrue(m_executionResponse == null); /* Monitor. */ monitor = SubMonitor.convert(monitor, Messages.getString("org.kalypso.service.wps.refactoring.DefaultWPSProcess.4"), 200); //$NON-NLS-1$ KalypsoServiceWPSDebug.DEBUG.printf("Checking for service URL ...\n"); //$NON-NLS-1$ /* Get the process description. */ final ProcessDescriptionType processDescription = getProcessDescription(monitor); /* Get the input data. */ final DataInputsType dataInputs = createDataInputs(processDescription, inputs); /* Get the output data. */ m_outputDefinitions = WPSUtilities.createOutputDefinitions(processDescription, outputs); /* Loop, until an result is available, a timeout is reached or the user has cancelled the job. */ final String title = processDescription.getTitle(); monitor.setTaskName(Messages.getString("org.kalypso.service.wps.client.WPSRequest.1") + title); //$NON-NLS-1$ final CodeType simulationIdentifier = WPS040ObjectFactoryUtilities.buildCodeType("", m_identifier); // decide between local and remote invocation if (WPSRequest.SERVICE_LOCAL.equals(m_serviceEndpoint)) { FileObject resultFile = null; try { /* Execute the simulation via a manager, so that more than one simulation can be run at the same time. */ final Execute execute = WPS040ObjectFactoryUtilities.buildExecute(simulationIdentifier, dataInputs, m_outputDefinitions, true, true); final WPSSimulationManager manager = WPSSimulationManager.getInstance(); final ExecuteMediator executeMediator = new ExecuteMediator(execute); final WPSSimulationInfo info = manager.startSimulation(executeMediator); m_jobId = info.getId(); /* Prepare the execute response. */ final FileObject resultDir = manager.getResultDir(info.getId()); resultFile = resultDir.resolveFile("executeResponse.xml"); final String statusLocation = WPSUtilities .convertInternalToClient(resultFile.getURL().toExternalForm()); final StatusType status = WPS040ObjectFactoryUtilities.buildStatusType("Process accepted.", true); m_executionResponse = WPS040ObjectFactoryUtilities.buildExecuteResponseType(simulationIdentifier, status, dataInputs, m_outputDefinitions, null, statusLocation, WPSUtilities.WPS_VERSION.V040.toString()); } catch (final IOException e) { throw new CoreException(StatusUtilities.statusFromThrowable(e)); } catch (final SimulationException e) { throw new CoreException(StatusUtilities.statusFromThrowable(e)); } catch (final OWSException e) { throw new CoreException(StatusUtilities.statusFromThrowable(e)); } finally { if (resultFile != null) try { resultFile.close(); } catch (final FileSystemException e) { // gobble } } } else { m_executionResponse = WPSUtilities.callExecute(m_serviceEndpoint, m_identifier, dataInputs, m_outputDefinitions); // TODO: check status, should now at least be 'accepted' } // TODO: move outside // final StatusType status = executeResponse.getStatus(); // final ProcessFailedType processFailed = status.getProcessFailed(); // if( processFailed != null ) // { // final String errorString = WPSUtilities.createErrorString( processFailed.getExceptionReport() ); // return StatusUtilities.createErrorStatus( errorString ); // } /* If the user aborted the job. */ // ProgressUtilities.worked( monitor, 100 ); }
From source file:org.kalypso.service.wps.utils.simulation.WPSSimulationHandler.java
/** * This function creates the execute response in the location for the given thread. * * @param status/*from ww w.j a va 2 s .co m*/ * The status of the process. * @param ioValues * The ioValues for creating the process outputs, if any are here. Otherwise leave it null. */ private synchronized void createExecuteResponse(final StatusType status, final List<IOValueType> ioValues) throws Exception { /* Prepare the execute response. */ final FileObject resultDir = m_service.getResultDir(m_jobID); final FileObject resultFile = resultDir.resolveFile("executeResponse.xml"); //$NON-NLS-1$ final String statusLocation = WPSUtilities.convertInternalToClient(resultFile.getURL().toExternalForm()); ProcessOutputs processOutputs = null; if (ioValues != null) processOutputs = WPS040ObjectFactoryUtilities.buildExecuteResponseTypeProcessOutputs(ioValues); final ExecuteResponseType value = WPS040ObjectFactoryUtilities.buildExecuteResponseType( m_execute.getIdentifier(), status, m_execute.getDataInputs(), m_execute.getOutputDefinitions(), processOutputs, statusLocation, WPSUtilities.WPS_VERSION.V040.toString()); final JAXBElement<ExecuteResponseType> executeResponse = WPS040ObjectFactoryUtilities .buildExecuteResponse(value); /* Marshall it into one XML string. */ final String xml = MarshallUtilities.marshall(executeResponse, WPS_VERSION.V040); /* Copy the execute response to this url. */ VFSUtilities.copyStringToFileObject(xml, resultFile); resultFile.close(); }
From source file:org.kalypso.service.wps.utils.WPSUtilities.java
public static ExecuteResponseType readExecutionResponse(final FileSystemManager manager, final String statusLocation) throws CoreException { try {/*from w w w. j a v a2s . c om*/ final FileObject statusFile = VFSUtilities.checkProxyFor(statusLocation, manager); if (!statusFile.exists()) return null; /* Try to read the status at least 3 times, before exiting. */ Exception lastError = new Exception(); // TODO: timeout defined as approximately 3 seconds is in some how not always usable, set to 100. // Better to set it from predefined properties. // Hi Ilya, I think you missunderstood the number here. // It does not represent a timeout, but the number of times to try. // The Thread.sleep( 1000 ) in case of an error is only the time to wait, // before it is retried to read the execution response. // I changed the value back to 3. Holger for (int i = 0; i < 3; i++) { InputStream inputStream = null; try { final FileContent content = statusFile.getContent(); inputStream = content.getInputStream(); final String xml = IOUtils.toString(inputStream); if (xml == null || "".equals(xml)) //$NON-NLS-1$ throw new IOException(Messages.getString("org.kalypso.service.wps.utils.WPSUtilities.4") //$NON-NLS-1$ + statusFile.toString()); final Object object = MarshallUtilities.unmarshall(xml); final JAXBElement<?> executeState = (JAXBElement<?>) object; return (ExecuteResponseType) executeState.getValue(); } catch (final Exception e) { lastError = e; KalypsoServiceWPSDebug.DEBUG .printf("An error has occured with the message: " + e.getLocalizedMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ KalypsoServiceWPSDebug.DEBUG.printf("Retry: " + String.valueOf(i) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ Thread.sleep(1000); } finally { IOUtils.closeQuietly(inputStream); statusFile.close(); } } KalypsoServiceWPSDebug.DEBUG.printf("The second retry has failed, rethrowing the error ..."); //$NON-NLS-1$ //$NON-NLS-2$ final IStatus status = StatusUtilities.createStatus(IStatus.ERROR, Messages.getString("org.kalypso.service.wps.utils.WPSUtilities.5") //$NON-NLS-1$ + lastError.getLocalizedMessage(), lastError); throw new CoreException(status); } catch (final Exception e) { e.printStackTrace(); final IStatus status = StatusUtilities.createStatus(IStatus.ERROR, Messages.getString("org.kalypso.service.wps.utils.WPSUtilities.6") + e.getLocalizedMessage(), //$NON-NLS-1$ e); throw new CoreException(status); } }
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;//from w w w . jav 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.ow2.proactive_grid_cloud_portal.dataspace.RestDataspaceImpl.java
/** * Delete file(s) from the specified location in the <i>dataspace</i>. The * format of the DELETE URI is:/*from www. j ava2 s . c om*/ * <p> * {@code http://<rest-server-path>/data/<dataspace>/<path-name>} * <p> * Example: * {@code http://localhost:8080/rest/rest/data/user/my-files/my-text-file.txt} * <ul> * <li>dataspace: can have two possible values, 'user' or 'global', * depending on the target <i>DATASPACE</i></li> * <li>path-name: location of the file(s) to be deleted.</li> * </ul> * <b>Notes:</b> * <ul> * <li>Only empty directories can be deleted.</li> * <li>File names or regular expressions can be used as 'includes' and * 'excludes' query parameters, in order to select which files to be deleted * inside the specified directory (path-name).</li> * </ul> * */ @DELETE @Path("/{dataspace}/{path-name:.*}") public Response delete(@HeaderParam("sessionid") String sessionId, @PathParam("dataspace") String dataspace, @PathParam("path-name") String pathname, @QueryParam("includes") List<String> includes, @QueryParam("excludes") List<String> excludes) throws NotConnectedRestException, PermissionRestException { checkPathParams(dataspace, pathname); Session session = checkSessionValidity(sessionId); try { FileObject fo = resolveFile(session, dataspace, pathname); if (!fo.exists()) { return Response.status(Response.Status.NO_CONTENT).build(); } if (fo.getType() == FileType.FOLDER) { logger.debug(String.format("Deleting directory %s in %s", pathname, dataspace)); return deleteDir(fo, includes, excludes); } else { logger.debug(String.format("Deleting file %s in %s", pathname, dataspace)); fo.close(); return fo.delete() ? noContentRes() : serverErrorRes("Cannot delete the file: %s", pathname); } } catch (Throwable error) { logger.error(String.format("Cannot delete %s in %s.", pathname, dataspace), error); throw rethrow(error); } }
From source file:org.pentaho.di.trans.steps.enhanced.jsonoutput.JsonOutput.java
private void createParentFolder(String filename) throws KettleStepException { if (!meta.isCreateParentFolder()) { return;/*from w ww. ja v a 2s.co m*/ } // Check for parent folder FileObject parentfolder = null; try { // Get parent folder parentfolder = KettleVFS.getFileObject(filename, getTransMeta()).getParent(); if (!parentfolder.exists()) { if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JsonOutput.Error.ParentFolderNotExist", parentfolder.getName())); } parentfolder.createFolder(); if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JsonOutput.Log.ParentFolderCreated")); } } } catch (Exception e) { throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.ErrorCreatingParentFolder", parentfolder.getName())); } finally { if (parentfolder != null) { try { parentfolder.close(); } catch (Exception ex) { /* Ignore */ } } } }
From source file:org.pentaho.di.ui.job.entries.trans.JobEntryBaseDialog.java
protected void selectLogFile(String[] filters) { FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterExtensions(new String[] { "*.txt", "*.log", "*" }); dialog.setFilterNames(filters);/* ww w .jav a 2s . c o m*/ if (wLogfile.getText() != null) { dialog.setFileName(jobMeta.environmentSubstitute(wLogfile.getText())); } if (dialog.open() != null) { wLogfile.setText(dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName()); String filename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName(); FileObject file = null; try { file = KettleVFS.getFileObject(filename); // Set file extension .. wLogext.setText(file.getName().getExtension()); // Set filename without extension ... wLogfile.setText(wLogfile.getText().substring(0, wLogfile.getText().length() - wLogext.getText().length() - 1)); } catch (Exception ex) { // Ignore } if (file != null) { try { file.close(); } catch (IOException ex) { /* Ignore */ } } } }
From source file:org.wso2.carbon.connector.FileAppend.java
/** * @param destination Location if the file * @param content Content that is going to be added * @param encoding Encoding type/*from w ww . j a v a2 s . co m*/ * @param messageContext The message context that is generated for processing the file * @return true/false */ private boolean appendFile(String destination, String content, String encoding, MessageContext messageContext) { OutputStream out = null; boolean resultStatus = false; FileObject fileObj = null; StandardFileSystemManager manager = null; try { manager = FileConnectorUtils.getManager(); fileObj = manager.resolveFile(destination, FileConnectorUtils.init(messageContext)); if (!fileObj.exists()) { fileObj.createFile(); } out = fileObj.getContent().getOutputStream(true); if (StringUtils.isEmpty(encoding)) { IOUtils.write(content, out, DEFAULT_ENCODING); } else { IOUtils.write(content, out, encoding); } resultStatus = true; if (log.isDebugEnabled()) { log.debug("File appending completed. " + destination); } } catch (IOException e) { handleException("Error while appending a file.", e, messageContext); } finally { try { if (fileObj != null) { //close the file object fileObj.close(); } } catch (FileSystemException e) { log.error("Error while closing FileObject: " + e.getMessage(), e); } try { if (out != null) { //close the output stream out.close(); } } catch (IOException e) { log.error("Error while closing OutputStream: " + e.getMessage(), e); } if (manager != null) { //close the StandardFileSystemManager manager.close(); } } return resultStatus; }
From source file:org.wso2.carbon.connector.FileAppendConnector.java
/** * Add the content into file.// w w w. ja v a2 s . c om * * @param messageContext The message context that is generated for processing the file. * @return true, if the content is successfully appended. * @throws FileSystemException On error parsing the file name, determining if the file exists and creating the * file. */ private boolean appendFile(MessageContext messageContext) throws FileSystemException { String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.NEW_FILE_LOCATION); String content = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.CONTENT); String encoding = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.ENCODING); if (StringUtils.isEmpty(encoding)) { encoding = FileConstants.DEFAULT_ENCODING; } FileSystemOptions opts = FileConnectorUtils.init(messageContext); OutputStream out = null; FileObject fileObj = null; StandardFileSystemManager manager = FileConnectorUtils.getManager(); try { fileObj = manager.resolveFile(destination, opts); if (!fileObj.exists()) { fileObj.createFile(); } // True, if the content should be appended. out = fileObj.getContent().getOutputStream(true); IOUtils.write(content, out, encoding); if (log.isDebugEnabled()) { log.debug("File appending completed. " + destination); } } catch (IOException e) { throw new SynapseException("Error while appending content", e); } finally { try { if (fileObj != null) { // close the file object fileObj.close(); } } catch (FileSystemException e) { log.error("Error while closing FileObject", e); } try { if (out != null) { // close the output stream out.close(); } } catch (IOException e) { log.error("Error while closing OutputStream", e); } // close the StandardFileSystemManager manager.close(); } return true; }
From source file:org.wso2.carbon.connector.FileArchiveConnector.java
/** * Archive a file/folder./*ww w. j a va 2 s . co m*/ * * @param messageContext The message context that is generated for processing the file. * @return return true, if the file/folder is successfully archived, false, if not. * @throws FileSystemException On error parsing the file name, determining if the file exists and getting file type. */ private boolean fileCompress(MessageContext messageContext) throws FileSystemException { String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.FILE_LOCATION); String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.NEW_FILE_LOCATION); StandardFileSystemManager manager = FileConnectorUtils.getManager(); FileSystemOptions opts = FileConnectorUtils.init(messageContext); FileObject fileObj = manager.resolveFile(source, opts); FileObject destObj = manager.resolveFile(destination, opts); if (!fileObj.exists()) { log.error("The File location does not exist."); return false; } if (FileType.FOLDER.equals(fileObj.getType())) { List<FileObject> fileList = new ArrayList<>(); addAllFilesToList(fileObj, fileList); writeZipFiles(fileObj, destObj, fileList); } else { ZipOutputStream outputStream = null; InputStream fileIn = null; try { outputStream = new ZipOutputStream(destObj.getContent().getOutputStream()); fileIn = fileObj.getContent().getInputStream(); ZipEntry zipEntry = new ZipEntry(fileObj.getName().getBaseName()); outputStream.putNextEntry(zipEntry); int length; while ((length = fileIn.read(bytes)) != -1) { outputStream.write(bytes, 0, length); } } catch (IOException e) { throw new SynapseException("Error while writing an array of bytes to the ZipOutputStream", e); } finally { try { // close the file object fileObj.close(); } catch (FileSystemException e) { log.error("Error while closing the source FileObject", e); } try { // close the file object destObj.close(); } catch (FileSystemException e) { log.error("Error while closing the destination FileObject", e); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { log.error("Error while closing ZipOutputStream", e); } try { if (fileIn != null) { fileIn.close(); } } catch (IOException e) { log.error("Error while closing InputStream:", e); } // close the StandardFileSystemManager manager.close(); } } if (log.isDebugEnabled()) { log.debug("File archiving completed." + destination); } return true; }