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:architecture.ee.jdbc.sqlquery.factory.impl.AbstractSqlQueryFactory.java

protected void loadResourceLocations() {

    List<FileObject> list = new ArrayList<FileObject>();
    Repository repository = Bootstrap.getBootstrapComponent(Repository.class);
    /**/*from   w w w .  j av  a 2 s.c om*/
     * log.debug("searching sql in jar ...");
     * if(!isEmpty(this.sqlLocations)){ for(Resource sqlLocation :
     * sqlLocations ){ if(sqlLocation == null) continue;
     * 
     * 
     * // log.debug(sqlLocation.toString()); } }
     **/

    /*
     * String value =
     * repository.getSetupApplicationProperties().getStringProperty(
     * "resources.sql", ""); String[] resources = StringUtils.split(value);
     * if( resources.length > 0 ){ log.debug(
     * "using custom sql resources instade of " + resourceLocations ); for(
     * String path : resources ){ try { FileObject f =
     * VFSUtils.resolveFile(path); if (f.exists()) { list.add(f); } } catch
     * (Throwable e) { log.warn(path + " not found.", e); } } }else{ for
     * (String path : resourceLocations) { try { FileObject f =
     * VFSUtils.resolveFile(path); if (f.exists()) { list.add(f); } } catch
     * (Throwable e) { log.warn(path + " not found.", e); } } }
     */

    try {
        log.debug("searching sql ...");
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> paths = cl.getResources("sql/");
        do {
            if (!paths.hasMoreElements())
                break;
            URL url = paths.nextElement();
            String pathToUse = "jar:" + url.getPath();
            log.debug("target:" + pathToUse);
            FileObject fo = VFSUtils.resolveFile(pathToUse);
            FileObject[] selected = findSqlFiles(fo);
            for (FileObject f : selected) {
                if (!list.contains(f)) {
                    list.add(f);
                }
            }
        } while (true);
    } catch (Throwable e) {
        log.warn(e);
    }

    for (FileObject fo : list) {
        try {
            log.debug("sql : " + fo.getName());
            if (!configuration.isResourceLoaded(fo.getName().getURI())) {
                buildSqlFromInputStream(fo.getContent().getInputStream(), configuration);
                configuration.addLoadedResource(fo.getName().getURI());
            }
        } catch (FileSystemException e) {
            log.warn(e);
        }
    }

}

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

/**
 * Process a single file through Axis2//from   ww  w.  j  a v  a 2s  .  com
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        metrics.incrementBytesReceived(content.getSize());

        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);

        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }

        MessageContext msgContext = entry.createMessageContext();

        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }

        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }

        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                    new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }

        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                        msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

            handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *//
                    contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }

    } catch (FileSystemException e) {
        handleException("Error reading file content or attributes : " + file, e);

    } finally {
        try {
            file.close();
        } catch (FileSystemException warn) {
            //  log.warn("Cannot close file after processing : " + file.getName().getPath(), warn);
            // ignore the warning, since we handed over the stream close job to AutocloseInputstream..
        }
    }
}

From source file:com.sludev.commons.vfs.simpleshell.SimpleShell.java

/**
 * Does an 'ls' command.// w  ww. j  av a 2  s  .c  o m
 * 
 * @param cmd
 * @throws org.apache.commons.vfs2.FileSystemException
 */
public void ls(final String[] cmd) throws FileSystemException {
    int pos = 1;
    final boolean recursive;
    if (cmd.length > pos && cmd[pos].equals("-R")) {
        recursive = true;
        pos++;
    } else {
        recursive = false;
    }

    final FileObject file;
    if (cmd.length > pos) {
        file = mgr.resolveFile(cwd, cmd[pos]);
    } else {
        file = cwd;
    }

    switch (file.getType()) {
    case FOLDER:
        // List the contents
        System.out.println("Contents of " + file.getName());
        listChildren(file, recursive, "");
        break;

    case FILE:
        // Stat the file
        System.out.println(file.getName());
        final FileContent content = file.getContent();
        System.out.println("Size: " + content.getSize() + " bytes.");
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
        System.out.println("Last modified: " + lastMod);
        break;

    case IMAGINARY:
        System.out.println(String.format("File '%s' is IMAGINARY", file.getName()));
        break;

    default:
        log.error(String.format("Unkown type '%d' on '%s'", file.getType(), file.getName()));
        break;
    }
}

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

