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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:pl.otros.logview.gui.actions.TailMultipleFilesIntoOneView.java

public void openFileObjectsIntoOneView(FileObject[] files, Object guiSource) {
    ArrayList<LoadingInfo> list = new ArrayList<LoadingInfo>();
    for (final FileObject file : files) {
        try {/*from  w w  w  .  j  a v a 2 s  .c o m*/
            list.add(Utils.openFileObject(file, true));
        } catch (Exception e1) {
            LOGGER.warning(
                    String.format("Can't open file %s: %s", file.getName().getFriendlyURI(), e1.getMessage()));
        }
    }

    if (list.size() == 0) {
        JOptionPane.showMessageDialog((Component) guiSource, "No files can be opened :(", "Open error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    LoadingInfo[] loadingInfos = new LoadingInfo[list.size()];
    loadingInfos = list.toArray(loadingInfos);

    Collection<LogImporter> elements = AllPluginables.getInstance().getLogImportersContainer().getElements();
    LogImporter[] importers = elements.toArray(new LogImporter[0]);
    String[] names = new String[elements.size()];
    for (int i = 0; i < names.length; i++) {
        names[i] = importers[i].getName();
    }

    TableColumns[] visibleColumns = new TableColumns[] { TableColumns.ID, //
            TableColumns.TIME, //
            TableColumns.LEVEL, //
            TableColumns.MESSAGE, //
            TableColumns.CLASS, //
            TableColumns.METHOD, //
            TableColumns.THREAD, //
            TableColumns.MARK, //
            TableColumns.NOTE, //
            TableColumns.LOG_SOURCE

    };
    final LogViewPanelWrapper logViewPanelWrapper = new LogViewPanelWrapper(
            "Multiple log files " + loadingInfos.length, null, visibleColumns, getOtrosApplication());

    logViewPanelWrapper.goToLiveMode();
    BaseConfiguration configuration = new BaseConfiguration();
    configuration.addProperty(ConfKeys.TAILING_PANEL_PLAY, true);
    configuration.addProperty(ConfKeys.TAILING_PANEL_FOLLOW, true);
    BufferingLogDataCollectorProxy logDataCollector = new BufferingLogDataCollectorProxy(
            logViewPanelWrapper.getDataTableModel(), 4000, configuration);

    StringBuilder sb = new StringBuilder();
    sb.append("<html>Multiple files:<br>");
    for (LoadingInfo loadingInfo : loadingInfos) {
        sb.append(loadingInfo.getFriendlyUrl());
        sb.append("<BR>");
    }
    sb.append("</html>");

    getOtrosApplication().addClosableTab(String.format("Multiple logs [%d]", loadingInfos.length),
            sb.toString(), Icons.ARROW_REPEAT, logViewPanelWrapper, true);

    LogImporter importer = new DetectOnTheFlyLogImporter(elements);
    try {
        importer.init(new Properties());
    } catch (InitializationException e1) {
        LOGGER.severe("Cant initialize DetectOnTheFlyLogImporter: " + e1.getMessage());
        JOptionPane.showMessageDialog((Component) guiSource,
                "Cant initialize DetectOnTheFlyLogImporter: " + e1.getMessage(), "Open error",
                JOptionPane.ERROR_MESSAGE);

    }
    for (LoadingInfo loadingInfo : loadingInfos) {
        TailLogActionListener tailLogActionListener = new TailLogActionListener(getOtrosApplication(),
                importer);
        tailLogActionListener.openFileObjectInTailMode(logViewPanelWrapper, loadingInfo, logDataCollector);
        ParsingContext parsingContext = new ParsingContext(
                loadingInfo.getFileObject().getName().getFriendlyURI(),
                loadingInfo.getFileObject().getName().getBaseName());
        logViewPanelWrapper
                .addHierarchyListener(new ReadingStopperForRemove(loadingInfo.getObserableInputStreamImpl(),
                        logDataCollector, new ParsingContextStopperForClosingTab(parsingContext)));
    }

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            logViewPanelWrapper.switchToContentView();
        }
    });
}

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 a  v a 2 s  . co  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 {/*from  w  w  w  .  j  a v  a2  s . c  o  m*/
        loadingInfo.setContentInputStream(observableInputStreamImpl);
        loadingInfo.setInputStreamBufferedStart(buff);
    }
    loadingInfo.setObserableInputStreamImpl(observableInputStreamImpl);

    loadingInfo.setTailing(tailing);

    return loadingInfo;

}

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

