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:org.datacleaner.util.VFSUtilsTest.java

public void test1VfsAssumptions() throws Exception {
    FileSystemManager manager = VFS.getManager();

    FileObject baseFile = manager.getBaseFile();
    assertTrue(baseFile == null || "core".equals(baseFile.getName().getBaseName()));

    File file = new File("src/main/java");
    assertNotNull(manager.resolveFile(file.getAbsolutePath()));

    ((DefaultFileSystemManager) manager).setBaseFile(new File("."));

    baseFile = manager.getBaseFile();//from w  ww  .ja  v a2  s .c o m

    assertEquals("core", baseFile.getName().getBaseName());

    FileObject javaFolder = manager.resolveFile("src/main/java");
    assertTrue(javaFolder.getType() == FileType.FOLDER);

    FileObject rootFolder = manager.resolveFile(".");
    assertTrue(rootFolder.getType() == FileType.FOLDER);
    assertEquals("core", rootFolder.getName().getBaseName());

    File javaFolderFile = VFSUtils.toFile(javaFolder);
    assertNotNull(javaFolderFile);
    assertTrue(javaFolderFile.exists());
    assertTrue(javaFolderFile.isDirectory());
}

From source file:org.datacleaner.widgets.OpenAnalysisJobMenuItem.java

public OpenAnalysisJobMenuItem(final FileObject file,
        final OpenAnalysisJobActionListener openAnalysisJobActionListener) {
    super();//w  w  w.ja  va  2s . c o  m
    _file = file;
    _openAnalysisJobActionListener = openAnalysisJobActionListener;

    final String title;
    final String filename = file.getName().getBaseName();
    final String jobExtension = FileFilters.ANALYSIS_XML.getExtension();
    final String resultExtension = FileFilters.ANALYSIS_RESULT_SER.getExtension();

    if (filename.toLowerCase().endsWith(jobExtension)) {
        title = filename.substring(0, filename.length() - jobExtension.length());
        setIcon(ICON_JOB);
    } else if (filename.toLowerCase().endsWith(resultExtension)) {
        title = filename.substring(0, filename.length() - resultExtension.length());
        setIcon(ICON_RESULT);
    } else {
        title = filename;
        setIcon(ICON_FILE);
    }

    setText(title);

    addActionListener(this);
}

From source file:org.eobjects.datacleaner.actions.DownloadFilesActionListener.java

@Override
protected FileObject[] doInBackground() throws Exception {
    for (int i = 0; i < _urls.length; i++) {
        final String url = _urls[i];
        final FileObject file = _files[i];

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {//from  w ww.j  ava 2 s.c  o  m
            byte[] buffer = new byte[1024];

            final HttpGet method = new HttpGet(url);

            if (!_cancelled) {
                final HttpResponse response = _httpClient.execute(method);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new InvalidHttpResponseException(url, response);
                }

                final HttpEntity responseEntity = response.getEntity();
                final long expectedSize = responseEntity.getContentLength();
                if (expectedSize > 0) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize);
                        }
                    });
                }

                inputStream = responseEntity.getContent();

                if (!file.exists()) {
                    file.createFile();
                }
                outputStream = file.getContent().getOutputStream();

                long bytes = 0;
                for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream
                        .read(buffer)) {
                    if (_cancelled) {
                        break;
                    }
                    outputStream.write(buffer, 0, numBytes);
                    bytes += numBytes;

                    final long totalBytes = bytes;
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes);
                        }
                    });
                }

                if (!_cancelled) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setFinished(file.getName().getBaseName());
                        }
                    });
                }
            }
        } catch (IOException e) {
            logger.debug("IOException occurred while downloading files", e);
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not close input stream: " + e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not flush & close output stream: " + e.getMessage(), e);
                }
            }
        }

        if (_cancelled) {
            logger.info("Deleting non-finished download-file '{}'", file);
            file.delete();
        }
    }

    return _files;
}

From source file:org.eobjects.datacleaner.actions.OpenAnalysisJobActionListener.java

public void openFile(FileObject file) {
    if (file.getName().getBaseName().endsWith(FileFilters.ANALYSIS_RESULT_SER.getExtension())) {
        openAnalysisResult(file, _parentModule);
    } else {/* w w  w  . ja  v  a 2 s  .c om*/
        Injector injector = openAnalysisJob(file);
        final AnalysisJobBuilderWindow window = injector.getInstance(AnalysisJobBuilderWindow.class);
        window.open();

        if (_parentWindow != null && !_parentWindow.isDatastoreSet()) {
            _parentWindow.close();
        }
    }
}

From source file:org.eobjects.datacleaner.actions.SaveAnalysisJobActionListener.java

