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

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

Introduction

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

Prototype

URL getURL() throws FileSystemException;

Source Link

Document

Returns a URL representing this file.

Usage

From source file:org.kalypso.service.wps.client.simulation.SimulationDelegate.java

/**
 * This function creates the inputs for the server. It will also copy the data to the right place, if needed and
 * ajdust the references according to it.
 *
 * @param description/*from  ww  w . j  av a  2 s .com*/
 *          The process description type.
 * @param monitor
 *          A progress monitor.
 * @return The inputs.
 */
public Map<String, Object> createInputs(final ProcessDescriptionType description, IProgressMonitor monitor)
        throws CoreException {
    /* Monitor. */
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    try {
        /* Monitor. */
        monitor.beginTask(Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.7"), //$NON-NLS-1$
                500);
        KalypsoServiceWPSDebug.DEBUG.printf("Collecting data ...\n"); //$NON-NLS-1$

        /* Need the filesystem manager. */
        final FileSystemManager fsManager = m_fsManager;

        /* Get the list with the input. */
        final Map<String, Object> wpsInputs = new HashMap<>();

        /* Get the input list. */
        final DataInputs dataInputs = description.getDataInputs();
        final List<InputDescriptionType> inputDescriptions = dataInputs.getInput();

        /* Create a resource visitor. */
        final CollectFilesVisitor visitor = new CollectFilesVisitor();

        /* Get the inputs. */
        final List<Input> inputList = m_data.getInput();

        /* Iterate over all inputs and build the data inputs for the execute request. */
        for (final InputDescriptionType inputDescription : inputDescriptions) {
            final CodeType identifier = inputDescription.getIdentifier();

            /* Check if the input is in our model data, too. */
            final Input input = SimulationUtilities.findInput(identifier.getValue(), inputList);
            if (input == null) {
                /* Check, if it is an optional one. */
                if (inputDescription.getMinimumOccurs().intValue() == 1) {
                    /* Ooops, it is a mandatory one, but it is missing in our model data. */
                    final IStatus status = StatusUtilities.createStatus(IStatus.ERROR,
                            Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.8", //$NON-NLS-1$
                                    identifier.getValue()),
                            null);
                    throw new CoreException(status);
                }

                continue;
            }

            /* Input is here. */
            final String inputPath = input.getPath();

            /* Supported complex data type. */
            final SupportedComplexDataType complexData = inputDescription.getComplexData();
            if (complexData != null) {
                /* Get the protocol if it is one. */
                final String protocol = SimulationUtilities.getProtocol(inputPath);

                /* If the protocol is null, it is a local file resource, otherwise it is a remote resource, */
                /* which is not allowed to be copied or it is a complex value type (file-protocol). */
                if ("file".equals(protocol)) //$NON-NLS-1$
                {
                    // TODO: Why do we need this?
                    final URL localFileUrl = new URL(inputPath);
                    final byte[] bytes = UrlUtilities.toByteArray(localFileUrl);
                    final String hexString = DatatypeConverter.printHexBinary(bytes);
                    wpsInputs.put(identifier.getValue(), hexString);
                    continue;
                } else if (protocol == null || protocol.equals("project") || protocol.equals("platform")) //$NON-NLS-1$ //$NON-NLS-2$
                {
                    /* If protocol is null or protocol is "project", it is a local file resource. */
                    /*
                     * If protocol is "platform", it is a resource from another project, but the same platform (i.e. same
                     * eclipse workspace).
                     */
                    if (m_calcCaseFolder == null) {
                        throw new WPSException(Messages
                                .getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.9")); //$NON-NLS-1$
                    }

                    final IProject project = m_calcCaseFolder.getProject();
                    final IResource inputResource;
                    if (protocol != null && protocol.equals(PlatformURLHandler.PROTOCOL)) {
                        final IContainer baseresource = project.getWorkspace().getRoot();
                        final String path = ResourceUtilities.findPathFromURL(new URL(inputPath))
                                .toPortableString();
                        inputResource = baseresource.findMember(path);
                    } else {
                        final IContainer baseresource = input.isRelativeToCalcCase() ? m_calcCaseFolder
                                : project;
                        inputResource = baseresource.findMember(inputPath);
                    }

                    if (inputResource == null) {
                        if (inputDescription.getMinimumOccurs().intValue() == 0) {
                            continue;
                        }

                        throw new CoreException(StatusUtilities.createErrorStatus(Messages.getString(
                                "org.kalypso.service.wps.client.simulation.SimulationDelegate.10", inputPath))); //$NON-NLS-1$
                    }

                    /* Collect all files. */
                    inputResource.accept(visitor);

                    /* Initialize the temporary directory. */
                    initServerTmpDirectory();

                    /* Build the URL for this input. */
                    /* Resource will be copied to server later (for example see SimulationDelegate.copyInputFiles). */
                    final String relativePathTo = inputResource.getFullPath().makeRelative().toString();

                    /**
                     * just put the existing resource to the inputs and DO NOT copy it in case of local calculation!! also
                     * prevent the creation of redundant data in base project folder
                     */
                    FileObject destination = fsManager.toFileObject(inputResource.getLocation().toFile());
                    if (!SERVER_INPUT_LOCAL.equals(m_input)) {
                        destination = fsManager.resolveFile(m_serverTmpDirectory, relativePathTo);
                    }

                    final String serverUrl = WPSUtilities
                            .convertInternalToServer(destination.getURL().toExternalForm(), m_input);
                    wpsInputs.put(identifier.getValue(), new URI(URIUtil.encodePath(serverUrl)));
                } else
                // maybe check the protocols?
                {
                    // Remote resource, will be passed to the service as reference
                    final URL clientUrl = new URL(inputPath);
                    final String serverUrl = WPSUtilities.convertInternalToServer(clientUrl.toExternalForm(),
                            m_input);
                    wpsInputs.put(identifier.getValue(), new URI(serverUrl));
                }
            }

            /* Literal input type */
            final LiteralInputType literalInput = inputDescription.getLiteralData();
            if (literalInput != null) {
                /* Add the input. */
                // TODO: normally we should marshall the string to the requested type
                // (the WPS-Client will unmarshall it again).
                // For the moment this works, as the WPS-Client just forwards any strings.
                wpsInputs.put(identifier.getValue(), inputPath);

                continue;
            }

            /* Supported CRSs type. */
            final SupportedCRSsType supportedCRSsType = inputDescription.getBoundingBoxData();
            if (supportedCRSsType != null) {
                // TODO Add supported CRSs type (bounding boxes).
                continue;
            }
        }

        /* Monitor. */
        monitor.worked(200);
        monitor.setTaskName(
                Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.11")); //$NON-NLS-1$
        KalypsoServiceWPSDebug.DEBUG.printf("Copy to the server ...\n"); //$NON-NLS-1$

        /* Copy all collected files. */
        final IFile[] files = visitor.getFiles();
        if (files.length > 0)
            copyInputFiles(files);

        /* Monitor. */
        monitor.worked(300);

        return wpsInputs;
    } catch (final CoreException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new CoreException(StatusUtilities.createStatus(IStatus.ERROR,
                Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.12"), ex)); //$NON-NLS-1$
    } finally {
        /* Monitor. */
        monitor.done();
    }
}

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.j a v a 2s .  com
@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//w  ww  . j av  a  2 s . c o  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.simulation.WPSSimulationResultEater.java

/**
 * This function will create ComplexValueReference with the given file and copies it directly to the result directory.
 *
 * @param sourceFile//  w  w  w.  j  a v  a  2s . c  o m
 *          The file to reference in the ComplexValueReference.
 * @return A ComplexValueReference with the given file.
 */
private synchronized ComplexValueReference addComplexValueReference(final File sourceFile)
        throws SimulationException {
    checkResultDir();

    try {
        /* Getting the relative path to the source file. */
        final String relativePathToSource = FileUtilities.getRelativePathTo(m_tmpDir, sourceFile);
        if (relativePathToSource == null)
            throw new SimulationException(Messages.getString(
                    "org.kalypso.service.wps.utils.simulation.WPSSimulationResultEater.12", sourceFile)); //$NON-NLS-1$
        final String uri = m_resultDir.getURL().toExternalForm() + "/" + relativePathToSource; //$NON-NLS-1$

        final FileObject destination = m_vfsManager.resolveFile(uri);

        /* assure old behavior - for none existing source files! */
        if (sourceFile.exists()) {
            final FileObject source = m_vfsManager.toFileObject(sourceFile);
            if (!source.equals(destination))
                VFSUtilities.copy(source, destination);
        }

        // keep track of file references
        m_references.put(sourceFile, destination);

        /* Build complex value reference. */
        return WPS040ObjectFactoryUtilities.buildComplexValueReference(
                WPSUtilities.convertInternalToClient(destination.getURL().toExternalForm()), null, null, null);
    } catch (final IOException e) {
        throw new SimulationException(Messages.getString(
                "org.kalypso.service.wps.utils.simulation.WPSSimulationResultEater.13", sourceFile), e); //$NON-NLS-1$
    }
}

From source file:org.luwrain.app.commander.Actions.java

PanelArea.ClickHandler.Result onClick(CommanderArea area, Object obj, boolean dir) {
    NullCheck.notNull(area, "area");
    NullCheck.notNull(obj, "obj");
    if (dir)/* w w w . ja  va2  s  .  c  o  m*/
        return PanelArea.ClickHandler.Result.OPEN_DIR;
    final PanelArea panelArea = (PanelArea) area;
    if (!panelArea.isLocalDir())//FIXME:
        return PanelArea.ClickHandler.Result.REJECTED;
    try {
        //Maybe it's better to make a separate method translating FileObject to java.io.File
        final FileObject fileObject = (FileObject) obj;
        final File file = org.luwrain.util.Urls.toFile(fileObject.getURL());
        luwrain.openFile(file.getAbsolutePath());
        return CommanderArea.ClickHandler.Result.OK;
    } catch (Exception e) {
        luwrain.crash(e);
        return PanelArea.ClickHandler.Result.REJECTED;
    }
}

From source file:org.metaborg.intellij.idea.languages.DefaultIdeaLanguageManager.java

/**
 * {@inheritDoc}//  w  ww  . j a v a 2  s  .c  o  m
 */
@Override
public Iterable<ILanguageDiscoveryRequest> requestFromArtifact(final FileObject artifact) throws IOException {

    final String zipUri;
    try {
        zipUri = "zip://" + artifact.getURL().getPath();
    } catch (final FileSystemException e) {
        throw LoggerUtils2.exception(this.logger, UnhandledException.class,
                "Unhandled exception while requesting languages from artifact: {}", e, artifact);
    }

    final FileObject file = this.resourceService.resolve(zipUri);
    return requestFromFolder(file);
}

From source file:org.metaborg.intellij.languages.LanguageUtils2.java

/**
 * Given an artifact file, returns the URI of the artifact file's root.
 *
 * @param artifact The artifact file.//from   www .ja  va  2  s  .c  o  m
 * @return The URI of the artifact file's root.
 */
public static String getArtifactUri(final FileObject artifact) {
    final String zipUri;
    try {
        zipUri = "zip:" + artifact.getURL() + "!/";
    } catch (final FileSystemException e) {
        throw new UnhandledException(e);
    }
    return zipUri;
}

From source file:org.mycore.common.content.MCRVFSContent.java

public MCRVFSContent(FileObject fo) throws IOException {
    this.fo = fo;
    setName(fo.getName().getBaseName());
    setSystemId(fo.getURL().toString());
}

From source file:org.obiba.opal.core.service.ProjectsServiceImpl.java

@NotNull
@Override//from   w  w  w . j  a va  2  s. c om
public String getProjectDirectoryPath(@NotNull Project project) {
    try {
        FileObject fo = getProjectDirectory(project);
        return fo.getURL().getPath().substring(2);
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.obiba.opal.web.FilesResource.java

private Response doUploadFile(String folderPath, FileObject folder, FileItem uploadedFile, UriInfo uriInfo)
        throws FileSystemException {
    String fileName = uploadedFile.getName();
    FileObject file = folder.resolveFile(fileName);
    boolean overwrite = file.exists();

    writeUploadedFileToFileSystem(uploadedFile, file);

    log.info("The following file was uploaded to Opal file system : {}", file.getURL());

    if (overwrite) {
        return Response.ok().build();
    }/*from  w  w w . j av  a  2  s  . c o  m*/
    URI fileUri = uriInfo.getBaseUriBuilder().path(FilesResource.class).path(folderPath).path(fileName).build();
    return Response.created(fileUri)//
            .header(AuthorizationInterceptor.ALT_PERMISSIONS, new OpalPermissions(fileUri, AclAction.FILES_ALL))//
            .build();
}