public static void closeQuietly(FileObject fileObject) {

    if (fileObject != null) {
        String friendlyURI = fileObject.getName().getFriendlyURI();
        try {/*from w  ww .j  av  a  2s.c  o  m*/
            LOGGER.info(String.format("Closing file %s", friendlyURI));
            fileObject.close();
            LOGGER.info(String.format("File %s closed", friendlyURI));
        } catch (FileSystemException ignore) {
            LOGGER.info(String.format("File %s is not closed: %s", friendlyURI, ignore.getMessage()));
        }
    }
}

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

/**
 * Get short name for URL//from w ww  .ja v  a  2 s.  com
 * 
 * @param fileObject
 * @return scheme://hostWithoutDomain/fileBaseName
 */
public static String getFileObjectShortName(FileObject fileObject) {
    StringBuilder sb = new StringBuilder();
    try {
        URI uri = new URI(fileObject.getName().getURI());
        String scheme = fileObject.getName().getScheme();
        sb.append(scheme);
        sb.append("://");
        if (!"file".equals(scheme)) {
            String host = uri.getHost();
            // if host name is not IP, return only host name
            if (!Pattern.matches("(\\d+\\.){3}\\d+", host)) {
                host = host.split("\\.")[0];
            }
            sb.append(host).append('/');
        }
        sb.append(fileObject.getName().getBaseName());
    } catch (URISyntaxException e) {
        LOGGER.warning("Problem with preparing short name of FileObject: " + e.getMessage());
        sb.setLength(0);
        sb.append(fileObject.getName().getScheme()).append("://").append(fileObject.getName().getBaseName());
    }
    return sb.toString();
}

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

@Test(enabled = false)
private void testGetObjectShortName(String scheme, String url, String baseName, String output) {
    // given/*  w w  w  .ja v a2  s. co m*/
    FileObject fileObjectMock = mock(FileObject.class);
    FileName fileNameMock = mock(FileName.class);

    when(fileObjectMock.getName()).thenReturn(fileNameMock);
    when(fileNameMock.getScheme()).thenReturn(scheme);
    when(fileNameMock.getURI()).thenReturn(url);
    when(fileNameMock.getBaseName()).thenReturn(baseName);

    // when
    String fileObjectShortName = Utils.getFileObjectShortName(fileObjectMock);

    // then
    AssertJUnit.assertEquals(output, fileObjectShortName);
}

From source file:pl.otros.logview.pluginsimpl.OpenLogsSwingWorker.java

private LoadingInfo[] getLoadingInfo() {
    ArrayList<LoadingInfo> list = new ArrayList<LoadingInfo>();
    publish("Opening  log files");
    for (final FileObject file : fileObjects) {
        try {/*ww w .j a  v a  2  s  . com*/
            list.add(Utils.openFileObject(file, true));
        } catch (Exception e1) {
            String msg = String.format("Can't open file %s: %s", file.getName().getFriendlyURI(),
                    e1.getMessage());
            publish(msg);
            LOGGER.warning(msg);
        }
    }
    LoadingInfo[] loadingInfos = new LoadingInfo[list.size()];
    loadingInfos = list.toArray(loadingInfos);
    return loadingInfos;
}

From source file:pl.otros.logview.pluginsimpl.OpenLogsSwingWorker.java

private String getTooltip() {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>Multiple files:<br>");
    for (FileObject fo : fileObjects) {
        sb.append(fo.getName().getFriendlyURI());
        sb.append("<BR>");
    }//from ww w.  ja va2s .  c  o m
    sb.append("</html>");
    return sb.toString();
}

From source file:pl.otros.vfs.browser.actions.AddCurrentLocationToFavoriteAction.java

@Override
public void actionPerformed(ActionEvent e) {
    FileObject currentLocation = vfsBrowser.getCurrentLocation();
    if (currentLocation != null) {

        String name = currentLocation.getName().getBaseName();
        if (remoteSchemas.contains(currentLocation.getName().getScheme())) {
            try {
                URI uri = new URI(currentLocation.getName().getURI());
                name = uri.getHost() + "/" + name;
            } catch (URISyntaxException e1) {
                e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }/*from w  ww . j a  v a2s  . c o m*/

        }
        Favorite favorite;
        try {
            favorite = new Favorite(name, currentLocation.getURL().toExternalForm(), Favorite.Type.USER);
            vfsBrowser.getFavoritesUserListModel().add(favorite);
        } catch (FileSystemException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

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/*from  w  ww.  ja v a 2 s .co  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);

        }
    });
}