Example usage for org.apache.commons.vfs2 FileContent getInputStream

List of usage examples for org.apache.commons.vfs2 FileContent getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileContent getInputStream.

Prototype

InputStream getInputStream() throws FileSystemException;

Source Link

Document

Returns an input stream for reading the file's content.

Usage

From source file:org.celeria.minecraft.backup.ArchiveWorldTaskTest.java

@Before
public void setUpFileContent(final FileContent fileContent, final InputStream inputStream) throws Exception {
    when(file.getContent()).thenReturn(fileContent);
    when(fileContent.getInputStream()).thenReturn(inputStream);
    when(inputStream.read(Matchers.<byte[]>any())).thenReturn(-1);
}

From source file:org.esupportail.portlet.filemanager.portlet.PortletControllerDownloadEvent.java

@EventMapping(EsupFileManagerConstants.DOWNLOAD_REQUEST_QNAME_STRING)
public void downloadEvent(EventRequest request, EventResponse response) {

    log.info("PortletControllerDownloadEvent.downloadEvent from EsupFilemanager is called");

    // INIT     /*w  w w.ja va  2s.c  o m*/
    portletController.init(request);

    PortletPreferences prefs = request.getPreferences();
    String[] prefsDefaultPathes = prefs.getValues(PortletController.PREF_DEFAULT_PATH, null);

    boolean showHiddenFiles = "true".equals(prefs.getValue(PortletController.PREF_SHOW_HIDDEN_FILES, "false"));
    userParameters.setShowHiddenFiles(showHiddenFiles);

    UploadActionType uploadOption = UploadActionType.valueOf(prefs
            .getValue(PortletController.PREF_UPLOAD_ACTION_EXIST_FILE, UploadActionType.OVERRIDE.toString()));
    userParameters.setUploadOption(uploadOption);

    serverAccess.initializeServices(userParameters);

    // DefaultPath
    String defaultPath = serverAccess.getFirstAvailablePath(userParameters, prefsDefaultPathes);

    // Event   
    final Event event = request.getEvent();
    final DownloadRequest downloadRequest = (DownloadRequest) event.getValue();

    String fileUrl = downloadRequest.getUrl();

    // FS     
    boolean success = false;
    try {
        FileSystemManager fsManager = VFS.getManager();

        FileSystemOptions fsOptions = new FileSystemOptions();

        FileObject file = fsManager.resolveFile(fileUrl, fsOptions);
        FileContent fc = file.getContent();
        String baseName = fc.getFile().getName().getBaseName();
        InputStream inputStream = fc.getInputStream();

        success = serverAccess.putFile(defaultPath, baseName, inputStream, userParameters,
                userParameters.getUploadOption());
    } catch (FileSystemException e) {
        log.error("putFile failed for this downloadEvent", e);
    }

    //Build the result object
    final DownloadResponse downloadResponse = new DownloadResponse();
    if (success)
        downloadResponse.setSummary("Upload OK");
    else
        downloadResponse.setSummary("Upload Failed");

    //Add the result to the results and send the event
    response.setEvent(EsupFileManagerConstants.DOWNLOAD_RESPONSE_QNAME, downloadResponse);

}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public DownloadFile getFile(String dir, SharedUserPortletParameters userParameters) {
    try {/*from   ww  w .j  a  va  2s.c o m*/
        FileObject file = cd(dir, userParameters);
        FileContent fc = file.getContent();
        int size = new Long(fc.getSize()).intValue();
        String baseName = fc.getFile().getName().getBaseName();
        // fc.getContentInfo().getContentType() use URLConnection.getFileNameMap, 
        // we prefer here to use our getMimeType : for Excel files and co 
        // String contentType = fc.getContentInfo().getContentType();
        String contentType = JsTreeFile.getMimeType(baseName.toLowerCase());
        InputStream inputStream = fc.getInputStream();
        DownloadFile dlFile = new DownloadFile(contentType, size, baseName, inputStream);
        return dlFile;
    } catch (FileSystemException e) {
        log.warn("can't download file : " + e.getMessage(), e);
    }
    return null;
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException {
    String resourceBundleName = module.getResourceBundleName();
    if (resourceBundleName == null) {
        resourceBundleName = "resources." + module.getId();
    }/*from   w  ww .j  a  v a  2s. co m*/
    String rbBasePath = "/src/main/resources/resources/"
            + StringUtils.substringAfterLast(resourceBundleName, ".");
    Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties();
    if (i18nProperties != null) {
        List<File> newFiles = new ArrayList<File>();
        for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) {
            String lang = entry.getKey();
            Map<String, String[]> properties = entry.getValue();

            String[] values = properties.get(Constants.JCR_TITLE);
            String title = ArrayUtils.isEmpty(values) ? null : values[0];

            values = properties.get(Constants.JCR_DESCRIPTION);
            String description = ArrayUtils.isEmpty(values) ? null : values[0];

            String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION;
            InputStream is = null;
            InputStreamReader isr = null;
            OutputStream os = null;
            OutputStreamWriter osw = null;
            try {
                FileObject file = getFile(rbPath);
                FileContent content = file.getContent();
                Properties p = new SortedProperties();
                if (file.exists()) {
                    is = content.getInputStream();
                    isr = new InputStreamReader(is, Charsets.ISO_8859_1);
                    p.load(isr);
                    isr.close();
                    is.close();
                } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) {
                    continue;
                } else {
                    newFiles.add(new File(file.getName().getPath()));
                }
                if (!StringUtils.isEmpty(title)) {
                    p.setProperty(key, title);
                }
                if (!StringUtils.isEmpty(description)) {
                    p.setProperty(key + "_description", description);
                }
                os = content.getOutputStream();
                osw = new OutputStreamWriter(os, Charsets.ISO_8859_1);
                p.store(osw, rbPath);
                ResourceBundle.clearCache();
            } catch (FileSystemException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } catch (IOException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(osw);
            }
        }
        SourceControlManagement sourceControl = module.getSourceControl();
        if (sourceControl != null) {
            try {
                sourceControl.add(newFiles);
            } catch (IOException e) {
                logger.error("Failed to add files to source control", e);
                throw new RepositoryException("Failed to add new files to source control: " + newFiles, e);
            }
        }
    }
}

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   ww w  . j  a  v  a2 s.co m*/
                    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.server.operations.ExecuteOperation.java

