public class EchoProperties extends Task {

    /**
     * the properties element.
     */
    private static final String PROPERTIES = "properties";

    /**
     * the property element.
     */
    private static final String PROPERTY = "property";

    /**
     * name attribute for property, testcase and testsuite elements.
     */
    private static final String ATTR_NAME = "name";

    /**
     * value attribute for property elements.
     */
    private static final String ATTR_VALUE = "value";

    /**
     * the input file.
     */
    private File inFile = null;

    /**
     *  File object pointing to the output file. If this is null, then
     *  we output to the project log, not to a file.
     */
    private File destfile = null;

    /**
     *  If this is true, then errors generated during file output will become
     *  build errors, and if false, then such errors will be logged, but not
     *  thrown.
     */
    private boolean failonerror = true;

    private Vector propertySets = new Vector();

    private String format = "text";

    private String prefix;

    /**
     * @since Ant 1.7
     */
    private String regex;

    /**
     * Sets the input file.
     *
     * @param file  the input file
     */
    public void setSrcfile(File file) {
        inFile = file;
    }

    /**
     *  Set a file to store the property output.  If this is never specified,
     *  then the output will be sent to the Ant log.
     *
     *@param destfile file to store the property output
     */
    public void setDestfile(File destfile) {
        this.destfile = destfile;
    }

    /**
     * If true, the task will fail if an error occurs writing the properties
     * file, otherwise errors are just logged.
     *
     *@param  failonerror  <tt>true</tt> if IO exceptions are reported as build
     *      exceptions, or <tt>false</tt> if IO exceptions are ignored.
     */
    public void setFailOnError(boolean failonerror) {
        this.failonerror = failonerror;
    }

    /**
     *  If the prefix is set, then only properties which start with this
     *  prefix string will be recorded. If regex is not set and  if this
     *  is never set, or it is set to an empty string or <tt>null</tt>,
     *  then all properties will be recorded.

     *
     *  For example, if the attribute is set as:
     *
<echoproperties  prefix="ant." />

     *  then the property "ant.home" will be recorded, but "ant-example"
     *  will not.
     *
     * @param  prefix  The new prefix value
     */
    public void setPrefix(String prefix) {
        if (prefix != null && prefix.length() != 0) {
            this.prefix = prefix;
            PropertySet ps = new PropertySet();
            ps.setProject(getProject());
            ps.appendPrefix(prefix);
            addPropertyset(ps);
        }
    }

    /**
     *  If the regex is set, then only properties whose names match it
     *  will be recorded.  If prefix is not set and if this is never set,
     *  or it is set to an empty string or <tt>null</tt>, then all
     *  properties will be recorded.

     *
     *  For example, if the attribute is set as:
     *
<echoproperties  prefix=".*ant.*" />

     *  then the properties "ant.home" and "user.variant" will be recorded,
     *  but "ant-example" will not.
     *
     * @param  regex  The new regex value
     *
     * @since Ant 1.7
     */
    public void setRegex(String regex) {
        if (regex != null && regex.length() != 0) {
            this.regex = regex;
            PropertySet ps = new PropertySet();
            ps.setProject(getProject());
            ps.appendRegex(regex);
            addPropertyset(ps);
        }
    }

    /**
     * A set of properties to write.
     * @param ps the property set to write
     * @since Ant 1.6
     */
    public void addPropertyset(PropertySet ps) {
        propertySets.addElement(ps);
    }

    /**
     * Set the output format - xml or text.
     * @param ea an enumerated FormatAttribute value
     */
    public void setFormat(FormatAttribute ea) {
        format = ea.getValue();
    }

    /**
     * A enumerated type for the format attribute.
     * The values are "xml" and "text".
     */
    public static class FormatAttribute extends EnumeratedAttribute {
        private String [] formats = new String[]{"xml", "text"};

        /**
         * @see EnumeratedAttribute#getValues()
         * @return accepted values
         */
        public String[] getValues() {
            return formats;
        }
    }

    /**
     *  Run the task.
     *
     *@exception  BuildException  trouble, probably file IO
     */
    public void execute() throws BuildException {
        if (prefix != null && regex != null) {
            throw new BuildException("Please specify either prefix"
                    + " or regex, but not both", getLocation());
        }
        Hashtable allProps = new Hashtable();

        /* load properties from file if specified, otherwise
        use Ant's properties */
        if (inFile == null && propertySets.size() == 0) {
            allProps.putAll(getProject().getProperties());
        } else if (inFile != null) {
            if (inFile.exists() && inFile.isDirectory()) {
                String message = "srcfile is a directory!";
                if (failonerror) {
                    throw new BuildException(message, getLocation());
                } else {
                    log(message, Project.MSG_ERR);
                }
                return;
            }

            if (inFile.exists() && !inFile.canRead()) {
                String message = "Can not read from the specified srcfile!";
                if (failonerror) {
                    throw new BuildException(message, getLocation());
                } else {
                    log(message, Project.MSG_ERR);
                }
                return;
            }

            FileInputStream in = null;
            try {
                in = new FileInputStream(inFile);
                Properties props = new Properties();
                props.load(in);
                allProps.putAll(props);
            } catch (FileNotFoundException fnfe) {
                String message =
                    "Could not find file " + inFile.getAbsolutePath();
                if (failonerror) {
                    throw new BuildException(message, fnfe, getLocation());
                } else {
                    log(message, Project.MSG_WARN);
                }
                return;
            } catch (IOException ioe) {
                String message =
                    "Could not read file " + inFile.getAbsolutePath();
                if (failonerror) {
                    throw new BuildException(message, ioe, getLocation());
                } else {
                    log(message, Project.MSG_WARN);
                }
                return;
            } finally {
                FileUtils.close(in);
            }
        }

        Enumeration e = propertySets.elements();
        while (e.hasMoreElements()) {
            PropertySet ps = (PropertySet) e.nextElement();
            allProps.putAll(ps.getProperties());
        }

        OutputStream os = null;
        try {
            if (destfile == null) {
                os = new ByteArrayOutputStream();
                saveProperties(allProps, os);
                log(os.toString(), Project.MSG_INFO);
            } else {
                if (destfile.exists() && destfile.isDirectory()) {
                    String message = "destfile is a directory!";
                    if (failonerror) {
                        throw new BuildException(message, getLocation());
                    } else {
                        log(message, Project.MSG_ERR);
                    }
                    return;
                }

                if (destfile.exists() && !destfile.canWrite()) {
                    String message =
                        "Can not write to the specified destfile!";
                    if (failonerror) {
                        throw new BuildException(message, getLocation());
                    } else {
                        log(message, Project.MSG_ERR);
                    }
                    return;
                }
                os = new FileOutputStream(this.destfile);
                saveProperties(allProps, os);
            }
        } catch (IOException ioe) {
            if (failonerror) {
                throw new BuildException(ioe, getLocation());
            } else {
                log(ioe.getMessage(), Project.MSG_INFO);
            }
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                }
            }
        }
    }

    /**
     *  Send the key/value pairs in the hashtable to the given output stream.
     *  Only those properties matching the <tt>prefix</tt> constraint will be
     *  sent to the output stream.
     *  The output stream will be closed when this method returns.
     *
     * @param  allProps         propfile to save
     * @param  os               output stream
     * @throws IOException      on output errors
     * @throws BuildException   on other errors
     */
    protected void saveProperties(Hashtable allProps, OutputStream os)
        throws IOException, BuildException {
        final List keyList = new ArrayList(allProps.keySet());
        Collections.sort(keyList);
        Properties props = new Properties() {
            private static final long serialVersionUID = 5090936442309201654L;
            public Enumeration keys() {
                return CollectionUtils.asEnumeration(keyList.iterator());
            }
            public Set entrySet() {
                Set result = super.entrySet();
                if (JavaEnvUtils.isKaffe()) {
                    TreeSet t = new TreeSet(new Comparator() {
                        public int compare(Object o1, Object o2) {
                            String key1 = (String) ((Map.Entry) o1).getKey();
                            String key2 = (String) ((Map.Entry) o2).getKey();
                            return key1.compareTo(key2);
                        }
                    });
                    t.addAll(result);
                    result = t;
                }
                return result;
            }
        };
        for (int i = 0; i < keyList.size(); i++) {
            String name = keyList.get(i).toString();
            String value = allProps.get(name).toString();
            props.setProperty(name, value);
        }
        if ("text".equals(format)) {
            jdkSaveProperties(props, os, "Ant properties");
        } else if ("xml".equals(format)) {
            xmlSaveProperties(props, os);
        }
    }

    /**
     * a tuple for the sort list.
     */
    private static final class Tuple implements Comparable {
        private String key;
        private String value;

        private Tuple(String key, String value) {
            this.key = key;
            this.value = value;
        }

        /**
         * Compares this object with the specified object for order.
         * @param o the Object to be compared.
         * @return a negative integer, zero, or a positive integer as this object is
         *         less than, equal to, or greater than the specified object.
         * @throws ClassCastException if the specified object's type prevents it
         *                            from being compared to this Object.
         */
        public int compareTo(Object o) {
            Tuple that = (Tuple) o;
            return key.compareTo(that.key);
        }
    }

    private List sortProperties(Properties props) {
        List sorted = new ArrayList(props.size());
        Enumeration e = props.propertyNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            sorted.add(new Tuple(name, props.getProperty(name)));
        }
        Collections.sort(sorted);
        return sorted;
    }

    /**
     * Output the properties as xml output.
     * @param props the properties to save
     * @param os    the output stream to write to (Note this gets closed)
     * @throws IOException on error in writing to the stream
     */
    protected void xmlSaveProperties(Properties props,
                                     OutputStream os) throws IOException {
        Document doc = getDocumentBuilder().newDocument();
        Element rootElement = doc.createElement(PROPERTIES);

        List sorted = sortProperties(props);

        Iterator iten = sorted.iterator();
        while (iten.hasNext()) {
            Tuple tuple = (Tuple) iten.next();
            Element propElement = doc.createElement(PROPERTY);
            propElement.setAttribute(ATTR_NAME, tuple.key);
            propElement.setAttribute(ATTR_VALUE, tuple.value);
            rootElement.appendChild(propElement);
        }

        Writer wri = null;
        try {
            wri = new OutputStreamWriter(os, "UTF8");
            wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            (new DOMElementWriter()).write(rootElement, wri, 0, "\t");
            wri.flush();
        } catch (IOException ioe) {
            throw new BuildException("Unable to write XML file", ioe);
        } finally {
            FileUtils.close(wri);
        }
    }

    /**
     *  JDK 1.2 allows for the safer method
     *  <tt>Properties.store(OutputStream, String)</tt>, which throws an
     *  <tt>IOException</tt> on an output error.
     *
     *@param props the properties to record
     *@param os record the properties to this output stream
     *@param header prepend this header to the property output
     *@exception IOException on an I/O error during a write.
     */
    protected void jdkSaveProperties(Properties props, OutputStream os,
                                     String header) throws IOException {
       try {
           props.store(os, header);

       } catch (IOException ioe) {
           throw new BuildException(ioe, getLocation());
       } finally {
           if (os != null) {
               try {
                   os.close();
               } catch (IOException ioex) {
                   log("Failed to close output stream");
               }
           }
       }
    }

    /**
     * Uses the DocumentBuilderFactory to get a DocumentBuilder instance.
     *
     * @return   The DocumentBuilder instance
     */
    private static DocumentBuilder getDocumentBuilder() {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);

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