@Override
public void actionPerformed(ActionEvent event) {
    final String actionCommand = event.getActionCommand();

    _window.setStatusLabelNotice();//from   ww w.  j ava  2  s.co  m
    _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB);

    AnalysisJob analysisJob = null;
    try {
        _window.applyPropertyValues();
        analysisJob = _analysisJobBuilder.toAnalysisJob();
    } catch (Exception e) {
        if ("No Analyzers in job".equals(e.getMessage())) {
            // TODO: Have a better way to diagnose this issue
            int result = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "You job does not have any analyzer components in it, and is thus 'incomplete'. Do you want to save it anyway?",
                    "No analyzers in job", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (result == JOptionPane.YES_OPTION) {
                analysisJob = _analysisJobBuilder.toAnalysisJob(false);
            } else {
                return;
            }
        } else {
            String detail = _window.getStatusLabelText();
            if (LABEL_TEXT_SAVING_JOB.equals(detail)) {
                detail = e.getMessage();
            }
            WidgetUtils.showErrorMessage("Errors in job",
                    "Please fix the errors that exist in the job before saving it:\n\n" + detail, e);
            return;
        }
    }

    final FileObject existingFile = _window.getJobFile();

    final FileObject file;
    if (existingFile == null || ACTION_COMMAND_SAVE_AS.equals(actionCommand)) {
        // ask the user to select a file to save to ("Save as" scenario)
        final DCFileChooser fileChooser = new DCFileChooser(_userPreferences.getAnalysisJobDirectory());
        fileChooser.setFileFilter(FileFilters.ANALYSIS_XML);

        final int result = fileChooser.showSaveDialog(_window.toComponent());
        if (result != JFileChooser.APPROVE_OPTION) {
            return;
        }
        FileObject candidate = fileChooser.getSelectedFileObject();

        final boolean exists;
        try {
            final String baseName = candidate.getName().getBaseName();
            if (!baseName.endsWith(".xml")) {
                final FileObject parent = candidate.getParent();
                file = parent.resolveFile(baseName + FileFilters.ANALYSIS_XML.getExtension());
            } else {
                file = candidate;
            }
            exists = file.exists();
        } catch (FileSystemException e) {
            throw new IllegalStateException("Failed to prepare file for saving", e);
        }

        if (exists) {
            int overwrite = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "Are you sure you want to overwrite the file '" + file.getName() + "'?",
                    "Overwrite existing file?", JOptionPane.YES_NO_OPTION);
            if (overwrite != JOptionPane.YES_OPTION) {
                return;
            }
        }
    } else {
        // overwrite existing file ("Save" scenario).
        file = existingFile;
    }

    try {
        final FileObject parent = file.getParent();
        final File parentFile = VFSUtils.toFile(parent);
        if (parentFile != null) {
            _userPreferences.setAnalysisJobDirectory(parentFile);
        }
    } catch (FileSystemException e) {
        logger.warn("Failed to determine parent of {}: {}", file, e.getMessage());
    }

    final String author = System.getProperty("user.name");
    final String jobName = null;
    final String jobDescription = "Created with DataCleaner " + Version.getEdition() + " "
            + Version.getVersion();
    final String jobVersion = null;

    final JaxbJobWriter writer = new JaxbJobWriter(_configuration,
            new JaxbJobMetadataFactoryImpl(author, jobName, jobDescription, jobVersion));

    OutputStream outputStream = null;
    try {
        outputStream = file.getContent().getOutputStream();
        writer.write(analysisJob, outputStream);
    } catch (IOException e1) {
        throw new IllegalStateException(e1);
    } finally {
        FileHelper.safeClose(outputStream);
    }

    if (file instanceof DelegateFileObject) {
        // this "file" is probably a HTTP URL resource (often provided by DC
        // monitor)
        final DelegateFileObject delegateFileObject = (DelegateFileObject) file;
        final String scheme = file.getName().getScheme();

        if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
            final String uri = delegateFileObject.getName().getURI();
            final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();
            if (monitorConnection.matchesURI(uri) && monitorConnection.isAuthenticationEnabled()
                    && monitorConnection.getEncodedPassword() == null) {
                // password is not configured, ask for it.
                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(_window.getWindowContext(),
                        _userPreferences);
                dialog.openBlocking();
            }

            final PublishJobToMonitorActionListener publisher = new PublishJobToMonitorActionListener(
                    delegateFileObject, _window.getWindowContext(), _userPreferences);
            publisher.actionPerformed(event);
        } else {
            throw new UnsupportedOperationException("Unexpected delegate file object: " + delegateFileObject
                    + " (delegate: " + delegateFileObject.getDelegateFile() + ")");
        }
    } else {
        _userPreferences.addRecentJobFile(file);
    }

    _window.setJobFile(file);

    _window.setStatusLabelNotice();
    _window.setStatusLabelText("Saved job to file " + file.getName().getBaseName());
}

