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:pl.otros.logview.api.io.UtilsTest.java

@Test
public void testEmptyGzipedFile() throws IOException {
    FileObject resolveFile = resolveFileObject("/empty.log.gz");
    AssertJUnit.assertEquals(26, resolveFile.getContent().getSize());
    boolean checkIfIsGzipped = Utils.checkIfIsGzipped(resolveFile);
    AssertJUnit.assertTrue(checkIfIsGzipped);
}

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

@Test
public void testLoadLocalNotGzipped() throws Exception {
    FileObject fileObject = resolveFileObject("/hierarchy/hierarchy.log");
    LoadingInfo loadingInfo = Utils.openFileObject(fileObject);
    InputStream contentInputStream = loadingInfo.getContentInputStream();
    byte[] actual = IOUtils.toByteArray(contentInputStream);
    byte[] expected = IOUtils.toByteArray(fileObject.getContent().getInputStream());

    AssertJUnit.assertFalse(loadingInfo.isGziped());
    AssertJUnit.assertEquals(expected.length, actual.length);
    // assertArrayEquals(expected, actual);
}

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

@Test
public void testLoadLocalGzipped() throws Exception {
    FileObject fileObject = resolveFileObject("/hierarchy/hierarchy.log.gz");
    LoadingInfo loadingInfo = Utils.openFileObject(fileObject);
    InputStream contentInputStream = loadingInfo.getContentInputStream();
    byte[] actual = IOUtils.toByteArray(contentInputStream);
    byte[] expected = IOUtils.toByteArray(new GZIPInputStream(fileObject.getContent().getInputStream()));

    AssertJUnit.assertTrue(loadingInfo.isGziped());
    AssertJUnit.assertArrayEquals(expected, actual);

}

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

@Test
public void testSequeceRead() throws Exception {
    String url = HTTP_NOT_GZIPPED;
    FileObject resolveFile = fsManager.resolveFile(url);
    InputStream httpInputStream = resolveFile.getContent().getInputStream();
    byte[] buff = Utils.loadProbe(httpInputStream, 10000);
    // int read = httpInputStream.read(buff);

    ByteArrayInputStream bin = new ByteArrayInputStream(buff);

    SequenceInputStream sequenceInputStream = new SequenceInputStream(bin, httpInputStream);

    byte[] byteArray = IOUtils.toByteArray(new ObservableInputStreamImpl(sequenceInputStream));

    LoadingInfo loadingInfo = Utils.openFileObject(fsManager.resolveFile(url), false);
    byte[] byteArrayUtils = IOUtils.toByteArray(loadingInfo.getContentInputStream());
    AssertJUnit.assertEquals(byteArrayUtils.length, byteArray.length);
}

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

@Test
public void testSequeceReadGzipped() throws Exception {
    String url = HTTP_GZIPPED;//from   w ww  .j a  v a 2 s . c  om
    FileObject resolveFile = fsManager.resolveFile(url);
    InputStream httpInputStream = resolveFile.getContent().getInputStream();
    byte[] buff = Utils.loadProbe(httpInputStream, 10000);
    // int read = httpInputStream.read(buff);

    ByteArrayInputStream bin = new ByteArrayInputStream(buff);

    SequenceInputStream sequenceInputStream = new SequenceInputStream(bin, httpInputStream);

    byte[] byteArray = IOUtils
            .toByteArray(new GZIPInputStream(new ObservableInputStreamImpl(sequenceInputStream)));

    LoadingInfo loadingInfo = Utils.openFileObject(fsManager.resolveFile(url), false);
    byte[] byteArrayUtils = IOUtils.toByteArray(loadingInfo.getContentInputStream());
    AssertJUnit.assertEquals(byteArrayUtils.length, byteArray.length);
}

From source file:pl.otros.logview.gui.Log4jPatternParserEditor.java

protected void loadLogContent(FileObject fileObject) throws IOException {
    try {/*from ww  w.  j av  a  2s  . c  o m*/
        byte[] loadProbe = Utils.loadProbe(fileObject.getContent().getInputStream(), 50 * 1024);
        logFileContent.setText(new String(loadProbe));
        logFileContent.setCaretPosition(0);
    } finally {
        Utils.closeQuietly(fileObject);
    }
}

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

public static boolean checkIfIsGzipped(FileObject fileObject) throws IOException {
    boolean gziped = false;
    if (fileObject.getContent().getSize() == 0) {
        LOGGER.fine("File object " + fileObject.getName() + " is empty, can't detect gzip compression");
        return false;
    }/*from  w w  w .j  av  a  2 s.c  o m*/
    InputStream inputStream = fileObject.getContent().getInputStream();
    byte[] loadProbe = loadProbe(inputStream, GZIP_CHECK_BUFFER_SIZE);
    // IOUtils.closeQuietly(inputStream);
    if (loadProbe.length < GZIP_MIN_SIZE) {
        LOGGER.info("Loaded probe is too small to check if it is gziped");
        return false;
    }
    try {
        ByteArrayInputStream bin = new ByteArrayInputStream(loadProbe);
        int available = bin.available();
        byte[] b = new byte[available < GZIP_CHECK_BUFFER_SIZE ? available : GZIP_CHECK_BUFFER_SIZE];
        int read = bin.read(b);
        gziped = checkIfIsGzipped(b, read);
    } catch (IOException e) {
        // Not gziped
        LOGGER.fine(fileObject.getName() + " is not gzip");
    }

    return gziped;
}

From source file:pl.otros.logview.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());

    InputStream httpInputStream = fileObject.getContent().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  av  a  2 s . c o  m
        loadingInfo.setContentInputStream(observableInputStreamImpl);
        loadingInfo.setInputStreamBufferedStart(buff);
    }
    loadingInfo.setObserableInputStreamImpl(observableInputStreamImpl);

    loadingInfo.setTailing(tailing);

    return loadingInfo;

}

