Example usage for org.apache.commons.vfs FileObject getContent

List of usage examples for org.apache.commons.vfs FileObject getContent

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject getContent.

Prototype

public FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

protected void writeContentFromString(String content, FileObject file) throws Exception {

    OutputStream os = null;/*from   w w  w.java2 s .  c  om*/

    os = file.getContent().getOutputStream();
    Result result = new StreamResult(os);
    IOUtils.write(content.getBytes(), os);
    IOUtils.closeQuietly(os);
    file.close();

}

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

protected void writeContentFromDom(String publicId, String systemId, Node node, FileObject file)
        throws Exception {
    OutputStream os = null;//from   w ww . j a v a2s  . co  m

    os = file.getContent().getOutputStream();
    Result result = new StreamResult(os);

    // Write the Server.xml document back to the file!
    Source source = new DOMSource(node);

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    if (publicId != null)
        xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicId);

    if (systemId != null)
        xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemId);

    xformer.transform(source, result);

    IOUtils.closeQuietly(os);

}

From source file:org.kalypso.dwd.servlet.dwdfilecopy.DWDCopyTask.java

@Override
public void run() {
    FileObject newFile = null;

    try {/*from w w w .  jav  a2 s . co m*/
        /* Check for the file or the base file (this could be a directory). */
        m_fo = m_fsManager.resolveFile(m_URI);

        if (m_fo.getType() != FileType.FOLDER) {
            System.out.println("The URI " + m_URI + " is no folder.");
            return;
        }

        /* Get all elements in this directory. */
        m_list = m_fo.getChildren();

        if (m_list.length == 0) {
            DWDFileCopyServlet.LOG.warning("There are no files in the Source:" + m_fo.getName().toString());
            return;
        }

        /* Find the newest file. */
        newFile = getNewestFile();

        if (newFile == null)
            return;

        DWDFileCopyServlet.LOG.info("Newest file: " + newFile.getName().getBaseName().toString());
    } catch (FileSystemException e) {
        DWDFileCopyServlet.LOG.warning("Error resolving the URI: " + e.getLocalizedMessage());
        return;
    } finally {
    }

    // looping twice over this code in the case an exception
    // occurs, we try it again...
    for (int i = 0; i < 2; i++) {
        FileOutputStream os = null;
        InputStream is = null;

        try {
            final Date newestDate = getDateFromRaster(newFile, m_dateFormat);
            final Date destFileDate = getDateFromRasterContent(m_destFile);

            DWDFileCopyServlet.LOG.info("Date of newest file: " + newestDate);
            DWDFileCopyServlet.LOG.info("Date of destination file: " + destFileDate);

            // if dest file either does not exist or is not up to date, overwrite with current DWD forecast
            if (destFileDate == null || newestDate.after(destFileDate)) {
                /* Copy the newest file. */
                DWDFileCopyServlet.LOG.info("Copying ...");

                final File dwdDest;

                if (m_destUpdate)
                    dwdDest = new File(m_destFile.getParentFile(), newFile.getName().getBaseName());
                else
                    dwdDest = m_destFile;

                DWDFileCopyServlet.LOG.info("Copying DWD-File \"" + newFile.getName().getBaseName() + "\" to: "
                        + dwdDest.getAbsolutePath());

                os = new FileOutputStream(dwdDest);
                is = newFile.getContent().getInputStream();

                /* The copy operation. */
                IOUtils.copy(is, os);

                os.close();
                is.close();

                // update file contents
                if (m_destUpdate) {
                    DWDFileCopyServlet.LOG.info("Updating " + m_destFile.getName() + " from " + dwdDest);
                    DWDRasterHelper.updateDWDFileContents(dwdDest, m_destFile, m_dateFormat);

                    m_destFile.setLastModified(newFile.getContent().getLastModifiedTime());

                    final boolean deleted = dwdDest.delete();

                    if (!deleted)
                        DWDFileCopyServlet.LOG
                                .warning("Could not delete temp DWD-File \"" + dwdDest.getName() + "\"");
                }
            }

            // delete source file if flag is set
            if (m_srcDel) {
                try {
                    /* Delete the old files. */
                    DWDFileCopyServlet.LOG.info("Deleting " + newFile.getName().getBaseName());

                    final boolean deleted = newFile.delete();
                    if (!deleted)
                        DWDFileCopyServlet.LOG.warning(
                                "Could not delete DWD-File \"" + newFile.getName().getBaseName() + "\"");
                } catch (final IOException e) {
                    DWDFileCopyServlet.LOG
                            .warning("Could not delete DWD-File \"" + newFile.getName().getBaseName() + "\"");

                    if (m_debug)
                        e.printStackTrace();
                }
            }

            // no exception, so end loop here
            return;
        } catch (final IOException e) {
            DWDFileCopyServlet.LOG.warning("Could not copy DWD-File \"" + newFile.getName().getBaseName()
                    + "\" to folder: " + m_destFile.getAbsolutePath() + " due to: " + e.getLocalizedMessage());

            if (m_debug)
                e.printStackTrace();
        } catch (final DWDException e) {
            DWDFileCopyServlet.LOG.warning("DWD-File could not be updated: " + e.getLocalizedMessage());
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }

        try {
            // make some pause before continuing
            Thread.sleep(500);
        } catch (final InterruptedException ignored) {
            // empty
        }
    }
}

