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:com.googlecode.vfsjfilechooser2.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override/*from ww  w.  j  a v  a2 s. c  o m*/
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectoryObject(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java

/**
 * Search for files that match the given regex pattern and create a list
 * Then process each of these files and update the status of the scan on
 * the poll table//from w  w w .j  ava 2  s  .c o m
 * @param entry the poll table entry for the scan
 * @param fileURI the file or directory to be scanned
 */
private void scanFileOrDirectory(final PollTableEntry entry, String fileURI) {

    FileObject fileObject = null;

    //TODO : Trying to make the correct URL out of the malformed one.
    if (fileURI.contains("vfs:")) {
        fileURI = fileURI.substring(fileURI.indexOf("vfs:") + 4);
    }

    if (log.isDebugEnabled()) {
        log.debug("Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }

    boolean wasError = true;
    int retryCount = 0;
    int maxRetryCount = entry.getMaxRetryCount();
    long reconnectionTimeout = entry.getReconnectTimeout();

    while (wasError) {
        try {
            retryCount++;
            fileObject = fsManager.resolveFile(fileURI);

            if (fileObject == null) {
                log.error("fileObject is null");
                throw new FileSystemException("fileObject is null");
            }

            wasError = false;

        } catch (FileSystemException e) {
            if (retryCount >= maxRetryCount) {
                processFailure(
                        "Repeatedly failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI), e,
                        entry);
                return;
            } else {
                log.warn("Failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI)
                        + ", in attempt " + retryCount + ", " + e.getMessage() + " Retrying in "
                        + reconnectionTimeout + " milliseconds.");
            }
        }

        if (wasError) {
            try {
                Thread.sleep(reconnectionTimeout);
            } catch (InterruptedException e2) {
                log.error("Thread was interrupted while waiting to reconnect.", e2);
            }
        }
    }

    try {
        if (fileObject.exists() && fileObject.isReadable()) {

            entry.setLastPollState(PollTableEntry.NONE);
            FileObject[] children = null;
            try {
                children = fileObject.getChildren();
            } catch (FileNotFolderException ignored) {
            } catch (FileSystemException ex) {
                log.error(ex.getMessage(), ex);
            }

            // if this is a file that would translate to a single message
            if (children == null || children.length == 0) {
                boolean isFailedRecord = false;
                if (entry.getMoveAfterMoveFailure() != null) {
                    isFailedRecord = isFailedRecord(fileObject, entry);
                }

                if (fileObject.getType() == FileType.FILE && !isFailedRecord) {
                    if (!entry.isFileLockingEnabled()
                            || (entry.isFileLockingEnabled() && VFSUtils.acquireLock(fsManager, fileObject))) {
                        try {
                            processFile(entry, fileObject);
                            entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                            metrics.incrementMessagesReceived();

                        } catch (AxisFault e) {
                            logException("Error processing File URI : " + fileObject.getName(), e);
                            entry.setLastPollState(PollTableEntry.FAILED);
                            metrics.incrementFaultsReceiving();
                        }

                        try {
                            moveOrDeleteAfterProcessing(entry, fileObject);
                        } catch (AxisFault axisFault) {
                            logException("File object '" + fileObject.getURL().toString() + "' "
                                    + "cloud not be moved", axisFault);
                            entry.setLastPollState(PollTableEntry.FAILED);
                            String timeStamp = VFSUtils.getSystemTime(entry.getFailedRecordTimestampFormat());
                            addFailedRecord(entry, fileObject, timeStamp);
                        }
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject);
                            if (log.isDebugEnabled()) {
                                log.debug("Removed the lock file '" + fileObject.toString()
                                        + ".lock' of the file '" + fileObject.toString());
                            }
                        }
                    } else if (log.isDebugEnabled()) {
                        log.debug("Couldn't get the lock for processing the file : " + fileObject.getName());
                    } else if (isFailedRecord) {
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject);
                        }
                        // schedule a cleanup task if the file is there
                        if (fsManager.resolveFile(fileObject.getURL().toString()) != null
                                && removeTaskState == STATE_STOPPED
                                && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, fileObject));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + fileObject.getURL() + "' has been marked as a failed"
                                    + " record, it will not process");
                        }
                    }
                }

            } else {
                int failCount = 0;
                int successCount = 0;
                int processCount = 0;
                Integer iFileProcessingInterval = entry.getFileProcessingInterval();
                Integer iFileProcessingCount = entry.getFileProcessingCount();

                if (log.isDebugEnabled()) {
                    log.debug("File name pattern : " + entry.getFileNamePattern());
                }
                for (FileObject child : children) {
                    //skipping *.lock file
                    if (child.getName().getBaseName().endsWith(".lock")) {
                        continue;
                    }
                    boolean isFailedRecord = false;
                    if (entry.getMoveAfterMoveFailure() != null) {
                        isFailedRecord = isFailedRecord(child, entry);
                    }

                    if (entry.getFileNamePattern() != null
                            && child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        //child's file name matches the file name pattern
                        //now we try to get the lock and process
                        if (log.isDebugEnabled()) {
                            log.debug("Matching file : " + child.getName().getBaseName());
                        }

                        if ((!entry.isFileLockingEnabled()
                                || (entry.isFileLockingEnabled() && VFSUtils.acquireLock(fsManager, child)))
                                && !isFailedRecord) {
                            //process the file
                            try {
                                if (log.isDebugEnabled()) {
                                    log.debug("Processing file :" + child);
                                }
                                processCount++;
                                processFile(entry, child);
                                successCount++;
                                // tell moveOrDeleteAfterProcessing() file was success
                                entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                                metrics.incrementMessagesReceived();

                            } catch (Exception e) {
                                logException("Error processing File URI : " + child.getName(), e);
                                failCount++;
                                // tell moveOrDeleteAfterProcessing() file failed
                                entry.setLastPollState(PollTableEntry.FAILED);
                                metrics.incrementFaultsReceiving();
                            }
                            //skipping un-locking file if failed to do delete/move after process
                            boolean skipUnlock = false;
                            try {
                                moveOrDeleteAfterProcessing(entry, child);
                            } catch (AxisFault axisFault) {
                                logException(
                                        "File object '" + child.getURL().toString()
                                                + "'cloud not be moved, will remain in \"locked\" state",
                                        axisFault);
                                skipUnlock = true;
                                failCount++;
                                entry.setLastPollState(PollTableEntry.FAILED);
                                String timeStamp = VFSUtils
                                        .getSystemTime(entry.getFailedRecordTimestampFormat());
                                addFailedRecord(entry, child, timeStamp);
                            }
                            // if there is a failure or not we'll try to release the lock
                            if (entry.isFileLockingEnabled() && !skipUnlock) {
                                VFSUtils.releaseLock(fsManager, child);
                            }
                        }
                    } else if (entry.getFileNamePattern() != null
                            && !child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        //child's file name does not match the file name pattern
                        if (log.isDebugEnabled()) {
                            log.debug("Non-Matching file : " + child.getName().getBaseName());
                        }
                    } else if (isFailedRecord) {
                        //it is a failed record
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, child);
                            VFSUtils.releaseLock(fsManager, fileObject);
                        }
                        if (fsManager.resolveFile(child.getURL().toString()) != null
                                && removeTaskState == STATE_STOPPED
                                && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, child));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + fileObject.getURL()
                                    + "' has been marked as a failed record, it will not " + "process");
                        }
                    }

                    if (iFileProcessingInterval != null && iFileProcessingInterval > 0) {
                        try {
                            if (log.isDebugEnabled()) {
                                log.debug("Put the VFS processor to sleep for : " + iFileProcessingInterval);
                            }
                            Thread.sleep(iFileProcessingInterval);
                        } catch (InterruptedException ie) {
                            log.error("Unable to set the interval between file processors." + ie);
                        }
                    } else if (iFileProcessingCount != null && iFileProcessingCount <= processCount) {
                        break;
                    }
                }

                if (failCount == 0 && successCount > 0) {
                    entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                } else if (successCount == 0 && failCount > 0) {
                    entry.setLastPollState(PollTableEntry.FAILED);
                } else {
                    entry.setLastPollState(PollTableEntry.WITH_ERRORS);
                }
            }

            // processing of this poll table entry is complete
            long now = System.currentTimeMillis();
            entry.setLastPollTime(now);
            entry.setNextPollTime(now + entry.getPollInterval());

        } else if (log.isDebugEnabled()) {
            log.debug("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "."
                    + " Reason: "
                    + (fileObject.exists()
                            ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!")
                            : "The file does not exists!"));
        }
        onPollCompletion(entry);
    } catch (FileSystemException e) {
        processFailure("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e,
                entry);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processAttachFromCloud(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {/*from   w  w w  .j a  va  2s.co m*/
        int storeId = ServletUtils.getIntParameter(request, "storeId", true);
        String path = ServletUtils.getStringParameter(request, "path", true);
        String tag = ServletUtils.getStringParameter(request, "tag", true);

        WebTopSession.UploadedFile uploadedFile = null;
        FileObject fo = vfsmanager.getStoreFile(storeId, path);
        if (fo == null)
            throw new WTException("Unable to get file [{}, {}]", storeId, path);
        InputStream is = null;
        try {
            is = fo.getContent().getInputStream();
            String name = fo.getName().getBaseName();
            String mediaType = ServletHelper.guessMediaType(name, true);
            uploadedFile = addAsUploadedFile(tag, name, mediaType, is);
        } finally {
            IOUtils.closeQuietly(is);
        }
        if (uploadedFile == null)
            throw new WTException("Unable to prepare uploaded file");

        MapItem data = new MapItem();
        data.add("uploadId", uploadedFile.getUploadId());
        data.add("name", uploadedFile.getFilename());
        data.add("size", uploadedFile.getSize());
        new JsonResult(data).printTo(out);

    } catch (FileSystemException | WTException ex) {
        Service.logger.error("Exception", ex);
        new JsonResult(false, ex.getMessage()).printTo(out);
    } catch (Exception ex) {
        Service.logger.error("Exception", ex);
        new JsonResult(false, ex.getMessage()).printTo(out);
    }
}

From source file:org.aludratest.service.file.impl.FileActionImpl.java

/** Copies a file or folder.
 *  @param fromPath the file/folder to copy
 *  @param toPath the name/location of the copy
 *  @param overwrite flag which indicates if an existing file may be overwritten by the operation
 *  @return true if a formerly existing file was overwritten.
 *  @throws FilePresentException if a file was already present and overwriting was disabled. */
@Override/*from   ww w .  j  a v a  2s  . c o  m*/
public boolean copy(String fromPath, String toPath, boolean overwrite) {
    assertWritingPermitted("copy()");
    FileUtil.verifyFilePath(fromPath);
    FileUtil.verifyFilePath(toPath);
    FileObject target = getFileObject(toPath);
    boolean existedBefore = checkWritable(target, overwrite);
    try {
        FileObject source = getFileObject(fromPath);
        FileSelector sourceSelector = new FilePathSelector(source.getName().getPath());
        target.copyFrom(source, sourceSelector);
        LOGGER.info("Copied {} to {}", fromPath, toPath);
        return existedBefore;
    } catch (FileSystemException e) {
        throw new TechnicalException("Error copying file " + fromPath + " -> " + toPath, e);
    }
}

From source file:org.aludratest.service.file.impl.FileInteractionImpl.java

/** Copies a file or folder.
 * @param fromPath the file/folder to copy
 * @param toPath the name/location of the copy
 * @param overwrite flag which indicates if an existing file may be overwritten by the operation
 * @return true if a formerly existing file was overwritten.
 * @throws FunctionalFailure if a file was already present and overwriting was disabled. */
@Override//from w ww . ja  va  2s.c  om
public boolean copy(String fromPath, String toPath, boolean overwrite) {
    assertWritingPermitted("copy()");
    File.verifyFilePath(fromPath);
    File.verifyFilePath(toPath);
    try {
        FileObject target = getFileObject(toPath);
        boolean existedBefore = checkWritable(target, overwrite);
        FileObject source = getFileObject(fromPath);
        FileSelector sourceSelector = new FilePathSelector(source.getName().getPath());
        target.copyFrom(source, sourceSelector);
        logger.debug("Copied {} to {}", fromPath, toPath);
        return existedBefore;
    } catch (IOException e) {
        throw new TechnicalException("Error copying file " + fromPath + " -> " + toPath, e);
    }
}

From source file:org.aludratest.service.file.impl.FileServiceConfiguration.java

/**
 * @param file the file/*from   w w  w . j a v a 2 s  .c  om*/
 * @return the full path
 */
public final String pathFromRoot(FileObject file) {
    FileName rootFolderName = rootFolder.getName();
    FileName fileName = file.getName();
    try {
        return rootFolderName.getRelativeName(fileName);
    } catch (FileSystemException e) {
        throw new AutomationException(
                "Error resolving relative path " + rootFolderName.getPath() + " -> " + fileName.getPath(), e);
    }
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloReloadingVFSClassLoader.java

public String stringify(FileObject[] files) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    String delim = "";
    for (FileObject file : files) {
        sb.append(delim);//from   w  w  w  .  j ava 2s  .  c  om
        delim = ", ";
        sb.append(file.getName());
    }
    sb.append(']');
    return sb.toString();
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader.java

static FileObject[] resolve(FileSystemManager vfs, String uris, ArrayList<FileObject> pathsToMonitor)
        throws FileSystemException {
    if (uris == null)
        return new FileObject[0];

    ArrayList<FileObject> classpath = new ArrayList<FileObject>();

    pathsToMonitor.clear();/* ww w .  j a v  a2s  .  c  o  m*/

    for (String path : uris.split(",")) {

        path = path.trim();

        if (path.equals(""))
            continue;

        path = AccumuloClassLoader.replaceEnvVars(path, System.getenv());

        FileObject fo = vfs.resolveFile(path);

        switch (fo.getType()) {
        case FILE:
        case FOLDER:
            classpath.add(fo);
            pathsToMonitor.add(fo);
            break;
        case IMAGINARY:
            // assume its a pattern
            String pattern = fo.getName().getBaseName();
            if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
                pathsToMonitor.add(fo.getParent());
                FileObject[] children = fo.getParent().getChildren();
                for (FileObject child : children) {
                    if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
                        classpath.add(child);
                    }
                }
            } else {
                log.warn("ignoring classpath entry " + fo);
            }
            break;
        default:
            log.warn("ignoring classpath entry " + fo);
            break;
        }

    }

    return classpath.toArray(new FileObject[classpath.size()]);
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader.java

public static ClassLoader getClassLoader() throws IOException {
    ReloadingClassLoader localLoader = loader;
    while (null == localLoader) {
        synchronized (lock) {
            if (null == loader) {

                FileSystemManager vfs = generateVfs();

                // Set up the 2nd tier class loader
                if (null == parent) {
                    parent = AccumuloClassLoader.getClassLoader();
                }/* w ww  . ja va 2 s  . c om*/

                FileObject[] vfsCP = resolve(vfs,
                        AccumuloClassLoader.getAccumuloString(VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY, ""));

                if (vfsCP.length == 0) {
                    localLoader = createDynamicClassloader(parent);
                    loader = localLoader;
                    return localLoader.getClassLoader();
                }

                // Create the Accumulo Context ClassLoader using the DEFAULT_CONTEXT
                localLoader = createDynamicClassloader(new VFSClassLoader(vfsCP, vfs, parent));
                loader = localLoader;

                // An HDFS FileSystem and Configuration object were created for each unique HDFS namespace in the call to resolve above.
                // The HDFS Client did us a favor and cached these objects so that the next time someone calls FileSystem.get(uri), they
                // get the cached object. However, these objects were created not with the system VFS classloader, but the classloader above
                // it. We need to override the classloader on the Configuration objects. Ran into an issue were log recovery was being attempted
                // and SequenceFile$Reader was trying to instantiate the key class via WritableName.getClass(String, Configuration)
                for (FileObject fo : vfsCP) {
                    if (fo instanceof HdfsFileObject) {
                        String uri = fo.getName().getRootURI();
                        Configuration c = new Configuration(true);
                        c.set(FileSystem.FS_DEFAULT_NAME_KEY, uri);
                        FileSystem fs = FileSystem.get(c);
                        fs.getConf().setClassLoader(loader.getClassLoader());
                    }
                }

            }
        }
    }

    return localLoader.getClassLoader();
}

From source file:org.apache.accumulo.start.classloader.vfs.providers.ReadOnlyHdfsFileProviderTest.java

@Test
public void testDoListChildren() throws Exception {
    FileObject fo = manager.resolveFile(TEST_DIR1);
    Assert.assertNotNull(fo);//  w  ww  .  j a va2s  .c  om
    Assert.assertFalse(fo.exists());

    // Create the test file
    FileObject file = createTestFile(hdfs);
    FileObject dir = file.getParent();

    FileObject[] children = dir.getChildren();
    Assert.assertTrue(children.length == 1);
    Assert.assertTrue(children[0].getName().equals(file.getName()));

}