Example usage for org.apache.commons.vfs FileType FOLDER

List of usage examples for org.apache.commons.vfs FileType FOLDER

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileType FOLDER.

Prototype

FileType FOLDER

To view the source code for org.apache.commons.vfs FileType FOLDER.

Click Source Link

Document

A folder.

Usage

From source file:com.panet.imeta.job.entries.unzip.JobEntryUnZip.java

private boolean unzipFile(LogWriter log, FileObject sourceFileObject, String realTargetdirectory,
        String realWildcard, String realWildcardExclude, Result result, Job parentJob, FileObject fileObject,
        FileObject movetodir, String realMovetodirectory) {
    boolean retval = false;

    try {/*from   w  w w  . j  a v  a  2  s. c  om*/

        if (log.isDetailed())
            log.logDetailed(toString(),
                    Messages.getString("JobUnZip.Log.ProcessingFile", sourceFileObject.toString()));

        // Do you create a root folder?
        //
        if (rootzip) {
            String shortSourceFilename = sourceFileObject.getName().getBaseName();
            int lenstring = shortSourceFilename.length();
            int lastindexOfDot = shortSourceFilename.lastIndexOf('.');
            if (lastindexOfDot == -1)
                lastindexOfDot = lenstring;

            String foldername = realTargetdirectory + "/" + shortSourceFilename.substring(0, lastindexOfDot);
            FileObject rootfolder = KettleVFS.getFileObject(foldername);
            if (!rootfolder.exists()) {
                try {
                    rootfolder.createFolder();
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobUnZip.Log.RootFolderCreated", foldername));
                } catch (Exception e) {
                    throw new Exception(Messages.getString("JobUnZip.Error.CanNotCreateRootFolder", foldername),
                            e);
                }
            }
        }

        // Try to read the entries from the VFS object...
        //
        String zipFilename = "zip:" + sourceFileObject.getName().getFriendlyURI();
        FileObject zipFile = KettleVFS.getFileObject(zipFilename);
        FileObject[] items = zipFile.findFiles(new AllFileSelector() {
            public boolean traverseDescendents(FileSelectInfo info) {
                return true;
            }

            public boolean includeFile(FileSelectInfo info) {
                // Never return the parent directory of a file list.
                if (info.getDepth() == 0) {
                    return false;
                }

                FileObject fileObject = info.getFile();
                return fileObject != null;
            }
        });

        Pattern pattern = null;
        if (!Const.isEmpty(realWildcard)) {
            pattern = Pattern.compile(realWildcard);

        }
        Pattern patternexclude = null;
        if (!Const.isEmpty(realWildcardExclude)) {
            patternexclude = Pattern.compile(realWildcardExclude);

        }

        for (FileObject item : items) {

            if (successConditionBroken) {
                if (!successConditionBrokenExit) {
                    log.logError(toString(),
                            Messages.getString("JobUnZip.Error.SuccessConditionbroken", "" + NrErrors));
                    successConditionBrokenExit = true;
                }
                return false;
            }

            try {
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobUnZip.Log.ProcessingZipEntry",
                            item.getName().getURI(), sourceFileObject.toString()));

                // get real destination filename
                //
                String newFileName = realTargetdirectory + Const.FILE_SEPARATOR
                        + getTargetFilename(item.getName().getPath());
                FileObject newFileObject = KettleVFS.getFileObject(newFileName);

                if (item.getType().equals(FileType.FOLDER)) {
                    // Directory
                    //
                    if (log.isDetailed())
                        log.logDetailed(toString(),
                                Messages.getString("JobUnZip.CreatingDirectory.Label", newFileName));

                    // Create Directory if necessary ...
                    //
                    if (!newFileObject.exists())
                        newFileObject.createFolder();
                } else {
                    // File
                    //
                    boolean getIt = true;
                    boolean getItexclude = false;

                    // First see if the file matches the regular expression!
                    //
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(item.getName().getURI());
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(item.getName().getURI());
                        getItexclude = matcherexclude.matches();
                    }

                    boolean take = takeThisFile(log, item, newFileName);

                    if (getIt && !getItexclude && take) {
                        if (log.isDetailed())
                            log.logDetailed(toString(), Messages.getString("JobUnZip.ExtractingEntry.Label",
                                    item.getName().getURI(), newFileName));

                        if (iffileexist == IF_FILE_EXISTS_UNIQ) {
                            // Create file with unique name

                            int lenstring = newFileName.length();
                            int lastindexOfDot = newFileName.lastIndexOf('.');
                            if (lastindexOfDot == -1)
                                lastindexOfDot = lenstring;

                            newFileName = newFileName.substring(0, lastindexOfDot)
                                    + StringUtil.getFormattedDateTimeNow(true)
                                    + newFileName.substring(lastindexOfDot, lenstring);

                            if (log.isDebug())
                                log.logDebug(toString(),
                                        Messages.getString("JobUnZip.Log.CreatingUniqFile", newFileName));
                        }

                        // See if the folder to the target file exists...
                        //
                        if (!newFileObject.getParent().exists()) {
                            newFileObject.getParent().createFolder(); // creates
                            // the
                            // whole
                            // path.
                        }
                        InputStream is = null;
                        OutputStream os = null;

                        try {
                            is = KettleVFS.getInputStream(item);
                            os = KettleVFS.getOutputStream(newFileObject, false);

                            if (is != null) {
                                byte[] buff = new byte[2048];
                                int len;

                                while ((len = is.read(buff)) > 0) {
                                    os.write(buff, 0, len);
                                }

                                // Add filename to result filenames
                                addFilenameToResultFilenames(result, parentJob, newFileName);
                            }
                        } finally {
                            if (is != null)
                                is.close();
                            if (os != null)
                                os.close();
                        }
                    } // end if take
                }
            } catch (Exception e) {
                updateErrors();
                log.logError(toString(), Messages.getString("JobUnZip.Error.CanNotProcessZipEntry",
                        item.getName().getURI(), sourceFileObject.toString()), e);
            }
        } // End while

        // Here gc() is explicitly called if e.g. createfile is used in the
        // same
        // job for the same file. The problem is that after creating the
        // file the
        // file object is not properly garbaged collected and thus the file
        // cannot
        // be deleted anymore. This is a known problem in the JVM.

        // System.gc();

        // Unzip done...
        if (afterunzip == 1) {
            // delete zip file
            boolean deleted = fileObject.delete();
            if (!deleted) {
                updateErrors();
                log.logError(toString(),
                        Messages.getString("JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString()));
            }
            // File deleted
            if (log.isDebug())
                log.logDebug(toString(),
                        Messages.getString("JobUnZip.File_Deleted.Label", sourceFileObject.toString()));
        } else if (afterunzip == 2) {
            FileObject destFile = null;
            // Move File
            try {
                String destinationFilename = movetodir + Const.FILE_SEPARATOR
                        + fileObject.getName().getBaseName();
                destFile = KettleVFS.getFileObject(destinationFilename);

                fileObject.moveTo(destFile);

                // File moved
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobUnZip.Log.FileMovedTo",
                            sourceFileObject.toString(), realMovetodirectory));
            } catch (Exception e) {
                updateErrors();
                log.logError(toString(), Messages.getString("JobUnZip.Cant_Move_File.Label",
                        sourceFileObject.toString(), realMovetodirectory, e.getMessage()));
            } finally {
                if (destFile != null) {
                    try {
                        destFile.close();
                    } catch (IOException ex) {
                    }
                    ;
                }
            }
        }

        retval = true;
    } catch (Exception e) {
        updateErrors();
        log.logError(Messages.getString("JobUnZip.Error.Label"),
                Messages.getString("JobUnZip.ErrorUnzip.Label", sourceFileObject.toString(), e.getMessage()),
                e);
    }

    return retval;
}

