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

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

Introduction

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

Prototype

FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

From source file:cz.lbenda.dataman.rc.DatamanHeadless.java

public void launch(@Nonnull CommandLine cmd) {
    DbConfig dbConfig = DbConfigFactory.getConfiguration(cmd.getOptionValue("c"));
    if (dbConfig == null) {
        LOG.error("Configuration with name " + cmd.getOptionValue("c") + " not exist.");
        System.exit(1);//from ww w .j  a  v  a  2 s. c om
    }

    try {
        List<FileObject> scripts = scripts(cmd);
        List<FileObject> outputs = outputs(cmd);
        if (scripts.size() == 0) {
            LOG.error("The scripts isn't defined");
            System.exit(3);
        } else {
            SQLSExecutorConsumerClass sqlEditorController = new SQLSExecutorConsumerClass(!cmd.hasOption("nos"),
                    format(cmd));
            SQLSExecutor executor = new SQLSExecutor(dbConfig, sqlEditorController, null);
            dbConfig.getConnectionProvider().getConnection();
            int i = 0;
            for (FileObject file : scripts) {
                if (outputs.size() > i) {
                    sqlEditorController.setOutputFile(outputs.get(i));
                } else {
                    sqlEditorController.setOutputFile(null);
                }
                i++;
                try {
                    InputStream is = file.getContent().getInputStream();
                    Reader reader = new InputStreamReader(is);
                    char[] buff = new char[262144];
                    int l;
                    String rest = "";
                    while ((l = reader.read(buff)) != -1) {
                        String str = rest + new String(buff, 0, l);
                        String[] strs = SQLSExecutor.splitSQLS(str);
                        if (strs.length == 1) {
                            rest = str;
                        } else {
                            rest = strs[strs.length - 1];
                            if (!str.endsWith("\n") && rest.endsWith("\n")) {
                                rest = rest.substring(0, rest.length() - 1);
                                rest = str.substring(str.lastIndexOf(rest), str.length());
                            }
                            String[] sqls = new String[strs.length - 1];
                            System.arraycopy(strs, 0, sqls, 0, strs.length - 1);
                            executor.executeBlocking(sqls);
                        }
                    }
                    executor.executeBlocking(SQLSExecutor.splitSQLS(rest));
                } catch (IOException e) {
                    LOG.error("Problem with read script file", e);
                    System.exit(4);
                }
            }
        }
    } catch (FileSystemException e) {
        LOG.error("Problem with read script data", e);
        System.exit(2);
    }
}

From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected void createMetadataFile(FileObject metadataFile) throws InstantiationException,
        IllegalAccessException, UnsupportedEncodingException, FileSystemException, IOException {
    DesignMetadata metadata = createDefaultMetadata();
    Writer writer = new OutputStreamWriter(metadataFile.getContent().getOutputStream(),
            getManager().getFileEncoding());
    writer.write(DesignSyncManager.getXstream().toXML(metadata.getInfo()));
    writer.close();/*w  w w  .j  a va  2  s  .com*/
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportSender.java

private void populateResponseFile(FileObject responseFile, MessageContext msgContext, boolean append,
        boolean lockingEnabled) throws AxisFault {

    MessageFormatter messageFormatter = getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);

    try {/*from   w w w .ja  v  a 2 s .  c om*/
        CountingOutputStream os = new CountingOutputStream(responseFile.getContent().getOutputStream(append));
        try {
            messageFormatter.writeTo(msgContext, format, os, true);
        } finally {
            os.close();
        }

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        metrics.incrementBytesSent(msgContext, os.getByteCount());

    } catch (FileSystemException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : " + responseFile.getName(), e);
    } catch (IOException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : " + responseFile.getName(), e);
    }
}

From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtility.java

/**
 * Helper method to stream file from source to destination folder.
 *
 * @param inputFile/*from w  w  w.j a v  a 2s  . c o m*/
 *            FileObject of input file
 * @param outputFile
 *            FileObject of output file
 * @return Boolean value of success. It is based on file length comparison.
 * @throws FileSystemException
 *             If given file operation fails
 */