/**
 * @see org.kalypso.service.wps.operations.IOperation#executeOperation(org.kalypso.service.ogc.RequestBean)
 *//*from  ww w .ja v  a  2s  .  co  m*/
@Override
public StringBuffer executeOperation(final RequestBean request) throws OWSException {
    final StringBuffer response = new StringBuffer();

    /* Start the operation. */
    KalypsoServiceWPSDebug.DEBUG.printf("Operation \"Execute\" started.\n"); //$NON-NLS-1$

    /* Gets the identifier, but also unmarshalls the request, so it has to be done! */
    final String requestXml = request.getBody();
    Object executeRequest = null;
    try {
        executeRequest = MarshallUtilities.unmarshall(requestXml);
    } catch (final JAXBException e) {
        throw new OWSException(OWSException.ExceptionCode.NO_APPLICABLE_CODE, e, ""); //$NON-NLS-1$
    }

    /* Execute the simulation via a manager, so that more than one simulation can be run at the same time. */
    final WPSSimulationManager manager = WPSSimulationManager.getInstance();

    // TODO version 1.0
    final ExecuteMediator executeMediator = new ExecuteMediator(executeRequest);
    final WPSSimulationInfo info = manager.startSimulation(executeMediator);

    /* Prepare the execute response. */
    FileObject resultFile = null;
    InputStream inputStream = null;
    try {
        final FileObject resultDir = manager.getResultDir(info.getId());
        resultFile = resultDir.resolveFile("executeResponse.xml"); //$NON-NLS-1$
        int time = 0;
        final int timeout = 10000;
        final int delay = 500;
        while (!resultFile.exists() && time < timeout) {
            Thread.sleep(delay);
            time += delay;
        }
        final FileContent content = resultFile.getContent();
        inputStream = content.getInputStream();
        final String responseXml = IOUtils.toString(inputStream);
        response.append(responseXml);
    } catch (final Exception e) {
        throw new OWSException(OWSException.ExceptionCode.NO_APPLICABLE_CODE, e, ""); //$NON-NLS-1$
    } finally {
        /* Close the file object. */
        VFSUtilities.closeQuietly(resultFile);

        /* Close the input stream. */
        IOUtils.closeQuietly(inputStream);
    }

    return response;
}

