Update of /cvsroot/xdoclet/xdoclet2/core/src/java/xdoclet/util
In directory sc8-pr-cvs1:/tmp/cvs-serv21720/core/src/java/xdoclet/util

Added Files:
        ClasspathManager.java FileUtils.java LoggerExt.java 
        VelocityConfigurer.java 
Log Message:
moved from xdoclet-commons. Keep it simpler.

--- NEW FILE: ClasspathManager.java ---
package xdoclet.util;

import java.io.File;

import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.log4j.Category;

/**
 * This class finds directories and jars/zips on the classpath.
 *
 * @author    <a href="mailto:[EMAIL PROTECTED]";>Aslak Helles&oslash;y</a>
 * @version   $Revision: 1.1 $
 */
public class ClasspathManager
{
    private final String _classpath;
    private final Predicate _zipsOnly = new ZipPredicate();
    private final Predicate _dirsOnly = new DirPredicate();

    /**
     * Contains directories and jars on the classpath that exist,
     * regardless of whether they have a descriptor
     */
    private final Collection _classpathFiles = new ArrayList();

    /**
     * Default constructor
     *
     * @param classpath where plugin jars and directories will be searched for.
     */
    public ClasspathManager(String classpath)
    {
        if (classpath == null)
        {
            throw new IllegalStateException("classpath can't be null");
        }

        _classpath = classpath;
        findExistingClasspathFiles();
    }

    /**
     * Gets all the files on the classpath that exist, both directories and files.
     *
     * @return Collection of File
     */
    public Collection getClasspathFiles()
    {
        return _classpathFiles;
    }

    /**
     * Returns the existing zip/jar files on the classpath.
     *
     * @return a Collection of File
     */
    public final Collection getZips()
    {
        return CollectionUtils.select(getClasspathFiles(), _zipsOnly);
    }

    /**
     * Returns the existing directories on the classpath.
     *
     * @return a Collection of File
     */
    public final Collection getDirectories()
    {
        return CollectionUtils.select(getClasspathFiles(), _dirsOnly);
    }

    /**
     * Finds existing files and directories on the classpath
     */
    private void findExistingClasspathFiles()
    {
        StringTokenizer pathTokenizer =
                new StringTokenizer(_classpath,
                                    System.getProperty("path.separator"));

        while (pathTokenizer.hasMoreTokens())
        {
            File file = new File(pathTokenizer.nextToken()).getAbsoluteFile();

            if (file.exists())
            {
                _classpathFiles.add(file);
            }
            else
            {
                Category.getInstance(getClass())
                        .warn("The file " + file.getAbsolutePath()
                              + " was on the classpath, but doesn't exist.");
            }
        }
    }

    private class ZipPredicate
        implements Predicate
    {
        public boolean evaluate(Object o)
        {
            File file = (File) o;

            return FileUtils.isZip(file);
        }
    }

    private class DirPredicate
        implements Predicate
    {
        public boolean evaluate(Object o)
        {
            File file = (File) o;

            return file.isDirectory();
        }
    }
}
--- NEW FILE: FileUtils.java ---
package xdoclet.util;

import java.io.*;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Utility methods for dealing with directories and zip files.
 *
 * @author <a href="mailto:aslak.hellesoy at bekk.no">Aslak Helles&oslash;y</a>
 * @version $Revision: 1.1 $
 */
public class FileUtils
{
    /**
     * Returns an InputStream for a resource relative to a file. The file can be a 
directory or a jar file.
     * The InputStream is the resource located relative to the resourcePath passed to 
the
     * ClasspathManager's constructor.
     *
     * @param file directory or zip/jar
     * @param resourcePath the path of the resource, relative to file.
     * @return an InputStream for the relative path to the dir or jar, or null if not 
found.
     */
    public static InputStream getResourceAsStream(File file,
                                                  String resourcePath)
    {
        if (file.isDirectory())
        {
            File descriptorFile =
                    new File(file, resourcePath).getAbsoluteFile();

            try
            {
                return new FileInputStream(descriptorFile);
            }
            catch (FileNotFoundException e)
            {
                // that's fair. just hand back null
                return null;
            }
        }
        else
        {
            // try to treat it as a zip (jar) file, regardless of its name
            try
            {
                ZipFile zip = new ZipFile(file);
                ZipEntry resourceEntry = zip.getEntry(resourcePath);

                if (resourceEntry != null)
                {
                    return zip.getInputStream(resourceEntry);
                }
            }
            catch (IOException e)
            {
                return null;
            }
        }

        return null;
    }

    /**
     * Returns true if the file can be read as a zip file.
     *
     * @param file the file to test.
     * @return true if zip. false otherwise.
     */
    public static boolean isZip(File file)
    {
        try
        {
            new ZipFile(file);

            return true;
        }
        catch (IOException e)
        {
            return false;
        }
    }
}
--- NEW FILE: LoggerExt.java ---
package xdoclet.util;

import org.apache.log4j.Logger;

import java.util.Map;
import java.util.HashMap;