From source file:org.kalypso.simulation.grid.GridJobSubmitter.java

public void submitJob(final FileObject workingDir, final String executable, ISimulationMonitor monitor,
        String... arguments) throws SimulationException {
    if (monitor == null) {
        monitor = new NullSimulationMonitor();
    }/*from   w w  w . ja  va2s. c o m*/

    // prepare streams
    FileObject stdoutFile = null;
    FileObject stderrFile = null;
    int returnCode = IStatus.ERROR;
    try {
        // stream stdout and stderr to files
        stdoutFile = workingDir.resolveFile("stdout");
        stderrFile = workingDir.resolveFile("stderr");

        // create process handle
        final String processFactoryId = "org.kalypso.simulation.gridprocess";
        // TODO: refactor so tempdir is created inside process
        final String tempDirName = workingDir.getName().getBaseName();
        final IProcess process = KalypsoCommonsExtensions.createProcess(processFactoryId, tempDirName,
                executable, arguments);
        // process.setProgressMonitor( new SimulationMonitorAdaptor( monitor ) );
        process.environment().put("OMP_NUM_THREADS", "4");

        final FileContent stdOutContent = stdoutFile.getContent();
        final OutputStream stdOut = stdOutContent.getOutputStream();
        final FileContent stdErrContent = stderrFile.getContent();
        final OutputStream stdErr = stdErrContent.getOutputStream();

        // stage-in files
        final FileSystemManager manager = workingDir.getFileSystem().getFileSystemManager();
        for (final URI einput : m_externalInputs.keySet()) {
            final FileObject inputFile = manager.resolveFile(getUriAsString(einput));
            final String destName = m_externalInputs.get(einput);
            if (destName != null) {
                final FileObject destFile = workingDir.resolveFile(destName);
                VFSUtil.copy(inputFile, destFile, null, true);
            } else {
                VFSUtil.copy(inputFile, workingDir, null, true);
            }
        }

        // start process
        returnCode = process.startProcess(stdOut, stdErr, null, null);
    } catch (final CoreException e) {
        // when process cannot be created
        throw new SimulationException("Could not create process.", e);
    } catch (final ProcessTimeoutException e) {
        e.printStackTrace();
    } catch (final FileNotFoundException e) {
        // can only happen when files cannot be created in tmpdir
        throw new SimulationException("Could not create temporary files for stdout and stderr.", e);
    } catch (final IOException e) {
        throw new SimulationException("Process I/O error.", e);
    } finally {
        // close files
        if (stdoutFile != null) {
            try {
                stdoutFile.getContent().close();
            } catch (final FileSystemException e) {
                // gobble
            }
        }
        if (stderrFile != null) {
            try {
                stderrFile.getContent().close();
            } catch (final FileSystemException e) {
                // gobble
            }
        }
    }

    // process failure handling
    if (returnCode != IStatus.OK) {
        String errString = "Process failed.";
        try {
            final FileContent content = stderrFile.getContent();
            final InputStream input2 = content.getInputStream();
            errString = errString + "\n" + IOUtils.toString(input2);
            content.close();
        } catch (final IOException e) {
            // ignore
        }
        monitor.setFinishInfo(returnCode, errString);
        throw new SimulationException(errString);
    } else {
        monitor.setFinishInfo(IStatus.OK, "Process finished successfully.");
    }
}

