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

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

Introduction

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

Prototype

@Override
void close() throws FileSystemException;

Source Link

Document

Closes this file, and its content.

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>//w  w w.ja  va2s.  c om
 * 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 closes the file object. It does not throw any exceptions. It calls {@link FileObject#close()} of the
 * given file objects./*  w  w  w.  ja v a2s.  c om*/
 *
 * @param files
 *          The file objects which should be closed. May be null or already closed.
 */
public static void closeQuietly(final FileObject... files) {
    for (final FileObject file : files) {
        try {
            if (Objects.isNotNull(file)) {
                /* Close the file object. */
                file.close();

                /* Close the connection of the file system (e.g. a FTP connection). */
                final FileSystem fileSystem = file.getFileSystem();
                if (fileSystem instanceof AbstractFileSystem)
                    ((AbstractFileSystem) fileSystem).closeCommunicationLink();
            }
        } catch (final FileSystemException ignore) {
            /* If a file system exception is thrown, it was probably already closed. */
        } catch (final Exception ex) {
            /* On other exceptions, do tell the developer on the console. */
            ex.printStackTrace();
        }
    }
}

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

private void prepareSWANResults()
        throws ZipException, IOException, URISyntaxException, FileSystemException, MalformedURLException {
    if (!m_resultDirSWAN.getName().getBaseName().endsWith("zip")) //$NON-NLS-1$
    {//from ww w  .  ja va  2s.  c o  m
        try {
            final FileObject swanResFile = m_resultDirSWAN
                    .getChild(ISimulation1D2DConstants.SIM_SWAN_TRIANGLE_FILE + "." //$NON-NLS-1$
                            + ISimulation1D2DConstants.SIM_SWAN_MAT_RESULT_EXT);
            final FileObject swanResShiftFile = m_resultDirSWAN
                    .getChild(ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_FILE);
            final FileObject swanResOutTabFile = m_resultDirSWAN
                    .getChild(ISimulation1D2DConstants.SIM_SWAN_TRIANGLE_FILE + "_out.tab"); //$NON-NLS-1$
            processSWANTabFile(swanResOutTabFile, swanResShiftFile);
            final File zipOutput = new File(m_outputDir,
                    ISimulation1D2DConstants.SIM_SWAN_TRIANGLE_FILE + ".zip"); //$NON-NLS-1$
            final List<File> lListFilesToZip = new ArrayList<>();
            lListFilesToZip.add(new File(swanResFile.getURL().toURI()));
            lListFilesToZip.add(new File(swanResShiftFile.getURL().toURI()));
            lListFilesToZip.add(new File(swanResOutTabFile.getURL().toURI()));
            if (m_controlModel.getINITialValuesSWAN() == 3) {
                final FileObject swanResHotFile = m_resultDirSWAN
                        .getChild(ISimulation1D2DConstants.SIM_SWAN_HOT_FILE);
                lListFilesToZip.add(new File(swanResHotFile.getURL().toURI()));
            }
            ZipUtilities.zip(zipOutput, lListFilesToZip.toArray(new File[lListFilesToZip.size()]),
                    new File(m_resultDirSWAN.getURL().toURI()));
            swanResFile.close();
            swanResShiftFile.close();
            swanResOutTabFile.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    } else {
        // swan mat file should be unpacked for using in within JMatIO-Reader, so we put the uncompressed version in
        // to the working directory.
        ZipUtilities.unzip(new File(m_resultDirSWAN.getURL().toURI()), new File(m_outputDir.toURI()));
        m_resultDirSWAN = m_vfsManager.resolveFile(m_outputDir.toURI().toURL().toExternalForm());
    }
}

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;// w w w  .ja va 2s. co  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.SwanResultProcessor.java

private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) {
    final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile);
    if (lShiftPosition == null)
        return;//from w  ww . jav a  2s  .  c  o m

    try {
        // FIXME: why?! should never happen...!
        if (swanResOutTabFile.isContentOpen())
            swanResOutTabFile.close();

        final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent()
                .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$
        swanResOutTabFile.moveTo(swanResOutTabFileBackUp);

        final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream();
        final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US);

        final BufferedReader lInDataStream = new BufferedReader(
                new InputStreamReader(swanResOutTabFileBackUp.getContent().getInputStream()));

        while (lInDataStream.ready()) {
            final String lStrTmpLine = lInDataStream.readLine().trim();
            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$
        }

        // FIXME: not closed in a save way!
        lFormatter.close();
        lInDataStream.close();
        lOutStream.close();
    } catch (final Exception e) {
        // FIXME: this is no way to handle an error !
    }
}