From source file:com.panet.imeta.job.entries.movefiles.JobEntryMoveFiles.java

private boolean MoveOneFile(FileObject Currentfile, FileObject sourcefilefolder,
        String realDestinationFilefoldername, String realWildcard, LogWriter log, Job parentJob, Result result,
        FileObject movetofolderfolder) {
    boolean entrystatus = false;
    FileObject file_name = null;//  www . j a  v a  2 s  . c  o m

    try {
        if (!Currentfile.toString().equals(sourcefilefolder.toString())) {
            // Pass over the Base folder itself

            // return destination short filename
            String sourceshortfilename = Currentfile.getName().getBaseName();
            String shortfilename = sourceshortfilename;
            try {
                shortfilename = getDestinationFilename(sourceshortfilename);
            } catch (Exception e) {
                log.logError(toString(),
                        Messages.getString(Messages.getString("JobMoveFiles.Error.GettingFilename",
                                Currentfile.getName().getBaseName(), e.toString())));
                return entrystatus;
            }

            int lenCurrent = sourceshortfilename.length();
            String short_filename_from_basefolder = shortfilename;
            if (!isDoNotKeepFolderStructure())
                short_filename_from_basefolder = Currentfile.toString()
                        .substring(sourcefilefolder.toString().length(), Currentfile.toString().length());
            short_filename_from_basefolder = short_filename_from_basefolder.substring(0,
                    short_filename_from_basefolder.length() - lenCurrent) + shortfilename;

            // Built destination filename
            file_name = KettleVFS.getFileObject(
                    realDestinationFilefoldername + Const.FILE_SEPARATOR + short_filename_from_basefolder);

            if (!Currentfile.getParent().toString().equals(sourcefilefolder.toString())) {

                // Not in the Base Folder..Only if include sub folders
                if (include_subfolders) {
                    // Folders..only if include subfolders
                    if (Currentfile.getType() == FileType.FOLDER) {
                        if (include_subfolders && move_empty_folders && Const.isEmpty(wildcard)) {
                            entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder,
                                    log, parentJob, result);
                        }
                    } else {

                        if (GetFileWildcard(sourceshortfilename, realWildcard)) {
                            entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder,
                                    log, parentJob, result);
                        }
                    }
                }
            } else {
                // In the Base Folder...
                // Folders..only if include subfolders
                if (Currentfile.getType() == FileType.FOLDER) {
                    if (include_subfolders && move_empty_folders && Const.isEmpty(wildcard)) {
                        entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder, log,
                                parentJob, result);
                    }
                } else {

                    // file...Check if exists
                    if (GetFileWildcard(sourceshortfilename, realWildcard)) {
                        entrystatus = MoveFile(shortfilename, Currentfile, file_name, movetofolderfolder, log,
                                parentJob, result);

                    }
                }

            }

        }
        entrystatus = true;

    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobMoveFiles.Log.Error", e.toString()));
    } finally {
        if (file_name != null) {
            try {
                file_name.close();

            } catch (IOException ex) {
            }
            ;
        }

    }
    return entrystatus;
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static boolean isFolder(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    try {/*from   ww w . j  ava  2s  .  c o m*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            if (ArgList[0].equals(null))
                return false;
            FileObject file = null;

            try {
                // Source file
                file = KettleVFS.getFileObject((String) ArgList[0]);
                boolean isafolder = false;
                if (file.exists()) {
                    if (file.getType().equals(FileType.FOLDER))
                        isafolder = true;
                    else
                        new RuntimeException("[" + (String) ArgList[0] + "] is not a folder!");
                } else {
                    new RuntimeException("folder [" + (String) ArgList[0] + "] can not be found!");
                }
                return isafolder;
            } catch (IOException e) {
                throw new RuntimeException("The function call isFolder throw an error : " + e.toString());
            } finally {
                if (file != null)
                    try {
                        file.close();
                    } catch (Exception e) {
                    }
            }

        } else {
            throw new RuntimeException("The function call isFolder is not valid.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static boolean isFolder(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    try {/*from   ww  w . j  a  v a 2s .  c  o  m*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            if (ArgList[0].equals(null))
                return false;
            FileObject file = null;

            try {
                // Source file
                file = KettleVFS.getFileObject(Context.toString(ArgList[0]));
                boolean isafolder = false;
                if (file.exists()) {
                    if (file.getType().equals(FileType.FOLDER))
                        isafolder = true;
                    else
                        Context.reportRuntimeError("[" + Context.toString(ArgList[0]) + "] is not a folder!");
                } else {
                    Context.reportRuntimeError(
                            "folder [" + Context.toString(ArgList[0]) + "] can not be found!");
                }
                return isafolder;
            } catch (IOException e) {
                throw Context.reportRuntimeError("The function call isFolder throw an error : " + e.toString());
            } finally {
                if (file != null)
                    try {
                        file.close();
                    } catch (Exception e) {
                    }
            }

        } else {
            throw Context.reportRuntimeError("The function call isFolder is not valid.");
        }
    } catch (Exception e) {
        throw Context.reportRuntimeError(e.toString());
    }
}

From source file:org.apache.commons.vfs.example.Shell.java

/**
 * Does a 'cp' command.//from w  w w  .j  ava2 s.  co  m
 */
private void cp(final String[] cmd) throws Exception {
    if (cmd.length < 3) {
        throw new Exception("USAGE: cp <src> <dest>");
    }

    final FileObject src = mgr.resolveFile(cwd, cmd[1]);
    FileObject dest = mgr.resolveFile(cwd, cmd[2]);
    if (dest.exists() && dest.getType() == FileType.FOLDER) {
        dest = dest.resolveFile(src.getName().getBaseName());
    }

    dest.copyFrom(src, Selectors.SELECT_ALL);
}

From source file:org.apache.commons.vfs.example.Shell.java

/**
 * Does an 'ls' command./*from   w  w w . jav  a2 s.  com*/
 */
private void ls(final String[] cmd) throws FileSystemException {
    int pos = 1;
    final boolean recursive;
    if (cmd.length > pos && cmd[pos].equals("-R")) {
        recursive = true;
        pos++;
    } else {
        recursive = false;
    }

    final FileObject file;
    if (cmd.length > pos) {
        file = mgr.resolveFile(cwd, cmd[pos]);
    } else {
        file = cwd;
    }

    if (file.getType() == FileType.FOLDER) {
        // List the contents
        System.out.println("Contents of " + file.getName());
        listChildren(file, recursive, "");
    } else {
        // Stat the file
        System.out.println(file.getName());
        final FileContent content = file.getContent();
        System.out.println("Size: " + content.getSize() + " bytes.");
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
        System.out.println("Last modified: " + lastMod);
    }
}

From source file:org.apache.commons.vfs.example.Shell.java

/**
 * Lists the children of a folder./*ww  w.  j  a  va2  s  .c  om*/
 */
private void listChildren(final FileObject dir, final boolean recursive, final String prefix)
        throws FileSystemException {
    final FileObject[] children = dir.getChildren();
    for (int i = 0; i < children.length; i++) {
        final FileObject child = children[i];
        System.out.print(prefix);
        System.out.print(child.getName().getBaseName());
        if (child.getType() == FileType.FOLDER) {
            System.out.println("/");
            if (recursive) {
                listChildren(child, recursive, prefix + "    ");
            }
        } else {
            System.out.println();
        }
    }
}

From source file:org.apache.commons.vfs.example.ShowProperties.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Please pass the name of a file as parameter.");
        System.err.println("e.g. java org.apache.commons.vfs.example.ShowProperties LICENSE.txt");
        return;/* ww  w  .  j av a2  s.co  m*/
    }
    for (int i = 0; i < args.length; i++) {
        try {
            FileSystemManager mgr = VFS.getManager();
            System.out.println();
            System.out.println("Parsing: " + args[i]);
            FileObject file = mgr.resolveFile(args[i]);
            System.out.println("URL: " + file.getURL());
            System.out.println("getName(): " + file.getName());
            System.out.println("BaseName: " + file.getName().getBaseName());
            System.out.println("Extension: " + file.getName().getExtension());
            System.out.println("Path: " + file.getName().getPath());
            System.out.println("Scheme: " + file.getName().getScheme());
            System.out.println("URI: " + file.getName().getURI());
            System.out.println("Root URI: " + file.getName().getRootURI());
            System.out.println("Parent: " + file.getName().getParent());
            System.out.println("Type: " + file.getType());
            System.out.println("Exists: " + file.exists());
            System.out.println("Readable: " + file.isReadable());
            System.out.println("Writeable: " + file.isWriteable());
            System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
            if (file.exists()) {
                if (file.getType().equals(FileType.FILE)) {
                    System.out.println("Size: " + file.getContent().getSize() + " bytes");
                } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
                    FileObject[] children = file.getChildren();
                    System.out.println("Directory with " + children.length + " files");
                    for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                        System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                        if (iterChildren > 5) {
                            break;
                        }
                    }
                }
                System.out.println("Last modified: "
                        + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
            } else {
                System.out.println("The file does not exist");
            }
            file.close();
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.apache.ivy.plugins.repository.vfs.VfsRepository.java

/**
 * Return a listing of the contents of a parent directory. Listing is a set of strings
 * representing VFS URIs./*from w ww.ja  v a  2  s. c  o m*/
 * 
 * @param vfsURI
 *            providing identifying a VFS provided resource
 * @throws IOException
 *             on failure.
 * @see "Supported File Systems in the jakarta-commons-vfs documentation"
 */
public List list(String vfsURI) throws IOException {
    ArrayList list = new ArrayList();
    Message.debug("list called for URI" + vfsURI);
    FileObject resourceImpl = getVFSManager().resolveFile(vfsURI);
    Message.debug("resourceImpl=" + resourceImpl.toString());
    Message.debug("resourceImpl.exists()" + resourceImpl.exists());
    Message.debug("resourceImpl.getType()" + resourceImpl.getType());
    Message.debug("FileType.FOLDER" + FileType.FOLDER);
    if ((resourceImpl != null) && resourceImpl.exists() && (resourceImpl.getType() == FileType.FOLDER)) {
        FileObject[] children = resourceImpl.getChildren();
        for (int i = 0; i < children.length; i++) {
            FileObject child = children[i];
            Message.debug("child " + i + child.getName().getURI());
            list.add(VfsResource.normalize(child.getName().getURI()));
        }
    }
    return list;
}

From source file:org.apache.ivy.plugins.repository.vfs.VfsResource.java

/**
 * Get a list of direct descendents of the given resource. Note that attempts to get a list of
 * children does <emphasize>not</emphasize> result in an error. Instead an error message is
 * logged and an empty ArrayList returned.
 * /*from www  . j  a  v a 2s. c om*/
 * @return A <code>ArrayList</code> of VFSResources
 */
public List getChildren() {
    init();
    ArrayList list = new ArrayList();
    try {
        if ((resourceImpl != null) && resourceImpl.exists() && (resourceImpl.getType() == FileType.FOLDER)) {
            FileObject[] children = resourceImpl.getChildren();
            for (int i = 0; i < children.length; i++) {
                FileObject child = children[i];
                list.add(normalize(child.getName().getURI()));
            }
        }
    } catch (IOException e) {
        Message.debug(e);
        Message.verbose(e.getLocalizedMessage());
    }
    return list;
}