List of usage examples for org.apache.commons.vfs2 FileObject getContent
FileContent getContent() throws FileSystemException;
From source file:org.kalypso.commons.io.VFSUtilities.java
/** * This function copies a string to a vfs file object. * * @param value/*from w w w . ja va 2 s . c o m*/ * This string will be copied to the file. * @param destination * The destination. It must be a file. */ public static void copyStringToFileObject(final String value, final FileObject destination) throws IOException { if (FileType.FOLDER.equals(destination.getType())) throw new IllegalArgumentException("Destination is a folder."); //$NON-NLS-1$ /* Copy the string to this url. */ OutputStream outputStream = null; StringReader stringReader = null; try { outputStream = destination.getContent().getOutputStream(false); stringReader = new StringReader(value); IOUtils.copy(stringReader, outputStream); outputStream.close(); stringReader.close(); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(stringReader); } }
From source file:org.kalypso.commons.io.VFSUtilities.java
/** * resolves the input stream from given {@link FileObject} based on the file extention, known types are gz and zip, in * case of zip archiv the first file will be taken. */// www .jav a2 s.com public static InputStream getInputStreamFromFileObject(final FileObject file) throws FileSystemException, IOException, URISyntaxException { /* open stream */ if ("gz".equalsIgnoreCase(file.getName().getExtension()))//$NON-NLS-1$ return new GZIPInputStream(new BufferedInputStream(file.getContent().getInputStream())); if ("zip".equalsIgnoreCase(file.getName().getExtension()))//$NON-NLS-1$ return ZipUtilities.getInputStreamForFirstFile(file.getURL()); return new BufferedInputStream(file.getContent().getInputStream()); }
From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverterSWAN.java
/** * *//*from w ww . ja va 2 s . co m*/ protected Formatter getFormatter(final String pStrFileName) throws IOException { Formatter lFormatter = null; { final FileObject lFileDataAdditional = m_fileObjWorkingDir.resolveFile(pStrFileName); lFormatter = new Formatter(lFileDataAdditional.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); } return lFormatter; }
From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverterTelemac.java
/** * //from w w w . j av a 2s.c o m */ protected Formatter getFormatter(final String pStrFileName) throws IOException { Formatter lFormatter = null; { FileObject lFileDataAdditional = m_fileObjWorkingDir.resolveFile(pStrFileName); lFormatter = new Formatter(lFileDataAdditional.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); } return lFormatter; }
From source file:org.kalypso.kalypsomodel1d2d.conv.Gml2TelemacConv.java
/** * *///from w ww . j a v a2 s . c o m public Map<GM_Position, Integer> writeTelemacModel(final FileObject pFileObjWorkingDir) { try { m_fileObjWorkingDir = pFileObjWorkingDir; // REMARK: Made a central formatter with US locale (causing decimal point to be '.'), // so no locale parameter for each format is needed any more . final FileObject lModelBoundNodesFile = pFileObjWorkingDir .resolveFile(getProjectFileName() + BOUNDARY_NODES_FILE_EXTENTION); final FileObject lModelBoundariesFile = pFileObjWorkingDir .resolveFile(getProjectFileName() + BOUNDARY_CONDITIONS_FILE_EXTENTION); m_formatterBoundNodes = new Formatter(lModelBoundNodesFile.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); m_formatterBoundaries = new Formatter(lModelBoundariesFile.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); determineBoundNodes(); initIParams(); writeTelemacNodesModel(pFileObjWorkingDir); FormatterUtils.checkIoException(m_formatterBoundNodes); FormatterUtils.checkIoException(m_formatterBoundaries); return m_mapNodesActPositions; } catch (Throwable t) { t.printStackTrace(); m_log.log(StatusUtilities.statusFromThrowable(t)); return null; } finally { if (m_formatterBoundNodes != null) { m_formatterBoundNodes.close(); } if (m_formatterBoundaries != null) { m_formatterBoundaries.close(); } } }
From source file:org.kalypso.kalypsomodel1d2d.conv.Gml2TelemacConv.java
private void writeWQBoundaries(Map<Integer, BoundaryConditionTelemac> wqBounds) { try {/* w w w. ja va 2s . c o m*/ final FileObject lModelWQBoundariesFile = m_fileObjWorkingDir .resolveFile(getProjectFileName() + WQ_BOUND_FILE_EXTENTION); m_formatterWQBoundaries = new Formatter(lModelWQBoundariesFile.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); for (Iterator<Integer> iterator = wqBounds.keySet().iterator(); iterator.hasNext();) { Integer boundId = iterator.next(); BoundaryConditionTelemac actBoundary = wqBounds.get(boundId); String headerLine = " Q(" + boundId + ") Z(" + boundId + ") %n";//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ m_formatterWQBoundaries.format(headerLine); headerLine = " m3/s m%n"; //$NON-NLS-1$ m_formatterWQBoundaries.format(headerLine); final TupleResult result = actBoundary.getObs().getResult(); final IComponent[] components = result.getComponents(); final int icompQ = result.indexOfComponent(ComponentUtilities.findComponentByID(components, Kalypso1D2DDictConstants.DICT_COMPONENT_DISCHARGE)); final int icompZ = result.indexOfComponent(ComponentUtilities.findComponentByID(components, Kalypso1D2DDictConstants.DICT_COMPONENT_WATERLEVEL)); for (IRecord record : result) { m_formatterWQBoundaries.format(" %f %f%n", record.getValue(icompQ), record.getValue(icompZ)); //$NON-NLS-1$ } } FormatterUtils.checkIoException(m_formatterWQBoundaries); } catch (Throwable t) { t.printStackTrace(); m_log.log(StatusUtilities.statusFromThrowable(t)); } finally { if (m_formatterWQBoundaries != null) { m_formatterWQBoundaries.close(); } } }
From source file:org.kalypso.kalypsomodel1d2d.conv.SWANAdditionalDataConverter.java
private void writeCurrentSeriesFile(final Date pDate, final FileObject modelCurrentFileSerie) { Formatter lFormatterCurrent = null; // put first the Y component of current into buffer to write it out after X-component according to SWAN formating // rules// w ww . j ava 2s . c om final StringBuffer lStrBuffY = new StringBuffer(); try { final List<INodeResult> lListActResults = m_resultsSimpleHandler.getResultsForDate(pDate); lFormatterCurrent = new Formatter(modelCurrentFileSerie.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); if (lListActResults == null) { // TODO: debug output... return; } final double lDoubleExclNr = Double.parseDouble(ISimulation1D2DConstants.SIM_SWAN_EXCLUSION_NUMBER); for (final INodeResult lResultAct : lListActResults) { if (lDoubleExclNr != lResultAct.getWaterlevel()) { try { final List<Double> lListDoubleVelocity = lResultAct.getVelocity();// AbsoluteVelocity(); lFormatterCurrent.format("%.2f\n", lListDoubleVelocity.get(0)); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%.2f\n", lListDoubleVelocity.get(1))); //$NON-NLS-1$ } catch (final Exception e) { lFormatterCurrent.format("%s\n", m_strDefaulCurrentValue); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%s\n", m_strDefaulCurrentValue)); //$NON-NLS-1$ } } else { lFormatterCurrent.format("%s\n", m_strDefaulCurrentValue); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%s\n", m_strDefaulCurrentValue)); //$NON-NLS-1$ } } lFormatterCurrent.format("%s\n", lStrBuffY.toString()); //$NON-NLS-1$ FormatterUtils.checkIoException(lFormatterCurrent); } catch (final Exception e) { e.printStackTrace(); } finally { if (lFormatterCurrent != null) { // REMARK: do not check io-exception here, else other exception would be hidden by this on lFormatterCurrent.close(); } } }
From source file:org.kalypso.kalypsomodel1d2d.conv.SWANAdditionalDataConverter.java
private void writeWLSeriesFile(final Date pDate, final FileObject modelWLFileSerie) { Formatter lFormatterWL = null; try {/*w ww.j a va 2 s. c o m*/ final List<INodeResult> lListActResults = m_resultsSimpleHandler.getResultsForDate(pDate); lFormatterWL = new Formatter(modelWLFileSerie.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); if (lListActResults == null) { return; } for (final INodeResult lResultAct : lListActResults) { if (lResultAct.isWet()) { lFormatterWL.format("%.3f\n", lResultAct.getWaterlevel()); //$NON-NLS-1$ } else { lFormatterWL.format("%s\n", ISimulation1D2DConstants.SIM_SWAN_EXCLUSION_NUMBER); //$NON-NLS-1$ } } FormatterUtils.checkIoException(lFormatterWL); } catch (final Exception e) { e.printStackTrace(); } finally { if (lFormatterWL != null) { // REMARK: do not check io-exception here, else other exception would be hidden by this on lFormatterWL.close(); } } }
From source file:org.kalypso.kalypsomodel1d2d.sim.ResultManager.java
private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) { final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile); if (lShiftPosition == null) { return;//from w w w . java 2 s . c o m } try { if (swanResOutTabFile.isContentOpen()) { swanResOutTabFile.close(); } final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent() .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$ swanResOutTabFile.moveTo(swanResOutTabFileBackUp); // int lIntLinesCounter = 0; final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream(); final DataInputStream lInDataStream = new DataInputStream( swanResOutTabFileBackUp.getContent().getInputStream()); BufferedReader streamReader = new BufferedReader(new InputStreamReader(lInDataStream)); final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US); while (lInDataStream.available() != 0) { final String lStrTmpLine = streamReader.readLine().trim(); // ++lIntLinesCounter; if (lStrTmpLine.startsWith("%")) { //$NON-NLS-1$ lFormatter.format("%s\n", lStrTmpLine); //$NON-NLS-1$ continue; } final StringTokenizer lStrTokenizer = new StringTokenizer(lStrTmpLine, " "); //$NON-NLS-1$ int lIntTokenCounter = 0; String lStrNewLine = ""; //$NON-NLS-1$ while (lStrTokenizer.hasMoreTokens()) { final String lStrToken = lStrTokenizer.nextToken(); if (lIntTokenCounter == 1) { lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$ NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getX()); } else if (lIntTokenCounter == 2) { lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$ NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getY()); } else { lStrNewLine += lStrToken + "\t"; //$NON-NLS-1$ } lIntTokenCounter++; } lFormatter.format("%s\n", lStrNewLine); //$NON-NLS-1$ } lFormatter.close(); lInDataStream.close(); lOutStream.close(); } catch (final Exception e) { return; } return; }
From source file:org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.java
/** * Runs < rma10s calculation. The following steps are processed: * <ul>/*from w ww .j a v a2 s .c om*/ * <li>write rma10s ASCII files to temporary directory according to provided gml-models</li> * <li>write .exe to temporary directory</li> * <li>execute the .exe</li> * </ul> * * @see org.kalypso.simulation.core.ISimulation#run(java.io.File, org.kalypso.simulation.core.ISimulationDataProvider, org.kalypso.simulation.core.ISimulationResultEater, * org.kalypso.simulation.core.ISimulationMonitor) */ @Override public void run(final File tmpdir, final ISimulationDataProvider inputProvider, final ISimulationResultEater resultEater, final ISimulationMonitor monitor) throws SimulationException { final SimulationMonitorAdaptor progressMonitor = new SimulationMonitorAdaptor(monitor); final ICancelable progressCancelable = new ProgressCancelable(progressMonitor); try { m_log = new GeoLog(KalypsoModel1D2DPlugin.getDefault().getLog()); } catch (final Exception e) { throw new SimulationException("Could not initialize GeoLog", e); //$NON-NLS-1$ } OutputStream logOS = null; OutputStream errorOS = null; FileSystemManagerWrapper manager = null; try { // TODO: use URI instead of URL final String version = (String) inputProvider.getInputForID(INPUT_RMA_VERSION); final URL modelFileUrl = (URL) inputProvider.getInputForID(INPUT_MESH); final URL controlFileUrl = (URL) inputProvider.getInputForID(INPUT_CONTROL); final URL buildingFileUrl = (URL) inputProvider.getInputForID(INPUT_BUILDINGS); final URL bcwqFileUrl = (URL) inputProvider.getInputForID(INPUT_BC_WQ); final URL windFileUrl = (URL) inputProvider.getInputForID(INPUT_WIND); final URL windCoordFileUrl = (URL) inputProvider.getInputForID(INPUT_WIND_COORD); manager = VFSUtilities.getNewManager(); final FileObject modelFile = manager.resolveFile(modelFileUrl.toString()); final FileObject controlFile = manager.resolveFile(controlFileUrl.toString()); final FileObject buildingFile = manager.resolveFile(buildingFileUrl.toString()); final FileObject bcwqFile = manager.resolveFile(bcwqFileUrl.toString()); final FileObject windFile = manager.resolveFile(windFileUrl.toString()); final FileObject windCoordFile = manager.resolveFile(windCoordFileUrl.toString()); // find executable for version final File exeFile = findRma10skExe(version); final FileObject executableFile = manager.toFileObject(exeFile); final String executableName = exeFile.getName(); // Generate the process-factory-id // TODO: at the moment, this is hard wired.... later we should get it from System.properties and/or from our own // simulation-id (as we are no simulation, this does not work yet). // Example1: org.kalypso.simulation.process.factory.<simulation-id>=<factory-id> // For the moment, we could also provide it directly from outside or from a system-property // (fall-back should always be the default factory) final String processFactoryId = IProcessFactory.DEFAULT_PROCESS_FACTORY_ID; // simply switch here and we run in the grid :) // final String processFactoryId = "org.kalypso.simulation.gridprocess"; //$NON-NLS-1$ final String tempDirName; if (inputProvider.hasID(INPUT_WORKING_DIR)) tempDirName = (String) inputProvider.getInputForID(INPUT_WORKING_DIR); else tempDirName = tmpdir.getName(); final IProcess process = KalypsoCommonsExtensions.createProcess(processFactoryId, tempDirName, executableName); // add sandbox dir to results for monitoring (empty at this time) final String sandboxDirectory = process.getSandboxDirectory(); try { final URI resultURI = new URI(sandboxDirectory); if (resultURI.getScheme().equals("file")) //$NON-NLS-1$ resultEater.addResult(OUTPUT_RESULTS, new File(resultURI)); else resultEater.addResult(OUTPUT_RESULTS, resultURI); } catch (final URISyntaxException e) { e.printStackTrace(); } // check if user cancelled if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // copy executable and write input files // final FileObject workingDir = manager.resolveFile(sandboxDirectory); VFSUtilities.copyFileTo(executableFile, workingDir); VFSUtilities.copyFileTo(modelFile, workingDir); VFSUtilities.copyFileTo(controlFile, workingDir); VFSUtilities.copyFileTo(buildingFile, workingDir); VFSUtilities.copyFileTo(bcwqFile, workingDir); VFSUtilities.copyFileTo(windFile, workingDir); VFSUtilities.copyFileTo(windCoordFile, workingDir); final File stdoutFile = new File(tmpdir, "exe.log"); //$NON-NLS-1$ final File stderrFile = new File(tmpdir, "exe.err"); //$NON-NLS-1$ logOS = new BufferedOutputStream(new FileOutputStream(stdoutFile)); errorOS = new BufferedOutputStream(new FileOutputStream(stderrFile)); // check if user cancelled if (monitor.isCanceled()) { throw new OperationCanceledException(); } System.gc(); // Run the Calculation m_log.formatLog(IStatus.INFO, ISimulation1D2DConstants.CODE_RUNNING, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMA10Calculation.0") + ": " //$NON-NLS-1$//$NON-NLS-2$ + executableName); process.startProcess(logOS, errorOS, null, progressCancelable); // decide based on ERROR.OUT if simulation was successful final FileObject errorFile = workingDir.resolveFile("ERROR.OUT"); //$NON-NLS-1$ if (errorFile == null || !errorFile.exists() || errorFile.getContent().getSize() == 0) { /* Successfully finished simulation */ progressMonitor.done(new Status(IStatus.OK, KalypsoModel1D2DPlugin.PLUGIN_ID, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMA10Calculation.20"))); //$NON-NLS-1$ } else { /* ERROR: return contents of error file as error message */ final byte[] content = FileUtil.getContent(errorFile); final String charset = Charset.defaultCharset().name(); final String errorMessage = new String(content, charset); final IStatus status = new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, errorMessage); progressMonitor.done(status); throw new CoreException(status); } } catch (final ProcessTimeoutException e) { throw new SimulationException( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.0"), e); //$NON-NLS-1$ } catch (final OperationCanceledException e) { // do not throw an exception if cancelled monitor.setFinishInfo(IStatus.CANCEL, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.1"));//$NON-NLS-1$ monitor.setMessage(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.1"));//$NON-NLS-1$ return; } catch (final CoreException e) { throw new SimulationException( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.2"), e); //$NON-NLS-1$ } catch (final IOException e) { throw new SimulationException( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.3"), e); //$NON-NLS-1$ } finally { IOUtils.closeQuietly(logOS); IOUtils.closeQuietly(errorOS); if (manager != null) manager.close(); } }