From source file:org.kalypso.project.database.client.core.base.worker.CreateRemoteProjectWorker.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *//*w  w w.  j  a v a  2  s .  c o  m*/
@Override
public IStatus execute(final IProgressMonitor monitor) throws CoreException {

    final IProject project = m_handler.getProject();
    final String zipName = String.format("%s.zip", project.getName()); //$NON-NLS-1$

    final File urlTempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$
    final File src = new File(urlTempDir, zipName); //$NON-NLS-1$

    try {
        final ProjectExportWorker worker = new ProjectExportWorker(project, src, false);
        final IStatus status = worker.execute(monitor);

        if (!status.isOK())
            throw new CoreException(
                    new Status(IStatus.ERROR, KalypsoProjectDatabaseClient.PLUGIN_ID, Messages.getString(
                            "org.kalypso.project.database.client.core.project.create.CreateRemoteProjectWorker.2"))); //$NON-NLS-1$

        final FileSystemManager manager = VFSUtilities.getManager();
        final FileObject source = manager.resolveFile(src.getAbsolutePath());

        final String urlDestination = ProjectModelUrlResolver
                .getUrlAsFtp(new ProjectModelUrlResolver.IResolverInterface() {
                    @Override
                    public String getPath() {
                        return System.getProperty(IProjectDataBaseClientConstant.SERVER_INCOMING_PATH);
                    }

                }, zipName); //$NON-NLS-1$

        // change caching strategy of destination file to avoid deadlocks!
        final FileObject destination = new OnCallRefreshFileObject(manager.resolveFile(urlDestination));

        VFSUtilities.copy(source, destination);

        final IProjectDatabase service = KalypsoProjectDatabaseClient.getService();

        // always commit - download of projects assert nature!
        final KalypsoProjectBean bean = new KalypsoProjectBean();
        bean.setName(project.getName());
        bean.setDescription(project.getName());
        bean.setUnixName(project.getName()); // TODO generate unixName
        bean.setProjectVersion(0);
        bean.setProjectType(m_commitType);
        bean.setModuleIdentifier(m_commitType);

        service.createProject(bean, new URL(urlDestination));

        final WorkspaceJob updateDescription = new WorkspaceJob("") //$NON-NLS-1$
        {
            int updateCount = 0;

            @Override
            public IStatus runInWorkspace(final IProgressMonitor m) throws CoreException {
                try {
                    // FIXME *grummel* why .project file is always locked and project.setDescription() fails?
                    final IProjectDescription description = project.getDescription();
                    description.setNatureIds(
                            ArrayUtils.add(description.getNatureIds(), RemoteProjectNature.NATURE_ID));
                    project.setDescription(description, m);

                    final RemoteProjectNature remote = (RemoteProjectNature) project
                            .getNature(RemoteProjectNature.NATURE_ID);
                    final IRemoteProjectPreferences preferences = remote.getRemotePreferences(project, null);
                    preferences.setVersion(0);
                    preferences.setIsOnServer(true);
                    preferences.setModified(false);
                } catch (final Exception e) {
                    updateCount += 1;
                    if (updateCount < 5)
                        this.schedule(250);
                    else
                        throw new CoreException(new Status(IStatus.ERROR,
                                KalypsoProjectDatabaseClient.PLUGIN_ID,
                                Messages.getString(
                                        "org.kalypso.project.database.client.core.project.create.CreateRemoteProjectWorker.0"), //$NON-NLS-1$
                                e));

                    return Status.CANCEL_STATUS;
                }

                return Status.OK_STATUS;
            }
        };

        updateDescription.schedule(250);

        // bad @hack if the client has committed a large file, it can happen, that the client looses the http connection.
        // file.close() reestablish this http-connection
        destination.close();
    } catch (final Exception e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e));
    } finally {
        src.delete();
    }

    return Status.OK_STATUS;
}

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)
 *//*from ww  w .  java2  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.service.wps.client.NonBlockingWPSRequest.java