public InputStream getFileData(String strFile) throws WGAPIException {
    try {//from   w w  w  . ja  v a 2s. c o  m
        if (getType() != WGDocument.TYPE_FILECONTAINER) {
            return null;
        }
        FileObject file = getFileContainerFile(strFile);
        if (file == null) {
            return null;
        }
        if (file.getType().equals(FileType.FILE)) {
            return file.getContent().getInputStream();
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new WGBackendException("Exception reading container file data", e);
    }
}

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

private long getLastModifiedTime(FileObject file) throws FileSystemException {

    if (file.getFileSystem() instanceof ZipFileSystem) {
        return file.getFileSystem().getParentLayer().getContent().getLastModifiedTime();
    }/* w w w .  ja  v a  2 s.  co m*/

    return file.getContent().getLastModifiedTime();

}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void copy(byte[] content, String targetPath) throws PublishException {

    String targetFullPath = targetFullPath(builder.getPath(), targetPath);
    logger.debug("Server file's path is {}", targetFullPath);

    FileObject root = null;/* w w  w  .  j  a  v  a2  s.c om*/
    FileObject target = null;
    try {
        root = getRootFileObject();
        //target = getTargetFileObject(root, targetFullPath);
        //-------------- Windows? ??----------------------
        targetPath = targetPath.replace("\\", "/").replace("//", "/");
        if (targetPath.indexOf("/") == 0) {
            targetPath = targetPath.substring(1);
        }
        target = getTargetFileObject(root, targetPath);
        //--------------------------------------------------------------
        FileContent fileContent = target.getContent();
        OutputStream stream = fileContent.getOutputStream();
        stream.write(content);
        stream.flush();

        stream.close();
        fileContent.close();
        target.close();
        root.close();
    } catch (FileSystemException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } catch (IOException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } finally {
        try {
            if (root != null) {
                root.close();
            }
            if (target != null) {
                target.close();
            }
        } catch (Exception e) {
            logger.error("vfs close is error:{}", e.toString());
        }
    }
}

From source file:com.ewcms.publication.deploy.provider.DeployOperatorBase.java

@Override
public void copy(File sourceFile, String targetPath) throws PublishException {
    //TODO ??????
    if (!sourceFile.exists()) {
        logger.debug("Source file path's {} is not exists.", sourceFile.getPath());
        return;/*from   ww  w  .  ja v  a2 s. co m*/
    }

    String targetFullPath = targetFullPath(builder.getPath(), targetPath);
    logger.debug("Server file's path is {}", targetFullPath);
    logger.debug("Source file's path is {}  ", sourceFile.getPath());

    FileObject root = null;
    FileObject target = null;
    try {
        root = getRootFileObject();
        //target = getTargetFileObject(root, targetFullPath);
        //-------------- Windows? ??----------------------
        targetPath = targetPath.replace("\\", "/").replace("//", "/");
        if (targetPath.indexOf("/") == 0) {
            targetPath = targetPath.substring(1);
        }
        target = getTargetFileObject(root, targetPath);
        //--------------------------------------------------------------
        FileContent fileContent = target.getContent();

        OutputStream out = fileContent.getOutputStream();
        InputStream in = new FileInputStream(sourceFile);

        byte[] buffer = new byte[1024 * 8];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.flush();

        in.close();
        out.close();
        fileContent.close();
    } catch (FileSystemException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } catch (IOException e) {
        logger.error("Copy {} is error:{}", targetFullPath, e);
        throw new PublishException(e);
    } finally {
        try {
            if (root != null) {
                root.close();
            }
            if (target != null) {
                target.close();
            }
        } catch (Exception e) {
            logger.error("vfs close is error:{}", e.toString());
        }
    }
}

From source file:de.innovationgate.wgpublisher.design.sync.FileContainerDeployment.java

public void performUpdate(WGDatabase db)
        throws IOException, WGException, InstantiationException, IllegalAccessException, WGDesignSyncException {

    FileObject codeFile = getCodeFile();
    // Check if file has been deleted in the meantime
    if (!codeFile.exists()) {
        return;//from  w w w  .j av  a  2 s .  c o m
    }

    WGFileContainer con = (WGFileContainer) db.getDocumentByDocumentKey(getDocumentKey());
    if (con == null) {
        WGDocumentKey docKey = new WGDocumentKey(getDocumentKey());
        con = db.createFileContainer(docKey.getName());
        con.save();
    }

    // Find new and updated files
    FileObject[] filesArray = codeFile.getChildren();
    if (filesArray == null) {
        throw new WGDesignSyncException("Cannot collect files from directory '"
                + codeFile.getName().getPathDecoded() + "'. Please verify directory existence.");
    }

    List<FileObject> files = new ArrayList<FileObject>(Arrays.asList(filesArray));
    Collections.sort(files, new FileNameComparator());

    FileObject file;
    Map existingFiles = new HashMap();
    for (int i = 0; i < files.size(); i++) {
        file = (FileObject) files.get(i);
        if (isExcludedFileContainerFile(file)) {
            continue;
        }

        ContainerFile containerFile = getContainerFile(file);
        if (containerFile != null) {
            if (existingFiles.containsKey(containerFile.getName())) {
                // Possible in case-sensitive file systems. Another file of the same name with another case is in the dir.
                continue;
            }

            if (file.getContent().getLastModifiedTime() != containerFile.getTimestamp()) {
                doRemoveFile(con, file.getName().getBaseName());
                doSaveDocument(con);
                doAttachFile(con, file);
                doSaveDocument(con);
                containerFile.setTimestamp(file.getContent().getLastModifiedTime());
            }
        } else {
            containerFile = new ContainerFile(file);
            if (con.hasFile(file.getName().getBaseName())) {
                doRemoveFile(con, file.getName().getBaseName());
                doSaveDocument(con);
            }
            doAttachFile(con, file);
            doSaveDocument(con);
        }
        existingFiles.put(containerFile.getName(), containerFile);
    }

    // Remove deleted files from container
    _files = existingFiles;
    List fileNamesInContainer = WGUtils.toLowerCase(con.getFileNames());
    fileNamesInContainer.removeAll(existingFiles.keySet());
    Iterator deletedFiles = fileNamesInContainer.iterator();
    while (deletedFiles.hasNext()) {
        con.removeFile((String) deletedFiles.next());
        con.save();
    }

    // Update metadata and save
    FCMetadata metaData = (FCMetadata) readMetaData();
    metaData.writeToDocument(con);
    con.save();
    FileObject metadataFile = getMetadataFile();
    if (metadataFile.exists()) {
        _timestampOfMetadataFile = metadataFile.getContent().getLastModifiedTime();
    }

    // We wont do this here, since this would rebuild all ContainerFiles, which is not neccessary
    // Instead we have updated just the metadata file timestamp
    // resetUpdateInformation();
}

From source file:maspack.fileutil.FileCacher.java

public OutputStream getOutputStream(URIx uri) throws FileSystemException {

    FileObject remoteFile = null; // will resolve next

    // loop through authenticators until we either succeed or cancel
    boolean cancel = false;
    while (remoteFile == null && cancel == false) {
        remoteFile = resolveRemote(uri);
    }//from   w w w .  j  a va 2  s .com

    if (remoteFile == null) {
        throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">",
                new FileNotFoundException("<" + uri.toString() + ">"));
    }

    // open stream content
    OutputStream stream = null;
    try {
        stream = remoteFile.getContent().getOutputStream();
    } catch (Exception e) {
        throw new RuntimeException("Failed to open " + remoteFile.getURL(), e);
    } finally {
        remoteFile.close();
    }

    return stream;

}

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

public WGFileMetaData getFileMetaData(String strFile) throws WGAPIException {
    try {/*from ww  w .j  a  va2s. co  m*/
        FileObject file = getFileContainerFile(strFile);
        if (file == null) {
            return null;
        }

        Date lastModified = new Date(getLastModifiedTime(file));
        WGFileMetaData md = new WGFileMetaData(null, strFile.toLowerCase(), file.getContent().getSize(),
                lastModified, lastModified, null, null, new HashMap<String, Object>());
        return md;
    } catch (Exception e) {
        throw new WGBackendException(
                "Exception retrieving file metadata for file " + strFile + " on document " + _docKey.toString(),
                e);
    }
}