From source file:org.mule.transports.vfs.VFSMessageDispatcher.java

protected void doDispatch(UMOEvent event) throws Exception {
    try {//from  w  w  w  .j a v a 2  s  .  co  m
        Object data = event.getTransformedMessage();
        String filename = (String) event.getProperty(VFSConnector.PROPERTY_FILENAME);

        if (filename == null) {
            String outPattern = (String) event.getProperty(VFSConnector.PROPERTY_OUTPUT_PATTERN);
            if (outPattern == null) {
                outPattern = connector.getOutputPattern();
            }
            filename = generateFilename(event, outPattern);
        }

        if (filename == null) {
            throw new IOException("Filename is null");
        }

        FileObject file = dirObject.resolveFile(filename);
        byte[] buf;
        if (data instanceof byte[]) {
            buf = (byte[]) data;
        } else {
            buf = data.toString().getBytes();
        }

        logger.info("Writing file to: " + file.getURL());
        OutputStream outputStream = file.getContent().getOutputStream(connector.isOutputAppend());
        try {
            outputStream.write(buf);
        } finally {
            outputStream.close();
        }
    } catch (Exception e) {
        Exception handled = e;
        if (e instanceof FileSystemException) {
            handled = new ConnectException(e, this);
        }
        getConnector().handleException(handled);
    }
}

From source file:org.mule.transports.vfs.VFSReceiver.java

protected boolean hasChanged(FileObject fileObject) {
    boolean changed = false;
    String key = fileObject.getName().getPath();
    long checksum = 0;
    if (checksumMap.containsKey(key)) {
        checksum = ((Long) checksumMap.get(key)).longValue();
    }//w  ww. j av  a  2 s  .  c  om
    long newChecksum = 0;
    CheckedInputStream checkedInputStream = null;
    try {
        InputStream inputStream = fileObject.getContent().getInputStream();
        checkedInputStream = new CheckedInputStream(inputStream, new Adler32());
        int bufferSize = 1;
        if (inputStream.available() > 0) {
            bufferSize = inputStream.available();
        }
        byte[] buffer = new byte[bufferSize];
        while (checkedInputStream.read(buffer) > -1) {
            ;
        }
        newChecksum = checkedInputStream.getChecksum().getValue();
        if (newChecksum != checksum) {
            if (logger.isDebugEnabled()) {
                logger.debug("calculated a new checksum of " + newChecksum);
            }
            checksumMap.put(key, new Long(newChecksum));
            changed = true;
        }
    } catch (IOException e) {
        connector.handleException(e);
    }
    return changed;
}

From source file:org.nanocontainer.deployer.NanoContainerDeployer.java

/**
 * Deploys an application./*from   w w  w.  j  av a  2  s. c o m*/
 *
 * @param applicationFolder the root applicationFolder of the application.
 * @param parentClassLoader the classloader that loads the application classes.
 * @param parentContainerRef reference to the parent container (can be used to lookup components form a parent container).
 * @return an ObjectReference holding a PicoContainer with the deployed components
 * @throws org.apache.commons.vfs.FileSystemException if the file structure was bad.
 * @throws org.nanocontainer.integrationkit.PicoCompositionException if the deployment failed for some reason.
 */
