Example usage for org.apache.commons.vfs2 FileObject exists

List of usage examples for org.apache.commons.vfs2 FileObject exists

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject exists.

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function copies a source file to a given destination. If no filename is given in the destination file handle,
 * the filename of the source is used.<br>
 * <br>/*from   w w  w  . jav a  2 s  .c  o m*/
 * It is tried to copy the file three times. If all three tries has failed, only then an IOException is thrown. <br>
 * All other exceptions are thrown normally.
 *
 * @param source
 *          The source file.
 * @param destination
 *          The destination file or path.
 * @param overwrite
 *          If set, always overwrite existing and newer files
 */
public static void copyFileTo(final FileObject source, final FileObject destination, final boolean overwrite)
        throws IOException {
    if (source.equals(destination)) {
        KalypsoCommonsDebug.DEBUG.printf(Messages.getString("org.kalypso.commons.io.VFSUtilities.1"), //$NON-NLS-1$
                source.getName(), destination.getName());
        return;
    }

    /* Some variables for handling the errors. */
    boolean success = false;
    int cnt = 0;

    while (success == false) {
        try {
            if (FileType.FOLDER.equals(source.getType()))
                throw new IllegalArgumentException(Messages.getString("org.kalypso.commons.io.VFSUtilities.2")); //$NON-NLS-1$

            /* If the destination is only a directory, use the sources filename for the destination file. */
            FileObject destinationFile = destination;
            if (FileType.FOLDER.equals(destination.getType()))
                destinationFile = destination.resolveFile(source.getName().getBaseName());

            if (overwrite || !destinationFile.exists()
                    || destinationFile.getContent().getSize() != source.getContent().getSize()) {
                /* Copy file. */
                KalypsoCommonsDebug.DEBUG.printf("Copy file '%s' to '%s'...%n", source.getName(), //$NON-NLS-1$
                        destinationFile.getName());
                FileUtil.copyContent(source, destinationFile);
                source.close();
            }

            /* End copying of this file, because it was a success. */
            success = true;
        } catch (final IOException e) {
            /* An error has occurred while copying the file. */
            KalypsoCommonsDebug.DEBUG.printf("An error has occured with the message: %s%n", //$NON-NLS-1$
                    e.getLocalizedMessage());

            /* If a certain amount (here 2) of retries was reached before, re-throw the error. */
            if (cnt >= 2) {
                KalypsoCommonsDebug.DEBUG.printf("The second retry has failed, rethrowing the error...%n"); //$NON-NLS-1$
                throw e;
            }

            /* Retry the copying of the file. */
            cnt++;
            KalypsoCommonsDebug.DEBUG.printf("Retry: %s%n", String.valueOf(cnt)); //$NON-NLS-1$
            success = false;

            /* Wait for some milliseconds. */
            try {
                Thread.sleep(1000);
            } catch (final InterruptedException e1) {
                /*
                 * Runs in the next loop then and if no error occurs then, it is ok. If an error occurs again, it is an
                 * exception thrown on the last failed retry or it is slept again.
                 */
            }
        }
    }
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function will copy one directory to another one. If the destination base directory does not exist, it will be
 * created.//www.ja v  a 2s.c  om
 *
 * @param source
 *          The source directory.
 * @param destination
 *          The destination directory.
 * @param overwrite
 *          If set, always overwrite existing and newer files
 */
public static void copyDirectoryToDirectory(final FileObject source, final FileObject destination,
        final boolean overwrite) throws IOException {
    if (!FileType.FOLDER.equals(source.getType()))
        throw new IllegalArgumentException(
                Messages.getString("org.kalypso.commons.io.VFSUtilities.3") + source.getURL()); //$NON-NLS-1$

    if (destination.exists()) {
        if (!FileType.FOLDER.equals(destination.getType()))
            throw new IllegalArgumentException(
                    Messages.getString("org.kalypso.commons.io.VFSUtilities.4") + destination.getURL()); //$NON-NLS-1$
    } else {
        KalypsoCommonsDebug.DEBUG.printf("Creating directory '%s'...%", destination.getName()); //$NON-NLS-1$
        destination.createFolder();
    }

    final FileObject[] children = source.getChildren();
    for (final FileObject child : children) {
        if (FileType.FILE.equals(child.getType())) {
            /* Need a destination file with the same name as the source file. */
            final FileObject destinationFile = destination.resolveFile(child.getName().getBaseName());

            /* Copy ... */
            copyFileTo(child, destinationFile, overwrite);
        } else if (FileType.FOLDER.equals(child.getType())) {
            /* Need the same name for destination directory, as the source directory has. */
            final FileObject destinationDir = destination.resolveFile(child.getName().getBaseName());

            /* Copy ... */
            KalypsoCommonsDebug.DEBUG.printf("Copy directory %s to %s ...", child.getName(), //$NON-NLS-1$
                    destinationDir.getName());
            copyDirectoryToDirectory(child, destinationDir, overwrite);
        } else {
            KalypsoCommonsDebug.DEBUG.printf("Could not determine the file type ...%n"); //$NON-NLS-1$
        }
    }
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function creates a temporary directory, which has a unique file name.
 *
 * @param prefix//from   w ww. j a  v  a 2s.  c o  m
 *          This prefix will be used for the temporary directory.
 * @param parentDir
 *          The parent directory. In it the new directory will be created.
 * @return The new unique directory.
 */
public static FileObject createTempDirectory(final String prefix, final FileObject parentDir,
        final FileSystemManager fsManager) throws FileSystemException {
    while (true) {
        final String dirParent = parentDir.getURL().toExternalForm();
        final String dirName = prefix + String.valueOf(System.currentTimeMillis());

        final FileObject newDir = fsManager.resolveFile(dirParent + "/" + dirName); //$NON-NLS-1$
        if (newDir.exists()) {
            continue;
        }

        KalypsoCommonsDebug.DEBUG.printf("Creating folder %s ...%n", newDir.getName().getPath()); //$NON-NLS-1$
        newDir.createFolder();
        return newDir;
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.java

/**
 * Runs < rma10s calculation. The following steps are processed:
 * <ul>//w  ww .  j ava2 s .  co  m
 * <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();
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.SWANKalypsoSimulation.java

/**
 * Runs SWAN calculation. The following steps are processed:
 * <ul>/*  w  w  w.  jav a2 s . c o m*/
 * <li>write swan.exe to temporary directory</li>
 * <li>execute the swan.exe</li>
 * <li>read results files and process them to the output directory</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 {
        manager = VFSUtilities.getNewManager();

        // TODO: specific error message if exe was not found
        final String version = (String) inputProvider.getInputForID(INPUT_SWAN_VERSION);
        final File exeFile = findSWANExe(version);
        final FileObject executableFile = manager.toFileObject(exeFile);
        final String executableName = exeFile.getName();

        final String processFactoryId = IProcessFactory.DEFAULT_PROCESS_FACTORY_ID;
        // simply switch here and we run in the grid :)
        // Remark: it would be good also for swan :)
        //      final String processFactoryId = "org.kalypso.simulation.gridprocess"; //$NON-NLS-1$

        final String tempDirName = tmpdir.getName();
        final IProcess process = KalypsoCommonsExtensions.createProcess(processFactoryId, tempDirName,
                executableName);
        // process.setProgressMonitor( progress );

        // add sandbox dir to results for monitoring (empty at this time)
        final String sandboxDirectory = process.getSandboxDirectory();
        try {
            resultEater.addResult(SWANKalypsoSimulation.OUTPUT_RESULTS, new URI(sandboxDirectory)); //$NON-NLS-1$
        } catch (final URISyntaxException e) {
            e.printStackTrace();
        }

        // copy executable and write input files
        final FileObject lFileObjWorkingDir = manager.resolveFile(sandboxDirectory);
        VFSUtilities.copyFileTo(executableFile, lFileObjWorkingDir);

        final String lStrPreSWANURL = (String) inputProvider.getInputForID(PreSWANKalypso.OUTPUT_PATH_SWAN);
        final FileObject lFileObjPreResultsDir = manager.resolveFile(lStrPreSWANURL);
        copyFilesToWorkDir(lFileObjPreResultsDir, lFileObjWorkingDir);

        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));

        // Run the Calculation
        // final SubMonitor progress = SubMonitor.convert( progressMonitor, m_controlModel.getNCYC() );
        m_log.formatLog(IStatus.INFO, CODE_RUNNING,
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.0") + ": " //$NON-NLS-1$//$NON-NLS-2$
                        + executableName);
        progressMonitor.subTask(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.15")); //$NON-NLS-1$
        process.startProcess(logOS, errorOS, null, progressCancelable);

        // decide based on ERROR.OUT if simulation was successful
        final FileObject errorFile = lFileObjWorkingDir.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.SWANCalculation.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);
        }
        // TODO: implement the results eater
    } catch (final ProcessTimeoutException e) {
        throw new SimulationException(
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.0"), e); //$NON-NLS-1$
    } catch (final OperationCanceledException e) {
        final CoreException ce = new CoreException(new Status(IStatus.CANCEL, KalypsoModel1D2DPlugin.PLUGIN_ID,
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.2"), e)); //$NON-NLS-1$

        throw new SimulationException(
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.1"), ce); //$NON-NLS-1$
    } 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();
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.TelemacKalypsoSimulation.java

/**
 * Runs SWAN calculation. The following steps are processed:
 * <ul>//from w w  w .ja v a  2s . c o m
 * <li>write swan.exe to temporary directory</li>
 * <li>execute the swan.exe</li>
 * <li>read results files and process them to the output directory</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 {
        manager = VFSUtilities.getNewManager();

        // TODO: specific error message if exe was not found
        final String version = (String) inputProvider.getInputForID(INPUT_TELEMAC_VERSION);
        final File exeFile = findTelemacBatch(version, tmpdir);
        final FileObject executableFile = manager.toFileObject(exeFile);
        final String executableName = exeFile.getName();

        final String processFactoryId = IProcessFactory.DEFAULT_PROCESS_FACTORY_ID;
        // simply switch here and we run in the grid :)
        // Remark: it would be good also for swan :)
        //      final String processFactoryId = "org.kalypso.simulation.gridprocess"; //$NON-NLS-1$

        final String tempDirName = tmpdir.getName();
        final IProcess process = KalypsoCommonsExtensions.createProcess(processFactoryId, tempDirName,
                executableName);
        // process.setProgressMonitor( progress );

        // add sandbox dir to results for monitoring (empty at this time)
        final String sandboxDirectory = process.getSandboxDirectory();
        try {
            resultEater.addResult(TelemacKalypsoSimulation.OUTPUT_RESULTS, new URI(sandboxDirectory)); //$NON-NLS-1$
        } catch (final URISyntaxException e) {
            e.printStackTrace();
        }

        // copy executable and write input files
        final FileObject lFileObjWorkingDir = manager.resolveFile(sandboxDirectory);
        VFSUtilities.copyFileTo(executableFile, lFileObjWorkingDir);

        final String lStrPreTelemacURL = (String) inputProvider
                .getInputForID(PreTelemacKalypso.OUTPUT_PATH_Telemac);
        final FileObject lFileObjPreResultsDir = manager.resolveFile(lStrPreTelemacURL);
        copyFilesToWorkDir(lFileObjPreResultsDir, lFileObjWorkingDir);

        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));

        // Run the Calculation
        // final SubMonitor progress = SubMonitor.convert( progressMonitor, m_controlModel.getNCYC() );
        m_log.formatLog(IStatus.INFO, CODE_RUNNING,
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.0") + ": " //$NON-NLS-1$//$NON-NLS-2$
                        + executableName);
        progressMonitor.subTask(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.15")); //$NON-NLS-1$
        process.startProcess(logOS, errorOS, null, progressCancelable);

        // decide based on ERROR.OUT if simulation was successful
        final FileObject errorFile = lFileObjWorkingDir.resolveFile("ERROR.OUT"); //$NON-NLS-1$
        if (errorFile == null || !errorFile.exists() || errorFile.getContent().getSize() == 0) {
            /* Successfully finished simulation */
            progressMonitor.done(StatusUtilities
                    .createOkStatus(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.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 = StatusUtilities.createErrorStatus(errorMessage);
            progressMonitor.done(status);
        }
        // TODO: implement the results eater
    } catch (final ProcessTimeoutException e) {
        throw new SimulationException(
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.0"), e); //$NON-NLS-1$
    } catch (final OperationCanceledException e) {
        throw new SimulationException(
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.RMAKalypsoSimulation.1"), //$NON-NLS-1$
                new CoreException(StatusUtilities.createStatus(IStatus.CANCEL,
                        Messages.getString("org.kalypso.kalypsomodel1d2d.sim.SWANCalculation.2"), e))); //$NON-NLS-1$
    } 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();
    }
}

From source file:org.kalypso.project.database.server.ProjectDatabase.java

/**
 * @see org.kalypso.project.database.sei.IProjectDatabase#createProject(java.lang.String)
 *//*  w  w w  .  j av  a 2s.c o  m*/
@Override
public KalypsoProjectBean createProject(final KalypsoProjectBean bean, final URL incoming) throws IOException {
    synchronized (this) {
        final FileSystemManager manager = VFSUtilities.getManager();
        final FileObject src = manager.resolveFile(incoming.toExternalForm());

        try {
            if (!src.exists())
                throw new FileNotFoundException(
                        String.format("Incoming file not exists: %s", incoming.toExternalForm())); //$NON-NLS-1$

            /* destination of incoming file */
            final String urlDestination = ProjectDatabaseHelper.resolveDestinationUrl(bean);

            final FileObject destination = manager.resolveFile(urlDestination);
            VFSUtilities.copy(src, destination);

            /* store project bean in database */
            bean.setCreationDate(Calendar.getInstance().getTime());

            final Session session = FACTORY.getCurrentSession();
            final Transaction tx = session.beginTransaction();
            session.save(bean);

            tx.commit();

            final IConfigurationElement confElementTrigger = KalypsoProjectDatabaseExtensions
                    .getProjectDatabaseTriggers(bean.getProjectType());
            if (confElementTrigger != null)
                TriggerHelper.handleBean(bean, confElementTrigger);

            return bean;
        } catch (final Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

}

From source file:org.kalypso.project.database.server.ProjectDatabaseHelper.java

protected static Boolean removeBean(final Session session, final KalypsoProjectBean bean) {
    try {/*from ww w . j  av  a2s. co  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.project.database.server.trigger.TriggerHelper.java

public static void handleBean(final KalypsoProjectBean bean, final IConfigurationElement element)
        throws Exception {
    /* resolve trigger extension class */
    final String pluginid = element.getContributor().getName();
    final Bundle bundle = Platform.getBundle(pluginid);
    final Class<?> triggerClass = bundle.loadClass(element.getAttribute("class")); //$NON-NLS-1$
    final Constructor<?> constructor = triggerClass.getConstructor();

    final IProjectDatabaseTrigger trigger = (IProjectDatabaseTrigger) constructor.newInstance();

    final FileSystemManager manager = VFSUtilities.getManager();

    /* resolve global dir */
    final String urlGlobalPath = System.getProperty(IProjectDataBaseServerConstant.SERVER_GLOBAL_DATA_PATH);
    final FileObject folderGlobal = manager.resolveFile(urlGlobalPath);
    if (!folderGlobal.exists()) {
        folderGlobal.createFolder();//from   ww  w .  j  av  a 2 s.co m
    }

    /* global "global" dir */
    final FileObject destinationCommonFolder = folderGlobal.resolveFile(COMMON_FOLDER);
    if (!destinationCommonFolder.exists()) {
        destinationCommonFolder.createFolder();
    }

    /* global project dir */
    final FileObject destinationProjectFolder = folderGlobal.resolveFile(bean.getUnixName());
    if (!destinationProjectFolder.exists()) {
        destinationProjectFolder.createFolder();
    }

    trigger.handleCommonData(bean, destinationCommonFolder);
    trigger.handleProjectData(bean, destinationProjectFolder);
}

From source file:org.kalypso.service.unittests.WebDavRead.java

/**
 * This function tries to copy a file from a webdav.
 *//*from   w  ww  .  j a  va  2  s . c  om*/
@Test
public void testWebDavRead() throws IOException {
    final DefaultFileSystemManager manager = new DefaultFileSystemManager();
    manager.addProvider("webdav", new WebdavFileProvider());
    manager.addProvider("file", new DefaultLocalFileProvider());
    manager.init();

    final FileObject davFile = manager
            .resolveFile("webdav://albert:gnimfe@ibpm.bjoernsen.de/dav/pub/Test/test.txt");
    Assert.assertNotNull(davFile);

    final File file = new File(FileUtilities.TMP_DIR, "davRead.txt");
    final FileObject tmpFile = manager.toFileObject(file);
    Assert.assertNotNull(tmpFile);

    InputStream is = null;
    OutputStream os = null;

    try {
        is = davFile.getContent().getInputStream();
        os = tmpFile.getContent().getOutputStream();

        /* Copying ... */
        IOUtils.copy(is, os);

        is.close();
        os.close();
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    Assert.assertTrue(tmpFile.exists());
}