/**
 * Starts the simulation.//from   w  ww  .  j  a  v  a 2  s . c o m
 *
 * @param monitor
 *          The progress monitor.
 */
public IStatus run(IProgressMonitor monitor) {
    // TODO: clear old results: No not here! We have to introduce additional operation to the service
    // So the client can tell the server to release any resources.

    /* Monitor. */
    monitor = SubMonitor.convert(monitor,
            Messages.getString("org.kalypso.service.wps.client.NonBlockingWPSRequest.4"), 200); //$NON-NLS-1$
    KalypsoServiceWPSDebug.DEBUG.printf("Checking for service URL ...\n"); //$NON-NLS-1$

    /* Check, if we have a service endpoint. */
    if (m_serviceEndpoint == null) {
        KalypsoServiceWPSDebug.DEBUG.printf("No URL to the service is given.\n"); //$NON-NLS-1$
        return StatusUtilities.statusFromThrowable(
                new WPSException(Messages.getString("org.kalypso.service.wps.client.NonBlockingWPSRequest.3"))); //$NON-NLS-1$
    }

    /* Send the request. */
    ExecuteResponseType executeResponse;
    final CodeType simulationIdentifier = WPS040ObjectFactoryUtilities.buildCodeType("", m_identifier); //$NON-NLS-1$

    try {
        // 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,
                        m_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"); //$NON-NLS-1$
                final String statusLocation = WPSUtilities
                        .convertInternalToClient(resultFile.getURL().toExternalForm());
                final StatusType status = WPS040ObjectFactoryUtilities.buildStatusType("Process accepted.", //$NON-NLS-1$
                        true);
                executeResponse = WPS040ObjectFactoryUtilities.buildExecuteResponseType(simulationIdentifier,
                        status, m_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 {
            executeResponse = WPSUtilities.callExecute(m_serviceEndpoint, m_identifier, m_dataInputs,
                    m_outputDefinitions);
        }
    } catch (final CoreException e) {
        return e.getStatus();
    }

    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. */
    monitor.worked(100);
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }

    /* Retrieve the path to the status file of the process. */
    m_statusLocation = executeResponse.getStatusLocation();

    /* Finish. */
    monitor.worked(100);

    return Status.OK_STATUS;
}

From source file:org.kalypso.service.wps.client.NonBlockingWPSRequest.java