public ObjectReference deploy(FileObject applicationFolder, ClassLoader parentClassLoader,
        ObjectReference parentContainerRef) throws FileSystemException, ClassNotFoundException {
    ClassLoader applicationClassLoader = new VFSClassLoader(applicationFolder, fileSystemManager,
            parentClassLoader);

    FileObject deploymentScript = getDeploymentScript(applicationFolder);

    ObjectReference result = new SimpleReference();

    String extension = "." + deploymentScript.getName().getExtension();
    Reader scriptReader = new InputStreamReader(deploymentScript.getContent().getInputStream());
    String builderClassName = ScriptedContainerBuilderFactory.getBuilderClassName(extension);

    ScriptedContainerBuilderFactory scriptedContainerBuilderFactory = new ScriptedContainerBuilderFactory(
            scriptReader, builderClassName, applicationClassLoader);
    ContainerBuilder builder = scriptedContainerBuilderFactory.getContainerBuilder();
    builder.buildContainer(result, parentContainerRef, null, true);

    return result;
}

From source file:org.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java

private FileObject createTemporaryShellFile(FileObject tempFile, String fileContent) throws Exception {
    // Create a unique new temporary filename in the working directory, put the script in there
    // Set the permissions to execute and then run it...
    ////from   w  w w .j  a  va  2 s  .c om
    if (tempFile != null && fileContent != null) {
        try {
            tempFile.createFile();
            OutputStream outputStream = tempFile.getContent().getOutputStream();
            outputStream.write(fileContent.getBytes());
            outputStream.close();
            if (!Const.getOS().startsWith("Windows")) {
                String tempFilename = KettleVFS.getFilename(tempFile);
                // Now we have to make this file executable...
                // On Unix-like systems this is done using the command "/bin/chmod +x filename"
                //
                ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
                Process proc = procBuilder.start();
                // Eat/log stderr/stdout all messages in a different thread...
                StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(),
                        toString() + " (stderr)");
                StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(),
                        toString() + " (stdout)");
                new Thread(errorLogger).start();
                new Thread(outputLogger).start();
                proc.waitFor();
            }

        } catch (Exception e) {
            throw new Exception("Unable to create temporary file to execute script", e);
        }
    }
    return tempFile;
}

From source file:org.openossad.util.core.row.ValueDataUtil.java

public static Object loadFileContentInBinary(ValueMetaInterface metaA, Object dataA)
        throws OpenDESIGNERValueException {
    if (dataA == null)
        return null;

    FileObject file = null;
    FileInputStream fis = null;//from  www . j a v  a2  s. co  m
    try {
        file = OpenDESIGNERVFS.getFileObject(dataA.toString());
        fis = (FileInputStream) ((LocalFile) file).getInputStream();
        int fileSize = (int) file.getContent().getSize();
        byte[] content = Const.createByteArray(fileSize);
        fis.read(content, 0, fileSize);
        return content;
    } catch (Exception e) {
        throw new OpenDESIGNERValueException(e);
    } finally {
        try {
            if (file != null)
                file.close();
            if (fis != null)
                fis.close();
        } catch (Exception e) {
        }
        ;
    }
}

From source file:org.org.eclipse.core.utils.platform.tools.ArchivesToolBox.java

private static void decompressFileObjectTo(FileObject fileObject, File targetFolder, IWriteHinter writeHinter)
        throws IOException {
    for (FileObject child : fileObject.getChildren()) {
        String childName = child.getName().getBaseName();
        FileType type = child.getType();
        if (type.equals(FileType.FOLDER)) {
            String folderName = writeHinter.alterFolderName(targetFolder, childName);
            File folder = new File(targetFolder, folderName);
            if (!folder.exists()) {
                folder.mkdirs();//  w  w  w. j a va 2s . co  m
            }
            decompressFileObjectTo(child, folder, writeHinter);
        }
        if (type.equals(FileType.FILE)) {
            String fileName = writeHinter.alterFileName(targetFolder, childName);
            File newFile = new File(targetFolder, fileName);
            newFile.createNewFile();
            WriteMode writeMode = writeHinter.getFileWriteMode(newFile);
            if (writeMode != WriteMode.SKIP) {
                FileOutputStream fileOutputStream = new FileOutputStream(newFile);
                InputStream inputStream = child.getContent().getInputStream();
                try {
                    IOToolBox.inToOut(inputStream, fileOutputStream);
                } finally {
                    inputStream.close();
                    fileOutputStream.close();
                }
            }
        }
    }
}