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

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

Introduction

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

Prototype

public FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:org.efaps.webdav4vfs.handler.PropPatchHandler.java

/**
 * Handle a PROPPATCH request.//  w w w.j a  v a 2  s.c o m
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            Document propDoc = saxReader.read(request.getInputStream());
            logXml(propDoc);

            Element propUpdateEl = propDoc.getRootElement();
            List<Element> requestedProperties = new ArrayList<Element>();
            for (Object elObject : propUpdateEl.elements()) {
                Element el = (Element) elObject;
                String command = el.getName();
                if (AbstractDavResource.TAG_PROP_SET.equals(command)
                        || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) {
                    for (Object propElObject : el.elements()) {
                        for (Object propNameElObject : ((Element) propElObject).elements()) {
                            Element propNameEl = (Element) propNameElObject;
                            requestedProperties.add(propNameEl);
                        }
                    }
                }
            }

            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties,
                    getBaseUrl(request));

            logXml(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            LOG.error("invalid request: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        LOG.error(object.getName().getPath() + " NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.efaps.webdav4vfs.test.ramvfs.RamFileSystem.java

/**
 * Moves the original file <code>_from</code> to the new file
 * <code>_to</code>.//from   ww w.j  av a2s .c o m
 *
 * @param _from     original file
 * @param _to       new file.
 * @throws FileSystemException if an error occurs
 */
void rename(final RamFileObject _from, final RamFileObject _to) throws FileSystemException {
    if (!this.cache.containsKey(_from.getName())) {
        throw new FileSystemException("File does not exist: " + _from.getName());
    }
    // copy data
    _to.getData().setBuffer(_from.getData().getBuffer());
    _to.getData().setLastModified(_from.getData().getLastModified());
    _to.getData().setType(_from.getData().getType());
    _to.getData().getAttributes().clear();
    _to.getData().getAttributes().putAll(_from.getData().getAttributes());
    // fix problem that the file name of the data was cleared
    _to.getData().setName(_to.getName());

    this.save(_to);

    // copy children
    if (_from.getType() == FileType.FOLDER) {
        for (final FileObject child : _from.getChildren()) {
            final FileName newFileName = ((LocalFileName) _to.getName()).createName(
                    _to.getName().getPath() + "/" + child.getName().getBaseName(), child.getName().getType());
            this.rename((RamFileObject) child, new RamFileObject(newFileName, this));
        }
    }

    this.delete(_from);
}

From source file:org.efaps.webdav4vfs.test.ramvfs.RamFileSystem.java

/**
 * Import the given file with the name relative to the given root.
 *
 * @param _fo       file object//from  w ww  .java  2  s  .c  om
 * @param _root     root file object
 * @throws FileSystemException if file object could not be imported
 */
void toRamFileObject(final FileObject _fo, final FileObject _root) throws FileSystemException {
    final RamFileObject memFo = (RamFileObject) this
            .resolveFile(_fo.getName().getPath().substring(_root.getName().getPath().length()));
    if (_fo.getType().hasChildren()) {
        // Create Folder
        memFo.createFolder();
        // Import recursively
        final FileObject[] fos = _fo.getChildren();
        for (int i = 0; i < fos.length; i++) {
            final FileObject child = fos[i];
            this.toRamFileObject(child, _root);
        }
    } else if (_fo.getType().equals(FileType.FILE)) {
        // Read bytes
        try {
            final InputStream is = _fo.getContent().getInputStream();
            try {
                final OutputStream os = new BufferedOutputStream(memFo.getOutputStream(), 512);
                int i;
                while ((i = is.read()) != -1) {
                    os.write(i);
                }
                os.flush();
                os.close();
            } finally {
                try {
                    is.close();
                } catch (final IOException e) {
                    // ignore on close exception
                }
            }
        } catch (final IOException e) {
            throw new FileSystemException(e.getClass().getName() + " " + e.getMessage());
        }
    } else {
        throw new FileSystemException("File is not a folder nor a file " + memFo);
    }
}

From source file:org.efaps.webdav4vfs.util.Util.java

/**
 *
 * @param _object/*from   w  w  w  .  j  a  va 2  s .  com*/
 * @return
 */
public static String getETag(final FileObject _object) {
    final String fileName = _object.getName().getPath();
    String lastModified = "";
    try {
        lastModified = String.valueOf(_object.getContent().getLastModifiedTime());
    } catch (final FileSystemException e) {
        // ignore error here
    }
    return DigestUtils.shaHex(fileName + lastModified);
}

From source file:org.geoserver.importer.VFSWorker.java

/**
 * //  w  ww. j ava2  s . c o  m
 * @param archiveFile
 * @param filter
 * 
 * @return
 */