@SuppressWarnings("unchecked")
public ExecuteResponseType getExecuteResponse(final FileSystemManager manager)
        throws Exception, InterruptedException {
    final FileObject statusFile = VFSUtilities.checkProxyFor(m_statusLocation, manager);
    if (statusFile.exists()) {
        /* Some variables for handling the errors. */
        boolean success = false;
        int cnt = 0;

        /* Try to read the status at least 3 times, before exiting. */
        JAXBElement<ExecuteResponseType> executeState = null;
        while (success == false) {
            final FileContent content = statusFile.getContent();
            InputStream inputStream = null;
            try {
                inputStream = content.getInputStream();
                final String xml = IOUtils.toString(inputStream);
                if (xml != null && !"".equals(xml)) //$NON-NLS-1$
                {/*from  w  w w. j a  v a 2  s.com*/
                    final Object object = MarshallUtilities.unmarshall(xml);
                    executeState = (JAXBElement<ExecuteResponseType>) object;
                    success = true;
                }
            } catch (final Exception e) {
                /* An error has occured while copying the file. */
                KalypsoServiceWPSDebug.DEBUG
                        .printf("An error has occured with the message: " + e.getLocalizedMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$

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

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

                /* Wait for some milliseconds. */
                Thread.sleep(1000);
            } finally {
                IOUtils.closeQuietly(inputStream);
                statusFile.close();
            }
        }
        return executeState.getValue();
    } else
        return null;
}

From source file:org.kalypso.service.wps.client.WPSRequest.java

public IStatus run(final Map<String, Object> inputs, final List<String> outputs,
        final IProgressMonitor progressMonitor) {
    final SubMonitor monitor = SubMonitor.convert(progressMonitor, 100);

    IStatus status = wpsRequest.init(inputs, outputs, monitor.newChild(1));

    // on error return immediately
    if (!status.isOK()) {
        return status;
    } else if (monitor.isCanceled() && doCanceled().matches(IStatus.CANCEL)) {
        return doCanceled();
    }//from  w  w w . ja  va  2s  .com

    // start request, returns immediately
    status = wpsRequest.run(monitor.newChild(1));

    // on error return immediately
    if (!status.isOK()) {
        return status;
    }

    // after success, the status location will be set
    final String statusLocation = wpsRequest.getStatusLocation();
    if (statusLocation.length() == 0) {
        return StatusUtilities
                .createErrorStatus(Messages.getString("org.kalypso.service.wps.client.WPSRequest.0")); //$NON-NLS-1$
    }

    final FileObject statusFile = null;
    try {
        KalypsoServiceWPSDebug.DEBUG.printf("Checking state file of the server ...\n"); //$NON-NLS-1$

        /* Poll to update the status. */
        final boolean run = true;
        long executed = 0;

        /* Loop, until an result is available, a timeout is reached or the user has cancelled the job. */
        final ProcessDescriptionType processDescription = getProcessDescription(monitor.newChild(1));
        final String title = processDescription.getTitle();
        final SubMonitor processMonitor = monitor.newChild(97);
        processMonitor.beginTask(Messages.getString("org.kalypso.service.wps.client.WPSRequest.1") + title, //$NON-NLS-1$
                MONITOR_SERVER_VALUE);

        m_manager = VFSUtilities.getNewManager();
        while (run) {
            try {
                Thread.sleep(500);
                executed += 500;
            } catch (final InterruptedException e) {
                return StatusUtilities.statusFromThrowable(e);
            }

            final ExecuteResponseType exState = wpsRequest.getExecuteResponse(m_manager);
            if (exState == null)
                return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                        Messages.getString("org.kalypso.service.wps.client.WPSRequest.2")); //$NON-NLS-1$

            final StatusType state = exState.getStatus();
            if (state.getProcessAccepted() != null)
                doProcessAccepted(exState);
            else if (state.getProcessFailed() != null)
                return doProcessFailed(exState);
            else if (state.getProcessStarted() != null)
                doProcessStarted(processMonitor, exState);
            else if (state.getProcessSucceeded() != null)
                return doProcessSucceeded(exState);
            else
                return doUnknownState(exState);

            /* If the user aborted the job. */
            // TODO
            if (monitor.isCanceled()) {
                final IStatus doCanceled = doCanceled();
                if (doCanceled.matches(IStatus.CANCEL | IStatus.ERROR | IStatus.WARNING))
                    return doCanceled;

                // Other cases: just continue, cancel not possible, hut the user should not know it...
            }

            /* If the timeout is reached. */
            if (m_timeout > 0 && executed > m_timeout)
                return doTimeout();
        }
    } catch (final Exception e) {
        return StatusUtilities.statusFromThrowable(e);
    } finally {
        if (statusFile != null) {
            try {
                statusFile.close();
            } catch (final FileSystemException e) {
                // gobble
            }
        }
        if (m_manager != null)
            m_manager.close();
    }

    // never reach this line
}