FUNC_DECL TRY PARAM PARAM PARAM IF CATCH BINARY_OP THROW_RAISE CALL TRY LITERAL_ANCHOR CALL CATCH CALL CALL CALL LITERAL_ANCHOR

FUNC_DECL TRY CATCH RETURN THROW_RAISE CALL CALL CALL


bsh.BSHCastExpression

class BSHCastExpression extends SimpleNode {

    public BSHCastExpression(int id) { super(id); }

	/**
		@return the result of the cast.
	*/
	public Object eval(
		CallStack callstack, Interpreter interpreter ) throws EvalError
    {
		NameSpace namespace = callstack.top();
        Class toType = ((BSHType)jjtGetChild(0)).getType(namespace);
		SimpleNode expression = (SimpleNode)jjtGetChild(1);

        // evaluate the expression
        Object fromValue = expression.eval(callstack, interpreter);
        Class fromType = fromValue.getClass();

		try {
			return castObject( fromValue, toType );
		} catch ( EvalError e ) {
			e.reThrow( this );
			throw new InterpreterError("can't happen"); // help the compiler
		}
    }

	/**
		Cast an object to a new type.
		This method can handle bsh.Primitive types (representing primitive
		casts) as well as arbitrary object casts.
		@param fromValue an Object or bsh.Primitive primitive value
		@param toType the class type of the cast result, which may include
		primitive types, e.g. Byte.TYPE
	*/
	public static Object castObject( Object fromValue, Class toType )
		throws EvalError
	{
        Class fromType = fromValue.getClass();

		// The compiler isn't smart enough to allow me to leave this unassigned
		// even though it is clearly assigned in all cases below.
        Object result = null;

		// Going to a primitive type
        if ( toType.isPrimitive() )
			if ( fromValue instanceof Primitive )
				result = castPrimitive( (Primitive)fromValue, toType );
			else
				// cannot convert from object to primitive
                castError(fromValue.getClass(), toType);
        else
			// Going to an object type
			if ( fromValue instanceof Primitive )
				// let castPrimitive handle trivial but legit case of NULL
				result = castPrimitive( (Primitive)fromValue, toType );
			else
				// Can we use the proxy mechanism to cast a bsh.This to
				// the correct interface?
				if ( Capabilities.canGenerateInterfaces() &&
					(fromValue instanceof bsh.This) && toType.isInterface() )
						result = ((bsh.This)fromValue).getInterface( toType );
				else
					// Could probably add getAssignableForm here to allow
					// special bsh widening converions... wrappers to wrappers
					if ( toType.isInstance(fromValue ) )
						result = fromValue;
					else
						castError(fromType, toType);

		if ( result == null )
			throw new InternalError("bad construct somewhere...");

		return result;
	}

	/**
		Wrap up the ClassCastException in a TargetError so that it can
		be caught...
		Node user should catch and add the node
	*/
    public static void castError(Class from, Class to) throws EvalError {
		castError(
			Reflect.normalizeClassName(from), Reflect.normalizeClassName(to) );
    }

    public static void castError(String from, String to) throws EvalError
	{
		Exception cce = new ClassCastException("Illegal cast. Cannot cast " +
            from + " to " + to );
		throw new TargetError( "Cast", cce );
    }

	/**
		Cast the bsh.Primitive value to a new bsh.Primitive value
		This is usually a numeric type cast.  Other cases include:
			boolean can be cast to boolen
			null can be cast to any object type
			void cannot be cast to anything
	*/
	public static Primitive castPrimitive( Primitive primValue, Class toType )
		throws EvalError
	{
		// can't cast void to anything
		if ( primValue == Primitive.VOID )
			castError( "void value", Reflect.normalizeClassName(toType) );

		// unwrap, etc.
		Object value = primValue.getValue();
		Class fromType = primValue.getType();

		// Trying to cast primitive to an object type?
		// only works for Primitive.NULL
		if ( !toType.isPrimitive() )
			if ( primValue != Primitive.NULL )
				castError("primitive value", "object type:" + toType);
			else
				return primValue;

		// can only cast boolean to boolean
		if ( fromType == Boolean.TYPE )
		{
			if ( toType != Boolean.TYPE )
				castError(fromType, toType);
			else
				return primValue;
		}

		// trying to do numeric promotion

		// first promote char to Number type to avoid duplicating code
		if (value instanceof Character)
			value = new Integer(((Character)value).charValue());

		if (value instanceof Number)
		{
			Number number = (Number)value;

			if (toType == Byte.TYPE)
				value = new Primitive(number.byteValue());
			else if(toType == Short.TYPE)
				value = new Primitive(number.shortValue());
			else if(toType == Character.TYPE)
				value = new Primitive((char)number.intValue());
			else if(toType == Integer.TYPE)
				value = new Primitive(number.intValue());
			else if(toType == Long.TYPE)
				value = new Primitive(number.longValue());
			else if(toType == Float.TYPE)
				value = new Primitive(number.floatValue());
			else if(toType == Double.TYPE)
				value = new Primitive(number.doubleValue());
			else
				castError(fromType, toType);

			return (Primitive)value;
		}

		throw new EvalError("unknown type in cast");

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


public class AxisUsedRecord
    extends Record
{
    public final static short      sid                             = 0x1046;
    private  short      field_1_numAxis;

    public AxisUsedRecord()
    {

    }

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

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

    }

    /**
     * Constructs a AxisUsed record and sets its fields appropriately.
     *
     * @param id    id must be 0x1046 or an exception
     *              will be throw upon validation
     * @param size  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 AxisUsedRecord(short id, short size, byte [] data, int offset)
    {
        super(id, size, data, offset);

    }

    /**
     * Checks the sid matches the expected side for this record
     *
     * @param id   the expected sid.
     */
    protected void validateSid(short id)
    {
        if (id != sid)
        {
            throw new RecordFormatException("Not a AxisUsed record");
        }
    }

    protected void fillFields(byte [] data, short size, int offset)
    {

        int pos = 0;
        field_1_numAxis                = LittleEndian.getShort(data, pos + 0x0 + offset);

    }

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

        buffer.append("[AXISUSED]\n");
        buffer.append("    .numAxis              = ")
            .append("0x").append(HexDump.toHex(  getNumAxis ()))
            .append(" (").append( getNumAxis() ).append(" )");
        buffer.append(System.getProperty("line.separator"));

        buffer.append("[/AXISUSED]\n");
        return buffer.toString();
    }

