org.apache.xalan.lib.sql.ObjectFactory

class ObjectFactory {

    private static final String DEFAULT_PROPERTIES_FILENAME =
                                                     "xalan.properties";

    private static final String SERVICES_PATH = "META-INF/services/";

    /** Set to true for debugging */
    private static final boolean DEBUG = false;

    /** cache the contents of the xalan.properties file.
     *  Until an attempt has been made to read this file, this will
     * be null; if the file does not exist or we encounter some other error
     * during the read, this will be empty.
     */
    private static Properties fXalanProperties = null;

    /***
     * Cache the time stamp of the xalan.properties file so
     * that we know if it's been modified and can invalidate
     * the cache when necessary.
     */
    private static long fLastModified = -1;

    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return instance of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Object createObject(String factoryId, String fallbackClassName)
        throws ConfigurationError {
        return createObject(factoryId, null, fallbackClassName);
		}
    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return instance of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Object createObject(String factoryId,
                                      String propertiesFilename,
                                      String fallbackClassName)
        throws ConfigurationError
    {
        Class factoryClass = lookUpFactoryClass(factoryId,
                                                propertiesFilename,
                                                fallbackClassName);

        if (factoryClass == null) {
            throw new ConfigurationError(
                "Provider for " + factoryId + " cannot be found", null);
        }

        try{
            Object instance = factoryClass.newInstance();
            debugPrintln("created new instance of factory " + factoryId);
            return instance;
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider for factory " + factoryId
                    + " could not be instantiated: " + x, x);
        }
	}
    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return Class object of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Class lookUpFactoryClass(String factoryId)
        throws ConfigurationError
    {
        return lookUpFactoryClass(factoryId, null, null);
	}
    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return Class object that provides factory service, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Class lookUpFactoryClass(String factoryId,
                                           String propertiesFilename,
                                           String fallbackClassName)
        throws ConfigurationError
    {
        String factoryClassName = lookUpFactoryClassName(factoryId,
                                                         propertiesFilename,
                                                         fallbackClassName);
        ClassLoader cl = findClassLoader();

        if (factoryClassName == null) {
            factoryClassName = fallbackClassName;
        }

        try{
            Class providerClass = findProviderClass(factoryClassName,
                                                    cl,
                                                    true);
            debugPrintln("created new instance of " + providerClass +
                   " using ClassLoader: " + cl);
            return providerClass;
        } catch (ClassNotFoundException x) {
            throw new ConfigurationError(
                "Provider " + factoryClassName + " not found", x);
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider "+factoryClassName+" could not be instantiated: "+x,
                x);
        }
	}
    /**
     * Finds the name of the required implementation class in the specified
     * order.  The specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return name of class that provides factory service, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static String lookUpFactoryClassName(String factoryId,
                                                String propertiesFilename,
                                                String fallbackClassName)
    {
        SecuritySupport ss = SecuritySupport.getInstance();

        try {
            String systemProp = ss.getSystemProperty(factoryId);
            if (systemProp != null) {
                debugPrintln("found system property, value=" + systemProp);
                return systemProp;
            }
        } catch (SecurityException se) {
        }

        String factoryClassName = null;
        if (propertiesFilename == null) {
            File propertiesFile = null;
            boolean propertiesFileExists = false;
            try {
                String javah = ss.getSystemProperty("java.home");
                propertiesFilename = javah + File.separator +
                    "lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
                propertiesFile = new File(propertiesFilename);
                propertiesFileExists = ss.getFileExists(propertiesFile);
            } catch (SecurityException e) {
                fLastModified = -1;
                fXalanProperties = null;
            }

            synchronized (ObjectFactory.class) {
                boolean loadProperties = false;
                FileInputStream fis = null;
                try {
                    if(fLastModified >= 0) {
                        if(propertiesFileExists &&
                                (fLastModified < (fLastModified = ss.getLastModified(propertiesFile)))) {
                            loadProperties = true;
                        } else {
                            if(!propertiesFileExists) {
                                fLastModified = -1;
                                fXalanProperties = null;
							}
                        }
                    } else {
                        if(propertiesFileExists) {
                            loadProperties = true;
                            fLastModified = ss.getLastModified(propertiesFile);
						}
                    }
                    if(loadProperties) {
                        fXalanProperties = new Properties();
                        fis = ss.getFileInputStream(propertiesFile);
                        fXalanProperties.load(fis);
                    }
	        } catch (Exception x) {
	            fXalanProperties = null;
	            fLastModified = -1;
	        }
                finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        }
                        catch (IOException exc) {}
                    }
                }
            }
            if(fXalanProperties != null) {
                factoryClassName = fXalanProperties.getProperty(factoryId);
            }
        } else {
            FileInputStream fis = null;
            try {
                fis = ss.getFileInputStream(new File(propertiesFilename));
                Properties props = new Properties();
                props.load(fis);
                factoryClassName = props.getProperty(factoryId);
            } catch (Exception x) {
            }
            finally {
                if (fis != null) {
                    try {
                        fis.close();
                    }
                    catch (IOException exc) {}
                }
            }
        }
        if (factoryClassName != null) {
            debugPrintln("found in " + propertiesFilename + ", value="
                          + factoryClassName);
            return factoryClassName;
        }

        return findJarServiceProviderName(factoryId);
	}

    /** Prints a message to standard error if debugging is enabled. */
    private static void debugPrintln(String msg) {
        if (DEBUG) {
            System.err.println("JAXP: " + msg);
        }
	}
    /**
     * Figure out which ClassLoader to use.  For JDK 1.2 and later use
     * the context ClassLoader.
     */
    static ClassLoader findClassLoader()
        throws ConfigurationError
    {
        SecuritySupport ss = SecuritySupport.getInstance();

        ClassLoader context = ss.getContextClassLoader();
        ClassLoader system = ss.getSystemClassLoader();

        ClassLoader chain = system;
        while (true) {
            if (context == chain) {
                ClassLoader current = ObjectFactory.class.getClassLoader();

                chain = system;
                while (true) {
                    if (current == chain) {
                        return system;
                    }
                    if (chain == null) {
                        break;
                    }
                    chain = ss.getParentClassLoader(chain);
                }

                return current;
            }

            if (chain == null) {
                break;
            }

            chain = ss.getParentClassLoader(chain);
        };

        return context;
	}
    /**
     * Create an instance of a class using the specified ClassLoader
     */
    static Object newInstance(String className, ClassLoader cl,
                                      boolean doFallback)
        throws ConfigurationError
    {
        try{
            Class providerClass = findProviderClass(className, cl, doFallback);
            Object instance = providerClass.newInstance();
            debugPrintln("created new instance of " + providerClass +
                   " using ClassLoader: " + cl);
            return instance;
        } catch (ClassNotFoundException x) {
            throw new ConfigurationError(
                "Provider " + className + " not found", x);
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider " + className + " could not be instantiated: " + x,
                x);
        }
    }

    /**
     * Find a Class using the specified ClassLoader
     */
    static Class findProviderClass(String className, ClassLoader cl,
                                           boolean doFallback)
        throws ClassNotFoundException, ConfigurationError
    {
        SecurityManager security = System.getSecurityManager();
        try{
                if (security != null){
                    final int lastDot = className.lastIndexOf(".");
                    String packageName = className;
                    if (lastDot != -1) packageName = className.substring(0, lastDot);
                    security.checkPackageAccess(packageName);
                 }
        }catch(SecurityException e){
            throw e;
        }

        Class providerClass;
        if (cl == null) {
            providerClass = Class.forName(className);
        } else {
            try {
                providerClass = cl.loadClass(className);
            } catch (ClassNotFoundException x) {
                if (doFallback) {
                    ClassLoader current = ObjectFactory.class.getClassLoader();
                    if (current == null) {
                        providerClass = Class.forName(className);
                    } else if (cl != current) {
                        cl = current;
                        providerClass = cl.loadClass(className);
                    } else {
                        throw x;
                    }
                } else {
                    throw x;
                }
            }
        }

        return providerClass;
    }

    /**
     * Find the name of service provider using Jar Service Provider Mechanism
     *
     * @return instance of provider class if found or null
     */
    private static String findJarServiceProviderName(String factoryId)
    {
        SecuritySupport ss = SecuritySupport.getInstance();
        String serviceId = SERVICES_PATH + factoryId;
        InputStream is = null;

        ClassLoader cl = findClassLoader();

        is = ss.getResourceAsStream(cl, serviceId);

        if (is == null) {
            ClassLoader current = ObjectFactory.class.getClassLoader();
            if (cl != current) {
                cl = current;
                is = ss.getResourceAsStream(cl, serviceId);
            }
        }

        if (is == null) {
            return null;
        }

        debugPrintln("found jar resource=" + serviceId +
               " using ClassLoader: " + cl);

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (java.io.UnsupportedEncodingException e) {
            rd = new BufferedReader(new InputStreamReader(is));
        }

        String factoryClassName = null;
        try {
            factoryClassName = rd.readLine();
        } catch (IOException x) {
            return null;
        }
        finally {
            try {
                rd.close();
            }
            catch (IOException exc) {}
        }

        if (factoryClassName != null &&
            ! "".equals(factoryClassName)) {
            debugPrintln("found in resource, value="
                   + factoryClassName);

            return factoryClassName;
        }

        return null;
    }

    /**
     * A configuration error.
     */
    static class ConfigurationError
        extends Error {
                static final long serialVersionUID = 3273432303767233578L;

        /** Exception. */
        private Exception exception;

        /**
         * Construct a new instance with the specified detail string and
         * exception.
         */
        ConfigurationError(String msg, Exception x) {
            super(msg);
            this.exception = x;
		}

        /** Returns the exception associated to this error. */
        Exception getException() {
            return exception;

FUNC_DECL RETURN PARAM PARAM CALL LITERAL_ANCHOR


public class URLResolver implements ExtensionResolver {
    private File destfile;
    private File destdir;
    private URL url;

    /**
     * Sets the URL
     * @param url the url
     */
    public void setUrl(final URL url) {
        this.url = url;
    }

    /**
     * Sets the destination file
     * @param destfile the destination file
     */
    public void setDestfile(final File destfile) {
        this.destfile = destfile;
    }

    /**
     * Sets the destination directory
     * @param destdir the destination directory
     */
    public void setDestdir(final File destdir) {
        this.destdir = destdir;
    }

    /**
     * Returns the file resolved from URL and directory
     * @param extension the extention
     * @param project the project
     * @return file the file resolved
     * @throws BuildException if the URL is invalid
     */
    public File resolve(final Extension extension,
                         final Project project) throws BuildException {
        validate();

        final File file = getDest();

        final Get get = new Get();
        get.setProject(project);
        get.setDest(file);
        get.setSrc(url);
        get.execute();

        return file;
    }

    /*
     * Gets the destination file
     */
    private File getDest() {
        File result;
        if (null != destfile) {
            result = destfile;
        } else {
            final String file = url.getFile();
            String filename;
            if (null == file || file.length() <= 1) {
                filename = "default.file";
            } else {
                int index = file.lastIndexOf('/');
                if (-1 == index) {
                    index = 0;
                }
                filename = file.substring(index);
            }
            result = new File(destdir, filename);
        }
        return result;
    }

    /*
     * Validates URL
     */
    private void validate() {
        if (null == url) {
            final String message = "Must specify URL";
            throw new BuildException(message);
        }

        if (null == destdir && null == destfile) {
            final String message = "Must specify destination file or directory";
            throw new BuildException(message);
        } else if (null != destdir && null != destfile) {
            final String message = "Must not specify both destination file or directory";
            throw new BuildException(message);
        }
    }

    /**
     * Returns a string representation of the URL
     * @return the string representation
     */
    public String toString() {
        return "URL[" + url + "]";

FUNC_DECL RETURN VAR_DECL VAR_DECL PARAM PARAM CALL CALL CALL CALL CALL CALL CALL


class ObjectFactory {

    private static final String DEFAULT_PROPERTIES_FILENAME =
                                                     "xalan.properties";

    private static final String SERVICES_PATH = "META-INF/services/";

    /** Set to true for debugging */
    private static final boolean DEBUG = false;

    /** cache the contents of the xalan.properties file.
     *  Until an attempt has been made to read this file, this will
     * be null; if the file does not exist or we encounter some other error
     * during the read, this will be empty.
     */
    private static Properties fXalanProperties = null;

    /***
     * Cache the time stamp of the xalan.properties file so
     * that we know if it's been modified and can invalidate
     * the cache when necessary.
     */
    private static long fLastModified = -1;

    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return instance of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Object createObject(String factoryId, String fallbackClassName)
        throws ConfigurationError {
        return createObject(factoryId, null, fallbackClassName);
		}
    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return instance of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Object createObject(String factoryId,
                                      String propertiesFilename,
                                      String fallbackClassName)
        throws ConfigurationError
    {
        Class factoryClass = lookUpFactoryClass(factoryId,
                                                propertiesFilename,
                                                fallbackClassName);

        if (factoryClass == null) {
            throw new ConfigurationError(
                "Provider for " + factoryId + " cannot be found", null);
        }

        try{
            Object instance = factoryClass.newInstance();
            debugPrintln("created new instance of factory " + factoryId);
            return instance;
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider for factory " + factoryId
                    + " could not be instantiated: " + x, x);
        }
	}
    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return Class object of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Class lookUpFactoryClass(String factoryId)
        throws ConfigurationError
    {
        return lookUpFactoryClass(factoryId, null, null);
	}
    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return Class object that provides factory service, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static Class lookUpFactoryClass(String factoryId,
                                           String propertiesFilename,
                                           String fallbackClassName)
        throws ConfigurationError
    {
        String factoryClassName = lookUpFactoryClassName(factoryId,
                                                         propertiesFilename,
                                                         fallbackClassName);
        ClassLoader cl = findClassLoader();

        if (factoryClassName == null) {
            factoryClassName = fallbackClassName;
        }

        try{
            Class providerClass = findProviderClass(factoryClassName,
                                                    cl,
                                                    true);
            debugPrintln("created new instance of " + providerClass +
                   " using ClassLoader: " + cl);
            return providerClass;
        } catch (ClassNotFoundException x) {
            throw new ConfigurationError(
                "Provider " + factoryClassName + " not found", x);
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider "+factoryClassName+" could not be instantiated: "+x,
                x);
        }
	}
    /**
     * Finds the name of the required implementation class in the specified
     * order.  The specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return name of class that provides factory service, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xalan.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    static String lookUpFactoryClassName(String factoryId,
                                                String propertiesFilename,
                                                String fallbackClassName)
    {
        SecuritySupport ss = SecuritySupport.getInstance();

        try {
            String systemProp = ss.getSystemProperty(factoryId);
            if (systemProp != null) {
                debugPrintln("found system property, value=" + systemProp);
                return systemProp;
            }
        } catch (SecurityException se) {
        }

        String factoryClassName = null;
        if (propertiesFilename == null) {
            File propertiesFile = null;
            boolean propertiesFileExists = false;
            try {
                String javah = ss.getSystemProperty("java.home");
                propertiesFilename = javah + File.separator +
                    "lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
                propertiesFile = new File(propertiesFilename);
                propertiesFileExists = ss.getFileExists(propertiesFile);
            } catch (SecurityException e) {
                fLastModified = -1;
                fXalanProperties = null;
            }

            synchronized (ObjectFactory.class) {
                boolean loadProperties = false;
                FileInputStream fis = null;
                try {
                    if(fLastModified >= 0) {
                        if(propertiesFileExists &&
                                (fLastModified < (fLastModified = ss.getLastModified(propertiesFile)))) {
                            loadProperties = true;
                        } else {
                            if(!propertiesFileExists) {
                                fLastModified = -1;
                                fXalanProperties = null;
							}
                        }
                    } else {
                        if(propertiesFileExists) {
                            loadProperties = true;
                            fLastModified = ss.getLastModified(propertiesFile);
						}
                    }
                    if(loadProperties) {
                        fXalanProperties = new Properties();
                        fis = ss.getFileInputStream(propertiesFile);
                        fXalanProperties.load(fis);
                    }
	        } catch (Exception x) {
	            fXalanProperties = null;
	            fLastModified = -1;
	        }
                finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        }
                        catch (IOException exc) {}
                    }
                }
            }
            if(fXalanProperties != null) {
                factoryClassName = fXalanProperties.getProperty(factoryId);
            }
        } else {
            FileInputStream fis = null;
            try {
                fis = ss.getFileInputStream(new File(propertiesFilename));
                Properties props = new Properties();
                props.load(fis);
                factoryClassName = props.getProperty(factoryId);
            } catch (Exception x) {
            }
            finally {
                if (fis != null) {
                    try {
                        fis.close();
                    }
                    catch (IOException exc) {}
                }
            }
        }
        if (factoryClassName != null) {
            debugPrintln("found in " + propertiesFilename + ", value="
                          + factoryClassName);
            return factoryClassName;
        }

        return findJarServiceProviderName(factoryId);
	}

    /** Prints a message to standard error if debugging is enabled. */
    private static void debugPrintln(String msg) {
        if (DEBUG) {
            System.err.println("JAXP: " + msg);
        }
	}
    /**
     * Figure out which ClassLoader to use.  For JDK 1.2 and later use
     * the context ClassLoader.
     */
    static ClassLoader findClassLoader()
        throws ConfigurationError
    {
        SecuritySupport ss = SecuritySupport.getInstance();

        ClassLoader context = ss.getContextClassLoader();
        ClassLoader system = ss.getSystemClassLoader();

        ClassLoader chain = system;
        while (true) {
            if (context == chain) {
                ClassLoader current = ObjectFactory.class.getClassLoader();

                chain = system;
                while (true) {
                    if (current == chain) {
                        return system;
                    }
                    if (chain == null) {
                        break;
                    }
                    chain = ss.getParentClassLoader(chain);
                }

                return current;
            }

            if (chain == null) {
                break;
            }

            chain = ss.getParentClassLoader(chain);
        };

        return context;
	}
    /**
     * Create an instance of a class using the specified ClassLoader
     */
    static Object newInstance(String className, ClassLoader cl,
                                      boolean doFallback)
        throws ConfigurationError
    {
        try{
            Class providerClass = findProviderClass(className, cl, doFallback);
            Object instance = providerClass.newInstance();
            debugPrintln("created new instance of " + providerClass +
                   " using ClassLoader: " + cl);
            return instance;
        } catch (ClassNotFoundException x) {
            throw new ConfigurationError(
                "Provider " + className + " not found", x);
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider " + className + " could not be instantiated: " + x,
                x);
        }
    }

    /**
     * Find a Class using the specified ClassLoader
     */
    static Class findProviderClass(String className, ClassLoader cl,
                                           boolean doFallback)
        throws ClassNotFoundException, ConfigurationError
    {
        SecurityManager security = System.getSecurityManager();
        try{
                if (security != null){
                    final int lastDot = className.lastIndexOf(".");
                    String packageName = className;
                    if (lastDot != -1) packageName = className.substring(0, lastDot);
                    security.checkPackageAccess(packageName);
                 }
        }catch(SecurityException e){
            throw e;
        }

        Class providerClass;
        if (cl == null) {
            providerClass = Class.forName(className);
        } else {
            try {
                providerClass = cl.loadClass(className);
            } catch (ClassNotFoundException x) {
                if (doFallback) {
                    ClassLoader current = ObjectFactory.class.getClassLoader();
                    if (current == null) {
                        providerClass = Class.forName(className);
                    } else if (cl != current) {
                        cl = current;
                        providerClass = cl.loadClass(className);
                    } else {
                        throw x;
                    }
                } else {
                    throw x;
                }
            }
        }

        return providerClass;
    }

    /**
     * Find the name of service provider using Jar Service Provider Mechanism
     *
     * @return instance of provider class if found or null
     */
    private static String findJarServiceProviderName(String factoryId)
    {
        SecuritySupport ss = SecuritySupport.getInstance();
        String serviceId = SERVICES_PATH + factoryId;
        InputStream is = null;

        ClassLoader cl = findClassLoader();

        is = ss.getResourceAsStream(cl, serviceId);

        if (is == null) {
            ClassLoader current = ObjectFactory.class.getClassLoader();
            if (cl != current) {
                cl = current;
                is = ss.getResourceAsStream(cl, serviceId);
            }
        }

        if (is == null) {
            return null;
        }

        debugPrintln("found jar resource=" + serviceId +
               " using ClassLoader: " + cl);

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (java.io.UnsupportedEncodingException e) {
            rd = new BufferedReader(new InputStreamReader(is));
        }

        String factoryClassName = null;
        try {
            factoryClassName = rd.readLine();
        } catch (IOException x) {
            return null;
        }
        finally {
            try {
                rd.close();
            }
            catch (IOException exc) {}
        }

        if (factoryClassName != null &&
            ! "".equals(factoryClassName)) {
            debugPrintln("found in resource, value="
                   + factoryClassName);

            return factoryClassName;
        }

        return null;
    }

    /**
     * A configuration error.
     */
    static class ConfigurationError
        extends Error {
                static final long serialVersionUID = -6072257854297546607L;

        /** Exception. */
        private Exception exception;

        /**
         * Construct a new instance with the specified detail string and
         * exception.
         */
        ConfigurationError(String msg, Exception x) {
            super(msg);
            this.exception = x;
		}

        /** Returns the exception associated to this error. */
        Exception getException() {
            return exception;


public class AtomEntryPollingConsumer extends AtomPollingConsumer {
    private Document<Feed> document;
    private int entryIndex;
    private EntryFilter entryFilter;
    private List<Entry> list;

    public AtomEntryPollingConsumer(AtomEndpoint endpoint, Processor processor, boolean filter,
                                    Date lastUpdate) {
        super(endpoint, processor);
        if (filter) {
            entryFilter = new UpdatedDateFilter(lastUpdate);
        }
    }

    public void poll() throws Exception {
        getDocument();
        Feed feed = document.getRoot();

        while (hasNextEntry()) {
            Entry entry = list.get(entryIndex--);

            boolean valid = true;
            if (entryFilter != null) {
                valid = entryFilter.isValidEntry(endpoint, document, entry);
            }
            if (valid) {
                Exchange exchange = endpoint.createExchange(feed, entry);
                getProcessor().process(exchange);
                return;
            }
        }

        document = null;
    }

    private Document<Feed> getDocument() throws IOException, ParseException {
        if (document == null) {
            document = AtomUtils.parseDocument(endpoint.getAtomUri());
            list = document.getRoot().getEntries();
            entryIndex = list.size() - 1;
        }
        return document;
    }

    private boolean hasNextEntry() {
        return entryIndex >= 0;

FUNC_DECL RETURN IF BINARY_OP LITERAL_ANCHOR ASSIGN ASSIGN ASSIGN BINARY_OP CALL CALL LITERAL_ANCHOR CALL CALL CALL

FUNC_DECL IF PARAM PARAM PARAM PARAM ASSIGN CALL


public class SQLErrorDocument extends DTMDocument
{
  /**
   */
  private static final String S_EXT_ERROR = "ext-error";
  /**
   */
  private static final String S_SQL_ERROR = "sql-error";
  /**
   */
  private static final String S_MESSAGE = "message";
  /**
   */
  private static final String S_CODE = "code";

  /**
   */
  private int m_ErrorExt_TypeID = DTM.NULL;
  /**
   */
  private int m_Message_TypeID = DTM.NULL;
  /**
   */
  private int m_Code_TypeID = DTM.NULL;

  /**
   */
  private int m_SQLError_TypeID = DTM.NULL;

  /**
   */
  private int m_rootID = DTM.NULL;
  /**
   */
  private int m_extErrorID = DTM.NULL;
  /**
   */
  private int m_MainMessageID = DTM.NULL;

  /**
   * Build up an SQLErrorDocument that includes the basic error information
   * along with the Extended SQL Error information.
   * @param mgr
   * @param ident
   * @param error
   */
  public SQLErrorDocument( DTMManager mgr, int ident, SQLException error )
  {
    super(mgr, ident);

    createExpandedNameTable();
    buildBasicStructure(error);

    int sqlError = addElement(2, m_SQLError_TypeID, m_extErrorID, m_MainMessageID);
    int element = DTM.NULL;

    element = addElementWithData(
      new Integer(error.getErrorCode()), 3,
      m_Code_TypeID, sqlError, element);

    element = addElementWithData(
      error.getLocalizedMessage(), 3,
      m_Message_TypeID, sqlError, element);

  }

  /**
   * Build up an Error Exception with just the Standard Error Information
   * @param mgr
   * @param ident
   * @param error
   */
  public SQLErrorDocument( DTMManager mgr, int ident, Exception error )
  {
    super(mgr, ident);
    createExpandedNameTable();
    buildBasicStructure(error);
  }

  /**
   * Build up the basic structure that is common for each error.
   * @param e
   * @return
   */
  private void buildBasicStructure( Exception e )
  {
    m_rootID = addElement(0, m_Document_TypeID, DTM.NULL, DTM.NULL);
    m_extErrorID = addElement(1, m_ErrorExt_TypeID, m_rootID, DTM.NULL);
    m_MainMessageID = addElementWithData
      (e.getLocalizedMessage(), 2, m_Message_TypeID, m_extErrorID, DTM.NULL);
  }

  /**
   * Populate the Expanded Name Table with the Node that we will use.
   * Keep a reference of each of the types for access speed.
   * @return
   */
  protected void createExpandedNameTable( )
  {

    super.createExpandedNameTable();

    m_ErrorExt_TypeID =
      m_expandedNameTable.getExpandedTypeID(S_NAMESPACE, S_EXT_ERROR, DTM.ELEMENT_NODE);

    m_SQLError_TypeID =
      m_expandedNameTable.getExpandedTypeID(S_NAMESPACE, S_SQL_ERROR, DTM.ELEMENT_NODE);

    m_Message_TypeID =
      m_expandedNameTable.getExpandedTypeID(S_NAMESPACE, S_MESSAGE, DTM.ELEMENT_NODE);

    m_Code_TypeID =
      m_expandedNameTable.getExpandedTypeID(S_NAMESPACE, S_CODE, DTM.ELEMENT_NODE);

FUNC_DECL PARAM ASSIGN ASSIGN ASSIGN CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR

FUNC_DECL ASSIGN ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL

FUNC_DECL VAR_DECL VAR_DECL PARAM PARAM PARAM ASSIGN ASSIGN CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL


public class ExtensionsTable
{
  /**
   * Table of extensions that may be called from the expression language
   * via the call(name, ...) function.  Objects are keyed on the call
   * name.
   * @xsl.usage internal
   */
  public Hashtable m_extensionFunctionNamespaces = new Hashtable();

  /**
   * The StylesheetRoot associated with this extensions table.
   */
  private StylesheetRoot m_sroot;

  /**
   * The constructor (called from TransformerImpl) registers the
   * StylesheetRoot for the transformation and instantiates an
   * ExtensionHandler for each extension namespace.
   * @xsl.usage advanced
   */
  public ExtensionsTable(StylesheetRoot sroot)
    throws javax.xml.transform.TransformerException
  {
    m_sroot = sroot;
    Vector extensions = m_sroot.getExtensions();
    for (int i = 0; i < extensions.size(); i++)
    {
      ExtensionNamespaceSupport extNamespaceSpt =
                 (ExtensionNamespaceSupport)extensions.elementAt(i);
      ExtensionHandler extHandler = extNamespaceSpt.launch();
        if (extHandler != null)
          addExtensionNamespace(extNamespaceSpt.getNamespace(), extHandler);
      }
    }

  /**
   * Get an ExtensionHandler object that represents the
   * given namespace.
   * @param extns A valid extension namespace.
   *
   * @return ExtensionHandler object that represents the
   * given namespace.
   */
  public ExtensionHandler get(String extns)
  {
    return (ExtensionHandler) m_extensionFunctionNamespaces.get(extns);
  }

  /**
   * Register an extension namespace handler. This handler provides
   * functions for testing whether a function is known within the
   * namespace and also for invoking the functions.
   *
   * @param uri the URI for the extension.
   * @param extNS the extension handler.
   * @xsl.usage advanced
   */
  public void addExtensionNamespace(String uri, ExtensionHandler extNS)
  {
    m_extensionFunctionNamespaces.put(uri, extNS);
  }

  /**
   * Execute the function-available() function.
   * @param ns       the URI of namespace in which the function is needed
   * @param funcName the function name being tested
   *
   * @return whether the given function is available or not.
   *
   * @throws javax.xml.transform.TransformerException
   */
  public boolean functionAvailable(String ns, String funcName)
          throws javax.xml.transform.TransformerException
  {
    boolean isAvailable = false;

    if (null != ns)
    {
      ExtensionHandler extNS =
           (ExtensionHandler) m_extensionFunctionNamespaces.get(ns);
      if (extNS != null)
        isAvailable = extNS.isFunctionAvailable(funcName);
    }
    return isAvailable;
  }

  /**
   * Execute the element-available() function.
   * @param ns       the URI of namespace in which the function is needed
   * @param elemName name of element being tested
   *
   * @return whether the given element is available or not.
   *
   * @throws javax.xml.transform.TransformerException
   */
  public boolean elementAvailable(String ns, String elemName)
          throws javax.xml.transform.TransformerException
  {
    boolean isAvailable = false;
    if (null != ns)
    {
      ExtensionHandler extNS =
               (ExtensionHandler) m_extensionFunctionNamespaces.get(ns);
        isAvailable = extNS.isElementAvailable(elemName);
    }
    return isAvailable;
  }

  /**
   * Handle an extension function.
   * @param ns        the URI of namespace in which the function is needed
   * @param funcName  the function name being called
   * @param argVec    arguments to the function in a vector
   * @param methodKey a unique key identifying this function instance in the
   *                  stylesheet
   * @param exprContext a context which may be passed to an extension function
   *                  and provides callback functions to access various
   *                  areas in the environment
   *
   * @return result of executing the function
   *
   * @throws javax.xml.transform.TransformerException
   */
  public Object extFunction(String ns, String funcName,
                            Vector argVec, Object methodKey,
                            ExpressionContext exprContext)
            throws javax.xml.transform.TransformerException
  {
    Object result = null;
    if (null != ns)
    {
      ExtensionHandler extNS =
        (ExtensionHandler) m_extensionFunctionNamespaces.get(ns);
      if (null != extNS)
      {
        try
        {
          result = extNS.callFunction(funcName, argVec, methodKey,
                                      exprContext);
        }
        catch (javax.xml.transform.TransformerException e)
        {
          throw e;
        }
        catch (Exception e)
        {
          throw new javax.xml.transform.TransformerException(e);
        }
      }
      else
      {
        throw new XPathProcessorException(XSLMessages.createMessage(XSLTErrorResources.ER_EXTENSION_FUNC_UNKNOWN, new Object[]{ns, funcName }));
      }
    }
    return result;
  }

  /**
   * Handle an extension function.
   * @param extFunction  the extension function
   * @param argVec    arguments to the function in a vector
   * @param exprContext a context which may be passed to an extension function
   *                  and provides callback functions to access various
   *                  areas in the environment
   *
   * @return result of executing the function
   *
   * @throws javax.xml.transform.TransformerException
   */
  public Object extFunction(FuncExtFunction extFunction, Vector argVec,
                            ExpressionContext exprContext)
         throws javax.xml.transform.TransformerException
  {
    Object result = null;
    String ns = extFunction.getNamespace();
    if (null != ns)
    {
      ExtensionHandler extNS =
        (ExtensionHandler) m_extensionFunctionNamespaces.get(ns);
      if (null != extNS)
      {
        try
        {
          result = extNS.callFunction(extFunction, argVec, exprContext);
        }
        catch (javax.xml.transform.TransformerException e)
        {
          throw e;
        }
        catch (Exception e)
        {
          throw new javax.xml.transform.TransformerException(e);
        }
      }
      else
      {
        throw new XPathProcessorException(XSLMessages.createMessage(XSLTErrorResources.ER_EXTENSION_FUNC_UNKNOWN,
                                          new Object[]{ns, extFunction.getFunctionName()}));
      }
    }
    return result;


public class ScriptLanguage implements Language {
    private final String language;

    public ScriptLanguage(String language) {
        this.language = language;
    }

    public Predicate<Exchange> createPredicate(String expression) {
        return new ScriptBuilder(language, expression);
    }

    public Expression<Exchange> createExpression(String expression) {
        return new ScriptBuilder(language, expression);


class ErrorListCellRenderer extends JComponent implements ListCellRenderer
{
	//{{{ ErrorListCellRenderer constructor
	ErrorListCellRenderer()
	{
		plainFont = UIManager.getFont("Label.font");
		boldFont = new Font(plainFont.getName(),Font.BOLD,plainFont.getSize());
		plainFM = getFontMetrics(plainFont);
		boldFM = getFontMetrics(boldFont);

		setBorder(new EmptyBorder(2,2,2,2));
	} //}}}

	//{{{ getListCellRendererComponent() method
	public Component getListCellRendererComponent(JList list, Object value,
		int index, boolean isSelected, boolean cellHasFocus)
	{
		ErrorListDialog.ErrorEntry entry = (ErrorListDialog.ErrorEntry)value;
		this.path = entry.path + ":";
		this.messages = entry.messages;
		return this;
	} //}}}

	//{{{ getPreferredSize() method
	public Dimension getPreferredSize()
	{
		int width = boldFM.stringWidth(path);
		int height = boldFM.getHeight();
		for(int i = 0; i < messages.length; i++)
		{
			width = Math.max(plainFM.stringWidth(messages[i]),width);
			height += plainFM.getHeight();
		}

		Insets insets = getBorder().getBorderInsets(this);
		width += insets.left + insets.right;
		height += insets.top + insets.bottom;

		return new Dimension(width,height);
	} //}}}

	//{{{ paintComponent() method
	public void paintComponent(Graphics g)
	{
		Insets insets = getBorder().getBorderInsets(this);
		g.setFont(boldFont);
		g.drawString(path,insets.left,insets.top + boldFM.getAscent());
		int y = insets.top + boldFM.getHeight() + 2;
		g.setFont(plainFont);
		for(int i = 0; i < messages.length; i++)
		{
			g.drawString(messages[i],insets.left,y + plainFM.getAscent());
			y += plainFM.getHeight();
		}
	} //}}}

	//{{{ Instance variables
	private String path;
	private String[] messages;
	private Font plainFont;
	private Font boldFont;
	private FontMetrics plainFM;
	private FontMetrics boldFM;

FUNC_DECL RETURN VAR_DECL PARAM PARAM PARAM PARAM PARAM ASSIGN ASSIGN BINARY_OP LITERAL_ANCHOR

FUNC_DECL CALL ASSIGN ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL LITERAL_ANCHOR


org.apache.tools.ant.taskdefs.Available

public class Available extends Task implements Condition {

    private String property;
    private String classname;
    private File file;
    private Path filepath;
    private String resource;
    private String type;
    private Path classpath;
    private AntClassLoader loader;
    private String value = "true";

    public void setClasspath(Path classpath) {
        createClasspath().append(classpath);
    }

    public Path createClasspath() {
        if (this.classpath == null) {
            this.classpath = new Path(project);
        }
        return this.classpath.createPath();
    }

    public void setClasspathRef(Reference r) {
        createClasspath().setRefid(r);
    }

    public void setFilepath(Path filepath) {
        createFilepath().append(filepath);
    }

    public Path createFilepath() {
        if (this.filepath == null) {
            this.filepath = new Path(project);
        }
        return this.filepath.createPath();
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setClassname(String classname) {
        if (!"".equals(classname)) {
            this.classname = classname;
        }
    }

    public void setFile(File file) {
        this.file = file;
    }

    public void setResource(String resource) {
        this.resource = resource;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void execute() throws BuildException {
        if (property == null) {
            throw new BuildException("property attribute is required", location);
        }

        if (eval()) {
            this.project.setProperty(property, value);
        }
    }

    public boolean  eval() throws BuildException {
        if (classname == null && file == null && resource == null) {
            throw new BuildException("At least one of (classname|file|resource) is required", location);
        }

        if (type != null){
            if (!type.equalsIgnoreCase("file") && !type.equalsIgnoreCase("dir")){
                throw new BuildException("Type must be one of either dir or file");
            }
        }

        if (classpath != null) {
            classpath.setProject(project);
            this.loader = new AntClassLoader(project, classpath);
        }

        if ((classname != null) && !checkClass(classname)) {
            log("Unable to load class " + classname + " to set property " + property, Project.MSG_VERBOSE);
            return false;
        }

        if ((file != null) && !checkFile()) {
            log("Unable to find " + file + " to set property " + property, Project.MSG_VERBOSE);
            return false;
        }

        if ((resource != null) && !checkResource(resource)) {
            log("Unable to load resource " + resource + " to set property " + property, Project.MSG_VERBOSE);
            return false;
        }

        if (loader != null) {
            loader.cleanup();
        }

        return true;
    }

    private boolean checkFile() {
        if (filepath == null) {
            return checkFile(file);
        } else {
            String[] paths = filepath.list();
            for(int i = 0; i < paths.length; ++i) {
                log("Searching " + paths[i], Project.MSG_VERBOSE);
                if(new File(paths[i], file.getName()).isFile()) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean checkFile(File file) {
        if (type != null) {
            if (type.equalsIgnoreCase("dir")) {
                return file.isDirectory();
            } else if (type.equalsIgnoreCase("file")) {
                return file.isFile();
            }
        }
        return file.exists();
    }

    private boolean checkResource(String resource) {
        if (loader != null) {
            return (loader.getResourceAsStream(resource) != null);
        } else {
            ClassLoader cL = this.getClass().getClassLoader();
            if (cL != null) {
                return (cL.getResourceAsStream(resource) != null);
            } else {
                return
                    (ClassLoader.getSystemResourceAsStream(resource) != null);
            }
        }
    }

    private boolean checkClass(String classname) {
        try {
            if (loader != null) {
                loader.loadClass(classname);
            } else {
                ClassLoader l = this.getClass().getClassLoader();
                if (l != null) {
                    l.loadClass(classname);
                } else {
                    Class.forName(classname);
                }
            }
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        } catch (NoClassDefFoundError e) {
            return false;

FUNC_DECL IF PARAM LITERAL_ANCHOR CALL ASSIGN

FUNC_DECL RETURN IF PARAM CALL BINARY_OP IF LITERAL_ANCHOR IF CALL CALL RETURN LITERAL_ANCHOR RETURN LITERAL_ANCHOR CALL CALL


public class NewVsSetLen {

  static String s;

  static int BIGBUF_LEN = 1048576;
  static int SBUF_LEN = 256;
  static int RUN_LENGTH = BIGBUF_LEN/4;

  static char[] sbuf = new char[SBUF_LEN];
  static char[] bigbuf = new char[BIGBUF_LEN];

  {
    for(int i = 0; i < SBUF_LEN; i++) {
      sbuf[i] = (char) (i);
    }

    for(int i = 0; i < BIGBUF_LEN; i++) {
      bigbuf[i] = (char) (i);
    }
  }

  static
  public
  void main(String[] args) {

    int t;

    for(int len = SBUF_LEN; len <= BIGBUF_LEN; len*=4, RUN_LENGTH /= 4) {
      System.out.println("<td>"+len+"\n");
      for(int second = 0; second < 16;) {
	System.out.println("SECOND loop="+second +", RUN_LENGTH="
			   +RUN_LENGTH+", len="+len);
	t = (int)newBuffer(len, second);

	System.out.print("<td>" + t);
	t = (int)setLen(len, second);
	System.out.println(" <td>" + t + " \n");
	if(second == 0) {
	  second = 1;
	} else {
	  second *= 2;
	}
      }
    }

  }

  static
  double newBuffer(int size, int second) {
    long before = System.currentTimeMillis();

    for(int i = 0; i < RUN_LENGTH; i++) {
      StringBuffer buf = new StringBuffer(SBUF_LEN);
      buf.append(sbuf, 0, sbuf.length);
      buf.append(bigbuf, 0, size);
      s = buf.toString();
    }

    for(int x = 0; x <  second; x++) {
      StringBuffer buf = new StringBuffer(SBUF_LEN);
      buf.append(sbuf, 0, SBUF_LEN);
      s = buf.toString();
    }
    return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH;
  }

  static
  double setLen(int size, int second) {
    long before = System.currentTimeMillis();

    StringBuffer buf = new StringBuffer(SBUF_LEN);

    for(int i = 0; i < RUN_LENGTH; i++) {
      buf.append(sbuf, 0, sbuf.length);
      buf.append(bigbuf, 0, size);
      s = buf.toString();
      buf.setLength(0);
    }

    for(int x = 0; x < second; x++) {
      buf.append(sbuf, 0, SBUF_LEN);
      s = buf.toString();
      buf.setLength(0);
    }
    return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH;


public class EventConsumer extends DefaultConsumer<Exchange> {
    private EventEndpoint endpoint;

    public EventConsumer(EventEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
        this.endpoint = endpoint;
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        endpoint.consumerStarted(this);
    }

    @Override
    protected void doStop() throws Exception {
        endpoint.consumerStopped(this);
        super.doStop();


org.apache.xalan.templates.ElemText

public class ElemText extends ElemTemplateElement
{
    static final long serialVersionUID = 1383140876182316711L;

  /**
   * Tells if this element should disable escaping.
   * @serial
   */
  private boolean m_disableOutputEscaping = false;

  /**
   * Set the "disable-output-escaping" attribute.
   * Normally, the xml output method escapes & and < (and
   * possibly other characters) when outputting text nodes.
   * This ensures that the output is well-formed XML. However,
   * it is sometimes convenient to be able to produce output
   * that is almost, but not quite well-formed XML; for
   * example, the output may include ill-formed sections
   * which are intended to be transformed into well-formed
   * XML by a subsequent non-XML aware process. For this reason,
   * XSLT provides a mechanism for disabling output escaping.
   * An xsl:value-of or xsl:text element may have a
   * disable-output-escaping attribute; the allowed values
   * are yes or no; the default is no; if the value is yes,
   * then a text node generated by instantiating the xsl:value-of
   * or xsl:text element should be output without any escaping.
   *
   * @param v Boolean flag indicating whether this element should disable escaping
   */
  public void setDisableOutputEscaping(boolean v)
  {
    m_disableOutputEscaping = v;
  }

  /**
   * Get the "disable-output-escaping" attribute.
   * Normally, the xml output method escapes & and < (and
   * possibly other characters) when outputting text nodes.
   * This ensures that the output is well-formed XML. However,
   * it is sometimes convenient to be able to produce output
   * that is almost, but not quite well-formed XML; for
   * example, the output may include ill-formed sections
   * which are intended to be transformed into well-formed
   * XML by a subsequent non-XML aware process. For this reason,
   * XSLT provides a mechanism for disabling output escaping.
   * An xsl:value-of or xsl:text element may have a
   * disable-output-escaping attribute; the allowed values
   * are yes or no; the default is no; if the value is yes,
   * then a text node generated by instantiating the xsl:value-of
   * or xsl:text element should be output without any escaping.
   *
   * @return Boolean flag indicating whether this element should disable escaping
   */
  public boolean getDisableOutputEscaping()
  {
    return m_disableOutputEscaping;
  }

  /**
   * Get an integer representation of the element type.
   *
   * @return An integer representation of the element, defined in the
   *     Constants class.
   * @see org.apache.xalan.templates.Constants
   */
  public int getXSLToken()
  {
    return Constants.ELEMNAME_TEXT;
  }

  /**
   * Return the node name.
   *
   * @return The element's name
   */
  public String getNodeName()
  {
    return Constants.ELEMNAME_TEXT_STRING;
  }

  /**
   * Add a child to the child list.
   *
   * @param newChild Child to add to children list
   *
   * @return Child added to children list
   *
   * @throws DOMException
   */
  public ElemTemplateElement appendChild(ElemTemplateElement newChild)
  {

    int type = ((ElemTemplateElement) newChild).getXSLToken();

    switch (type)
    {
    case Constants.ELEMNAME_TEXTLITERALRESULT :
      break;
    default :
      error(XSLTErrorResources.ER_CANNOT_ADD,
            new Object[]{ newChild.getNodeName()});

    }

    return super.appendChild(newChild);


public class SAX2DOM implements ContentHandler, LexicalHandler, Constants {

    private Node _root = null;
    private Document _document = null;
    private Stack _nodeStk = new Stack();
    private Vector _namespaceDecls = null;

    public SAX2DOM() throws ParserConfigurationException {
	final DocumentBuilderFactory factory =
		DocumentBuilderFactory.newInstance();
	_document = factory.newDocumentBuilder().newDocument();
	_root = _document;
    }

    public SAX2DOM(Node root) throws ParserConfigurationException {
	_root = root;
	if (root instanceof Document) {
	  _document = (Document)root;
	}
	else if (root != null) {
	  _document = root.getOwnerDocument();
	}
	else {
	  final DocumentBuilderFactory factory =
		DocumentBuilderFactory.newInstance();
	  _document = factory.newDocumentBuilder().newDocument();
	  _root = _document;
	}
    }

    public Node getDOM() {
	return _root;
    }

    public void characters(char[] ch, int start, int length) {
	final Node last = (Node)_nodeStk.peek();

	if (last != _document) {
	    final String text = new String(ch, start, length);
	    last.appendChild(_document.createTextNode(text));
	}
    }

    public void startDocument() {
	_nodeStk.push(_root);
    }

    public void endDocument() {
        _nodeStk.pop();
    }

    public void startElement(String namespace, String localName, String qName,
	Attributes attrs)
    {
	final Element tmp = (Element)_document.createElementNS(namespace, qName);

	if (_namespaceDecls != null) {
	    final int nDecls = _namespaceDecls.size();
	    for (int i = 0; i < nDecls; i++) {
		final String prefix = (String) _namespaceDecls.elementAt(i++);

		if (prefix == null || prefix.equals(EMPTYSTRING)) {
		    tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX,
			(String) _namespaceDecls.elementAt(i));
		}
		else {
		    tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix,
			(String) _namespaceDecls.elementAt(i));
		}
	    }
	    _namespaceDecls.clear();
	}

	final int nattrs = attrs.getLength();
	for (int i = 0; i < nattrs; i++) {
	    if (attrs.getLocalName(i) == null) {
		tmp.setAttribute(attrs.getQName(i), attrs.getValue(i));
	    }
	    else {
		tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i),
		    attrs.getValue(i));
	    }
	}

	Node last = (Node)_nodeStk.peek();
	last.appendChild(tmp);

	_nodeStk.push(tmp);
    }

    public void endElement(String namespace, String localName, String qName) {
	_nodeStk.pop();
    }

    public void startPrefixMapping(String prefix, String uri) {
	if (_namespaceDecls == null) {
	    _namespaceDecls = new Vector(2);
	}
	_namespaceDecls.addElement(prefix);
	_namespaceDecls.addElement(uri);
    }

    public void endPrefixMapping(String prefix) {
    }

    /**
     * This class is only used internally so this method should never
     * be called.
     */
    public void ignorableWhitespace(char[] ch, int start, int length) {
    }

    /**
     * adds processing instruction node to DOM.
     */
    public void processingInstruction(String target, String data) {
	final Node last = (Node)_nodeStk.peek();
	ProcessingInstruction pi = _document.createProcessingInstruction(
		target, data);
	if (pi != null)  last.appendChild(pi);
    }

    /**
     * This class is only used internally so this method should never
     * be called.
     */
    public void setDocumentLocator(Locator locator) {
    }

    /**
     * This class is only used internally so this method should never
     * be called.
     */
    public void skippedEntity(String name) {
    }

    /**
     * Lexical Handler method to create comment node in DOM tree.
     */
    public void comment(char[] ch, int start, int length) {
	final Node last = (Node)_nodeStk.peek();
	Comment comment = _document.createComment(new String(ch,start,length));
	if (comment != null) last.appendChild(comment);
    }

    public void startCDATA() { }
    public void endCDATA() { }
    public void startEntity(java.lang.String name) { }
    public void endDTD() { }
    public void endEntity(String name) { }
    public void startDTD(String name, String publicId, String systemId)

    public Node getDOM() {
	return _root;

FUNC_DECL IF VAR_DECL PARAM PARAM PARAM BINARY_OP VAR_DECL CALL CALL CALL CALL

FUNC_DECL VAR_DECL ASSIGN ASSIGN CALL CALL CALL

FUNC_DECL IF PARAM IF BINARY_OP ASSIGN BINARY_OP VAR_DECL LITERAL_ANCHOR ASSIGN ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL


public abstract class ScheduledPollEndpoint<E extends Exchange> extends DefaultEndpoint<E> {
    private Map consumerProperties;

    protected ScheduledPollEndpoint(String endpointUri, Component component) {
        super(endpointUri, component);
    }

    protected ScheduledPollEndpoint(String endpointUri, CamelContext context) {
        super(endpointUri, context);
    }

    public Map getConsumerProperties() {
        return consumerProperties;
    }

    public void setConsumerProperties(Map consumerProperties) {
        this.consumerProperties = consumerProperties;
    }

    protected void configureConsumer(Consumer<E> consumer) throws Exception {
        if (consumerProperties != null) {
            IntrospectionSupport.setProperties(getContext().getTypeConverter(), consumer, consumerProperties);
        }
    }

    public void configureProperties(Map options) {
        Map consumerProperties = IntrospectionSupport.extractProperties(options, "consumer.");
        if (consumerProperties != null) {
            setConsumerProperties(consumerProperties);


gnu.regexp.RETokenEndSub

final class RETokenEndSub extends REToken {
    RETokenEndSub(int subIndex) {
	super(subIndex);
    }

    boolean match(CharIndexed input, REMatch mymatch) {
	mymatch.end[subIndex] = mymatch.index;
	return next(input, mymatch);
    }

    void dump(StringBuffer os) {

FUNC_DECL RETURN PARAM PARAM CALL ASSIGN


org.gjt.sp.jedit.BeanShell

public class BeanShell
{
	//{{{ evalSelection() method
	/**
	 * Evaluates the text selected in the specified text area.
	 * @since jEdit 2.7pre2
	 */
	public static void evalSelection(View view, JEditTextArea textArea)
	{
		String command = textArea.getSelectedText();
		if(command == null)
		{
			view.getToolkit().beep();
			return;
		}
		Object returnValue = eval(view,global,command);
		if(returnValue != null)
			textArea.setSelectedText(returnValue.toString());
	} //}}}

	//{{{ showEvaluateDialog() method
	/**
	 * Prompts for a BeanShell expression to evaluate.
	 * @since jEdit 2.7pre2
	 */
	public static void showEvaluateDialog(View view)
	{
		String command = GUIUtilities.input(view,"beanshell-eval-input",null);
		if(command != null)
		{
			if(!command.endsWith(";"))
				command = command + ";";

			int repeat = view.getInputHandler().getRepeatCount();

			if(view.getMacroRecorder() != null)
			{
				view.getMacroRecorder().record(repeat,command);
			}

			Object returnValue = null;
			try
			{
				for(int i = 0; i < repeat; i++)
				{
					returnValue = _eval(view,global,command);
				}
			}
			catch(Throwable e)
			{
				Log.log(Log.ERROR,BeanShell.class,e);

				handleException(view,null,e);
			}

			if(returnValue != null)
			{
				String[] args = { returnValue.toString() };
				GUIUtilities.message(view,"beanshell-eval",args);
			}
		}
	} //}}}

	//{{{ showEvaluateLinesDialog() method
	/**
	 * Evaluates the specified script for each selected line.
	 * @since jEdit 4.0pre1
	 */
	public static void showEvaluateLinesDialog(View view)
	{
		String command = GUIUtilities.input(view,"beanshell-eval-line",null);

		JEditTextArea textArea = view.getTextArea();
		Buffer buffer = view.getBuffer();

		Selection[] selection = textArea.getSelection();
		if(selection.length == 0 || command == null || command.length() == 0)
		{
			view.getToolkit().beep();
			return;
		}

		if(!command.endsWith(";"))
			command = command + ";";

		if(view.getMacroRecorder() != null)
			view.getMacroRecorder().record(1,command);

		try
		{
			buffer.beginCompoundEdit();

			for(int i = 0; i < selection.length; i++)
			{
				Selection s = selection[i];
				for(int j = s.getStartLine(); j <= s.getEndLine(); j++)
				{
					// if selection ends on the start of a
					// line, don't filter that line
					if(s.getEnd() == textArea.getLineStartOffset(j))
						break;

					global.setVariable("line",new Integer(j));
					global.setVariable("index",new Integer(
						j - s.getStartLine()));
					int start = s.getStart(buffer,j);
					int end = s.getEnd(buffer,j);
					String text = buffer.getText(start,
						end - start);
					global.setVariable("text",text);

					Object returnValue = _eval(view,global,command);
					if(returnValue != null)
					{
						buffer.remove(start,end - start);
						buffer.insert(start,
							returnValue.toString());
					}
				}
			}
		}
		catch(Throwable e)
		{
			Log.log(Log.ERROR,BeanShell.class,e);

			handleException(view,null,e);
		}
		finally
		{
			buffer.endCompoundEdit();
		}

		textArea.selectNone();
	} //}}}

	//{{{ showRunScriptDialog() method
	/**
	 * Prompts for a BeanShell script to run.
	 * @since jEdit 2.7pre2
	 */
	public static void showRunScriptDialog(View view)
	{
		Macros.showRunScriptDialog(view);
	} //}}}

	//{{{ runScript() method
	/**
	 * Runs a BeanShell script. Errors are shown in a dialog box.
	 * @param view The view
	 * @param path For error reporting only
	 * @param in The reader to read the script from. If null, script will
	 * be read from the VFS corresponding to its path.
	 * @param ownNamespace Macros are run in their own namespace, startup
	 * scripts are run on the global namespace
	 * @since jEdit 4.0pre7
	 */
	public static void runScript(View view, String path, Reader in,
		boolean ownNamespace)
	{
		try
		{
			_runScript(view,path,in,ownNamespace);
		}
		catch(Throwable e)
		{
			Log.log(Log.ERROR,BeanShell.class,e);

			handleException(view,path,e);
		}
	} //}}}

	//{{{ _runScript() method
	/**
	 * Runs a BeanShell script. Errors are passed to the caller.
	 * @param view The view
	 * @param path For error reporting only
	 * @param in The reader to read the script from. If null, script will
	 * be read from the VFS corresponding to its path.
	 * @param ownNamespace Macros are run in their own namespace, startup
	 * scripts are run on the global namespace
	 * @exception Exception instances are thrown when various BeanShell errors
	 * occur
	 * @since jEdit 4.0pre7
	 */
	public static void _runScript(View view, String path, Reader in,
		boolean ownNamespace) throws Exception
	{
		Log.log(Log.MESSAGE,BeanShell.class,"Running script " + path);

		NameSpace namespace;
		if(ownNamespace)
			namespace = new NameSpace(global,"script namespace");
		else
			namespace = global;

		Interpreter interp = createInterpreter(namespace);

		VFS vfs = null;
		Object session = null;

		try
		{
			if(in == null)
			{
				Buffer buffer = jEdit.getBuffer(path);

				vfs = VFSManager.getVFSForPath(path);
				session = vfs.createVFSSession(path,view);
				if(session == null)
				{
					// user cancelled???
					return;
				}

				if(buffer != null)
				{
					if(!buffer.isLoaded())
						VFSManager.waitForRequests();

					in = new StringReader(buffer.getText(0,
						buffer.getLength()));
				}
				else
				{
					in = new BufferedReader(new InputStreamReader(
						vfs._createInputStream(session,
						path,false,view)));
				}
			}

			if(view != null)
			{
				EditPane editPane = view.getEditPane();
				interp.set("view",view);
				interp.set("editPane",editPane);
				interp.set("buffer",editPane.getBuffer());
				interp.set("textArea",editPane.getTextArea());
			}

			running = true;

			interp.eval(in,namespace,path);
		}
		catch(Exception e)
		{
			unwrapException(e);
		}
		finally
		{
			running = false;

			if(session != null)
			{
				try
				{
					vfs._endVFSSession(session,view);
				}
				catch(IOException io)
				{
					Log.log(Log.ERROR,BeanShell.class,io);
					GUIUtilities.error(view,"read-error",
						new String[] { path, io.toString() });
				}
			}
		}
	} //}}}

	//{{{ eval() method
	/**
	 * Evaluates the specified BeanShell expression. Errors are reported in
	 * a dialog box.
	 * @param view The view (may be null)
	 * @param namespace The namespace
	 * @param command The expression
	 * @since jEdit 4.0pre8
	 */
	public static Object eval(View view, NameSpace namespace, String command)
	{
		try
		{
			return _eval(view,namespace,command);
		}
		catch(Throwable e)
		{
			Log.log(Log.ERROR,BeanShell.class,e);

			handleException(view,null,e);
		}

		return null;
	} //}}}

	//{{{ _eval() method
	/**
	 * Evaluates the specified BeanShell expression. Unlike
	 * eval(), this method passes any exceptions to the caller.
	 *
	 * @param view The view (may be null)
	 * @param namespace The namespace
	 * @param command The expression
	 * @exception Exception instances are thrown when various BeanShell
	 * errors occur
	 * @since jEdit 3.2pre7
	 */
	public static Object _eval(View view, NameSpace namespace, String command)
		throws Exception
	{
		Interpreter interp = createInterpreter(namespace);

		try
		{
			if(view != null)
			{
				EditPane editPane = view.getEditPane();
				interp.set("view",view);
				interp.set("editPane",editPane);
				interp.set("buffer",editPane.getBuffer());
				interp.set("textArea",editPane.getTextArea());
			}

			return interp.eval(command);
		}
		catch(Exception e)
		{
			unwrapException(e);
			// never called
			return null;
		}
	} //}}}

	//{{{ cacheBlock() method
	/**
	 * Caches a block of code, returning a handle that can be passed to
	 * runCachedBlock().
	 * @param id An identifier. If null, a unique identifier is generated
	 * @param code The code
	 * @param childNamespace If the method body should be run in a new
	 * namespace (slightly faster). Note that you must pass a null namespace
	 * to the runCachedBlock() method if you do this
	 * @exception Exception instances are thrown when various BeanShell errors
	 * occur
	 * @since jEdit 3.2pre5
	 */
	public static String cacheBlock(String id, String code,
		boolean childNamespace) throws Exception
	{
		String name;
		if(id == null)
			name = "b_" + (cachedBlockCounter++);
		else
			name = "b_" + id;

		code = "setNameSpace(__cruft.namespace);\n"
			+ name
			+ "(ns) {\n"
			+ "setNameSpace(ns);"
			+ code
			+ "\n}";

		_eval(null,global,code);

		return name;
	} //}}}

	//{{{ runCachedBlock() method
	/**
	 * Runs a cached block of code in the specified namespace. Faster than
	 * evaluating the block each time.
	 * @param id The identifier returned by cacheBlock()
	 * @param view The view
	 * @param namespace The namespace to run the code in. Can only be null if
	 * childNamespace parameter was true in cacheBlock() call
	 * @exception Exception instances are thrown when various BeanShell errors
	 * occur
	 * @since jEdit 3.2pre5
	 */
	public static Object runCachedBlock(String id, View view, NameSpace namespace)
		throws Exception
	{
		if(namespace == null)
			namespace = global;

		Object[] args = { namespace };

		try
		{
			if(view != null)
			{
				namespace.setVariable("view",view);
				EditPane editPane = view.getEditPane();
				namespace.setVariable("editPane",editPane);
				namespace.setVariable("buffer",editPane.getBuffer());
				namespace.setVariable("textArea",editPane.getTextArea());
			}

			Object retVal = internal.invokeMethod(id,args,interpForMethods);
			if(retVal instanceof Primitive)
			{
				if(retVal == Primitive.VOID)
					return null;
				else
					return ((Primitive)retVal).getValue();
			}
			else
				return retVal;
		}
		catch(Exception e)
		{
			unwrapException(e);
			// never called
			return null;
		}
		finally
		{
			try
			{
				namespace.setVariable("view",null);
				namespace.setVariable("editPane",null);
				namespace.setVariable("buffer",null);
				namespace.setVariable("textArea",null);
			}
			catch(EvalError e)
			{
				// can't do much
			}
		}
	} //}}}

	//{{{ isScriptRunning() method
	/**
	 * Returns if a BeanShell script or macro is currently running.
	 * @since jEdit 2.7pre2
	 */
	public static boolean isScriptRunning()
	{
		return running;
	} //}}}

	//{{{ getNameSpace() method
	/**
	 * Returns the global namespace.
	 * @since jEdit 3.2pre5
	 */
	public static NameSpace getNameSpace()
	{
		return global;
	} //}}}

	//{{{ Deprecated functions

	//{{{ runScript() method
	/**
	 * @deprecated The rethrowBshErrors parameter is now
	 * obsolete; call _runScript() or runScript()
	 * instead.
	 */
	public static void runScript(View view, String path,
		boolean ownNamespace, boolean rethrowBshErrors)
	{
		runScript(view,path,null,ownNamespace);
	} //}}}

	//{{{ runScript() method
	/**
	 * @deprecated The rethrowBshErrors parameter is now
	 * obsolete; call _runScript() or runScript()
	 * instead.
	 */
	public static void runScript(View view, String path, Reader in,
		boolean ownNamespace, boolean rethrowBshErrors)
	{
		runScript(view,path,in,ownNamespace);
	} //}}}

	//{{{ eval() method
	/**
	 * @deprecated The rethrowBshErrors parameter is now
	 * obsolete; call _eval() or eval() instead.
	 */
	public static Object eval(View view, String command,
		boolean rethrowBshErrors)
	{
		return eval(view,global,command);
	} //}}}

	//{{{ eval() method
	/**
	 * @deprecated The rethrowBshErrors parameter is now
	 * obsolete; call _eval() or eval() instead.
	 */
	public static Object eval(View view, NameSpace namespace,
		String command, boolean rethrowBshErrors)
	{
		return eval(view,namespace,command);
	} //}}}

	//}}}

	//{{{ Package-private members

	//{{{ init() method
	static void init()
	{
		BshClassManager.setClassLoader(new JARClassLoader());

		global = new NameSpace("jEdit embedded BeanShell interpreter");
		global.importPackage("org.gjt.sp.jedit");
		global.importPackage("org.gjt.sp.jedit.browser");
		global.importPackage("org.gjt.sp.jedit.gui");
		global.importPackage("org.gjt.sp.jedit.io");
		global.importPackage("org.gjt.sp.jedit.msg");
		global.importPackage("org.gjt.sp.jedit.options");
		global.importPackage("org.gjt.sp.jedit.pluginmgr");
		global.importPackage("org.gjt.sp.jedit.print");
		global.importPackage("org.gjt.sp.jedit.search");
		global.importPackage("org.gjt.sp.jedit.syntax");
		global.importPackage("org.gjt.sp.jedit.textarea");
		global.importPackage("org.gjt.sp.util");

		interpForMethods = createInterpreter(global);

		internal = (NameSpace)eval(null,"__cruft = object();__cruft.namespace;",false);

		Log.log(Log.DEBUG,BeanShell.class,"BeanShell interpreter version "
			+ Interpreter.VERSION);
	} //}}}

	//}}}

	//{{{ Private members

	//{{{ Instance variables
	private static Interpreter interpForMethods;
	private static NameSpace global;
	private static NameSpace internal;
	private static boolean running;
	private static int cachedBlockCounter;
	//}}}

	//{{{ unwrapException() method
	/**
	 * This extracts an exception from a 'wrapping' exception, as BeanShell
	 * sometimes throws. This gives the user a more accurate error traceback
	 */
	private static void unwrapException(Exception e) throws Exception
	{
		if(e instanceof TargetError)
		{
			Throwable t = ((TargetError)e).getTarget();
			if(t instanceof Exception)
				throw (Exception)t;
			else if(t instanceof Error)
				throw (Error)t;
		}

		if(e instanceof InvocationTargetException)
		{
			Throwable t = ((InvocationTargetException)e).getTargetException();
			if(t instanceof Exception)
				throw (Exception)t;
			else if(t instanceof Error)
				throw (Error)t;
		}

		throw e;
	} //}}}

	//{{{ handleException() method
	private static void handleException(View view, String path, Throwable t)
	{
		if(t instanceof IOException)
		{
			VFSManager.error(view,path,"ioerror.read-error",
				new String[] { t.toString() });
		}
		else
			new BeanShellErrorDialog(view,t.toString());
	} //}}}

	//{{{ createInterpreter() method
	private static Interpreter createInterpreter(NameSpace nameSpace)
	{
		return new Interpreter(null,System.out,System.err,false,nameSpace);

FUNC_DECL TRY PARAM PARAM PARAM PARAM CATCH CALL CALL CALL

FUNC_DECL RETURN TRY PARAM PARAM PARAM LITERAL_ANCHOR CATCH RETURN CALL CALL CALL LITERAL_ANCHOR

FUNC_DECL PARAM PARAM PARAM PARAM CALL LITERAL_ANCHOR

FUNC_DECL PARAM PARAM PARAM PARAM PARAM CALL

FUNC_DECL RETURN PARAM PARAM PARAM PARAM CALL

FUNC_DECL IF PARAM PARAM PARAM BINARY_OP CALL CALL CALL LITERAL_ANCHOR CALL


public class VfsResource implements Resource {
    private String vfsURI;

    private FileSystemManager fsManager;

    private transient boolean init = false;

    private transient boolean exists;

    private transient long lastModified;

    private transient long contentLength;

    private transient FileContent content = null;

    private transient FileObject resourceImpl;

    // Constructor
    public VfsResource(String vfsURI, FileSystemManager fsManager) {
        this.vfsURI = vfsURI;
        this.fsManager = fsManager;
        this.init = false;
    }

    private void init() {
        if (!init) {
            try {
                resourceImpl = fsManager.resolveFile(vfsURI);
                content = resourceImpl.getContent();

                exists = resourceImpl.exists();
                lastModified = content.getLastModifiedTime();
                contentLength = content.getSize();
            } catch (FileSystemException e) {
                Message.verbose(e.getLocalizedMessage());
                exists = false;
                lastModified = 0;
                contentLength = 0;
            }

            init = true;
        }
    }

    /**
     * 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.
     *
     * @return A ArrayList 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.verbose(e.getLocalizedMessage());
        }
        return list;
    }

    public FileContent getContent() {
        init();
        return content;
    }

    /**
     * Get the name of the resource.
     *
     * @return a String representing the Resource URL.
     */
    public String getName() {
        return normalize(vfsURI);
    }

    public Resource clone(String cloneName) {
        return new VfsResource(cloneName, fsManager);
    }

    /**
     * The VFS FileName getURI method seems to have a bug in it where file: URIs will have 4 forward
     * slashes instead of 3.
     *
     * @param vfsURI
     * @return a normalized <class>String</class> representing the VFS URI
     */
    public static String normalize(String vfsURI) {
        if (vfsURI == null) {
            return "";
        }

        if (vfsURI.startsWith("file:////")) {
            vfsURI = vfsURI.replaceFirst("////", "///");
        }
        return vfsURI;
    }

    /**
     * Get the last modification time of the resource.
     *
     * @return a long indicating last modified time.
     */
    public long getLastModified() {
        init();
        return lastModified;
    }

    /**
     * Get the size of the resource
     *
     * @return a long representing the size of the resource (in bytes).
     */
    public long getContentLength() {
        init();
        return contentLength;
    }

    /**
     * Flag indicating whether a resource is available for querying
     *
     * @return true if the resource is available for querying, false
     *         otherwise.
     */
    public boolean exists() {
        init();
        return exists;
    }

    /**
     * Return a flag indicating whether a provided VFS resource physically exists
     *
     * @return true if the resource physically exists, false
     *         otherwise.
     */
    public boolean physicallyExists() {
        // TODO: there is no need for this method anymore, replace it by calling exists();
        init();

        try {
            return resourceImpl.exists();
            // originally I only checked for a FileSystemException. I expanded it to
            // include all exceptions when I found it would throw a NPE exception when the query was
            // run on non-wellformed VFS URI.
        } catch (Exception e) {
            Message.verbose(e.getLocalizedMessage());
            return false;
        }
    }

    public String toString() {
        return VfsResolver.prepareForDisplay(getName());
    }

    public boolean isLocal() {
        return getName().startsWith("file:");
    }

    public InputStream openStream() throws IOException {
        return getContent().getInputStream();

FUNC_DECL IF TRY ASSIGN CATCH LITERAL_ANCHOR ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL

FUNC_DECL TRY CATCH RETURN CALL RETURN CALL LITERAL_ANCHOR CALL CALL

FUNC_DECL PARAM PARAM ASSIGN ASSIGN ASSIGN LITERAL_ANCHOR


public class SupBookRecord extends Record
{
    public final static short sid = 0x1AE;
    private short             field_1_number_of_sheets;
    private short             field_2_flag;

    public SupBookRecord()
    {
        setFlag((short)0x401);
    }

    /**
     * Constructs a Extern Sheet record and sets its fields appropriately.
     *
     * @param id     id must be 0x16 or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     */
    public SupBookRecord(short id, short size, byte[] data)
    {
        super(id, size, data);
    }

    /**
     * Constructs a Extern Sheet record and sets its fields appropriately.
     *
     * @param id     id must be 0x1ae or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     * @param offset of the record's data
     */
    public SupBookRecord(short id, short size, byte[] data, int offset)
    {
        super(id, size, data, offset);
    }

    protected void validateSid(short id)
    {
        if (id != sid)
        {
            throw new RecordFormatException("NOT An Supbook RECORD");
        }
    }

    /**
     * called by the constructor, should set class level fields.  Should throw
     * runtime exception for bad/icomplete data.
     *
     * @param data raw data
     * @param size size of data
     * @param offset of the record's data (provided a big array of the file)
     */
    protected void fillFields(byte [] data, short size, int offset)
    {
        field_1_number_of_sheets = LittleEndian.getShort(data,offset+0);
        field_2_flag = LittleEndian.getShort(data,offset+2);
    }

    public String toString()
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[SUPBOOK]\n");
        buffer.append("numberosheets = ").append(getNumberOfSheets()).append('\n');
        buffer.append("flag          = ").append(getFlag()).append('\n');
        buffer.append("[/SUPBOOK]\n");
        return buffer.toString();
    }

    /**
     * called by the class that is responsible for writing this sucker.
     * Subclasses should implement this so that their data is passed back in a
     * byte array.
     *
     * @param offset to begin writing at
     * @param data byte array containing instance data
     * @return number of bytes written
     */
    public int serialize(int offset, byte [] data)
    {
        LittleEndian.putShort(data, 0 + offset, sid);
        LittleEndian.putShort(data, 2 + offset, (short) 4);
        LittleEndian.putShort(data, 4 + offset, field_1_number_of_sheets);
        LittleEndian.putShort(data, 6 + offset, field_2_flag);

        return getRecordSize();
    }

    public void setNumberOfSheets(short number){
        field_1_number_of_sheets = number;
    }

    public short getNumberOfSheets(){
        return field_1_number_of_sheets;
    }

    public void setFlag(short flag){
        field_2_flag = flag;
    }

    public short getFlag() {
        return field_2_flag;
    }

    public int getRecordSize()
    {
        return 4 + 4;
    }

    public short getSid()
    {
        return this.sid;


public class CalcCountRecord
    extends Record
{
    public final static short sid = 0xC;
    private short             field_1_iterations;

    public CalcCountRecord()
    {
    }

    /**
     * Constructs a CalcCountRecord and sets its fields appropriately
     *
     * @param id     id must be 0xC or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     *
     */

    public CalcCountRecord(short id, short size, byte [] data)
    {
        super(id, size, data);
    }

    /**
     * Constructs a CalcCountRecord and sets its fields appropriately
     *
     * @param id     id must be 0xC or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     * @param offset of the record's data
     */

    public CalcCountRecord(short id, short size, byte [] data, int offset)
    {
        super(id, size, data, offset);
    }

    protected void validateSid(short id)
    {
        if (id != sid)
        {
            throw new RecordFormatException("NOT An Calc Count RECORD");
        }
    }

    protected void fillFields(byte [] data, short size, int offset)
    {
        field_1_iterations = LittleEndian.getShort(data, 0 + offset);
    }

    /**
     * set the number of iterations to perform
     * @param iterations to perform
     */

    public void setIterations(short iterations)
    {
        field_1_iterations = iterations;
    }

    /**
     * get the number of iterations to perform
     * @return iterations
     */

    public short getIterations()
    {
        return field_1_iterations;
    }

    public String toString()
    {
        StringBuffer buffer = new StringBuffer();

        buffer.append("[CALCCOUNT]\n");
        buffer.append("    .iterations     = ")
            .append(Integer.toHexString(getIterations())).append("\n");
        buffer.append("[/CALCCOUNT]\n");
        return buffer.toString();
    }

    public int serialize(int offset, byte [] data)
    {
        LittleEndian.putShort(data, 0 + offset, sid);
        LittleEndian.putShort(data, 2 + offset, ( short ) 0x2);
        LittleEndian.putShort(data, 4 + offset, getIterations());
        return getRecordSize();
    }

    public int getRecordSize()
    {
        return 6;
    }

    public short getSid()
    {
        return this.sid;

    public int getRecordSize()
    {
        return 6;