From source file:org.eobjects.datacleaner.panels.OpenAnalysisJobPanel.java

public OpenAnalysisJobPanel(final FileObject file, final AnalyzerBeansConfiguration configuration,
        final OpenAnalysisJobActionListener openAnalysisJobActionListener) {
    super(WidgetUtils.BG_COLOR_LESS_BRIGHT, WidgetUtils.BG_COLOR_LESS_BRIGHT);
    _file = file;/* w w  w.j a v a  2s  . c  o m*/
    _openAnalysisJobActionListener = openAnalysisJobActionListener;

    setLayout(new BorderLayout());
    setBorder(WidgetUtils.BORDER_LIST_ITEM);

    final AnalysisJobMetadata metadata = getMetadata(configuration);
    final String jobName = metadata.getJobName();
    final String jobDescription = metadata.getJobDescription();
    final String datastoreName = metadata.getDatastoreName();

    final boolean isDemoJob = isDemoJob(metadata);

    final DCPanel labelListPanel = new DCPanel();
    labelListPanel.setLayout(new VerticalLayout(4));
    labelListPanel.setBorder(new EmptyBorder(4, 4, 4, 0));

    final String title;
    final String filename = file.getName().getBaseName();
    if (Strings.isNullOrEmpty(jobName)) {
        final String extension = FileFilters.ANALYSIS_XML.getExtension();
        if (filename.toLowerCase().endsWith(extension)) {
            title = filename.substring(0, filename.length() - extension.length());
        } else {
            title = filename;
        }
    } else {
        title = jobName;
    }

    final JButton titleButton = new JButton(title);
    titleButton.setFont(WidgetUtils.FONT_HEADER1);
    titleButton.setForeground(WidgetUtils.BG_COLOR_BLUE_MEDIUM);
    titleButton.setHorizontalAlignment(SwingConstants.LEFT);
    titleButton.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, WidgetUtils.BG_COLOR_MEDIUM));
    titleButton.setToolTipText("Open job");
    titleButton.setOpaque(false);
    titleButton.setMargin(new Insets(0, 0, 0, 0));
    titleButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    titleButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (isDemoDatastoreConfigured(datastoreName, configuration)) {
                _openAnalysisJobActionListener.openFile(_file);
            }
        }
    });

    final JButton executeButton = new JButton(executeIcon);
    executeButton.setOpaque(false);
    executeButton.setToolTipText("Execute job directly");
    executeButton.setMargin(new Insets(0, 0, 0, 0));
    executeButton.setBorderPainted(false);
    executeButton.setHorizontalAlignment(SwingConstants.RIGHT);
    executeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (isDemoDatastoreConfigured(datastoreName, configuration)) {
                final ImageIcon executeIconLarge = ImageManager.get().getImageIcon(IconUtils.ACTION_EXECUTE);
                final String question = "Are you sure you want to execute the job\n'" + title + "'?";
                final int choice = JOptionPane.showConfirmDialog(null, question, "Execute job?",
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, executeIconLarge);
                if (choice == JOptionPane.YES_OPTION) {
                    final Injector injector = _openAnalysisJobActionListener.openAnalysisJob(_file);
                    if (injector != null) {
                        final ResultWindow resultWindow = injector.getInstance(ResultWindow.class);
                        resultWindow.open();
                        resultWindow.startAnalysis();
                    }
                }
            }
        }
    });

    final DCPanel titlePanel = new DCPanel();
    titlePanel.setLayout(new BorderLayout());
    titlePanel.add(DCPanel.around(titleButton), BorderLayout.CENTER);
    titlePanel.add(executeButton, BorderLayout.EAST);

    labelListPanel.add(titlePanel);

    if (!Strings.isNullOrEmpty(jobDescription)) {
        String desc = StringUtils.replaceWhitespaces(jobDescription, " ");
        desc = StringUtils.replaceAll(desc, "  ", " ");
        final JLabel label = new JLabel(desc);
        label.setFont(WidgetUtils.FONT_SMALL);
        labelListPanel.add(label);
    }

    final Icon icon;
    {
        if (!StringUtils.isNullOrEmpty(datastoreName)) {
            final JLabel label = new JLabel(" " + datastoreName);
            label.setFont(WidgetUtils.FONT_SMALL);
            labelListPanel.add(label);

            final Datastore datastore = configuration.getDatastoreCatalog().getDatastore(datastoreName);
            if (isDemoJob) {
                icon = demoBadgeIcon;
            } else {
                icon = IconUtils.getDatastoreSpecificAnalysisJobIcon(datastore);
            }
        } else {
            icon = ImageManager.get().getImageIcon(IconUtils.MODEL_JOB, IconUtils.ICON_SIZE_LARGE);
        }
    }

    final JLabel iconLabel = new JLabel(icon);
    iconLabel.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));

    add(iconLabel, BorderLayout.WEST);
    add(labelListPanel, BorderLayout.CENTER);
}