From source file:pl.otros.vfs.browser.demo.TestBrowser.java

public static void main(final String[] args)
        throws InterruptedException, InvocationTargetException, SecurityException, IOException {
    if (args.length > 1)
        throw new IllegalArgumentException(
                "SYNTAX:  java... " + TestBrowser.class.getName() + " [initialPath]");

    SwingUtilities.invokeAndWait(new Runnable() {

        @Override/* w ww.  j  a v  a  2  s  .c  o m*/
        public void run() {
            tryLoadSubstanceLookAndFeel();
            final JFrame f = new JFrame("OtrosVfsBrowser demo");
            Container contentPane = f.getContentPane();
            contentPane.setLayout(new BorderLayout());
            DataConfiguration dc = null;
            final PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
            File favoritesFile = new File("favorites.properties");
            propertiesConfiguration.setFile(favoritesFile);
            if (favoritesFile.exists()) {
                try {
                    propertiesConfiguration.load();
                } catch (ConfigurationException e) {
                    e.printStackTrace();
                }
            }
            dc = new DataConfiguration(propertiesConfiguration);
            propertiesConfiguration.setAutoSave(true);
            final VfsBrowser comp = new VfsBrowser(dc, (args.length > 0) ? args[0] : null);
            comp.setSelectionMode(SelectionMode.FILES_ONLY);
            comp.setMultiSelectionEnabled(true);
            comp.setApproveAction(new AbstractAction(Messages.getMessage("demo.showContentButton")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    FileObject[] selectedFiles = comp.getSelectedFiles();
                    System.out.println("Selected files count=" + selectedFiles.length);
                    for (FileObject selectedFile : selectedFiles) {
                        try {
                            FileSize fileSize = new FileSize(selectedFile.getContent().getSize());
                            System.out.println(selectedFile.getName().getURI() + ": " + fileSize.toString());
                            byte[] bytes = readBytes(selectedFile.getContent().getInputStream(), 150 * 1024l);
                            JScrollPane sp = new JScrollPane(new JTextArea(new String(bytes)));
                            JDialog d = new JDialog(f);
                            d.setTitle("Content of file: " + selectedFile.getName().getFriendlyURI());
                            d.getContentPane().add(sp);
                            d.setSize(600, 400);
                            d.setVisible(true);
                        } catch (Exception e1) {
                            LOGGER.error("Failed to read file", e1);
                            JOptionPane.showMessageDialog(f,
                                    (e1.getMessage() == null) ? e1.toString() : e1.getMessage(), "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            });

            comp.setCancelAction(new AbstractAction(Messages.getMessage("general.cancelButtonText")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    f.dispose();
                    try {
                        propertiesConfiguration.save();
                    } catch (ConfigurationException e1) {
                        e1.printStackTrace();
                    }
                    System.exit(0);
                }
            });
            contentPane.add(comp);

            f.pack();
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        }
    });
}

From source file:pl.otros.vfs.browser.preview.PreviewListener.java

private void makePreview(final FileObject fileObjectToPreview) {
    if (worker != null) {
        worker.cancel(false);/* w w  w  . j av a2  s  .  c om*/
    }
    worker = new SwingWorker<PreviewStatus, PreviewStatus>() {
        private int previewLimit = 20 * 1024;
        private String name = fileObjectToPreview.getName().getBaseName();

        @Override
        protected PreviewStatus doInBackground() throws Exception {
            publish(new PreviewStatus(State.NOT_STARTED, 0, 1, KB, name, EMPTY_BYTE_ARRAY));
            for (int i = 0; i < 5; i++) {
                Thread.sleep(100);
                if (isCancelled()) {
                    return new PreviewStatus(State.CANCELLED, 0, previewLimit / 1024, KB, name,
                            EMPTY_BYTE_ARRAY);
                }
            }
            ByteArrayOutputStream outputStreamRef = null;
            try {
                try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(previewLimit);
                        InputStream inputStream = fileObjectToPreview.getContent().getInputStream()) {
                    outputStreamRef = outputStream;
                    byte[] buff = new byte[512];
                    int read;
                    int max = inputStream.available();
                    max = max == 0 ? previewLimit : Math.min(max, previewLimit);
                    while ((read = inputStream.read(buff)) > 0 && outputStream.size() < previewLimit) {
                        if (isCancelled()) {
                            return new PreviewStatus(State.CANCELLED, 0, max / 1024, KB, name,
                                    EMPTY_BYTE_ARRAY);
                        }
                        outputStream.write(buff, 0, read);
                        publish(new PreviewStatus(State.LOADING, outputStream.size() / 1024, max / 1024, KB,
                                name, outputStream.toByteArray()));
                    }
                }
            } catch (Exception e) {
                LOGGER.error("Exception when downloading preview", e);
                return new PreviewStatus(State.ERROR, outputStreamRef.size() / 1024,
                        outputStreamRef.size() / 1024, KB, name, outputStreamRef.toByteArray());
            }

            return new PreviewStatus(State.FINISHED, outputStreamRef.size() / 1024,
                    outputStreamRef.size() / 1024, KB, name, outputStreamRef.toByteArray());
        }

        @Override
        protected void done() {
            try {
                if (!isCancelled()) {
                    PreviewStatus previewStatus = get();
                    previewComponent.setPreviewStatus(previewStatus);
                }
            } catch (Exception e) {
                LOGGER.error("Exception when getting result of preview downloading", e);
            }
        }

        @Override
        protected void process(List<PreviewStatus> chunks) {
            PreviewStatus previewStatus = chunks.get(chunks.size() - 1);
            previewComponent.setPreviewStatus(previewStatus);
        }
    };
    executor.execute(worker);

}