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

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

Introduction

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

Prototype

long getSize() throws FileSystemException;

Source Link

Document

Determines the size of the file, in bytes.

Usage

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  ww w  .j a  v  a 2 s  .  c o m*/
    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;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java

/**
 * Actual processing of the file/folder//from w  ww  .j a  v a2s .c  o m
 * 
 * @param file
 * @return
 * @throws synapseException
 */
private FileObject processFile(FileObject file) throws SynapseException {
    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        if (injectHandler != null) {
            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 e) {
                log.warn("Unable to set file length or last modified date header.", e);
            }

            injectHandler.setTransportHeaders(transportHeaders);
            // injectHandler
            if (!injectHandler.invoke(file, name)) {
                return null;
            }
        }

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

From source file:org.wso2.carbon.transport.file.connector.server.FileConsumer.java

/**
 * Actual processing of the file/folder//from w  ww.ja v  a  2s .  c  om
 *
 * @param file
 * @return
 */
private FileObject processFile(FileObject file) throws FileServerConnectorException {
    FileContent content;
    String fileURI;

    String fileName = file.getName().getBaseName();
    String filePath = file.getName().getPath();
    fileURI = file.getName().getURI();

    try {
        content = file.getContent();
    } catch (FileSystemException e) {
        throw new FileServerConnectorException(
                "Could not read content of file at URI: " + FileTransportUtils.maskURLPassword(fileURI) + ". ",
                e);
    }

    InputStream inputStream;
    try {
        inputStream = content.getInputStream();
    } catch (FileSystemException e) {
        throw new FileServerConnectorException("Error occurred when trying to get "
                + "input stream from file at URI :" + FileTransportUtils.maskURLPassword(fileURI), e);
    }
    CarbonMessage cMessage = new StreamingCarbonMessage(inputStream);
    cMessage.setProperty(org.wso2.carbon.messaging.Constants.PROTOCOL, Constants.PROTOCOL_NAME);
    cMessage.setProperty(Constants.FILE_TRANSPORT_PROPERTY_SERVICE_NAME, serviceName);
    cMessage.setHeader(Constants.FILE_PATH, filePath);
    cMessage.setHeader(Constants.FILE_NAME, fileName);
    cMessage.setHeader(Constants.FILE_URI, fileURI);
    try {
        cMessage.setHeader(Constants.FILE_LENGTH, Long.toString(content.getSize()));
        cMessage.setHeader(Constants.LAST_MODIFIED, Long.toString(content.getLastModifiedTime()));
    } catch (FileSystemException e) {
        log.warn("Unable to set file length or last modified date header.", e);
    }

    FileServerConnectorCallback callback = new FileServerConnectorCallback();
    try {
        messageProcessor.receive(cMessage, callback);
    } catch (Exception e) {
        throw new FileServerConnectorException("Failed to send stream from file: "
                + FileTransportUtils.maskURLPassword(fileURI) + " to message processor. ", e);
    }
    try {
        callback.waitTillDone(timeOutInterval, deleteIfNotAck, fileURI);
    } catch (InterruptedException e) {
        throw new FileServerConnectorException("Interrupted while waiting for message "
                + "processor to consume the file input stream. Aborting processing of file: "
                + FileTransportUtils.maskURLPassword(fileURI), e);
    }
    return file;
}

From source file:pl.otros.logview.api.io.Utils.java

public static LoadingInfo openFileObject(FileObject fileObject, boolean tailing) throws Exception {
    LoadingInfo loadingInfo = new LoadingInfo();
    loadingInfo.setFileObject(fileObject);
    loadingInfo.setFriendlyUrl(fileObject.getName().getFriendlyURI());

    final FileContent content = fileObject.getContent();
    InputStream httpInputStream = content.getInputStream();
    byte[] buff = Utils.loadProbe(httpInputStream, 10000);

    loadingInfo.setGziped(checkIfIsGzipped(buff, buff.length));

    ByteArrayInputStream bin = new ByteArrayInputStream(buff);

    SequenceInputStream sequenceInputStream = new SequenceInputStream(bin, httpInputStream);

    ObservableInputStreamImpl observableInputStreamImpl = new ObservableInputStreamImpl(sequenceInputStream);

    if (loadingInfo.isGziped()) {
        loadingInfo.setContentInputStream(new GZIPInputStream(observableInputStreamImpl));
        loadingInfo.setInputStreamBufferedStart(ungzip(buff));
    } else {/*w  w  w.j  a  va  2s . c  om*/
        loadingInfo.setContentInputStream(observableInputStreamImpl);
        loadingInfo.setInputStreamBufferedStart(buff);
    }
    loadingInfo.setObserableInputStreamImpl(observableInputStreamImpl);

    loadingInfo.setTailing(tailing);
    if (fileObject.getType().hasContent()) {
        loadingInfo.setLastFileSize(content.getSize());
    }
    return loadingInfo;

}

From source file:tain.kr.test.vfs.v01.Shell.java

/**
 * Does an 'ls' command./*from  w w  w  .  ja v  a  2s  .c  om*/
 */
private 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;
    }

    if (file.getType() == FileType.FOLDER) {
        // List the contents
        System.out.println("Contents of " + file.getName());
        listChildren(file, recursive, "");
    } else {
        // 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);
    }
}

From source file:tain.kr.test.vfs.v01.TestVfs2FilehandleService.java

@Test
public void testAccessFile() throws Exception {

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(this.absoluteFilePath);
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    //   /*from   w  w w  .  j a  v  a  2 s . co m*/
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());

    //  
    file.createFile();
    assertTrue(file.exists());

    FileContent fileContent = file.getContent();
    assertEquals(0, fileContent.getSize());

    //  
    String string = "test.";
    OutputStream os = fileContent.getOutputStream();

    try {
        os.write(string.getBytes());
        os.flush();
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }
    assertNotSame(0, fileContent.getSize());

    //  
    StringBuffer sb = new StringBuffer();
    FileObject writtenFile = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileContent writtenContents = writtenFile.getContent();
    InputStream is = writtenContents.getInputStream();

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }

    //  
    assertEquals(sb.toString(), string);
}