From source file:org.kalypso.service.wps.utils.WPSUtilities.java

public static ExecuteResponseType readExecutionResponse(final FileSystemManager manager,
        final String statusLocation) throws CoreException {
    try {//from   w  w  w. ja v a2  s  . c  om
        final FileObject statusFile = VFSUtilities.checkProxyFor(statusLocation, manager);
        if (!statusFile.exists())
            return null;

        /* Try to read the status at least 3 times, before exiting. */
        Exception lastError = new Exception();

        // TODO: timeout defined as approximately 3 seconds is in some how not always usable, set to 100.
        // Better to set it from predefined properties.

        // Hi Ilya, I think you missunderstood the number here.
        // It does not represent a timeout, but the number of times to try.
        // The Thread.sleep( 1000 ) in case of an error is only the time to wait,
        // before it is retried to read the execution response.
        // I changed the value back to 3. Holger
        for (int i = 0; i < 3; i++) {
            InputStream inputStream = null;
            try {
                final FileContent content = statusFile.getContent();
                inputStream = content.getInputStream();
                final String xml = IOUtils.toString(inputStream);
                if (xml == null || "".equals(xml)) //$NON-NLS-1$
                    throw new IOException(Messages.getString("org.kalypso.service.wps.utils.WPSUtilities.4") //$NON-NLS-1$
                            + statusFile.toString());

                final Object object = MarshallUtilities.unmarshall(xml);
                final JAXBElement<?> executeState = (JAXBElement<?>) object;
                return (ExecuteResponseType) executeState.getValue();
            } catch (final Exception e) {
                lastError = e;

                KalypsoServiceWPSDebug.DEBUG
                        .printf("An error has occured with the message: " + e.getLocalizedMessage() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
                KalypsoServiceWPSDebug.DEBUG.printf("Retry: " + String.valueOf(i) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$

                Thread.sleep(1000);
            } finally {
                IOUtils.closeQuietly(inputStream);
                statusFile.close();
            }
        }

        KalypsoServiceWPSDebug.DEBUG.printf("The second retry has failed, rethrowing the error ..."); //$NON-NLS-1$ //$NON-NLS-2$
        final IStatus status = StatusUtilities.createStatus(IStatus.ERROR,
                Messages.getString("org.kalypso.service.wps.utils.WPSUtilities.5") //$NON-NLS-1$
                        + lastError.getLocalizedMessage(),
                lastError);
        throw new CoreException(status);
    } catch (final Exception e) {
        e.printStackTrace();

        final IStatus status = StatusUtilities.createStatus(IStatus.ERROR,
                Messages.getString("org.kalypso.service.wps.utils.WPSUtilities.6") + e.getLocalizedMessage(), //$NON-NLS-1$
                e);
        throw new CoreException(status);
    }
}

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

@Override
public InputStream getInputStream() throws IOException {
    final FileContent content = fo.getContent();
    LOGGER.debug(() -> getDebugMessage("{}: returning InputStream of {}"));
    return new FilterInputStream(content.getInputStream()) {
        @Override/*from ww w. ja  va 2  s  . c  o m*/
        public void close() throws IOException {
            LOGGER.debug(() -> getDebugMessage("{}: closing InputStream of {}"));
            super.close();
            content.close();
        }
    };
}

From source file:org.pentaho.di.trans.steps.propertyinput.PropertyInputMetaTest.java

@Test
public void testOpenNextFile() throws Exception {

    PropertyInputMeta propertyInputMeta = Mockito.mock(PropertyInputMeta.class);
    PropertyInputData propertyInputData = new PropertyInputData();
    FileInputList fileInputList = new FileInputList();
    FileObject fileObject = Mockito.mock(FileObject.class);
    FileName fileName = Mockito.mock(FileName.class);
    Mockito.when(fileName.getRootURI()).thenReturn("testFolder");
    Mockito.when(fileName.getURI()).thenReturn("testFileName.ini");

    String header = "test ini data with umlauts";
    String key = "key";
    String testValue = "value-with-";
    String testData = "[" + header + "]\r\n" + key + "=" + testValue;
    String charsetEncode = "Windows-1252";

    InputStream inputStream = new ByteArrayInputStream(testData.getBytes(Charset.forName(charsetEncode)));
    FileContent fileContent = Mockito.mock(FileContent.class);
    Mockito.when(fileObject.getContent()).thenReturn(fileContent);
    Mockito.when(fileContent.getInputStream()).thenReturn(inputStream);
    Mockito.when(fileObject.getName()).thenReturn(fileName);
    fileInputList.addFile(fileObject);/*from  w  w  w .  j av  a 2s  . com*/

    propertyInputData.files = fileInputList;
    propertyInputData.propfiles = false;
    propertyInputData.realEncoding = charsetEncode;

    PropertyInput propertyInput = Mockito.mock(PropertyInput.class);

    Field logField = BaseStep.class.getDeclaredField("log");
    logField.setAccessible(true);
    logField.set(propertyInput, Mockito.mock(LogChannelInterface.class));

    Mockito.doCallRealMethod().when(propertyInput).dispose(propertyInputMeta, propertyInputData);

    propertyInput.dispose(propertyInputMeta, propertyInputData);

    Method method = PropertyInput.class.getDeclaredMethod("openNextFile");
    method.setAccessible(true);
    method.invoke(propertyInput);

    Assert.assertEquals(testValue, propertyInputData.wini.get(header).get(key));
}

From source file:org.pentaho.di.trans.steps.ssh.SSHData.java

public static Connection OpenConnection(String serveur, int port, String username, String password,
        boolean useKey, String keyFilename, String passPhrase, int timeOut, VariableSpace space,
        String proxyhost, int proxyport, String proxyusername, String proxypassword) throws KettleException {
    Connection conn = null;//from www  .  ja v  a2 s.c  om
    char[] content = null;
    boolean isAuthenticated = false;
    try {
        // perform some checks
        if (useKey) {
            if (Utils.isEmpty(keyFilename)) {
                throw new KettleException(
                        BaseMessages.getString(SSHMeta.PKG, "SSH.Error.PrivateKeyFileMissing"));
            }
            FileObject keyFileObject = KettleVFS.getFileObject(keyFilename);

            if (!keyFileObject.exists()) {
                throw new KettleException(
                        BaseMessages.getString(SSHMeta.PKG, "SSH.Error.PrivateKeyNotExist", keyFilename));
            }

            FileContent keyFileContent = keyFileObject.getContent();

            CharArrayWriter charArrayWriter = new CharArrayWriter((int) keyFileContent.getSize());

            try (InputStream in = keyFileContent.getInputStream()) {
                IOUtils.copy(in, charArrayWriter);
            }

            content = charArrayWriter.toCharArray();
        }
        // Create a new connection
        conn = createConnection(serveur, port);

        /* We want to connect through a HTTP proxy */
        if (!Utils.isEmpty(proxyhost)) {
            /* Now connect */
            // if the proxy requires basic authentication:
            if (!Utils.isEmpty(proxyusername)) {
                conn.setProxyData(new HTTPProxyData(proxyhost, proxyport, proxyusername, proxypassword));
            } else {
                conn.setProxyData(new HTTPProxyData(proxyhost, proxyport));
            }
        }

        // and connect
        if (timeOut == 0) {
            conn.connect();
        } else {
            conn.connect(null, 0, timeOut * 1000);
        }
        // authenticate
        if (useKey) {
            isAuthenticated = conn.authenticateWithPublicKey(username, content,
                    space.environmentSubstitute(passPhrase));
        } else {
            isAuthenticated = conn.authenticateWithPassword(username, password);
        }
        if (isAuthenticated == false) {
            throw new KettleException(
                    BaseMessages.getString(SSHMeta.PKG, "SSH.Error.AuthenticationFailed", username));
        }
    } catch (Exception e) {
        // Something wrong happened
        // do not forget to disconnect if connected
        if (conn != null) {
            conn.close();
        }
        throw new KettleException(
                BaseMessages.getString(SSHMeta.PKG, "SSH.Error.ErrorConnecting", serveur, username), e);
    }
    return conn;
}