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.freedesktop.wallpapers.DefaultWallpaperService.java

protected Collection<Wallpaper> scanBase(FileObject base) throws IOException {
    List<Wallpaper> themes = new ArrayList<Wallpaper>();
    for (FileObject dir : listImages(base)) {
        try {//from  ww w.j  a  v a2 s .c  om
            themes.add(new Wallpaper(dir));
        } catch (IOException ioe) {
            Log.warn("Invalid wallpaper directory " + dir.getName().getPath() + ". " + ioe.getMessage());
        } catch (ParseException ioe) {
            Log.warn("Invalid wallpaper definition in " + dir.getName().getPath() + ". " + ioe.getMessage());
        }
    }
    return themes;
}

From source file:org.freedesktop.wallpapers.Wallpaper.java

public Wallpaper(FileObject... base) throws IOException, ParseException {
    super(WALLPAPER, base);
    for (FileObject b : base) {
        FileObject f = b.getParent().resolveFile(b.getName() + ".desktop");
        if (f.exists()) {
            themeFile = f;/*from  w w w . j a  va 2  s . co  m*/
            break;
        }
    }
    if (themeFile == null) {
        throw new FileNotFoundException();
    }
}

From source file:org.fuin.vfs2.filter.BaseFilterTest.java

private boolean find(final FileObject[] files, final String filename) {
    for (FileObject file : files) {
        final String name = file.getName().getBaseName();
        if (name.equals(filename)) {
            return true;
        }// ww  w.j  av a 2  s  .co  m
    }
    return false;
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * @param zos//from w  ww .j av  a 2s .  c  om
 * @param sourceFile
 * @throws FileSystemException
 * @throws IOException
 */
private static void writeEntry(ZipOutputStream zos, FileObject sourceFile, String baseDir)
        throws FileSystemException, IOException {
    if (sourceFile.getType() == FileType.FOLDER) {
        // add entry/-ies.
        for (FileObject file : sourceFile.getChildren()) {
            writeEntry(zos, file, Paths.path(baseDir, sourceFile.getName().getBaseName()));
        }
    } else {
        String fileName = (baseDir != null ? Paths.path(baseDir, sourceFile.getName().getBaseName())
                : sourceFile.getName().getBaseName());
        ZipEntry zipEntry = new ZipEntry(fileName);
        InputStream is = sourceFile.getContent().getInputStream();

        // Write to zip.
        byte[] buf = new byte[1024];
        zos.putNextEntry(zipEntry);
        for (int readNum; (readNum = is.read(buf)) != -1;) {
            zos.write(buf, 0, readNum);
        }
        zos.closeEntry();
        is.close();
    }
}

From source file:org.helios.ember.sftp.FileObjectWrapperCollection.java

/**
 * Creates a new FileObjectWrapperCollection
        //from w  ww  .  ja v a2  s.  c om
 * @param parent The parent folder
 * @param fileObjects The wrapped file objects to aggregate
 */
public FileObjectWrapperCollection(FileObject parent, FileObjectWrapper... fileObjects) {
    this.parentFolder = parent.getName().getPath();
    this.root = parent.getFileSystem().getRootName().equals(parent.getName());
    this.urlPrefix = parent.getFileSystem().getRootURI();

    if (fileObjects != null) {
        for (FileObjectWrapper fileObject : fileObjects) {
            if (fileObject == null)
                continue;
            try {
                if (FileType.FILE.getName().equals(fileObject.getType())) {
                    files.add(fileObject);
                    totalSize += fileObject.getSize();
                } else if (FileType.FOLDER.getName().equals(fileObject.getType())) {
                    folders.add(fileObject);
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
            }
        }
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

/**
 * Allows to know the nodetype associated to a filetype.
 *
 * @param fileObject the file object that we want to know the associated nodetype
 * @return the associated nodetype/*from w w w. j a v a2s . c om*/
 * @throws FileSystemException
 */
@Override
public String getDataType(FileObject fileObject) throws FileSystemException {
    String relativeName = getFile("/").getName().getRelativeName(fileObject.getName());
    int relativeDepth = ".".equals(relativeName) ? 0 : StringUtils.split(relativeName, "/").length;
    String type = null;
    if (fileObject.getType().equals(FileType.FOLDER)) {
        if (relativeDepth == ROOT_DEPTH_TOKEN) {
            // we are in root
            type = Constants.JAHIANT_MODULEVERSIONFOLDER;
        } else {
            if (relativeDepth == TARGET_DEPTH_TOKEN
                    && StringUtils.equals("target", fileObject.getName().getBaseName())) {
                type = "jnt:mavenTargetFolder";
            } else if (StringUtils.equals("resources", fileObject.getName().getBaseName())
                    && relativeDepth == SOURCES_DEPTH_TOKEN) {
                type = "jnt:folder";
            } else if (relativeDepth == NODETYPE_FOLDER_DEPTH_TOKEN
                    && isNodeType(fileObject.getName().getBaseName())) {
                type = Constants.JAHIANT_NODETYPEFOLDER;
            } else if (relativeDepth == TEMPLATE_TYPE_FOLDER_DEPTH_TOKEN) {
                FileObject parent = fileObject.getParent();
                if (parent != null && Constants.JAHIANT_NODETYPEFOLDER.equals(getDataType(parent))) {
                    type = Constants.JAHIANT_TEMPLATETYPEFOLDER;
                }
            } else if (StringUtils.split(relativeName, "/").length >= SOURCES_DEPTH_TOKEN && StringUtils
                    .equals(StringUtils.split(relativeName, "/")[SOURCES_DEPTH_TOKEN - 1], "java")) {
                type = "jnt:javaPackageFolder";
            }
        }
        if (type == null) {
            type = folderTypeMapping.get(fileObject.getName().getBaseName());
        }
    } else {
        String extension = fileObject.getName().getExtension();
        if (StringUtils.isNotEmpty(extension)) {
            type = fileTypeMapping.get(extension);
            if (type == null) {
                try {
                    if (ScriptEngineUtils.canFactoryForExtensionProcessViews(extension,
                            module.getBundle().getHeaders())) {
                        type = Constants.JAHIANT_VIEWFILE;
                    }
                } catch (IllegalArgumentException e) {
                    // ignore: no ScriptEngineFactory exists for the provided extension
                }
            }
        }

    }
    if (type != null && StringUtils.equals(type, "jnt:propertiesFile")) {
        // we've detected a properties file, check if its parent is of type jnt:resourceBundleFolder
        // -> than this one gets the type jnt:resourceBundleFile; otherwise just jnt:file
        FileObject parent = fileObject.getParent();
        type = parent != null
                && StringUtils.equals(Constants.JAHIANT_RESOURCEBUNDLE_FOLDER, getDataType(parent))
                        ? Constants.JAHIANT_RESOURCEBUNDLE_FILE
                        : type;
    }
    boolean isFile = fileObject.getType() == FileType.FILE;
    if (isFile && relativeDepth == VIEWS_FOLDER_DEPTH_TOKEN && (fileObject.getParent() != null
            && StringUtils.equals(Constants.JAHIANT_TEMPLATETYPEFOLDER, getDataType(fileObject.getParent())))) {
        if (StringUtils.endsWith(fileObject.getName().toString(), PROPERTIES_EXTENSION)) {
            type = JNT_EDITABLE_FILE;
        } else {
            type = Constants.JAHIANT_VIEWFILE;
        }
    }

    String contentType = getContentType(fileObject.getContent());
    if (type == null && isFile) {
        boolean isMedia = contentType != null && (contentType.contains("image") || contentType.contains("video")
                || contentType.contains("audio") || contentType.contains("flash"));
        if (!isMedia) {
            type = JNT_EDITABLE_FILE;
        }
    }

    // in case of the file name ends with .xml.generated we should have no type.
    if (StringUtils.endsWith(fileObject.getName().toString(), ".xml.generated")) {
        type = null;
    }
    return type != null ? type : super.getDataType(fileObject);
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException {
    String resourceBundleName = module.getResourceBundleName();
    if (resourceBundleName == null) {
        resourceBundleName = "resources." + module.getId();
    }// w  w  w. j a  v  a 2  s .  c  om
    String rbBasePath = "/src/main/resources/resources/"
            + StringUtils.substringAfterLast(resourceBundleName, ".");
    Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties();
    if (i18nProperties != null) {
        List<File> newFiles = new ArrayList<File>();
        for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) {
            String lang = entry.getKey();
            Map<String, String[]> properties = entry.getValue();

            String[] values = properties.get(Constants.JCR_TITLE);
            String title = ArrayUtils.isEmpty(values) ? null : values[0];

            values = properties.get(Constants.JCR_DESCRIPTION);
            String description = ArrayUtils.isEmpty(values) ? null : values[0];

            String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION;
            InputStream is = null;
            InputStreamReader isr = null;
            OutputStream os = null;
            OutputStreamWriter osw = null;
            try {
                FileObject file = getFile(rbPath);
                FileContent content = file.getContent();
                Properties p = new SortedProperties();
                if (file.exists()) {
                    is = content.getInputStream();
                    isr = new InputStreamReader(is, Charsets.ISO_8859_1);
                    p.load(isr);
                    isr.close();
                    is.close();
                } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) {
                    continue;
                } else {
                    newFiles.add(new File(file.getName().getPath()));
                }
                if (!StringUtils.isEmpty(title)) {
                    p.setProperty(key, title);
                }
                if (!StringUtils.isEmpty(description)) {
                    p.setProperty(key + "_description", description);
                }
                os = content.getOutputStream();
                osw = new OutputStreamWriter(os, Charsets.ISO_8859_1);
                p.store(osw, rbPath);
                ResourceBundle.clearCache();
            } catch (FileSystemException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } catch (IOException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(osw);
            }
        }
        SourceControlManagement sourceControl = module.getSourceControl();
        if (sourceControl != null) {
            try {
                sourceControl.add(newFiles);
            } catch (IOException e) {
                logger.error("Failed to add files to source control", e);
                throw new RepositoryException("Failed to add new files to source control: " + newFiles, e);
            }
        }
    }
}

From source file:org.jahia.modules.external.vfs.VFSDataSource.java

public List<String> getChildren(String path) throws RepositoryException {
    try {/*from w  ww.  java 2  s.  c  om*/
        if (!path.endsWith(JCR_CONTENT_SUFFIX)) {
            FileObject fileObject = getFile(path);
            if (fileObject.getType() == FileType.FILE) {
                return JCR_CONTENT_LIST;
            } else if (fileObject.getType() == FileType.FOLDER) {
                FileObject[] files = fileObject.getChildren();
                if (files.length > 0) {
                    List<String> children = new LinkedList<String>();
                    for (FileObject object : files) {
                        if (getSupportedNodeTypes().contains(getDataType(object))) {
                            children.add(object.getName().getBaseName());
                        }
                    }
                    return children;
                } else {
                    return Collections.emptyList();
                }
            } else {
                if (fileObject.exists()) {
                    logger.warn("Found non file or folder entry at path {}, maybe an alias. VFS file type: {}",
                            fileObject, fileObject.getType());
                } else {
                    throw new PathNotFoundException(path);
                }
            }
        }
    } catch (FileSystemException e) {
        logger.error("Cannot get node children", e);
    }

    return Collections.emptyList();
}

From source file:org.jahia.modules.external.vfs.VFSDataSource.java

private ExternalData getFile(FileObject fileObject) throws FileSystemException {
    String type = getDataType(fileObject);

    Map<String, String[]> properties = new HashMap<String, String[]>();
    List<String> addedMixins = new ArrayList<>();
    final FileContent content = fileObject.getContent();
    if (content != null) {
        long lastModifiedTime = fileObject.getContent().getLastModifiedTime();
        if (lastModifiedTime > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(lastModifiedTime);
            String[] timestamp = new String[] { ISO8601.format(calendar) };
            properties.put(Constants.JCR_CREATED, timestamp);
            properties.put(Constants.JCR_LASTMODIFIED, timestamp);
        }//from w  w  w .  j a v a 2s  .  c  o  m
        // Add jmix:image mixin in case of the file is a picture.
        if (content.getContentInfo() != null && content.getContentInfo().getContentType() != null
                && fileObject.getContent().getContentInfo().getContentType().matches("image/(.*)")) {
            addedMixins.add(Constants.JAHIAMIX_IMAGE);
        }

    }

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

    ExternalData result = new ExternalData(path, path, type, properties);
    result.setMixin(addedMixins);
    return result;
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function copies a source file to a given destination. If no filename is given in the destination file handle,
 * the filename of the source is used.<br>
 * <br>/*  ww w .  j av a2 s. c  o m*/
 * It is tried to copy the file three times. If all three tries has failed, only then an IOException is thrown. <br>
 * All other exceptions are thrown normally.
 *
 * @param source
 *          The source file.
 * @param destination
 *          The destination file or path.
 * @param overwrite
 *          If set, always overwrite existing and newer files
 */
public static void copyFileTo(final FileObject source, final FileObject destination, final boolean overwrite)
        throws IOException {
    if (source.equals(destination)) {
        KalypsoCommonsDebug.DEBUG.printf(Messages.getString("org.kalypso.commons.io.VFSUtilities.1"), //$NON-NLS-1$
                source.getName(), destination.getName());
        return;
    }

    /* Some variables for handling the errors. */
    boolean success = false;
    int cnt = 0;

    while (success == false) {
        try {
            if (FileType.FOLDER.equals(source.getType()))
                throw new IllegalArgumentException(Messages.getString("org.kalypso.commons.io.VFSUtilities.2")); //$NON-NLS-1$

            /* If the destination is only a directory, use the sources filename for the destination file. */
            FileObject destinationFile = destination;
            if (FileType.FOLDER.equals(destination.getType()))
                destinationFile = destination.resolveFile(source.getName().getBaseName());

            if (overwrite || !destinationFile.exists()
                    || destinationFile.getContent().getSize() != source.getContent().getSize()) {
                /* Copy file. */
                KalypsoCommonsDebug.DEBUG.printf("Copy file '%s' to '%s'...%n", source.getName(), //$NON-NLS-1$
                        destinationFile.getName());
                FileUtil.copyContent(source, destinationFile);
                source.close();
            }

            /* End copying of this file, because it was a success. */
            success = true;
        } catch (final IOException e) {
            /* An error has occurred while copying the file. */
            KalypsoCommonsDebug.DEBUG.printf("An error has occured with the message: %s%n", //$NON-NLS-1$
                    e.getLocalizedMessage());

            /* If a certain amount (here 2) of retries was reached before, re-throw the error. */
            if (cnt >= 2) {
                KalypsoCommonsDebug.DEBUG.printf("The second retry has failed, rethrowing the error...%n"); //$NON-NLS-1$
                throw e;
            }

            /* Retry the copying of the file. */
            cnt++;
            KalypsoCommonsDebug.DEBUG.printf("Retry: %s%n", String.valueOf(cnt)); //$NON-NLS-1$
            success = false;

            /* Wait for some milliseconds. */
            try {
                Thread.sleep(1000);
            } catch (final InterruptedException e1) {
                /*
                 * Runs in the next loop then and if no error occurs then, it is ok. If an error occurs again, it is an
                 * exception thrown on the last failed retry or it is slept again.
                 */
            }
        }
    }
}