public List<String> listFiles(final File archiveFile, final FilenameFilter filter) {
    FileSystemManager fsManager;
    try {
        fsManager = VFS.getManager();
        String absolutePath = resolveArchiveURI(archiveFile);
        FileObject resolvedFile = fsManager.resolveFile(absolutePath);

        FileSelector fileSelector = new FileSelector() {
            /**
             * @see org.apache.commons.vfs.FileSelector#traverseDescendents(org.apache.commons.vfs.FileSelectInfo)
             */
            public boolean traverseDescendents(FileSelectInfo folderInfo) throws Exception {
                return true;
            }

            /**
             * @see org.apache.commons.vfs.FileSelector#includeFile(org.apache.commons.vfs.FileSelectInfo)
             */
            public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
                File folder = archiveFile.getParentFile();
                String name = fileInfo.getFile().getName().getFriendlyURI();
                return filter.accept(folder, name);
            }
        };

        FileObject fileSystem;
        if (fsManager.canCreateFileSystem(resolvedFile)) {
            fileSystem = fsManager.createFileSystem(resolvedFile);
        } else {
            fileSystem = resolvedFile;
        }
        LOGGER.fine("Listing spatial data files archived in " + archiveFile.getName());
        FileObject[] containedFiles = fileSystem.findFiles(fileSelector);
        List<String> names = new ArrayList<String>(containedFiles.length);
        for (FileObject fo : containedFiles) {
            // path relative to its filesystem (ie, to the archive file)
            String pathDecoded = fo.getName().getPathDecoded();
            names.add(pathDecoded);
        }
        LOGGER.fine("Found " + names.size() + " spatial data files in " + archiveFile.getName() + ": " + names);
        return names;
    } catch (FileSystemException e) {
        e.printStackTrace();
    } finally {
        // fsManager.closeFileSystem(fileSystem.getFileSystem());
    }
    return Collections.emptyList();
}

From source file:org.inquidia.kettle.plugins.tokenreplacement.TokenReplacement.java

private void createParentFolder(String filename) throws Exception {
    // Check for parent folder
    FileObject parentfolder = null;
    try {//from   ww w  .  j a v a 2s.  c  om
        // Get parent folder
        parentfolder = KettleVFS.getFileObject(filename).getParent();
        if (parentfolder.exists()) {
            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "TokenReplacement.Log.ParentFolderExist",
                        parentfolder.getName()));
            }
        } else {
            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "TokenReplacement.Log.ParentFolderNotExist",
                        parentfolder.getName()));
            }
            if (meta.isCreateParentFolder()) {
                parentfolder.createFolder();
                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "TokenReplacement.Log.ParentFolderCreated",
                            parentfolder.getName()));
                }
            } else {
                throw new KettleException(BaseMessages.getString(PKG,
                        "TokenReplacement.Log.ParentFolderNotExistCreateIt", parentfolder.getName(), filename));
            }
        }

    } finally {
        if (parentfolder != null) {
            try {
                parentfolder.close();
            } catch (Exception ex) {
                // Ignore
            }
        }
    }
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfigurator.java

public FileObject findVFSFile(String parentPath, String fileMatchingPattern) {
    Pattern matchingPattern = Pattern.compile(fileMatchingPattern);
    try {//from  w  ww.  ja  v  a  2  s .c  om
        FileSystemManager fsManager = VFS.getManager();
        FileObject parentFileObject = fsManager.resolveFile(parentPath);
        FileObject[] children = parentFileObject.getChildren();
        for (FileObject child : children) {
            Matcher matcher = matchingPattern.matcher(child.getName().getBaseName());
            if (matcher.matches()) {
                return child;
            }
        }
    } catch (FileSystemException e) {
        logger.debug("Couldn't find file matching pattern " + fileMatchingPattern + " at path " + parentPath);
    }
    return null;
}

From source file:org.jahia.services.content.impl.external.vfs.VFSDataSource.java

public List<String> getChildren(String path) {
    try {//from   w w  w  .  j ava2s .c  om
        if (!path.endsWith("/" + Constants.JCR_CONTENT)) {
            FileObject fileObject = getFile(path);
            if (fileObject.getType() == FileType.FILE) {
                return Arrays.asList(Constants.JCR_CONTENT);
            } else if (fileObject.getType() == FileType.FOLDER) {
                List<String> children = new ArrayList<String>();
                for (FileObject object : fileObject.getChildren()) {
                    children.add(object.getName().getBaseName());
                }
                return children;
            } else {
                logger.warn("Found non file or folder entry, maybe an alias. VFS file type="
                        + fileObject.getType());
            }
        }
    } catch (FileSystemException e) {
        logger.error("Cannot get node children", e);
    }

    return new ArrayList<String>();
}

From source file:org.jahia.services.content.impl.external.vfs.VFSDataSource.java

private ExternalData getFile(FileObject fileObject) throws FileSystemException {
    String identifier = fileObject.getURL().toString();
    String type;//from  w ww .  j  a v a2  s. c om

    type = getDataType(fileObject);

    Map<String, String[]> properties = new HashMap<String, String[]>();
    if (fileObject.getContent() != null) {
        long lastModifiedTime = fileObject.getContent().getLastModifiedTime();
        if (lastModifiedTime > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(lastModifiedTime);
            String[] timestampt = new String[] { ISO8601.format(calendar) };
            properties.put(Constants.JCR_CREATED, timestampt);
            properties.put(Constants.JCR_LASTMODIFIED, timestampt);
        }
    }

    String path = fileObject.getName().getPath().substring(rootPath.length());
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    return new ExternalData(identifier, path, type, properties);
}

From source file:org.jboss.dashboard.filesystem.BinariesMapping.java

/**
 * If this file can be accessed through an URI, return it.
 *//*from w w  w  .  j a  v a2  s .c  om*/
public String getURI(FileObject file) {
    if (this.getServerUri() != null) {
        String fileName = file.getName().getPath();
        if (fileName.startsWith("/" + getJunctionPoint())) {
            fileName = fileName.substring(getJunctionPoint().length() + 1);
            String uri = getServerUri() + fileName;
            return uri;
        }
    }
    return null;
}