private void streamFromFileToFile(FileObject inputFile, FileObject outputFile) {

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        inputStream = inputFile.getContent().getInputStream();

        outputStream = outputFile.getContent().getOutputStream();

        String blockSize = DEFAULT_STREAMING_BLOCK_SIZE;

        if (options.getStreamingBlockSize() == null || !options.getStreamingBlockSize().matches("^\\d+$")) {
            blockSize = DEFAULT_STREAMING_BLOCK_SIZE;
            log.warn(
                    "Streaming block size not numeric, using default value of " + DEFAULT_STREAMING_BLOCK_SIZE);
        } else {
            blockSize = options.getStreamingBlockSize();
        }

        int length;
        byte[] buffer = new byte[new Integer(blockSize)];
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }

        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        throw new SynapseException("Unexpected error during the file transfer", e);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException ex) {
            // making sure that output streams were closed in error situation
        }

        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ex) {
            // making sure that inputstream is closed
        }

    }

}

From source file:com.streamsets.pipeline.stage.origin.remote.RemoteDownloadSource.java

private void queueFiles() throws FileSystemException {
    remoteDir.refresh();//from w  w  w.j  a  v  a 2s  .c o m
    for (FileObject remoteFile : remoteDir.getChildren()) {
        if (remoteFile.getType().toString().equals("folder"))
            continue;
        long lastModified = remoteFile.getContent().getLastModifiedTime();
        RemoteFile tempFile = new RemoteFile(remoteFile.getName().getBaseName(), lastModified, remoteFile);
        if (shouldQueue(tempFile)) {
            // If we are done with all files, the files with the final mtime might get re-ingested over and over.
            // So if it is the one of those, don't pull it in.
            fileQueue.add(tempFile);
        }
    }
}

From source file:cz.lbenda.dataman.db.ExtConfFactory.java

/** Load extend configuration to given database configuration */
public void load() {
    if (exConf != null && StringUtils.isBlank(exConf.getSrc())) {
        loadExConfType(exConf);/*from  w w  w .  j  av  a  2 s. c om*/
    } else if (exConf != null) {
        if (exConf.getSrc().startsWith("db://")) {
            String path = exConf.getSrc().substring(5, exConf.getSrc().length());
            dbConfig.getConnectionProvider()
                    .onPreparedStatement(String.format(
                            "select usr, exConf from %s where (usr = ? or usr is null or usr = '')", path),
                            tuple2 -> {
                                PreparedStatement ps = tuple2.get1();
                                String extendConfiguration = null;
                                try {
                                    ps.setString(1, dbConfig.getConnectionProvider().getUser().getUsername());
                                    try (ResultSet rs = ps.executeQuery()) {
                                        while (rs.next()) {
                                            if (rs.getString(1) == null && extendConfiguration == null) { // The null user is used only if no specific user configuration is read
                                                extendConfiguration = rs.getString(2);
                                            } else if (rs.getString(1) != null) {
                                                extendConfiguration = rs.getString(2);
                                            }
                                        }
                                    }
                                } catch (SQLException e) {
                                    LOG.error("Problem with read extend config from table: " + exConf.getSrc(),
                                            e);
                                    ExceptionMessageFrmController.showException(
                                            "Problem with read extend config from table: " + exConf.getSrc(),
                                            e);
                                }
                                if (!StringUtils.isBlank(extendConfiguration)) {
                                    loadExConfType(new StringReader(extendConfiguration));
                                } else {
                                    StringUtils.isBlank(null);
                                }
                            });
        } else {
            try {
                FileSystemManager fsManager = VFS.getManager();
                FileObject file = fsManager.resolveFile(exConf.getSrc());
                if (!file.exists()) {
                    ExceptionMessageFrmController.showException("File not exist: " + exConf.getSrc());
                } else if (file.getChildren() == null || file.getChildren().length == 0) {
                    new Thread(() -> {
                        try {
                            FileContent content = file.getContent();
                            loadExConfType(new InputStreamReader(content.getInputStream()));
                            content.close();
                        } catch (FileSystemException e) {
                            LOG.error("Problem with read extend config from file: " + exConf.getSrc(), e);
                            ExceptionMessageFrmController.showException(
                                    "Problem with read extend config from file: " + exConf.getSrc(), e);
                        }
                    }).start();
                } else {
                    ExceptionMessageFrmController
                            .showException("The file type isn't supported: " + exConf.getSrc());
                }
            } catch (FileSystemException e) {
                LOG.error("Problem with read extend config from file: " + exConf.getSrc(), e);
                ExceptionMessageFrmController
                        .showException("Problem with read extend config from file: " + exConf.getSrc(), e);
            }
        }
    }
}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