From source file:org.eobjects.datacleaner.user.DataCleanerConfigurationReaderInterceptor.java

@Override
public String createFilename(String filename) {
    if (filename == null) {
        return null;
    }/*from   ww  w . ja va  2  s. c  o  m*/

    final File file = new File(filename);
    if (file.isAbsolute()) {
        return filename;
    }

    try {
        FileObject fileObject = _dataCleanerHome.resolveFile(filename);
        return fileObject.getName().getPathDecoded();
    } catch (FileSystemException e) {
        logger.warn("Could not resolve absolute path using VFS: " + filename, e);
        return filename;
    }
}

From source file:org.eobjects.datacleaner.widgets.OpenAnalysisJobMenuItem.java

public OpenAnalysisJobMenuItem(final FileObject file,
        final OpenAnalysisJobActionListener openAnalysisJobActionListener) {
    super(icon);// ww w  .  java 2s. co  m
    _file = file;
    _openAnalysisJobActionListener = openAnalysisJobActionListener;

    final String title;
    final String filename = file.getName().getBaseName();
    final String extension = FileFilters.ANALYSIS_XML.getExtension();
    if (filename.toLowerCase().endsWith(extension)) {
        title = filename.substring(0, filename.length() - extension.length());
    } else {
        title = filename;
    }

    setText(title);

    addActionListener(this);
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

private boolean isFileHidden(FileObject file) {
    boolean isHidden = false;
    // file.isHidden() works in current version of VFS (1.0) only for local file object :(
    if (file instanceof LocalFile) {
        try {/*from  w ww. j a va  2 s.com*/
            isHidden = file.isHidden();
        } catch (FileSystemException e) {
            log.warn("Error on file.isHidden() method ...", e);
        }
    } else {
        // at the moment here we just check if the file begins with a dot 
        // ... so it works just for unix files ...
        isHidden = file.getName().getBaseName().startsWith(".");
    }
    return isHidden;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

private JsTreeFile resourceAsJsTreeFile(FileObject resource, boolean folderDetails, boolean fileDetails,
        boolean showHiddenFiles) throws FileSystemException {
    String lid = resource.getName().getPath();
    String rootPath = this.root.getName().getPath();
    // lid must be a relative path from rootPath
    if (lid.startsWith(rootPath))
        lid = lid.substring(rootPath.length());
    if (lid.startsWith("/"))
        lid = lid.substring(1);//from ww  w  .j  av  a 2  s.  com

    String title = "";
    String type = "drive";
    if (!"".equals(lid)) {
        type = resource.getType().getName();
        title = resource.getName().getBaseName();
    }
    JsTreeFile file = new JsTreeFile(title, lid, type);

    file.setHidden(this.isFileHidden(resource));

    if ("file".equals(type)) {
        String icon = resourceUtils.getIcon(title);
        file.setIcon(icon);
        file.setSize(resource.getContent().getSize());
        file.setOverSizeLimit(file.getSize() > resourceUtils.getSizeLimit(title));
    }

    try {
        if (folderDetails && ("folder".equals(type) || "drive".equals(type))) {
            if (resource.getChildren() != null) {
                long totalSize = 0;
                long fileCount = 0;
                long folderCount = 0;
                for (FileObject child : resource.getChildren()) {
                    if (showHiddenFiles || !this.isFileHidden(child)) {
                        if ("folder".equals(child.getType().getName())) {
                            ++folderCount;
                        } else if ("file".equals(child.getType().getName())) {
                            ++fileCount;
                            totalSize += child.getContent().getSize();
                        }
                    }
                }
                file.setTotalSize(totalSize);
                file.setFileCount(fileCount);
                file.setFolderCount(folderCount);
            }
        }

        final Calendar date = Calendar.getInstance();
        date.setTimeInMillis(resource.getContent().getLastModifiedTime());
        // In order to have a readable date
        file.setLastModifiedTime(new SimpleDateFormat(this.datePattern).format(date.getTime()));

        file.setReadable(resource.isReadable());
        file.setWriteable(resource.isWriteable());

    } catch (FileSystemException fse) {
        // we don't want that exception during retrieving details 
        // of the folder breaks  all this method ...
        log.error("Exception during retrieveing details on " + lid
                + " ... maybe broken symbolic links or whatever ...", fse);
    }

    return file;
}