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:org.apache.synapse.commons.vfs.VFSUtils.java

public synchronized static void markFailRecord(FileSystemManager fsManager, FileObject fo) {

    // generate a random fail value to ensure that there are no two parties
    // processing the same file
    Random random = new Random();
    byte[] failValue = (Long.toString((new Date()).getTime())).getBytes();

    try {//from   w  ww  .  j  a  v a  2 s.  co m
        String fullPath = fo.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject failObject = fsManager.resolveFile(fullPath + ".fail");
        if (!failObject.exists()) {
            failObject.createFile();
        }

        // write a lock file before starting of the processing, to ensure that the
        // item is not processed by any other parties

        OutputStream stream = failObject.getContent().getOutputStream();
        try {
            stream.write(failValue);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            failObject.delete();
            log.error("Couldn't create the fail file before processing the file " + maskURLPassword(fullPath),
                    e);
        } finally {
            failObject.close();
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI())
                + " before processing");
    }
}

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

private static boolean releaseLock(byte[] bLockValue, String sLockValue, FileObject lockObject,
        Boolean autoLockReleaseSameNode, Long autoLockReleaseInterval) {
    try {//from w ww . j  a  v a2s . co m
        InputStream is = lockObject.getContent().getInputStream();
        byte[] val = new byte[bLockValue.length];
        // noinspection ResultOfMethodCallIgnored
        is.read(val);
        String strVal = new String(val);
        // Lock format random:hostname:hostip:time
        String[] arrVal = strVal.split(":");
        String[] arrValNew = sLockValue.split(STR_SPLITER);
        if (arrVal.length == 4 && arrValNew.length == 4) {
            if (!autoLockReleaseSameNode
                    || (arrVal[1].equals(arrValNew[1]) && arrVal[2].equals(arrValNew[2]))) {
                long lInterval = 0;
                try {
                    lInterval = Long.parseLong(arrValNew[3]) - Long.parseLong(arrVal[3]);
                } catch (NumberFormatException nfe) {
                }
                if (autoLockReleaseInterval == null || autoLockReleaseInterval <= lInterval) {
                    try {
                        lockObject.delete();
                    } catch (Exception e) {
                        log.warn("Unable to delete the lock file during auto release cycle.", e);
                    } finally {
                        lockObject.close();
                    }
                    return true;
                }
            }
        }
    } catch (FileSystemException e) {
        log.error("Couldn't verify the lock", e);
        return false;
    } catch (IOException e) {
        log.error("Couldn't verify the lock", e);
        return false;
    }
    return false;
}

From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java

/**
 * Process a single file through Axis2//from w w  w .  j av  a2 s.co  m
 * @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 : " + VFSUtils.maskURLPassword(file.toString()) + " of Content-type : "
                    + contentType);
        }

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

    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (FileSystemException warn) {
            // ignore the warning,  since we handed over the stream close job to
            // AutocloseInputstream..
        }
    }
}

From source file:org.apache.synapse.transport.vfs.VFSTransportSender.java

private void populateResponseFile(FileObject responseFile, MessageContext msgContext, boolean append,
        boolean lockingEnabled, FileSystemOptions fso) throws AxisFault {
    MessageFormatter messageFormatter = getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);

    try {//from www . jav 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, fso);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : "
                + VFSUtils.maskURLPassword(responseFile.getName().getURI()), e);
    } catch (IOException e) {
        if (lockingEnabled) {
            VFSUtils.releaseLock(fsManager, responseFile, fso);
        }
        metrics.incrementFaultsSending();
        handleException("IO Error while creating response file : "
                + VFSUtils.maskURLPassword(responseFile.getName().getURI()), e);
    }
}

From source file:org.apache.zeppelin.notebook.repo.OldVFSNotebookRepo.java

private Note getNote(FileObject noteDir) throws IOException {
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }/*  w  w w.  ja  v a2s. com*/

    FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
    if (!noteJson.exists()) {
        throw new IOException(noteJson.getName().toString() + " not found");
    }

    FileContent content = noteJson.getContent();
    InputStream ins = content.getInputStream();
    String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING));
    ins.close();

    return Note.fromJson(json);
}

From source file:org.apache.zeppelin.notebook.repo.OldVFSNotebookRepo.java

@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
    LOG.info("Saving note:" + note.getId());
    String json = note.toJson();/*from   ww w .  j av a2  s  .c o  m*/

    FileObject rootDir = getRootDir();

    FileObject noteDir = rootDir.resolveFile(note.getId(), NameScope.CHILD);

    if (!noteDir.exists()) {
        noteDir.createFolder();
    }
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }

    FileObject noteJson = noteDir.resolveFile(".note.json", NameScope.CHILD);
    // false means not appending. creates file if not exists
    OutputStream out = noteJson.getContent().getOutputStream(false);
    out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
    out.close();
    noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}

From source file:org.apache.zeppelin.notebook.repo.VFSNotebookRepo.java

private Note getNote(FileObject noteDir) throws IOException {
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }//from  w ww. j  a  va2s . c om

    FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
    if (!noteJson.exists()) {
        throw new IOException(noteJson.getName().toString() + " not found");
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.create();

    FileContent content = noteJson.getContent();
    InputStream ins = content.getInputStream();
    String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING));
    ins.close();

    Note note = gson.fromJson(json, Note.class);
    //    note.setReplLoader(replLoader);
    //    note.jobListenerFactory = jobListenerFactory;

    for (Paragraph p : note.getParagraphs()) {
        if (p.getStatus() == Status.PENDING || p.getStatus() == Status.RUNNING) {
            p.setStatus(Status.ABORT);
        }
    }

    return note;
}

From source file:org.apache.zeppelin.notebook.repo.VFSNotebookRepo.java

@Override
public void save(Note note) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();// w w w .  j  a  v a  2s.c  om
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(note);

    FileObject rootDir = getRootDir();

    FileObject noteDir = rootDir.resolveFile(note.id(), NameScope.CHILD);

    if (!noteDir.exists()) {
        noteDir.createFolder();
    }
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }

    FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
    // false means not appending. creates file if not exists
    OutputStream out = noteJson.getContent().getOutputStream(false);
    out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
    out.close();
}

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

private void archiveFile(final FileObject baseFolder, final FileObject file) throws IOException {
    archive.write(relativeNameOf(baseFolder, file), file.getContent());
}

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

private OutputStream streamFor(final FileObject file) throws FileSystemException {
    return file.getContent().getOutputStream();
}