    public int serialize(int offset, byte[] data)
    {
        int pos = 0;

        LittleEndian.putShort(data, 0 + offset, sid);
        LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4));

        LittleEndian.putShort(data, 4 + offset + pos, field_1_numAxis);

        return getRecordSize();
    }

    /**
     * Size of record (exluding 4 byte header)
     */
    public int getRecordSize()
    {
        return 4  + 2;
    }

    public short getSid()
    {
        return this.sid;
    }

    public Object clone() {
        AxisUsedRecord rec = new AxisUsedRecord();

        rec.field_1_numAxis = field_1_numAxis;
        return rec;
    }

    /**
     * Get the num axis field for the AxisUsed record.
     */
    public short getNumAxis()
    {
        return field_1_numAxis;
    }

    /**
     * Set the num axis field for the AxisUsed record.
     */
    public void setNumAxis(short field_1_numAxis)
    {
        this.field_1_numAxis = field_1_numAxis;


public abstract class XQueryBuilder implements Expression<Exchange>, Predicate<Exchange>, NamespaceAware, Processor {
    private static final transient Log LOG = LogFactory.getLog(XQueryBuilder.class);
    private Configuration configuration;
    private XQueryExpression expression;
    private StaticQueryContext staticQueryContext;
    private Map<String, Object> parameters = new HashMap<String, Object>();
    private Map<String, String> namespacePrefixes = new HashMap<String, String>();
    private XmlConverter converter = new XmlConverter();
    private ResultFormat resultsFormat = ResultFormat.DOM;
    private Properties properties = new Properties();
    private Class resultType;
    private final AtomicBoolean initialized = new AtomicBoolean(false);

    @Override
    public String toString() {
        return "XQuery[" + expression + "]";
    }

    public void process(Exchange exchange) throws Exception {
        Object body = evaluate(exchange);
        exchange.getOut(true).setBody(body);

        exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
    }

    public Object evaluate(Exchange exchange) {
        try {
            initialize();

            if (LOG.isDebugEnabled()) {
                LOG.debug("Evaluation " + expression + " for exchange: " + exchange);
            }

            if (resultType != null) {
                if (resultType.equals(String.class)) {
                    return evaluateAsString(exchange);
                } else if (resultType.isAssignableFrom(Collection.class)) {
                    return evaluateAsList(exchange);
                } else if (resultType.isAssignableFrom(Node.class)) {
                    return evaluateAsDOM(exchange);
                } else {
                }
            }
            switch (resultsFormat) {
            case Bytes:
                return evaluateAsBytes(exchange);
            case BytesSource:
                return evaluateAsBytesSource(exchange);
            case DOM:
                return evaluateAsDOM(exchange);
            case List:
                return evaluateAsList(exchange);
            case StringSource:
                return evaluateAsStringSource(exchange);
            case String:
            default:
                return evaluateAsString(exchange);
            }
        } catch (Exception e) {
            throw new RuntimeExpressionException(e);
        }
    }

    public List evaluateAsList(Exchange exchange) throws Exception {
        initialize();

        return getExpression().evaluate(createDynamicContext(exchange));
    }

    public Object evaluateAsStringSource(Exchange exchange) throws Exception {
        initialize();

        String text = evaluateAsString(exchange);
        return new StringSource(text);
    }

    public Object evaluateAsBytesSource(Exchange exchange) throws Exception {
        initialize();

        byte[] bytes = evaluateAsBytes(exchange);
        return new BytesSource(bytes);
    }

    public Node evaluateAsDOM(Exchange exchange) throws Exception {
        initialize();

        DOMResult result = new DOMResult();
        DynamicQueryContext context = createDynamicContext(exchange);
        XQueryExpression expression = getExpression();
        expression.pull(context, result, properties);
        return result.getNode();
    }

    public byte[] evaluateAsBytes(Exchange exchange) throws Exception {
        initialize();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        Result result = new StreamResult(buffer);
        getExpression().pull(createDynamicContext(exchange), result, properties);
        byte[] bytes = buffer.toByteArray();
        return bytes;
    }

    public String evaluateAsString(Exchange exchange) throws Exception {
        initialize();

        StringWriter buffer = new StringWriter();
        SequenceIterator iter = getExpression().iterator(createDynamicContext(exchange));
        for (Item item = iter.next(); item != null; item = iter.next()) {
            buffer.append(item.getStringValueCS());
        }
        return buffer.toString();
    }

    public boolean matches(Exchange exchange) {
        try {
            List list = evaluateAsList(exchange);
            return matches(exchange, list);
        } catch (Exception e) {
            throw new RuntimeExpressionException(e);
        }
    }

    public void assertMatches(String text, Exchange exchange) throws AssertionError {
        try {
            List list = evaluateAsList(exchange);
            if (!matches(exchange, list)) {
                throw new AssertionError(this + " failed on " + exchange + " as evaluated: " + list);
            }
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }

    public static XQueryBuilder xquery(final String queryText) {
        return new XQueryBuilder() {
            protected XQueryExpression createQueryExpression(StaticQueryContext staticQueryContext)
                throws XPathException {
                return staticQueryContext.compileQuery(queryText);
            }
        };
    }

    public static XQueryBuilder xquery(final Reader reader) {
        return new XQueryBuilder() {
            protected XQueryExpression createQueryExpression(StaticQueryContext staticQueryContext)
                throws XPathException, IOException {
                return staticQueryContext.compileQuery(reader);
            }
        };
    }

    public static XQueryBuilder xquery(final InputStream in, final String characterSet) {
        return new XQueryBuilder() {
            protected XQueryExpression createQueryExpression(StaticQueryContext staticQueryContext)
                throws XPathException, IOException {
                return staticQueryContext.compileQuery(in, characterSet);
            }
        };
    }

    public static XQueryBuilder xquery(File file, String characterSet) throws FileNotFoundException {
        return xquery(IOConverter.toInputStream(file), characterSet);
    }

    public static XQueryBuilder xquery(URL url, String characterSet) throws IOException {
        return xquery(IOConverter.toInputStream(url), characterSet);
    }

    public static XQueryBuilder xquery(File file) throws FileNotFoundException {
        return xquery(IOConverter.toInputStream(file), ObjectHelper.getDefaultCharacterSet());
    }

    public static XQueryBuilder xquery(URL url) throws IOException {
        return xquery(IOConverter.toInputStream(url), ObjectHelper.getDefaultCharacterSet());
    }

    public XQueryBuilder parameter(String name, Object value) {
        parameters.put(name, value);
        return this;
    }

    public XQueryBuilder namespace(String prefix, String uri) {
        namespacePrefixes.put(prefix, uri);
        initialized.set(false);
        return this;
    }

    public XQueryBuilder resultType(Class resultType) {
        setResultType(resultType);
        return this;
    }

    public XQueryBuilder asBytes() {
        setResultsFormat(ResultFormat.Bytes);
        return this;
    }

    public XQueryBuilder asBytesSource() {
        setResultsFormat(ResultFormat.BytesSource);
        return this;
    }

    public XQueryBuilder asDOM() {
        setResultsFormat(ResultFormat.DOM);
        return this;
    }

    public XQueryBuilder asDOMSource() {
        setResultsFormat(ResultFormat.DOMSource);
        return this;
    }

    public XQueryBuilder asList() {
        setResultsFormat(ResultFormat.List);
        return this;
    }

    public XQueryBuilder asString() {
        setResultsFormat(ResultFormat.String);
        return this;
    }

    public XQueryBuilder asStringSource() {
        setResultsFormat(ResultFormat.StringSource);
        return this;
    }

    /**
     * Configures the namespace context from the given DOM element
     */
    public void setNamespaces(Map<String, String> namespaces) {
        namespacePrefixes.putAll(namespaces);
        initialized.set(false);
    }

    public XQueryExpression getExpression() throws IOException, XPathException {
        return expression;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
        initialized.set(false);
    }

    public StaticQueryContext getStaticQueryContext() {
        return staticQueryContext;
    }

    public void setStaticQueryContext(StaticQueryContext staticQueryContext) {
        this.staticQueryContext = staticQueryContext;
        initialized.set(false);
    }

    public Map<String, Object> getParameters() {
        return parameters;
    }

    public void setParameters(Map<String, Object> parameters) {
        this.parameters = parameters;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public ResultFormat getResultsFormat() {
        return resultsFormat;
    }

    public void setResultsFormat(ResultFormat resultsFormat) {
        this.resultsFormat = resultsFormat;
    }

    public Class getResultType() {
        return resultType;
    }

    public void setResultType(Class resultType) {
        this.resultType = resultType;
    }

    /**
     * A factory method to create the XQuery expression
     */
    protected abstract XQueryExpression createQueryExpression(StaticQueryContext staticQueryContext)
        throws XPathException, IOException;

    /**
     * Creates a dynamic context for the given exchange
     */
    protected DynamicQueryContext createDynamicContext(Exchange exchange) throws Exception {
        Configuration config = getConfiguration();
        DynamicQueryContext dynamicQueryContext = new DynamicQueryContext(config);

        Message in = exchange.getIn();
        Item item = in.getBody(Item.class);
        Source source = null;
        if (item != null) {
            dynamicQueryContext.setContextItem(item);
        } else {
            source = in.getBody(Source.class);
            if (source == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No body available on exchange so using an empty document: " + exchange);
                }
                source = converter.toSource(converter.createDocument());
            }
            DocumentInfo doc = getStaticQueryContext().buildDocument(source);
            dynamicQueryContext.setContextItem(doc);
        }

        configureQuery(dynamicQueryContext, exchange);
        return dynamicQueryContext;
    }

    /**
     * Configures the dynamic context with exchange specific parameters
     *
     * @param dynamicQueryContext
     * @param exchange
     * @throws Exception
     */
    protected void configureQuery(DynamicQueryContext dynamicQueryContext, Exchange exchange)
        throws Exception {
        addParameters(dynamicQueryContext, exchange.getProperties());
        addParameters(dynamicQueryContext, exchange.getIn().getHeaders());
        addParameters(dynamicQueryContext, getParameters());

        dynamicQueryContext.setParameter("exchange", exchange);
        if (exchange.getPattern().isOutCapable()) {
            dynamicQueryContext.setParameter("out", exchange.getOut());
        }
    }

    protected void addParameters(DynamicQueryContext dynamicQueryContext, Map<String, Object> map) {
        Set<Map.Entry<String, Object>> propertyEntries = map.entrySet();
        for (Map.Entry<String, Object> entry : propertyEntries) {
            dynamicQueryContext.setParameter(entry.getKey(), entry.getValue());
        }
    }

    protected boolean matches(Exchange exchange, List results) {
        return ObjectHelper.matches(results);
    }

    /**
     * Initializes this builder - <b>Must be invoked before evaluation</b>.
     */
    protected synchronized void initialize() throws XPathException, IOException {
        if (!initialized.get()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Initializing XQueryBuilder " + this);
            }
            configuration = new Configuration();
            configuration.setHostLanguage(Configuration.XQUERY);

            staticQueryContext = new StaticQueryContext(getConfiguration());
            Set<Map.Entry<String, String>> entries = namespacePrefixes.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String prefix = entry.getKey();
                String uri = entry.getValue();
                staticQueryContext.declareNamespace(prefix, uri);
                staticQueryContext.setInheritNamespaces(true);
            }

            expression = createQueryExpression(staticQueryContext);

            initialized.set(true);

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

FUNC_DECL TRY PARAM CATCH SWITCH IF IF THROW_RAISE BINARY_OP CALL CALL CALL RETURN RETURN RETURN RETURN RETURN RETURN IF LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL IF CALL CALL IF CALL RETURN BINARY_OP CALL RETURN CALL BINARY_OP RETURN CALL LITERAL_ANCHOR BINARY_OP CALL LITERAL_ANCHOR

FUNC_DECL RETURN PARAM CALL CALL CALL CALL

FUNC_DECL RETURN VAR_DECL PARAM CALL CALL CALL

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

FUNC_DECL RETURN LOOP VAR_DECL VAR_DECL PARAM CALL ASSIGN BINARY_OP CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL

FUNC_DECL TRY PARAM CATCH RETURN VAR_DECL THROW_RAISE CALL CALL CALL

FUNC_DECL RETURN PARAM CALL FUNC_DECL RETURN PARAM CALL

FUNC_DECL RETURN PARAM PARAM CALL FUNC_DECL RETURN PARAM CALL

FUNC_DECL RETURN PARAM PARAM CALL CALL LITERAL_ANCHOR

FUNC_DECL IF PARAM PARAM CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR

FUNC_DECL LOOP VAR_DECL PARAM PARAM CALL CALL CALL CALL

FUNC_DECL IF CALL LOOP VAR_DECL IF CALL ASSIGN ASSIGN CALL ASSIGN CALL LITERAL_ANCHOR CALL VAR_DECL VAR_DECL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL BINARY_OP LITERAL_ANCHOR


org.apache.xalan.transformer.KeyTable

public class KeyTable
{
  /**
   * The document key.  This table should only be used with contexts
   * whose Document roots match this key.
   */
  private int m_docKey;

  /**
   * Vector of KeyDeclaration instances holding the key declarations.
   */
  private Vector m_keyDeclarations;

  /**
   * Hold a cache of key() function result for each ref.
   * Key is XMLString, the ref value
   * Value is XNodeSet, the key() function result for the given ref value.
   */
  private Hashtable m_refsTable = null;

  /**
   * Get the document root matching this key.
   *
   * @return the document root matching this key
   */
  public int getDocKey()
  {
    return m_docKey;
  }

  /**
   * The main iterator that will walk through the source
   * tree for this key.
   */
  private XNodeSet m_keyNodes;

  KeyIterator getKeyIterator()
  {
  	return (KeyIterator)(m_keyNodes.getContainedIter());
  }

  /**
   * Build a keys table.
   * @param doc The owner document key.
   * @param nscontext The stylesheet's namespace context.
   * @param name The key name
   * @param keyDeclarations The stylesheet's xsl:key declarations.
   * @param xmlLiaison The parser liaison for support of getNodeData(useNode).
   *
   * @throws javax.xml.transform.TransformerException
   */
  public KeyTable(
          int doc, PrefixResolver nscontext, QName name, Vector keyDeclarations, XPathContext xctxt)
            throws javax.xml.transform.TransformerException
  {
    m_docKey = doc;
    m_keyDeclarations = keyDeclarations;
    KeyIterator ki = new KeyIterator(name, keyDeclarations);

    m_keyNodes = new XNodeSet(ki);
    m_keyNodes.allowDetachToRelease(false);
    m_keyNodes.setRoot(doc, xctxt);
  }

  /**
   * Given a valid element key, return the corresponding node list.
   *
   * @param name The name of the key, which must match the 'name' attribute on xsl:key.
   * @param ref The value that must match the value found by the 'match' attribute on xsl:key.
   * @return a set of nodes referenced by the key named name and the reference ref. If no node is referenced by this key, an empty node set is returned.
   */
  public XNodeSet getNodeSetDTMByKey(QName name, XMLString ref)

  {
    XNodeSet refNodes = (XNodeSet) getRefsTable().get(ref);
   try
    {
      if (refNodes != null)
      {
         refNodes = (XNodeSet) refNodes.cloneWithReset();
       }
    }
    catch (CloneNotSupportedException e)
    {
      refNodes = null;
    }

    if (refNodes == null) {
      KeyIterator ki = (KeyIterator) (m_keyNodes).getContainedIter();
      XPathContext xctxt = ki.getXPathContext();
      refNodes = new XNodeSet(xctxt.getDTMManager()) {
        public void setRoot(int nodeHandle, Object environment) {
        }
      };
      refNodes.reset();
    }

    return refNodes;
  }

  /**
   * Get Key Name for this KeyTable
   *
   * @return Key name
   */
  public QName getKeyTableName()
  {
    return getKeyIterator().getName();
  }

  /**
   * @return key declaration for the key associated to this KeyTable
   */
  private KeyDeclaration getKeyDeclaration() {
    int nDeclarations = m_keyDeclarations.size();

    for (int i = 0; i < nDeclarations; i++)
    {
      KeyDeclaration kd = (KeyDeclaration) m_keyDeclarations.elementAt(i);

      if (kd.getName().equals(getKeyTableName()))
      {
        return kd;
      }
    }

    return null;
  }

  /**
   * @return lazy initialized refs table associating evaluation of key function
   *         with a XNodeSet
   */
  private Hashtable getRefsTable()
  {
    if (m_refsTable == null)
    {

      KeyIterator ki = (KeyIterator) (m_keyNodes).getContainedIter();
      XPathContext xctxt = ki.getXPathContext();

      KeyDeclaration keyDeclaration = getKeyDeclaration();

      int currentNode;
      m_keyNodes.reset();
      while (DTM.NULL != (currentNode = m_keyNodes.nextNode()))
      {
        try
        {
          XObject xuse = keyDeclaration.getUse().execute(xctxt, currentNode, ki.getPrefixResolver());

          if (xuse.getType() != xuse.CLASS_NODESET)
          {
            XMLString exprResult = xuse.xstr();
            addValueInRefsTable(xctxt, exprResult, currentNode);
          }
          else
          {
            DTMIterator i = ((XNodeSet)xuse).iterRaw();
            int currentNodeInUseClause;

            while (DTM.NULL != (currentNodeInUseClause = i.nextNode()))
            {
              DTM dtm = xctxt.getDTM(currentNodeInUseClause);
              XMLString exprResult = dtm.getStringValue(currentNodeInUseClause);
              addValueInRefsTable(xctxt, exprResult, currentNode);
            }
          }
        }
        catch (TransformerException te)
        {
          throw new WrappedRuntimeException(te);
        }
      }
    }
    return m_refsTable;
  }

  /**
   * Add an association between a ref and a node in the m_refsTable.
   * Requires that m_refsTable != null
   * @param xctxt XPath context
   * @param ref the value of the use clause of the current key for the given node
   * @param node the node to reference
   */
  private void addValueInRefsTable(XPathContext xctxt, XMLString ref, int node) {

    XNodeSet nodes = (XNodeSet) m_refsTable.get(ref);
    if (nodes == null)
    {
      nodes = new XNodeSet(node, xctxt.getDTMManager());
      nodes.nextNode();
      m_refsTable.put(ref, nodes);
    }
    else
    {
      if (nodes.getCurrentNode() != node) {
          nodes.mutableNodeset().addNode(node);
          nodes.nextNode();

FUNC_DECL RETURN IF TRY VAR_DECL PARAM PARAM BINARY_OP CATCH IF VAR_DECL VAR_DECL LITERAL_ANCHOR BINARY_OP CALL ASSIGN ASSIGN LITERAL_ANCHOR CALL CALL CALL LITERAL_ANCHOR ASSIGN CALL FUNC_DECL CALL PARAM PARAM CALL CALL

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

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


org.apache.camel.impl.DefaultExchange

public class DefaultExchange implements Exchange {

    private static final UuidGenerator DEFAULT_ID_GENERATOR = new UuidGenerator();
    protected final CamelContext context;
    private Map<String, Object> properties;
    private Message in;
    private Message out;
    private Message fault;
    private Throwable exception;
    private String exchangeId;
    private UnitOfWork unitOfWork;
    private ExchangePattern pattern;

    public DefaultExchange(CamelContext context) {
        this(context, ExchangePattern.InOnly);
    }

    public DefaultExchange(CamelContext context, ExchangePattern pattern) {
        this.context = context;
        this.pattern = pattern;
    }

    public DefaultExchange(DefaultExchange parent) {
        this(parent.getContext(), parent.getPattern());
        this.unitOfWork = parent.getUnitOfWork();
    }

    @Override
    public String toString() {
        return "Exchange[" + in + "]";
    }

    public Exchange copy() {
        Exchange exchange = newInstance();
        exchange.copyFrom(this);
        return exchange;
    }

    public void copyFrom(Exchange exchange) {
        if (exchange == this) {
            return;
        }
        setProperties(safeCopy(exchange.getProperties()));

        safeCopy(getIn(), exchange, exchange.getIn());
        Message copyOut = exchange.getOut(false);
        if (copyOut != null) {
            safeCopy(getOut(true), exchange, copyOut);
        }
        Message copyFault = exchange.getFault(false);
        if (copyFault != null) {
            safeCopy(getFault(true), exchange, copyFault);
        }
        setException(exchange.getException());

        unitOfWork = exchange.getUnitOfWork();
        pattern = exchange.getPattern();
    }

    private static void safeCopy(Message message, Exchange exchange, Message that) {
        if (message != null) {
            message.copyFrom(that);
        }
    }

    private static Map<String, Object> safeCopy(Map<String, Object> properties) {
        if (properties == null) {
            return null;
        }
        return new ConcurrentHashMap<String, Object>(properties);
    }

    private static Message safeCopy(Exchange exchange, Message message) {
        if (message == null) {
            return null;
        }
        Message answer = message.copy();
        if (answer instanceof MessageSupport) {
            MessageSupport messageSupport = (MessageSupport) answer;
            messageSupport.setExchange(exchange);
        }
        return answer;
    }

    public Exchange newInstance() {
        return new DefaultExchange(this);
    }

    public CamelContext getContext() {
        return context;
    }

    public Object getProperty(String name) {
        if (properties != null) {
            return properties.get(name);
        }
        return null;
    }

    public <T> T getProperty(String name, Class<T> type) {
        Object value = getProperty(name);

        ExchangeProperty<?> property = ExchangeProperty.getByName(name);
        if (property != null) {
            validateExchangePropertyIsExpectedType(property, type, value);
        }

        return getContext().getTypeConverter().convertTo(type, this, value);
    }

    public void setProperty(String name, Object value) {
        ExchangeProperty<?> property = ExchangeProperty.getByName(name);

        if (property != null) {
            Class type = value.getClass();
            validateExchangePropertyIsExpectedType(property, type, value);
        }
        if (value != null) {
            getProperties().put(name, value);
        } else {
            if (name != null) {
                getProperties().remove(name);
            }
        }
    }

    private <T> void validateExchangePropertyIsExpectedType(ExchangeProperty<?> property, Class<T> type, Object value) {
        if (value != null && property != null && !property.type().isAssignableFrom(type)) {
            throw new RuntimeCamelException("Type cast exception while getting an "
                    + "Exchange Property value '" + value.toString()
                    + "' on Exchange " + this
                    + " for a well known Exchange Property with these traits: " + property);
        }
    }

    public Object removeProperty(String name) {
        return getProperties().remove(name);
    }

    public Map<String, Object> getProperties() {
        if (properties == null) {
            properties = new ConcurrentHashMap<String, Object>();
        }
        return properties;
    }

    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }

    public Message getIn() {
        if (in == null) {
            in = createInMessage();
            configureMessage(in);
        }
        return in;
    }

    public void setIn(Message in) {
        this.in = in;
        configureMessage(in);
    }

    public Message getOut() {
        return getOut(true);
    }

    public Message getOut(boolean lazyCreate) {
        if (out == null && lazyCreate) {
            out = createOutMessage();
            configureMessage(out);
        }
        return out;
    }

    public void setOut(Message out) {
        this.out = out;
        configureMessage(out);
    }

    public Throwable getException() {
        return exception;
    }

    public void setException(Throwable exception) {
        this.exception = exception;
    }

    public ExchangePattern getPattern() {
        return pattern;
    }

    public void setPattern(ExchangePattern pattern) {
        this.pattern = pattern;
    }

    public void throwException() throws Exception {
        if (exception == null) {
            return;
        }
        if (exception instanceof RuntimeException) {
            throw (RuntimeException)exception;
        }
        if (exception instanceof Exception) {
            throw (Exception)exception;
        }
        throw wrapRuntimeCamelException(exception);
    }

    public Message getFault() {
        return getFault(true);
    }

    public Message getFault(boolean lazyCreate) {
        if (fault == null && lazyCreate) {
            fault = createFaultMessage();
            configureMessage(fault);
        }
        return fault;
    }

    public void setFault(Message fault) {
        this.fault = fault;
        configureMessage(fault);
    }

    public String getExchangeId() {
        if (exchangeId == null) {
            exchangeId = DefaultExchange.DEFAULT_ID_GENERATOR.generateId();
        }
        return exchangeId;
    }

    public void setExchangeId(String id) {
        this.exchangeId = id;
    }

    public boolean isFailed() {
        Message faultMessage = getFault(false);
        if (faultMessage != null) {
            Object faultBody = faultMessage.getBody();
            if (faultBody != null) {
                return true;
            }
        }
        return getException() != null;
    }

    public boolean isTransacted() {
        ExchangeProperty<?> property = ExchangeProperty.get("transacted");
        return property != null && property.get(this) == Boolean.TRUE;
    }

    public UnitOfWork getUnitOfWork() {
        return unitOfWork;
    }

    public void setUnitOfWork(UnitOfWork unitOfWork) {
        this.unitOfWork = unitOfWork;
    }

    /**
     * Factory method used to lazily create the IN message
     */
    protected Message createInMessage() {
        return new DefaultMessage();
    }

    /**
     * Factory method to lazily create the OUT message
     */
    protected Message createOutMessage() {
        return new DefaultMessage();
    }

    /**
     * Factory method to lazily create the FAULT message
     */
    protected Message createFaultMessage() {
        return new DefaultMessage();
    }

    /**
     * Configures the message after it has been set on the exchange
     */
    protected void configureMessage(Message message) {
        if (message instanceof MessageSupport) {
            MessageSupport messageSupport = (MessageSupport)message;
            messageSupport.setExchange(this);

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


public class JhcServerEngine {
    private static final Log LOG = LogFactory.getLog(JhcServerEngine.class);
    private final HttpParams params;
    private int port;
    private String protocol;
    private int nbThreads = 2;
    private ListeningIOReactor ioReactor;
    private ThreadFactory threadFactory;
    private Thread runner;
    private SSLContext sslContext;
    private AsyncBufferingHttpServiceHandler serviceHandler;
    private HttpRequestHandlerRegistry handlerRegistry;
    private boolean isStarted;
    private int referenceCounter;

    JhcServerEngine(HttpParams params, int port, String protocol) {
        this.params = params;
        serviceHandler = new AsyncBufferingHttpServiceHandler(params);
        handlerRegistry = new HttpRequestHandlerRegistry();
        serviceHandler.setHandlerResolver(handlerRegistry);
        this.port = port;
        this.protocol = protocol;
    }

    public int getPort() {
        return port;
    }

    public String getProtocol() {
        return this.protocol;
    }

    public void setSslContext(SSLContext sslContext) {
        this.sslContext = sslContext;
    }

    public SSLContext getSslContext() {
        return this.sslContext;
    }

    public synchronized void register(String pattern, AsyncHttpRequestHandler handler) {
        handlerRegistry.register(pattern, handler);
        referenceCounter++;
    }

    public synchronized void unregister(String pattern) {
        handlerRegistry.unregister(pattern);
        referenceCounter--;
    }

    public int getReferenceCounter() {
        return referenceCounter;
    }

    public boolean isStarted() {
        return isStarted;
    }

    public void start() throws IOReactorException {
        final SocketAddress addr = new InetSocketAddress(port);
        ioReactor = new DefaultListeningIOReactor(nbThreads, threadFactory, params);

        final IOEventDispatch ioEventDispatch;
        if ("https".equals(protocol)) {
            ioEventDispatch = new SSLServerIOEventDispatch(serviceHandler, sslContext, params);
        } else {
            ioEventDispatch = new DefaultServerIOEventDispatch(serviceHandler, params);
        }
        runner = new Thread() {
            public void run() {
                try {
                    ioReactor.listen(addr);
                    isStarted = true;
                    ioReactor.execute(ioEventDispatch);
                } catch (InterruptedIOException ex) {
                    LOG.info("Interrupted");
                } catch (IOException e) {
                    LOG.warn("I/O error: " + e.getMessage());
                }
                LOG.debug("Shutdown");
            }
        };
        runner.start();
    }

    public void stop() throws IOException {
        LOG.debug("Stopping the jhc ioReactor ");
        ioReactor.shutdown();
        LOG.debug("Waiting the runner");
        try {
            runner.join();
        } catch (InterruptedException e) {
        }
        isStarted = false;
        LOG.debug("Runner stopped");

    public int getPort() {
        return port;

FUNC_DECL IF VAR_DECL VAR_DECL CALL ASSIGN LITERAL_ANCHOR ASSIGN CALL CALL CALL CALL FUNC_DECL ASSIGN ASSIGN TRY CALL CALL CALL CATCH CATCH LITERAL_ANCHOR CALL ASSIGN CALL CALL CALL LITERAL_ANCHOR BINARY_OP LITERAL_ANCHOR CALL LITERAL_ANCHOR

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


public class NumberPtg
    extends Ptg
{
    public final static int  SIZE = 9;
    public final static byte sid  = 0x1f;
    private double            field_1_value;

    private NumberPtg() {
    }

    /** Create a NumberPtg from a byte array read from disk */
    public NumberPtg(byte [] data, int offset)
    {
        setValue(LittleEndian.getDouble(data, offset + 1));
    }

    /** Create a NumberPtg from a string representation of  the number
     *  Number format is not checked, it is expected to be validated in the parser
     *   that calls this method.
     *  @param value : String representation of a floating point number
     */
    public NumberPtg(String value) {
        setValue(Double.parseDouble(value));
    }

    public void setValue(double value)
    {
        field_1_value = value;
    }

    public double getValue()
    {
        return field_1_value;
    }

    public void writeBytes(byte [] array, int offset)
    {
        array[ offset + 0 ] = sid;
        LittleEndian.putDouble(array, offset + 1, getValue());
    }

    public int getSize()
    {
        return SIZE;
    }

    public String toFormulaString(Workbook book)
    {
        return "" + getValue();
    }
       public byte getDefaultOperandClass() {return Ptg.CLASS_VALUE;}

    public Object clone() {
      NumberPtg ptg = new NumberPtg();
      ptg.field_1_value = field_1_value;
      return ptg;

    public int getSize()
    {
        return SIZE;


org.apache.poi.hssf.util.CellReference

public class CellReference {

    /** Creates new CellReference */
    private int row;
    private int col;
    private String sheetName;
    private boolean rowAbs;
    private boolean colAbs;

    public CellReference(String cellRef) {
        String[] parts = separateRefParts(cellRef);
        sheetName = parts[0];
        String ref = parts[1];
        if (ref.charAt(0) == '$') {
            colAbs=true;
            ref=ref.substring(1);
        }
        col = convertColStringToNum(ref);
        ref=parts[2];
        if (ref.charAt(0) == '$') {
            rowAbs=true;
            ref=ref.substring(1);
        }
        row = Integer.parseInt(ref)-1;
    }

    public CellReference(int pRow, int pCol) {
        this(pRow,pCol,false,false);
    }

    public CellReference(int pRow, int pCol, boolean pAbsRow, boolean pAbsCol) {
        row=pRow;col=pCol;
        rowAbs = pAbsRow;
        colAbs=pAbsCol;

    }

    public int getRow(){return row;}
    public short getCol(){return (short) col;}
    public boolean isRowAbsolute(){return rowAbs;}
    public boolean isColAbsolute(){return colAbs;}
    public String getSheetName(){return sheetName;}

    /**
     * takes in a column reference portion of a CellRef and converts it from
     * ALPHA-26 number format to 0-based base 10.
     */
    private int convertColStringToNum(String ref) {
        int len = ref.length();
        int retval=0;
        int pos = 0;

        for (int k = ref.length()-1; k > -1; k--) {
            char thechar = ref.charAt(k);
            if ( pos == 0) {
                retval += (Character.getNumericValue(thechar)-9);
            } else {
                retval += (Character.getNumericValue(thechar)-9) * (pos * 26);
            }
            pos++;
        }
        return retval-1;
    }

    /**
     * Seperates the row from the columns and returns an array.  Element in
     * position one is the substring containing the columns still in ALPHA-26
     * number format.
     */
    private String[] separateRefParts(String reference) {

        String retval[] = new String[3];

        int start = reference.indexOf("!");
        if (start != -1) retval[0] = reference.substring(0, start);
        start += 1;

        int length = reference.length();

        char[] chars = reference.toCharArray();
        int loc = start;
        if (chars[loc]=='$') loc++;
        for (; loc < chars.length; loc++) {
            if (Character.isDigit(chars[loc]) || chars[loc] == '$') {
                break;
            }
        }

        retval[1] = reference.substring(start,loc);
        retval[2] = reference.substring(loc);
        return retval;
    }

    /**
     * takes in a 0-based base-10 column and returns a ALPHA-26 representation
     */
    private static String convertNumToColString(int col) {
        String retval = null;
        int mod = col % 26;
        int div = col / 26;
        char small=(char)(mod + 65);
        char big = (char)(div + 64);

        if (div == 0) {
            retval = ""+small;
        } else {
            retval = ""+big+""+small;
        }

        return retval;
    }

    public String toString() {
        StringBuffer retval = new StringBuffer();
        retval.append( (colAbs)?"$":"");
        retval.append( convertNumToColString(col));
        retval.append((rowAbs)?"$":"");
        retval.append(row+1);

    return retval.toString();

FUNC_DECL PARAM PARAM PARAM PARAM ASSIGN ASSIGN ASSIGN ASSIGN


public interface Member
{

  /**
   * Returns the Class object representing the class or
   * interface that declares the member or constructor
   * represented by this Member.
   *
   */
  public abstract org.apache.xml.utils.synthetic.Class getDeclaringClass();

  /**
   * Returns the Java language modifiers for the
   * member or constructor represented by this
   * Member, as an integer. The Modifier class should
   * be used to decode the modifiers in the integer.
   *
   */
  public abstract int getModifiers();

  /**
   * Returns the Class object representing the class or
   * interface that declares the member or constructor
   * represented by this Member.
   *
   * @param declaringClass
   *
   * @throws SynthesisException
   */
  public abstract void setDeclaringClass(
    org.apache.xml.utils.synthetic.Class declaringClass)
      throws SynthesisException;

  /**
   * Returns the Java language modifiers for the
   * member or constructor represented by this
   * Member, as an integer. The Modifier class should
   * be used to decode the modifiers in the integer.
   *
   * @param modifiers
   *
   * @throws SynthesisException
   */
  public abstract void setModifiers(int modifiers) throws SynthesisException;


  private static int [] zzUnpackAction() {
    int [] result = new int[51];
    int offset = 0;
    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
    return result;

  private static int zzUnpackAction(String packed, int offset, int [] result) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      do result[j++] = value; while (--count > 0);
    }
    return j;

  private static int [] zzUnpackRowMap() {
    int [] result = new int[51];
    int offset = 0;
    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
    return result;

  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
    int i = 0;  /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int high = packed.charAt(i++) << 16;
      result[j++] = high | packed.charAt(i++);
    }
    return j;

  private static int [] zzUnpackTrans() {
    int [] result = new int[658];
    int offset = 0;
    offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
    return result;

  private static int zzUnpackTrans(String packed, int offset, int [] result) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      value--;
      do result[j++] = value; while (--count > 0);
    }
    return j;

  private static int [] zzUnpackAttribute() {
    int [] result = new int[51];
    int offset = 0;
    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
    return result;

  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      do result[j++] = value; while (--count > 0);
    }
    return j;

public final int yychar()
{
    return yychar;

final void getText(Token t) {
  t.setTermBuffer(zzBuffer, zzStartRead, zzMarkedPos-zzStartRead);

  private static char [] zzUnpackCMap(String packed) {
    char [] map = new char[0x10000];
    int i = 0;  /* index in packed string  */
    int j = 0;  /* index in unpacked array */
    while (i < 1154) {
      int  count = packed.charAt(i++);
      char value = packed.charAt(i++);
      do map[j++] = value; while (--count > 0);
    }
    return map;

  private boolean zzRefill() throws java.io.IOException {

    /* first: make room (if you can) */
    if (zzStartRead > 0) {
      System.arraycopy(zzBuffer, zzStartRead,
                       zzBuffer, 0,
                       zzEndRead-zzStartRead);

      /* translate stored positions */
      zzEndRead-= zzStartRead;
      zzCurrentPos-= zzStartRead;
      zzMarkedPos-= zzStartRead;
      zzPushbackPos-= zzStartRead;
      zzStartRead = 0;
    }

    /* is the buffer big enough? */
    if (zzCurrentPos >= zzBuffer.length) {
      /* if not: blow it up */
      char newBuffer[] = new char[zzCurrentPos*2];
      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
      zzBuffer = newBuffer;
    }

    /* finally: fill the buffer with new input */
    int numRead = zzReader.read(zzBuffer, zzEndRead,
                                            zzBuffer.length-zzEndRead);

    if (numRead < 0) {
      return true;
    }
    else {
      zzEndRead+= numRead;
      return false;

  public final void yyclose() throws java.io.IOException {
    zzAtEOF = true;            /* indicate end of file */
    zzEndRead = zzStartRead;  /* invalidate buffer    */

    if (zzReader != null)
      zzReader.close();

  public final void yyreset(java.io.Reader reader) {
    zzReader = reader;
    zzAtBOL  = true;
    zzAtEOF  = false;
    zzEndRead = zzStartRead = 0;
    zzCurrentPos = zzMarkedPos = zzPushbackPos = 0;
    yyline = yychar = yycolumn = 0;
    zzLexicalState = YYINITIAL;

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

  public final int yystate() {
    return zzLexicalState;

  public final void yybegin(int newState) {
    zzLexicalState = newState;

  public final String yytext() {
    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );

  public final char yycharat(int pos) {
    return zzBuffer[zzStartRead+pos];

  public final int yylength() {
    return zzMarkedPos-zzStartRead;

  private void zzScanError(int errorCode) {
    String message;
    try {
      message = ZZ_ERROR_MSG[errorCode];
    }
    catch (ArrayIndexOutOfBoundsException e) {
      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
    }

    throw new Error(message);

FUNC_DECL THROW_RAISE TRY VAR_DECL PARAM CALL CATCH ASSIGN ASSIGN

  public void yypushback(int number)  {
    if ( number > yylength() )
      zzScanError(ZZ_PUSHBACK_2BIG);

    zzMarkedPos -= number;

FUNC_DECL IF PARAM ASSIGN BINARY_OP CALL CALL

  public int getNextToken() throws java.io.IOException {
    int zzInput;
    int zzAction;

    int zzCurrentPosL;
    int zzMarkedPosL;
    int zzEndReadL = zzEndRead;
    char [] zzBufferL = zzBuffer;
    char [] zzCMapL = ZZ_CMAP;

    int [] zzTransL = ZZ_TRANS;
    int [] zzRowMapL = ZZ_ROWMAP;
    int [] zzAttrL = ZZ_ATTRIBUTE;

    while (true) {
      zzMarkedPosL = zzMarkedPos;

      yychar+= zzMarkedPosL-zzStartRead;

      zzAction = -1;

      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;

      zzState = zzLexicalState;

      zzForAction: {
        while (true) {

          if (zzCurrentPosL < zzEndReadL)
            zzInput = zzBufferL[zzCurrentPosL++];
          else if (zzAtEOF) {
            zzInput = YYEOF;
            break zzForAction;
          }
          else {
            zzCurrentPos  = zzCurrentPosL;
            zzMarkedPos   = zzMarkedPosL;
            boolean eof = zzRefill();
            zzCurrentPosL  = zzCurrentPos;
            zzMarkedPosL   = zzMarkedPos;
            zzBufferL      = zzBuffer;
            zzEndReadL     = zzEndRead;
            if (eof) {
              zzInput = YYEOF;
              break zzForAction;
            }
            else {
              zzInput = zzBufferL[zzCurrentPosL++];
            }
          }
          int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
          if (zzNext == -1) break zzForAction;
          zzState = zzNext;

          int zzAttributes = zzAttrL[zzState];
          if ( (zzAttributes & 1) == 1 ) {
            zzAction = zzState;
            zzMarkedPosL = zzCurrentPosL;
            if ( (zzAttributes & 8) == 8 ) break zzForAction;
          }

        }
      }

      zzMarkedPos = zzMarkedPosL;

      switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
        case 4:
          { return HOST;
          }
        case 11: break;
        case 9:
          { return ACRONYM;
          }
        case 12: break;
        case 8:
          { return ACRONYM_DEP;
          }
        case 13: break;
        case 1:
          { /* ignore */
          }
        case 14: break;
        case 5:
          { return NUM;
          }
        case 15: break;
        case 3:
          { return CJ;
          }
        case 16: break;
        case 2:
          { return ALPHANUM;
          }
        case 17: break;
        case 7:
          { return COMPANY;
          }
        case 18: break;
        case 6:
          { return APOSTROPHE;
          }
        case 19: break;
        case 10:
          { return EMAIL;
          }
        case 20: break;
        default:
          if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
            zzAtEOF = true;
            return YYEOF;
          }
          else {
            zzScanError(ZZ_NO_MATCH);

  StandardTokenizerImpl(java.io.Reader in) {
    this.zzReader = in;

  StandardTokenizerImpl(java.io.InputStream in) {
    this(new java.io.InputStreamReader(in));


public class CellReference {

    /** Creates new CellReference */
    private int row;
    private int col;
    private String sheetName;
    private boolean rowAbs;
    private boolean colAbs;

    public CellReference(String cellRef) {
        String[] parts = separateRefParts(cellRef);
        sheetName = parts[0];
        String ref = parts[1];
        if ((ref == null)||("".equals(ref)))
        	throw new IllegalArgumentException("Invalid Formula cell reference: '"+cellRef+"'");
        if (ref.charAt(0) == '$') {
            colAbs=true;
            ref=ref.substring(1);
        }
        col = convertColStringToNum(ref);
        ref=parts[2];
        if ((ref == null)||("".equals(ref)))
        	throw new IllegalArgumentException("Invalid Formula cell reference: '"+cellRef+"'");
        if (ref.charAt(0) == '$') {
            rowAbs=true;
            ref=ref.substring(1);
        }
        row = Integer.parseInt(ref)-1;
    }

    public CellReference(int pRow, int pCol) {
        this(pRow,pCol,false,false);
    }

    public CellReference(int pRow, int pCol, boolean pAbsRow, boolean pAbsCol) {
        row=pRow;col=pCol;
        rowAbs = pAbsRow;
        colAbs=pAbsCol;

    }

    public int getRow(){return row;}
    public short getCol(){return (short) col;}
    public boolean isRowAbsolute(){return rowAbs;}
    public boolean isColAbsolute(){return colAbs;}
    public String getSheetName(){return sheetName;}

    /**
     * takes in a column reference portion of a CellRef and converts it from
     * ALPHA-26 number format to 0-based base 10.
     */
    private int convertColStringToNum(String ref) {
        int len = ref.length();
        int retval=0;
        int pos = 0;

        for (int k = ref.length()-1; k > -1; k--) {
            char thechar = ref.charAt(k);
            if ( pos == 0) {
                retval += (Character.getNumericValue(thechar)-9);
            } else {
                retval += (Character.getNumericValue(thechar)-9) * (pos * 26);
            }
            pos++;
        }
        return retval-1;
    }

    /**
     * Seperates the row from the columns and returns an array.  Element in
     * position one is the substring containing the columns still in ALPHA-26
     * number format.
     */
    private String[] separateRefParts(String reference) {

        String retval[] = new String[3];

        int start = reference.indexOf("!");
        if (start != -1) retval[0] = reference.substring(0, start);
        start += 1;

        int length = reference.length();

        char[] chars = reference.toCharArray();
        int loc = start;
        if (chars[loc]=='$') loc++;
        for (; loc < chars.length; loc++) {
            if (Character.isDigit(chars[loc]) || chars[loc] == '$') {
                break;
            }
        }

        retval[1] = reference.substring(start,loc);
        retval[2] = reference.substring(loc);
        return retval;
    }

    /**
     * takes in a 0-based base-10 column and returns a ALPHA-26 representation
     */
    private static String convertNumToColString(int col) {
        String retval = null;
        int mod = col % 26;
        int div = col / 26;
        char small=(char)(mod + 65);
        char big = (char)(div + 64);

        if (div == 0) {
            retval = ""+small;
        } else {
            retval = ""+big+""+small;
        }

        return retval;
    }

    public String toString() {
        StringBuffer retval = new StringBuffer();
        retval.append( (colAbs)?"$":"");
        retval.append( convertNumToColString(col));
        retval.append((rowAbs)?"$":"");
        retval.append(row+1);

    return retval.toString();


public class MergeCellsRecord
    extends Record
{
    public final static short sid = 0xe5;
    private ArrayList         field_2_regions;

    public MergeCellsRecord()
    {
    }

    /**
     * Constructs a MergedCellsRecord and sets its fields appropriately
     *
     * @param sid     id must be 0xe5 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 MergeCellsRecord(short sid, short size, byte [] data)
    {
        super(sid, size, data);
    }

    /**
     * Constructs a MergedCellsRecord and sets its fields appropriately
     *
     * @param sid     id must be 0xe5 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 the offset of the record's data
     */

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

    protected void fillFields(byte [] data, short size, int offset)
    {
        short numAreas    = LittleEndian.getShort(data, 0 + offset);
        field_2_regions   = new ArrayList(numAreas + 10);
        int pos = 2;

        for (int k = 0; k < numAreas; k++)
        {
            MergedRegion region =
                new MergedRegion(LittleEndian
                    .getShort(data, pos + offset), LittleEndian
                    .getShort(data, pos + 2 + offset), LittleEndian
                    .getShort(data, pos + 4 + offset), LittleEndian
                    .getShort(data, pos + 6 + offset));

            pos += 8;
            field_2_regions.add(region);
        }
    }

    /**
     * get the number of merged areas.  If this drops down to 0 you should just go
     * ahead and delete the record.
     * @return number of areas
     */

    public short getNumAreas()
    {
        if (field_2_regions == null) return 0;
        return (short)field_2_regions.size();
    }

    /**
     * set the number of merged areas.  You do not need to call this if you use addArea,
     * it will be incremented automatically or decremented when an area is removed.  If
     * you are setting this to 0 then you are a terrible person.  Just remove the record.
     * (just kidding about you being a terrible person..hehe)
     * @deprecated We now link the size to the actual array of merged regions
     * @see #getNumAreas()
     * @param numareas  number of areas
     */

    public void setNumAreas(short numareas)
    {

    }

    /**
     * Add an area to consider a merged cell.  The index returned is only gauranteed to
     * be correct provided you do not add ahead of or remove ahead of it  (in which case
     * you should increment or decrement appropriately....in other words its an arrayList)
     *
     * @param rowfrom - the upper left hand corner's row
     * @param colfrom - the upper left hand corner's col
     * @param rowto - the lower right hand corner's row
     * @param colto - the lower right hand corner's col
     * @return new index of said area (don't depend on it if you add/remove)
     */

    public int addArea(int rowfrom, short colfrom, int rowto, short colto)
    {
        if (field_2_regions == null)
        {
            field_2_regions = new ArrayList(10);
        }
        MergedRegion region = new MergedRegion(rowfrom, rowto, colfrom,
                                               colto);

        field_2_regions.add(region);
        return field_2_regions.size() - 1;
    }

    /**
     * essentially unmerge the cells in the "area" stored at the passed in index
     * @param area index
     */

    public void removeAreaAt(int area)
    {
        field_2_regions.remove(area);
    }

    /**
     * return the MergedRegion at the given index.
     *
     * @return MergedRegion representing the area that is Merged (r1,c1 - r2,c2)
     */

    public MergedRegion getAreaAt(int index)
    {
        return ( MergedRegion ) field_2_regions.get(index);
    }

    public int getRecordSize()
    {
        int retValue;

        retValue = 6 + (8 * field_2_regions.size());
        return retValue;
    }

    public short getSid()
    {
        return sid;
    }

    public int serialize(int offset, byte [] data)
    {
        int recordsize = getRecordSize();
        int pos        = 6;

        LittleEndian.putShort(data, offset + 0, sid);
        LittleEndian.putShort(data, offset + 2, ( short ) (recordsize - 4));
        LittleEndian.putShort(data, offset + 4, getNumAreas());
        for (int k = 0; k < getNumAreas(); k++)
        {
            MergedRegion region = getAreaAt(k);

            LittleEndian.putShort(data, offset + pos, ( short ) region.row_from);
            pos += 2;
            LittleEndian.putShort(data, offset + pos, ( short ) region.row_to);
            pos += 2;
            LittleEndian.putShort(data, offset + pos, region.col_from);
            pos += 2;
            LittleEndian.putShort(data, offset + pos, region.col_to);
            pos += 2;
        }
        return recordsize;
    }

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

        retval.append("[MERGEDCELLS]").append("\n");
        retval.append("     .sid        =").append(sid).append("\n");
        retval.append("     .numregions =").append(getNumAreas())
            .append("\n");
        for (int k = 0; k < getNumAreas(); k++)
        {
            MergedRegion region = ( MergedRegion ) field_2_regions.get(k);

            retval.append("     .rowfrom    =").append(region.row_from)
                .append("\n");
            retval.append("     .colfrom    =").append(region.col_from)
                .append("\n");
            retval.append("     .rowto      =").append(region.row_to)
                .append("\n");
            retval.append("     .colto      =").append(region.col_to)
                .append("\n");
        }
        retval.append("[MERGEDCELLS]").append("\n");
        return retval.toString();
    }

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

    /**
     * this is a low level representation of a MergedRegion of cells.  It is an
     * inner class because we do not want it used without reference to this class.
     *
     */

    public class MergedRegion
    {

        /**
         * create a merged region all in one stroke.
         */

        public MergedRegion(int row_from, int row_to, short col_from,
                            short col_to)
        {
            this.row_from = row_from;
            this.row_to   = row_to;
            this.col_from = col_from;
            this.col_to   = col_to;
        }

        /**
         * upper lefthand corner row
         */

        public int row_from;

        /**
         * lower right hand corner row
         */

        public int row_to;

        /**
         * upper right hand corner col
         */

        public short col_from;

        /**
         * lower right hand corner col
         */

        public short col_to;
    }

    public Object clone() {
        MergeCellsRecord rec = new MergeCellsRecord();
        rec.field_2_regions = new ArrayList();
        Iterator iterator = field_2_regions.iterator();
        while (iterator.hasNext()) {
           MergedRegion oldRegion = (MergedRegion)iterator.next();
           rec.addArea(oldRegion.row_from, oldRegion.col_from, oldRegion.row_to, oldRegion.col_to);
        }

        return rec;

    public short getSid()
    {
        return sid;

FUNC_DECL RETURN LOOP VAR_DECL VAR_DECL CALL ASSIGN VAR_DECL CALL CALL CALL CALL CALL


final class Fallback extends Instruction {

    private boolean _active = false;

    /**
     * This element never produces any data on the stack
     */
    public Type typeCheck(SymbolTable stable) throws TypeCheckError {
	if (_active) {
	    return(typeCheckContents(stable));
	}
	else {
	    return Type.Void;
	}
    }

    /**
     * Activate this fallback element
     */
    public void activate() {
	_active = true;
    }

    public String toString() {
	return("fallback");
    }

    /**
     * Parse contents only if this fallback element is put in place of
     * some unsupported element or non-XSLTC extension element
     */
    public void parseContents(Parser parser) {
	if (_active) parseChildren(parser);
    }

    /**
     * Translate contents only if this fallback element is put in place of
     * some unsupported element or non-XSLTC extension element
     */
    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
	final ConstantPoolGen cpg = classGen.getConstantPool();
	final InstructionList il = methodGen.getInstructionList();

	if (_active) translateContents(classGen, methodGen);

FUNC_DECL IF VAR_DECL VAR_DECL PARAM PARAM CALL CALL CALL


public class PersistentReplyToFutureHandler extends FutureHandler {

    private static final transient Log LOG = LogFactory.getLog(PersistentReplyToFutureHandler.class);
    protected PersistentReplyToRequestor requestor;
    protected DeferredMessageSentCallback callback;
    protected String correlationID;

    public PersistentReplyToFutureHandler(PersistentReplyToRequestor requestor,
                                          String correlationID) {
        super();
        this.requestor = requestor;
        this.correlationID = correlationID;
    }

    public PersistentReplyToFutureHandler(PersistentReplyToRequestor requestor,
                                          DeferredMessageSentCallback callback) {
        super();
        this.requestor = requestor;
        this.callback = callback;
    }

    @Override
    public Message get() throws InterruptedException, ExecutionException {
        Message result = null;
        try {
            updateSelector();
            result = super.get();
        } finally {
            revertSelector();
        }
        return result;
    }

    @Override
    public Message get(long timeout, TimeUnit unit) throws InterruptedException,
                                                           ExecutionException,
                                                           TimeoutException {
        Message result = null;
        try {
            updateSelector();
            result = super.get(timeout, unit);
        } finally {
            revertSelector();
        }
        return result;
    }

    protected void updateSelector() throws ExecutionException {
        try {
            MessageSelectorComposer composer = (MessageSelectorComposer)requestor.getListenerContainer();
            composer.addCorrelationID((correlationID != null) ? correlationID : callback.getMessage().getJMSMessageID());
        } catch (Exception e) {
            throw new ExecutionException(e);
        }
    }

    protected void revertSelector() throws ExecutionException {
        try {
            MessageSelectorComposer composer = (MessageSelectorComposer)requestor.getListenerContainer();
            composer.removeCorrelationID((correlationID != null) ? correlationID : callback.getMessage().getJMSMessageID());
        } catch (Exception e) {
            throw new ExecutionException(e);

FUNC_DECL RETURN TRY VAR_DECL PARAM PARAM CALL ASSIGN CALL LITERAL_ANCHOR


org.apache.xpath.functions.FuncConcat

public class FuncConcat extends FunctionMultiArgs
{

  /**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
  public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
  {

    StringBuffer sb = new StringBuffer();

    sb.append(m_arg0.execute(xctxt).str());
    sb.append(m_arg1.execute(xctxt).str());

    if (null != m_arg2)
      sb.append(m_arg2.execute(xctxt).str());

    if (null != m_args)
    {
      for (int i = 0; i < m_args.length; i++)
      {
        sb.append(m_args[i].execute(xctxt).str());
      }
    }

    return new XString(sb.toString());
  }

  /**
   * Check that the number of arguments passed to this function is correct.
   *
   *
   * @param argNum The number of arguments that is being passed to the function.
   *
   * @throws WrongNumberArgsException
   */
  public void checkNumberArgs(int argNum) throws WrongNumberArgsException
  {
    if (argNum < 2)
      reportWrongNumberArgs();
  }

  /**
   * Constructs and throws a WrongNumberArgException with the appropriate
   * message for this function object.
   *
   * @throws WrongNumberArgsException
   */
  protected void reportWrongNumberArgs() throws WrongNumberArgsException {
      throw new WrongNumberArgsException(XSLMessages.createXPATHMessage("gtone", null));

FUNC_DECL RETURN IF IF VAR_DECL PARAM CALL BINARY_OP BINARY_OP CALL CALL CALL LOOP LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL CALL CALL BINARY_OP CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL


org.gjt.sp.jedit.gui.ViewRegisters

public class ViewRegisters extends EnhancedDialog
{
	public ViewRegisters(View view)
	{
		super(view,jEdit.getProperty("view-registers.title"),true);

		JPanel content = new JPanel(new BorderLayout());
		content.setBorder(new EmptyBorder(12,12,12,12));
		setContentPane(content);

		JPanel panel = new JPanel(new BorderLayout());
		panel.setBorder(new EmptyBorder(0,12,0,0));

		JLabel label = new JLabel(jEdit.getProperty("view-registers.register"));
		label.setBorder(new EmptyBorder(0,0,3,0));
		panel.add(BorderLayout.NORTH,label);

		DefaultListModel registerModel = new DefaultListModel();
		registerList = new JList(registerModel);
		registerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		registerList.setCellRenderer(new Renderer());

		Registers.Register[] registers = Registers.getRegisters();

		int index = 0;
		for(int i = 0; i < registers.length; i++)
		{
			Registers.Register reg = registers[i];
			if(reg == null)
				continue;

			String value = reg.toString();
			if(value == null || value.length() == 0)
				continue;

			registerModel.addElement(new Character((char)i));
		}

		if(registerModel.getSize() == 0)
			registerModel.addElement(jEdit.getProperty("view-registers.none"));

		panel.add(BorderLayout.CENTER,new JScrollPane(registerList));

		content.add(BorderLayout.WEST,panel);

		panel = new JPanel(new BorderLayout());
		panel.setBorder(new EmptyBorder(0,12,0,0));

		label = new JLabel(jEdit.getProperty("view-registers.contents"));
		label.setBorder(new EmptyBorder(0,0,3,0));
		panel.add(BorderLayout.NORTH,label);

		contentTextArea = new JTextArea(10,80);
		contentTextArea.setEditable(false);
		panel.add(BorderLayout.CENTER,new JScrollPane(contentTextArea));
		content.add(BorderLayout.CENTER,panel);

		panel = new JPanel();
		panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
		panel.setBorder(new EmptyBorder(12,0,0,0));
		close = new JButton(jEdit.getProperty("common.close"));
		close.addActionListener(new ActionHandler());
		panel.add(Box.createGlue());
		panel.add(close);
		panel.add(Box.createGlue());
		getRootPane().setDefaultButton(close);
		content.add(BorderLayout.SOUTH,panel);

		registerList.addListSelectionListener(new ListHandler());
		registerList.setSelectedIndex(index);

		pack();
		setLocationRelativeTo(view);
		show();
	}

	// EnhancedDialog implementation
	public void ok()
	{
		dispose();
	}

	public void cancel()
	{
		dispose();
	}
	// end EnhancedDialog implementation

	// private members
	private JList registerList;
	private JTextArea contentTextArea;
	private JButton close;

	class Renderer extends DefaultListCellRenderer
	{
		public Component getListCellRendererComponent(
			JList list, Object value, int index,
			boolean isSelected, boolean cellHasFocus)
		{
			super.getListCellRendererComponent(list,value,
				index,isSelected,cellHasFocus);

			if(value instanceof Character)
			{
				char name = ((Character)value).charValue();

				String label;

				if(name == '\n')
					label = "\n";
				else if(name == '\t')
					label = "\t";
				else if(name == '$')
					label = jEdit.getProperty("view-registers.clipboard");
				else if(name == '%')
					label = jEdit.getProperty("view-registers.selection");
				else
					label = String.valueOf((char)name);

				setText(label);
			}

			return this;
		}
	}

	class ActionHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent evt)
		{
			if(evt.getSource() == close)
				cancel();
		}
	}

	class ListHandler implements ListSelectionListener
	{
		public void valueChanged(ListSelectionEvent evt)
		{
			Object value = registerList.getSelectedValue();
			if(!(value instanceof Character))
				return;

			char name = ((Character)value).charValue();

			Registers.Register reg = Registers.getRegister(name);

			if(reg == null)
				return;

			contentTextArea.setText(reg.toString());
			contentTextArea.setCaretPosition(0);


public class DefaultColWidthRecord
    extends Record
{
    public final static short sid = 0x55;
    private short             field_1_col_width;

    public DefaultColWidthRecord()
    {
    }

    /**
     * Constructs a DefaultColumnWidth record and sets its fields appropriately.
     *
     * @param id     id must be 0x55 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 DefaultColWidthRecord(short id, short size, byte [] data)
    {
        super(id, size, data);
    }

    /**
     * Constructs a DefaultColumnWidth record and sets its fields appropriately.
     *
     * @param id     id must be 0x55 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 DefaultColWidthRecord(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 A DefaultColWidth RECORD");
        }
    }

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

    /**
     * set the default column width
     * @param height defaultwidth for columns
     */

    public void setColWidth(short height)
    {
        field_1_col_width = height;
    }

    /**
     * get the default column width
     * @return defaultwidth for columns
     */

    public short getColWidth()
    {
        return field_1_col_width;
    }

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

        buffer.append("[DEFAULTCOLWIDTH]\n");
        buffer.append("    .colwidth      = ")
            .append(Integer.toHexString(getColWidth())).append("\n");
        buffer.append("[/DEFAULTCOLWIDTH]\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, getColWidth());
        return getRecordSize();
    }

    public int getRecordSize()
    {
        return 6;
    }

    public short getSid()
    {
        return this.sid;

    public int getRecordSize()
    {
        return 6;


public class SendProcessor extends ServiceSupport implements Processor, Service {
    private Endpoint destination;
    private Producer producer;

    public SendProcessor(Endpoint destination) {
        this.destination = destination;
    }

    protected void doStop() throws Exception {
        if (producer != null) {
            try {
                producer.stop();
            }
            finally {
                producer = null;
            }
        }
    }

    protected void doStart() throws Exception {
        this.producer = destination.createProducer();
    }

    public void process(Exchange exchange) throws Exception {
        if (producer == null) {
            throw new IllegalStateException("No producer, this processor has not been started!");
        }
        producer.process(exchange);
    }

    public Endpoint getDestination() {
        return destination;
    }

    @Override
    public String toString() {
        return "sendTo(" + destination + ")";