private File getFileFromVFSObject(FileSystemManager fileSystemManager, FileSystemOptions opts, String vfsPath) {
    OutputStream outputStream = null;
    try {//from   w  w  w . j  av  a 2 s.  c  o  m
        FileObject downloadFile = fileSystemManager.resolveFile(vfsPath, opts);
        FileContent fc = downloadFile.getContent();
        InputStream inputStream = fc.getInputStream();
        String fn = getDisplayPath(vfsPath);
        String tDir = System.getProperty("java.io.tmpdir");
        File locFile = new File(tDir, fn);
        outputStream = new FileOutputStream(locFile);
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        return locFile;

    } catch (FileSystemException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;

}

From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected DesignMetadata readMetaData() throws FileNotFoundException, IOException, InstantiationException,
        IllegalAccessException, WGDesignSyncException {

    FileObject metadataFile = getMetadataFile();

    // If not exists we return a default
    if (!metadataFile.exists()) {
        return createDefaultMetadata();
    }//from  ww  w  . j  a v a 2 s.c om

    // If the file exists, but is empty, we put default metadata information into it
    if (metadataFile.getContent().getSize() == 0) {
        createMetadataFile(metadataFile);
    }

    String metaXML;
    Reader reader = createReader(metadataFile);
    try {
        metaXML = WGUtils.readString(reader);
    } finally {
        reader.close();
        metadataFile.close();
    }

    DesignMetadata metaData;
    if (metaXML.trim().equals("")) {
        createMetadataFile(metadataFile);
        metaData = createDefaultMetadata();
    } else {
        DesignMetadataInfo info = (DesignMetadataInfo) DesignSyncManager.getXstream().fromXML(metaXML);
        if (info instanceof TMLMetadataInfo) {
            metaData = new TMLMetadata();
        } else if (info instanceof FCMetadataInfo) {
            metaData = new FCMetadata();
        } else if (info instanceof ScriptMetadataInfo) {
            metaData = new ScriptMetadata();
        } else {
            metaData = new DesignMetadata();
        }
        metaData.setInfo(info);
    }

    return metaData;
}

From source file:com.streamsets.pipeline.stage.origin.remote.RemoteDownloadSource.java

private void queueFiles(FileObject remoteDir) throws FileSystemException {
    remoteDir.refresh();//  www  .j a  v a  2  s .  c  om
    for (FileObject remoteFile : remoteDir.getChildren()) {
        if (remoteFile.getType().toString().equals("folder")) {
            queueFiles(remoteFile);
            continue;
        }
        long lastModified = remoteFile.getContent().getLastModifiedTime();
        RemoteFile tempFile = new RemoteFile(remoteFile.getName().getBaseName(), lastModified, remoteFile);

        if (shouldQueue(tempFile)) {
            // If we are done with all files, the files with the final mtime might get re-ingested over and over.
            // So if it is the one of those, don't pull it in.
            fileQueue.add(tempFile);
        }
    }
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private void tryInitialize() throws IOException, ParseException {
    log.log(Level.FINE, MessageNames.STARTER_SERVICE_DEPLOYER_STARTING, myName);
    /*//from  ww  w.j  a va 2s .  c om
     Read and parse the configuration file.
     */

    FileObject configFile = fileUtility.getProfileDirectory().resolveFile(config);
    InputStream in = configFile.getContent().getInputStream();
    configNode = DeployerConfigParser.parseConfig(in);
    log.log(Level.FINE, MessageNames.STARTER_SERVICE_DEPLOYER_INITIALIZED, new Object[] { myName });
}