/**
 * Extension of Log4J's Logger class which adds a parameter to the
 * static getLogger method. This is in order to have finer granularity
 * of logging.
 *
 * @author <a href="mailto:[EMAIL PROTECTED]";>Mathias Bogaert</a>
 * @author <a href="aslak.hellesoy at bekk.no">Aslak Helles&oslash;y</a>
 * @version   $Revision: 1.1 $
 */
public class LoggerExt extends Logger {
    // Reusable StringBuffer. Give it an initial length to avoid checking
    // length when clearing it.
    private static final StringBuffer _buffer = new StringBuffer(" ");

    protected LoggerExt(String name) {
        super(name);
    }

    /**
     * Gets a logger
     *
     * @param clazz class using the logger.
     * @param name method name (or some other name) used to get a finer grained
     * logger.
     * @return a Logger instance.
     */
    public static final Logger getLogger(final Class clazz, final String name) {
        _buffer.delete(0,_buffer.length());
        return 
getLogger(_buffer.append(clazz.getName()).append('.').append(name).toString());
    }
}

--- NEW FILE: VelocityConfigurer.java ---
package xdoclet.util;

import java.io.File;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.FileResourceLoader;
import org.apache.velocity.runtime.resource.loader.JarResourceLoader;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

/**
 * Utility class that makes configuration of Velocity's ResourceLoaders easy.
 *
 * @author    <a href="mailto:[EMAIL PROTECTED]";>Aslak Helles&oslash;y</a>
 * @version   $Revision: 1.1 $
 */
public class VelocityConfigurer
{
    private static final Map _resourceLoaders = new HashMap();

    static
    {
        _resourceLoaders.put(JarResourceLoader.class, 
                             new String[] { "jar", "jar:file:" });
        _resourceLoaders.put(FileResourceLoader.class, 
                             new String[] { "file", "" });
    }

    // the engine to configure
    private final VelocityEngine _velocityEngine;

    // comma-separated list of loaders, built incrementally for each invocation of 
addLoader()
    private final StringBuffer _loaders = new StringBuffer();

    /**
     * Constructor
     *
     * @param velocityEngine the engine to configure
     */
    public VelocityConfigurer(VelocityEngine velocityEngine)
    {
        _velocityEngine = velocityEngine;
    }

    /**
     * Returns a Map that should have java.lang.Class objects as keys and a 
2-dimensional
     * String[] as value. the class should be of type 
org.apache.velocity.runtime.resource.loader.ResourceLoader,
     * and the String array should be {name, pathPrefix}. Name is the logical name for 
the loader, and
     * pathPerfix is the required prefix for path entries. The map is preconfigured 
with
     * <ul>
     * <li>org.apache.velocity.runtime.resource.loader.JarResourceLoader -> {"jar", 
"jar:file:"}</li>
     * <li>org.apache.velocity.runtime.resource.loader.FileResourceLoader -> {"file", 
""}</li>
     * </ul>
     * If you need to configure VelocityConfigurer to handle additional Resource 
loader types.
     *
     * @return a Map as described above.
     */
    public static Map getResourceLoaderMap()
    {
        return _resourceLoaders;
    }

    /**
     * Adds a Velocity ResourceLoader
     *
     * @param resourceLoaderClass resource loader class
     * @param files Files to put on resource loader's path
     */
    public void addLoader(Class resourceLoaderClass, Collection files)
    {
        // sanity check
        if (!ResourceLoader.class.isAssignableFrom(resourceLoaderClass))
        {
            throw new IllegalArgumentException(resourceLoaderClass.getName()
                                               + " isn't of type "
                                               + ResourceLoader.class.getName());
        }

        // Setup the loader. See Javadocs for JarResourceLoader or
        // http://jakarta.apache.org/velocity/developer-guide.html
        String[] config = (String[]) _resourceLoaders.get(resourceLoaderClass);

        _velocityEngine.setProperty(config[0] + "." + Velocity.RESOURCE_LOADER
                                    + ".class", resourceLoaderClass.getName());

        // Register all the files.
        StringBuffer fileList = new StringBuffer();
        boolean comma = false;

        if (!files.isEmpty())
        {
            for (Iterator filesIter = files.iterator(); filesIter.hasNext();)
            {
                if (comma)
                {
                    fileList.append(",");
                }

                File file = (File) filesIter.next();

                fileList.append(config[1]).append(file.getAbsolutePath());
                comma = true;
            }

            _velocityEngine.setProperty(config[0] + "."
                                        + Velocity.RESOURCE_LOADER + ".path", 
                                        fileList.toString());

            // Add to the list of loaders
            if (_loaders.length() != 0)
            {
                _loaders.append(",");
            }

            _loaders.append(config[0]);
        }
        else
        {
            System.out.println("No " + config[0] + " resources.");
        }
    }

    public void initVelocity()
                      throws Exception
    {
        _velocityEngine.setProperty(Velocity.RESOURCE_LOADER, 
                                    _loaders.toString());
        _velocityEngine.init();
    }
}


-------------------------------------------------------
This sf.net email is sponsored by: To learn the basics of securing 
your web site with SSL, click here to get a FREE TRIAL of a Thawte 
Server Certificate: http://www.gothawte.com/rd524.html
_______________________________________________
Xdoclet-devel mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/xdoclet-devel

Reply via email to