public class AreaFormatRecord
    extends Record
{
    public final static short      sid                             = 0x100a;
    private  int        field_1_foregroundColor;
    private  int        field_2_backgroundColor;
    private  short      field_3_pattern;
    private  short      field_4_formatFlags;
    private  BitField   automatic                                   = new BitField(0x1);
    private  BitField   invert                                      = new BitField(0x2);
    private  short      field_5_forecolorIndex;
    private  short      field_6_backcolorIndex;

    public AreaFormatRecord()
    {

    }

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

    }

    /**
     * Constructs a AreaFormat record and sets its fields appropriately.
     *
     * @param id    id must be 0x100a 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 AreaFormatRecord(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 AreaFormat record");
        }
    }

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

        int pos = 0;
        field_1_foregroundColor        = LittleEndian.getInt(data, pos + 0x0 + offset);
        field_2_backgroundColor        = LittleEndian.getInt(data, pos + 0x4 + offset);
        field_3_pattern                = LittleEndian.getShort(data, pos + 0x8 + offset);
        field_4_formatFlags            = LittleEndian.getShort(data, pos + 0xa + offset);
        field_5_forecolorIndex         = LittleEndian.getShort(data, pos + 0xc + offset);
        field_6_backcolorIndex         = LittleEndian.getShort(data, pos + 0xe + offset);

    }

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

        buffer.append("[AREAFORMAT]\n");
        buffer.append("    .foregroundColor      = ")
            .append("0x").append(HexDump.toHex(  getForegroundColor ()))
            .append(" (").append( getForegroundColor() ).append(" )");
        buffer.append(System.getProperty("line.separator"));
        buffer.append("    .backgroundColor      = ")
            .append("0x").append(HexDump.toHex(  getBackgroundColor ()))
            .append(" (").append( getBackgroundColor() ).append(" )");
        buffer.append(System.getProperty("line.separator"));
        buffer.append("    .pattern              = ")
            .append("0x").append(HexDump.toHex(  getPattern ()))
            .append(" (").append( getPattern() ).append(" )");
        buffer.append(System.getProperty("line.separator"));
        buffer.append("    .formatFlags          = ")
            .append("0x").append(HexDump.toHex(  getFormatFlags ()))
            .append(" (").append( getFormatFlags() ).append(" )");
        buffer.append(System.getProperty("line.separator"));
        buffer.append("         .automatic                = ").append(isAutomatic()).append('\n');
        buffer.append("         .invert                   = ").append(isInvert()).append('\n');
        buffer.append("    .forecolorIndex       = ")
            .append("0x").append(HexDump.toHex(  getForecolorIndex ()))
            .append(" (").append( getForecolorIndex() ).append(" )");
        buffer.append(System.getProperty("line.separator"));
        buffer.append("    .backcolorIndex       = ")
            .append("0x").append(HexDump.toHex(  getBackcolorIndex ()))
            .append(" (").append( getBackcolorIndex() ).append(" )");
        buffer.append(System.getProperty("line.separator"));

        buffer.append("[/AREAFORMAT]\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.putInt(data, 4 + offset + pos, field_1_foregroundColor);
        LittleEndian.putInt(data, 8 + offset + pos, field_2_backgroundColor);
        LittleEndian.putShort(data, 12 + offset + pos, field_3_pattern);
        LittleEndian.putShort(data, 14 + offset + pos, field_4_formatFlags);
        LittleEndian.putShort(data, 16 + offset + pos, field_5_forecolorIndex);
        LittleEndian.putShort(data, 18 + offset + pos, field_6_backcolorIndex);

        return getRecordSize();
    }

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

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

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

        rec.field_1_foregroundColor = field_1_foregroundColor;
        rec.field_2_backgroundColor = field_2_backgroundColor;
        rec.field_3_pattern = field_3_pattern;
        rec.field_4_formatFlags = field_4_formatFlags;
        rec.field_5_forecolorIndex = field_5_forecolorIndex;
        rec.field_6_backcolorIndex = field_6_backcolorIndex;
        return rec;
    }

    /**
     * Get the foreground color field for the AreaFormat record.
     */
    public int getForegroundColor()
    {
        return field_1_foregroundColor;
    }

    /**
     * Set the foreground color field for the AreaFormat record.
     */
    public void setForegroundColor(int field_1_foregroundColor)
    {
        this.field_1_foregroundColor = field_1_foregroundColor;
    }

    /**
     * Get the background color field for the AreaFormat record.
     */
    public int getBackgroundColor()
    {
        return field_2_backgroundColor;
    }

    /**
     * Set the background color field for the AreaFormat record.
     */
    public void setBackgroundColor(int field_2_backgroundColor)
    {
        this.field_2_backgroundColor = field_2_backgroundColor;
    }

    /**
     * Get the pattern field for the AreaFormat record.
     */
    public short getPattern()
    {
        return field_3_pattern;
    }

    /**
     * Set the pattern field for the AreaFormat record.
     */
    public void setPattern(short field_3_pattern)
    {
        this.field_3_pattern = field_3_pattern;
    }

    /**
     * Get the format flags field for the AreaFormat record.
     */
    public short getFormatFlags()
    {
        return field_4_formatFlags;
    }

    /**
     * Set the format flags field for the AreaFormat record.
     */
    public void setFormatFlags(short field_4_formatFlags)
    {
        this.field_4_formatFlags = field_4_formatFlags;
    }

    /**
     * Get the forecolor index field for the AreaFormat record.
     */
    public short getForecolorIndex()
    {
        return field_5_forecolorIndex;
    }

    /**
     * Set the forecolor index field for the AreaFormat record.
     */
    public void setForecolorIndex(short field_5_forecolorIndex)
    {
        this.field_5_forecolorIndex = field_5_forecolorIndex;
    }

    /**
     * Get the backcolor index field for the AreaFormat record.
     */
    public short getBackcolorIndex()
    {
        return field_6_backcolorIndex;
    }

    /**
     * Set the backcolor index field for the AreaFormat record.
     */
    public void setBackcolorIndex(short field_6_backcolorIndex)
    {
        this.field_6_backcolorIndex = field_6_backcolorIndex;
    }

    /**
     * Sets the automatic field value.
     * automatic formatting
     */
    public void setAutomatic(boolean value)
    {
        field_4_formatFlags = automatic.setShortBoolean(field_4_formatFlags, value);
    }

    /**
     * automatic formatting
     * @return  the automatic field value.
     */
    public boolean isAutomatic()
    {
        return automatic.isSet(field_4_formatFlags);
    }

    /**
     * Sets the invert field value.
     * swap foreground and background colours when data is negative
     */
    public void setInvert(boolean value)
    {
        field_4_formatFlags = invert.setShortBoolean(field_4_formatFlags, value);
    }

    /**
     * swap foreground and background colours when data is negative
     * @return  the invert field value.
     */
    public boolean isInvert()
    {
        return invert.isSet(field_4_formatFlags);

FUNC_DECL RETURN VAR_DECL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL LITERAL_ANCHOR CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL

FUNC_DECL RETURN VAR_DECL ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN CALL


bsh.Name

class Name implements java.io.Serializable
{
	// These do not change during evaluation
	public NameSpace namespace;
	String value = null;

	// ---------------------------------------------------------
	// The following instance variables mutate during evaluation and should
	// be reset by the reset() method where necessary

	// For evaluation
	private String evalName;		// text left to eval
	private Object evalBaseObject;	// base object for current eval

	private int callstackDepth;		// number of times eval hit 'this.caller'
	/**
		The last round consume the literal 'this' reference (not super,
		global, or another This type var).  We use this flag to support magic
		variables that can only be referenced through 'this.xxx', e.g.
		this.interpreter and this.caller;
	*/
	private boolean literalThisReference;
	/**
		The last round consume the literal 'caller' reference (not super,
		global, or another This type var).  This is used to limit references
		to .caller to only after a literal 'this' or compound '.caller'.
	*/
	private boolean literalCallerReference;

	//
	//  End mutable instance variables.
	// ---------------------------------------------------------

	private void reset() {
		evalName = value;
		evalBaseObject = null;
		callstackDepth = 0;
		literalThisReference=false;
		literalCallerReference=false;
	}

	/**
		This constructor should *not* be used in general.
		Use NameSpace getNameResolver() which supports caching.
		I wish I could make this "friendly" to just that class.
		@see NameSpace getNameResolver().
	*/
	public Name(NameSpace namespace, String s)
	{
		this.namespace = namespace;
		value = s;
	}

	/**
		Resolve possibly complex name to an object value.

		Throws EvalError on various failures.
		A null object value is indicated by a Primitive.NULL.
		A return type of Primitive.VOID comes from attempting to access
		an undefined variable.

		Some cases:
			myVariable
			myVariable.foo
			myVariable.foo.bar
			java.awt.GridBagConstraints.BOTH
			my.package.stuff.MyClass.someField.someField...

		Interpreter reference is necessary to allow resolution of
		"this.interpreter" magic field.
		CallStack reference is necessary to allow resolution of
		"this.caller" magic field.
		"this.callstack" magic field.
	*/
	public Object toObject( CallStack callstack, Interpreter interpreter )
		throws EvalError
	{
		return toObject( callstack, interpreter, false );
	}

	/**
		@see toObject()
		@param forceClass if true then resolution will only produce a class.
		This is necessary to disambiguate in cases where the grammar knows
		that we want a class; where in general the var path may be taken.
	*/
	synchronized public Object toObject(
		CallStack callstack, Interpreter interpreter, boolean forceClass )
		throws EvalError
	{
		reset();

		Object obj = null;
		while( evalName != null )
			obj = consumeNextObjectField( callstack, interpreter, forceClass );

		if ( obj == null )
			throw new InterpreterError("null value in toObject()");

		return obj;
	}

	/**
		Get next prefixed object field component
	*/
	private Object consumeNextObjectField(
		CallStack callstack, Interpreter interpreter, boolean forceClass )
		throws EvalError
	{
		/*
			Is it a simple variable name?
			Doing this first gives the correct Java precedence for vars
			vs. imported class names (at least in the simple case - see
			tests/precedence1.bsh).  It should also speed things up a bit.
		*/
		if ( (evalBaseObject == null && !isCompound(evalName) )
			&& !forceClass )
		{
			Object obj = resolveThisFieldReference(
				callstack, namespace, interpreter, evalName, false );

			if ( obj != Primitive.VOID ) {
				evalName = null; // finished
				return evalBaseObject = obj;  // convention
			}
		}

		/*
			Is it a bsh script variable reference?
			If we're just starting the eval of name (no base object)
			or we're evaluating relative to a This reference check.
		*/
		if ( ( evalBaseObject == null || evalBaseObject instanceof This  )
			&& !forceClass )
		{
			String varName = prefix(evalName, 1);
			if ( Interpreter.DEBUG )
				Interpreter.debug("trying to resolve variable: " + varName);
			Object obj;
			if ( evalBaseObject == null ) {
				obj = resolveThisFieldReference(
					callstack, namespace, interpreter, varName, false );
			} else {
				// null callstack, cannot be caller reference
				obj = resolveThisFieldReference(
					callstack, ((This)evalBaseObject).namespace,
					interpreter, varName, true );
			}

			if ( obj != Primitive.VOID )
			{
				// Resolved the variable
				if ( Interpreter.DEBUG )
					Interpreter.debug( "resolved variable: " + varName +
					" in namespace: "+namespace);
				evalName = suffix(evalName);
				return evalBaseObject = obj;
			}
		}

		/*
			Is it a class name?
			If we're just starting eval of name try to make it, else fail.
		*/
		if ( evalBaseObject == null ) {
			if ( Interpreter.DEBUG )
				Interpreter.debug( "trying class: " + evalName);

			/*
				Keep adding parts until we have a class
			*/
			Class clas = null;
			int i = 1;
			for(; i <= countParts(evalName); i++)
				if ( (clas = namespace.getClass(prefix(evalName, i))) != null )
					break;

			if( clas != null )  {
				evalName = suffix(evalName, countParts(evalName) - i);
				return ( evalBaseObject = new ClassIdentifier(clas) );
			}
			// not a class (or variable per above)
			if ( Interpreter.DEBUG )
				Interpreter.debug( "not a class, trying var prefix "+evalName );
		}

		/*
			If we didn't find a class or variable name (or prefix) above
			there are two possibilities:

			- If we are a simple name then we can pass as a void variable
			reference.
			- If we are compound then we must fail at this point.
		*/
		if ( evalBaseObject == null ) {
			if( !isCompound(evalName) ) {
				evalName = null; // finished
				return evalBaseObject = Primitive.VOID;  // convention
			} else
				throw new EvalError(
					"Class or variable not found:" + evalName);
		}

		/*
			--------------------------------------------------------
			After this point we're definitely evaluating relative to
			a base object.
			--------------------------------------------------------
		*/

		/*
			Do some basic validity checks.
		*/

		if(evalBaseObject == Primitive.NULL) // previous round produced null
			throw new TargetError( "Null Pointer while evaluating: "
				+value, new NullPointerException() );

		if(evalBaseObject == Primitive.VOID) // previous round produced void
			throw new EvalError(
				"Undefined variable or class name while evaluating: "+value);

		if(evalBaseObject instanceof Primitive)
			throw new EvalError("Can't treat primitive like an object. "+
			"Error while evaluating: "+value);

		/*
			Resolve relative to a class type
			static field, inner class, ?
		*/
		if ( evalBaseObject instanceof ClassIdentifier )
		{
			Class clas = ((ClassIdentifier)evalBaseObject).getTargetClass();
			String field = prefix(evalName, 1);

			Object obj = null;
			// static field?
			try {
				if ( Interpreter.DEBUG )
					Interpreter.debug("Name call to getStaticField, class: "
						+clas+", field:"+field);
				obj = Reflect.getStaticField(clas, field);
			} catch( ReflectError e ) {
				if ( Interpreter.DEBUG )
					Interpreter.debug("field reflect error: "+e);
			}

			// inner class?
			if ( obj == null ) {
				String iclass = clas.getName()+"$"+field;
				Class c = namespace.getClass( iclass );
				if ( c != null )
					obj = new ClassIdentifier(c);
			}

			if ( obj == null )
				throw new EvalError(
					"No static field or inner class: " + field + " of " + clas);

			evalName = suffix(evalName);
			return (evalBaseObject = obj);
		}

		/*
			If we've fallen through here we are no longer resolving to
			a class type.
		*/
		if ( forceClass )
			throw new EvalError( value +" does not resolve to a class name." );

		/*
			Some kind of field access?
		*/

		String field = prefix(evalName, 1);

		/* length access on array? */
		if(field.equals("length") && evalBaseObject.getClass().isArray())
		{
			Object obj = new Primitive(Array.getLength(evalBaseObject));
			evalName = suffix(evalName);
			return (evalBaseObject = obj);
		}

		/* check for field on object */
		// Note: could eliminate throwing the exception somehow
		try
		{
			Object obj = Reflect.getObjectField(evalBaseObject, field);
			evalName = suffix(evalName);
			return (evalBaseObject = obj);
		}
		catch(ReflectError e) { /* not a field */ }

		// if we get here we have failed
		throw new EvalError(
			"Cannot access field: " + field + ", on object: " + evalBaseObject);
	}

	/**
		Resolve a variable relative to a This reference.

		This is the general variable resolution method, accomodating special
		fields from the This context.  Together the namespace and interpreter
		comprise the This context.  The callstack, if available allows for the
		this.caller construct.
		Optionally interpret special "magic" field names: e.g. interpreter.

		@param callstack may be null, but this is only legitimate in special
		cases where we are sure resolution will not involve this.caller.

		@param namespace the namespace of the this reference (should be the
		same as the top of the stack?
	*/
	Object resolveThisFieldReference(
		CallStack callstack, NameSpace thisNamespace, Interpreter interpreter,
		String varName, boolean specialFieldsVisible )
		throws EvalError
	{
		Object obj = null;
		// preserve the state of the last round flags until the end
		boolean
			wasThis = false,
			wasCaller = false;

		if ( varName.equals("this") ) {
			// Hack! If the special fields are visible turn of further .this
			// prevent user from skipping to things like super.this.caller
			if ( specialFieldsVisible )
				throw new EvalError("Redundant to call .this on This type");
			obj = thisNamespace.getThis( interpreter );
			wasThis = true;
		}

		if ( obj == null ) {
			if ( varName.equals("super") )
				obj = thisNamespace.getSuper().getThis( interpreter );
			else if ( varName.equals("global") )
				obj = thisNamespace.getGlobal().getThis( interpreter );
		}

		if ( obj == null && specialFieldsVisible ) {
			if (varName.equals("namespace"))
				obj = thisNamespace;
			else if (varName.equals("variables"))
				obj = thisNamespace.getVariableNames();
			else if (varName.equals("methods"))
				obj = thisNamespace.getMethodNames();
			else if ( varName.equals("interpreter") )
				if ( literalThisReference )
					obj = interpreter;
				else
					throw new EvalError(
						"Can only call .interpreter on literal 'this'");
		}

		if ( obj == null && specialFieldsVisible && varName.equals("caller") )
		{
			if ( literalThisReference || literalCallerReference )
			{
				// get the previous context (see notes for this class)
				if ( callstack == null )
					throw new InterpreterError("no callstack");
				obj = callstack.get( ++callstackDepth ).getThis(
					interpreter );
			}
			else
				throw new EvalError(
				"Can only call .caller on literal 'this' or literal '.caller'");

			wasCaller = true;
		}

		if ( obj == null && specialFieldsVisible
			&& varName.equals("callstack") )
		{
			if ( literalThisReference )
			{
				// get the previous context (see notes for this class)
				if ( callstack == null )
					throw new InterpreterError("no callstack");
				obj = callstack;
			}
			else
				throw new EvalError(
				"Can only call .callstack on literal 'this'");
		}

		if ( obj == null )
			obj = thisNamespace.getVariable(varName);

		literalThisReference = wasThis;
		literalCallerReference = wasCaller;
		return obj;
	}

	/**
		Check the cache, else use toObject() to try to resolve to a class
		identifier.

		Throws EvalError on class not found...
	*/
	synchronized public Class toClass() throws EvalError
	{
		reset();

		/* Try straightforward class name first */
		Class clas = namespace.getClass(evalName);

		if ( clas == null ) {
			/*
				Try toObject() which knows how to work through inner classes
				and see what we end up with
			*/
			Object obj = null;
			try {
				// Null interpreter and callstack references.
				// class only resolution should not require them.
				obj = toObject( null, null, true );
			} catch ( EvalError  e ) { }; // couldn't resolve it

			if ( obj instanceof ClassIdentifier )
				clas = ((ClassIdentifier)obj).getTargetClass();
		}

		if( clas == null )
			throw new EvalError(
				"Class: " + value+ " not found in namespace");

		return clas;
	}

	/*
	*/
	synchronized public LHS toLHS(
		CallStack callstack, Interpreter interpreter )
		throws EvalError
	{
		reset();

		/* if ( Interpreter.DEBUG )
			Interpreter.debug("Name toLHS: "+evalName+ " isCompound = "
			+ isCompound(evalName));
		*/

		// variable
		if(!isCompound(evalName)) {
			//if ( Interpreter.DEBUG )
				//Interpreter.debug("returning simple var LHS...");
			return new LHS(namespace,evalName);
		}

		// field
		Object obj = null;
		try
		{
			while(isCompound(evalName))
				obj = consumeNextObjectField( callstack, interpreter, false );
		}
		catch( EvalError e )
		{
			throw new EvalError("LHS evaluation: " + e);
		}

		if ( obj == null )
			throw new InterpreterError("internal error 2893749283");

		if(obj instanceof This)
		{
			Interpreter.debug("found This reference evaluating LHS");
			return new LHS(((This)obj).namespace, evalName);
		}

		if(evalName != null)
		{
			try
			{
//System.err.println("Name getLHSObjectField call obj = "
//	+obj+", name="+evalName);

				if ( obj instanceof ClassIdentifier )
				{
					Class clas = ((ClassIdentifier)obj).getTargetClass();
					return Reflect.getLHSStaticField(clas, evalName);
				} else
					return Reflect.getLHSObjectField(obj, evalName);
			} catch(ReflectError e)
			{
				throw new EvalError("Field access: "+e);
			}
		}

		throw new InterpreterError("Internal error in lhs...");

	/*
	This appears to have been something very old and incorrect...
	I don't think we need it anymore.

		// We bit off our field in the very first bite
		// have to back off and make a class out of the prefix
		Interpreter.debug("very first field was it...");

		Class clas = namespace.getClass(prefix(value));
		if(clas == null)
			throw new InterpreterError("internal error 238974983");

		String field = suffix(value, 1);

		try
		{
			return Reflect.getLHSStaticField(clas, field);
		}
		catch(ReflectError e)
		{
			if ( Interpreter.DEBUG ) Interpreter.debug("reflect error:" + e);
			return null;
		}
	*/

	}

	private BshMethod toLocalMethod( Object [] args )
	{
		Class [] sig = Reflect.getTypes( args );
		return namespace.getMethod( value, sig );
	}

    /**
		Invoke the method identified by name.

        Name contains a wholely unqualfied messy name; resolve it to
		( object | static prefix ) + method name and invoke.

        The interpreter is necessary to support 'this.interpreter' references
		in the called code. (e.g. debug());

        Some cases:

            // dynamic
            local();
            myVariable.foo();
            myVariable.bar.blah.foo();
            // static
            java.lang.Integer.getInteger("foo");

    */
    public Object invokeMethod(
		Interpreter interpreter, Object[] args, CallStack callstack,
		SimpleNode callerInfo
	)
        throws EvalError, ReflectError, InvocationTargetException
    {
        if ( !Name.isCompound(value) )
            return invokeLocalMethod(interpreter, args, callstack, callerInfo);

        // find target object
        Name targetName = namespace.getNameResolver( Name.prefix(value));
        String methodName = Name.suffix(value, 1);

        Object obj = targetName.toObject( callstack, interpreter );

		if ( obj == Primitive.VOID )
			throw new EvalError( "Attempt to invoke method: "+methodName
					+"() on undefined variable or class name: "+targetName);

        // if we've got an object, invoke the method
        if ( !(obj instanceof Name.ClassIdentifier) ) {

            if (obj instanceof Primitive) {

                if (obj == Primitive.NULL)
                    throw new TargetError( "Null Pointer in Method Invocation",
					new NullPointerException() );

                // some other primitive
                // should avoid calling methods on primitive, as we do
                // in Name (can't treat primitive like an object message)
                // but the hole is useful right now.
                interpreter.error("Attempt to access method on primitive..." +
                    " allowing bsh.Primitive to peek through for debugging");
            }

            // found an object and it's not an undefined variable
            return Reflect.invokeObjectMethod(
				interpreter, obj, methodName, args, callerInfo);
        }

        // try static method
        if ( Interpreter.DEBUG )
			Interpreter.debug("invokeMethod: trying static - " + targetName);

        Class clas = ((Name.ClassIdentifier)obj).getTargetClass();
        if (clas != null)
            return Reflect.invokeStaticMethod(clas, methodName, args);

        // return null; ???
		throw new EvalError("unknown target: " + targetName);
    }

	/**
		Invoke a locally declared method or a bsh command.
		If the method is not already declared in the namespace then try
		to load it as a resource from the /bsh/commands path.

		Note: instead of invoking the method directly here we should probably
		call invokeObjectMethod passing a This reference.  That would have
		the side effect of allowing a locally defined invoke() method to
		handle undeclared method invocations just like in objects.  Not sure
		if this is desirable...  It seems that if you invoke a method directly
		in scope it should be there.

		Keeping this code separate allows us to differentiate between methods
		invoked directly in scope and those invoked through object references.
	*/
    public Object invokeLocalMethod(
		Interpreter interpreter, Object[] args, CallStack callstack,
		SimpleNode callerInfo
	)
        throws EvalError, ReflectError, InvocationTargetException
    {
        if ( Interpreter.DEBUG )
			Interpreter.debug("invoke local method: " + value);

        // Check for locally declared method
        BshMethod meth = toLocalMethod( args );
        if ( meth != null )
            return meth.invokeDeclaredMethod( args, interpreter, callstack, callerInfo );
        else
            if ( Interpreter.DEBUG )
				Interpreter.debug("no locally declared method: " + value);

        /*
			Look for scripted command as resource
		*/
		// Why not /bsh/commands here?  Why relative to Interpreter?
        String commandName = "commands/" + value + ".bsh";
        InputStream in = Interpreter.class.getResourceAsStream(commandName);
        if (in != null)
        {
            if ( Interpreter.DEBUG )
				Interpreter.debug("loading resource: " + commandName);

			if ( interpreter == null )
				throw new InterpreterError("2234432 interpreter = null");

            interpreter.eval(
				new InputStreamReader(in), namespace, commandName);

            // try again
            meth = toLocalMethod( args );
            if(meth != null)
                return meth.invokeDeclaredMethod(
					args, interpreter, callstack, callerInfo );
            else
                throw new EvalError("Loaded resource: " + commandName +
                    "had an error or did not contain the correct method");
        }

        // check for compiled bsh command class
        commandName = "bsh.commands." + value;
        // create class outside of any namespace
        Class c = BshClassManager.classForName( commandName );
        if(c == null)
            throw new EvalError("Command not found: " + value);

        // add interpereter and namespace to args list
        Object[] invokeArgs = new Object[args.length + 2];
        invokeArgs[0] = interpreter;
        invokeArgs[1] = namespace;
        System.arraycopy(args, 0, invokeArgs, 2, args.length);
        try
        {
            return Reflect.invokeStaticMethod(c, "invoke", invokeArgs);
        }
        catch(ReflectError e)
        {
            if ( Interpreter.DEBUG )
				Interpreter.debug("invoke command args error:" + e);
            // bad args
        }
        // try to print help
        try
        {
            String s = (String)Reflect.invokeStaticMethod(c, "usage", null);
            interpreter.println(s);
            return Primitive.VOID;
        }
        catch(ReflectError e)
        {
            if ( Interpreter.DEBUG ) Interpreter.debug("usage threw: " + e);
            throw new EvalError("Wrong number or type of args for command");
        }
    }

	// Static methods that operate on compound ('.' separated) names

	static boolean isCompound(String value)
	{
		return countParts(value) > 1;
	}

	static int countParts(String value)
	{
		if(value == null)
			return 0;

		int count = 0;
		int index = -1;
		while((index = value.indexOf('.', index + 1)) != -1)
			count++;
		return count + 1;
	}

	static String prefix(String value)
	{
		if(!isCompound(value))
			return null;

		return prefix(value, countParts(value) - 1);
	}

	static String prefix(String value, int parts)
	{
		if(parts < 1)
			return null;

		int count = 0;
		int index = -1;

		while(((index = value.indexOf('.', index + 1)) != -1) && (++count < parts))
		{ ; }

		return (index == -1) ? value : value.substring(0, index);
	}

	static String suffix(String name)
	{
		if(!isCompound(name))
			return null;

		return suffix(name, countParts(name) - 1);
	}

	public static String suffix(String value, int parts)
	{
		if(parts < 1)
			return null;

		int count = 0;
		int index = value.length() + 1;

		while(((index = value.lastIndexOf('.', index - 1)) != -1) && (++count < parts))
		{ ; }

		return (index == -1) ? value : value.substring(index + 1);
	}

	// end compound name routines

	public String toString() { return value; }

	static class ClassIdentifier {
		Class clas;

		public ClassIdentifier( Class clas ) {
			this.clas = clas;
		}

		public Class getTargetClass() {
			return clas;
		}

		public String toString() {
			return "Class Identifier: "+clas.getName();

FUNC_DECL RETURN PARAM PARAM CALL LITERAL_ANCHOR

FUNC_DECL RETURN VAR_DECL PARAM CALL CALL


public abstract class AbstractMessageInInterceptor<T extends Message>
       extends AbstractPhaseInterceptor<T> {
    private static final Logger LOG = LogUtils.getL7dLogger(AbstractMessageInInterceptor.class);

    public AbstractMessageInInterceptor(String phase) {
        super(phase);
    }

    protected boolean isRequestor(Message message) {
        return Boolean.TRUE.equals(message.get(Message.REQUESTOR_ROLE));
    }

    /**
     * Infer the OperationInfo from the XML Document and get the list of
     * parts as DOM Element
     */
    public void handleMessage(T message) throws Fault {
        Logger logger = getLogger();

        if (isFaultMessage(message)) {
            message.getInterceptorChain().abort();
            Endpoint ep = message.getExchange().get(Endpoint.class);
            if (ep.getInFaultObserver() != null) {
                ep.getInFaultObserver().onMessage(message);
                return;
            }
        }

        Document document = createDOMMessage(message);
        Element payloadEl = (Element)document.getChildNodes().item(0);

        Exchange ex = message.getExchange();
        BindingOperationInfo boi = ex.get(BindingOperationInfo.class);
        if (boi == null) {
            BindingInfo bi = ex.get(BindingInfo.class);
            if (bi == null) {
                Endpoint ep = ex.get(Endpoint.class);
                bi = ep.getEndpointInfo().getBinding();
                ex.put(BindingInfo.class, bi);
            }
            if (logger.isLoggable(Level.INFO)) {
                logger.info("AbstractRoutingMessageInInterceptor Infer BindingOperationInfo.");
            }

            boi = getBindingOperation(message, document);

            if (boi == null) {
                QName startQName = new QName(payloadEl.getNamespaceURI(), payloadEl.getLocalName());

                throw new Fault(new org.apache.cxf.common.i18n.Message(
                                "REQ_NOT_UNDERSTOOD", LOG, startQName));
            }

            if (boi != null) {
                ex.put(BindingOperationInfo.class, boi);
                ex.put(OperationInfo.class, boi.getOperationInfo());
                ex.setOneWay(boi.getOperationInfo().isOneWay());
                if (logger.isLoggable(Level.INFO)) {
                    logger.info("DOMInInterceptor- BindingOperation is:" + boi.getName());
                }
            }
        }

        BindingMessageInfo bmi = isRequestor(message) ?  boi.getOutput() : boi.getInput();
        List<Element> partList = getPartList(message, payloadEl, bmi);
        message.put(List.class, partList);

        Element header = getHeader(message);
        message.put(Element.class, header);
    }

    /**
     * This method is called to convert a incoming message format e.g Stax Stream
     * to a DOM Tree. Default Implementation converts Stax Stream to a DOM
     * @param inMessage
     * @param Document
     */
    protected Document createDOMMessage(T message) {
        Document doc = null;
        try {
            if (getLogger().isLoggable(Level.INFO)) {
                getLogger().info("AbstractMessageInInterceptor Converting Stax Stream to DOM");
            }
            XMLStreamReader xsr = message.getContent(XMLStreamReader.class);
            doc = StaxUtils.read(xsr);
        } catch (XMLStreamException xe) {
            throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_READ_EXC", LOG), xe);
        }
        return doc;
    }

    protected abstract Logger getLogger();

    /**
     * This method is called on incoming to check if it is a fault.
     * @param inMessage
     * @param boolean
     */
    protected abstract boolean isFaultMessage(T message);

    /**
     * This method is called when the routing message interceptor has received a inbound message
     * It infers the binding operation by matching the root Element with a binding operation
     * from the service model.
     * @param inMessage
     * @param resultPayload
     */
    protected abstract BindingOperationInfo getBindingOperation(T inMessage, Document document);

    /**
     * This method is called when the routing message interceptor has intercepted a inbound
     * message as a DOM Content.  It retreives the message parts as DOM Element
     * and returns a List<Element>
     * @param inMessage
     * @param rootElement
     * @param bindingMessageInfo
     * @return List<Element>
     */
    protected abstract List<Element> getPartList(T inMessage, Element rootElement, BindingMessageInfo boi);

    /**
     * This method is called when the routing message interceptor has intercepted a inbound
     * message as a DOM Content.  It retreives the header parts as DOM Element
     * and returns a Element.
     * @param inMessage
     * @return Element
     */
    protected abstract Element getHeader(T inMessage);

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


org.apache.xml.utils.SAXSourceLocator

public class SAXSourceLocator extends LocatorImpl
        implements SourceLocator, Serializable
{
    static final long serialVersionUID = 3181680946321164112L;
  /** The SAX Locator object.
   *  @serial
   */
  Locator m_locator;

  /**
   * Constructor SAXSourceLocator
   *
   */
  public SAXSourceLocator(){}

  /**
   * Constructor SAXSourceLocator
   *
   *
   * @param locator Source locator
   */
  public SAXSourceLocator(Locator locator)
  {
    m_locator = locator;
    this.setColumnNumber(locator.getColumnNumber());
    this.setLineNumber(locator.getLineNumber());
    this.setPublicId(locator.getPublicId());
    this.setSystemId(locator.getSystemId());
  }

  /**
   * Constructor SAXSourceLocator
   *
   *
   * @param locator Source locator
   */
  public SAXSourceLocator(javax.xml.transform.SourceLocator locator)
  {
    m_locator = null;
    this.setColumnNumber(locator.getColumnNumber());
    this.setLineNumber(locator.getLineNumber());
    this.setPublicId(locator.getPublicId());
    this.setSystemId(locator.getSystemId());
  }

  /**
   * Constructor SAXSourceLocator
   *
   *
   * @param spe SAXParseException exception.
   */
  public SAXSourceLocator(SAXParseException spe)
  {
    this.setLineNumber( spe.getLineNumber() );
    this.setColumnNumber( spe.getColumnNumber() );
    this.setPublicId( spe.getPublicId() );
    this.setSystemId( spe.getSystemId() );
  }

  /**
   * Return the public identifier for the current document event.
   *
   *
The return value is the public identifier of the document
   * entity or of the external parsed entity in which the markup
   * triggering the event appears.

   *
   * @return A string containing the public identifier, or
   *         null if none is available.
   * @see #getSystemId
   */
  public String getPublicId()
  {
    return (null == m_locator) ? super.getPublicId() : m_locator.getPublicId();
  }

  /**
   * Return the system identifier for the current document event.
   *
   *
The return value is the system identifier of the document
   * entity or of the external parsed entity in which the markup
   * triggering the event appears.

   *
   *
If the system identifier is a URL, the parser must resolve it
   * fully before passing it to the application.

   *
   * @return A string containing the system identifier, or null
   *         if none is available.
   * @see #getPublicId
   */
  public String getSystemId()
  {
    return (null == m_locator) ? super.getSystemId() : m_locator.getSystemId();
  }

  /**
   * Return the line number where the current document event ends.
   *
   *
Warning: The return value from the method
   * is intended only as an approximation for the sake of error
   * reporting; it is not intended to provide sufficient information
   * to edit the character content of the original XML document.

   *
   *
The return value is an approximation of the line number
   * in the document entity or external parsed entity where the
   * markup triggering the event appears.

   *
   * @return The line number, or -1 if none is available.
   * @see #getColumnNumber
   */
  public int getLineNumber()
  {
    return (null == m_locator) ? super.getLineNumber() : m_locator.getLineNumber();
  }

  /**
   * Return the column number where the current document event ends.
   *
   *
Warning: The return value from the method
   * is intended only as an approximation for the sake of error
   * reporting; it is not intended to provide sufficient information
   * to edit the character content of the original XML document.

   *
   *
The return value is an approximation of the column number
   * in the document entity or external parsed entity where the
   * markup triggering the event appears.

   *
   * @return The column number, or -1 if none is available.
   * @see #getLineNumber
   */
  public int getColumnNumber()
  {
    return (null == m_locator) ? super.getColumnNumber() : m_locator.getColumnNumber();

FUNC_DECL PARAM ASSIGN CALL CALL CALL CALL CALL CALL CALL CALL

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

FUNC_DECL PARAM CALL CALL CALL CALL CALL CALL CALL CALL


public class SpringTransactionPolicy<E> implements Policy<E> {
    private static final transient Log LOG = LogFactory.getLog(SpringTransactionPolicy.class);
    private TransactionTemplate template;

    public SpringTransactionPolicy(TransactionTemplate template) {
        this.template = template;
    }

    public Processor wrap(Processor processor) {
        final TransactionTemplate transactionTemplate = getTemplate();
        if (transactionTemplate == null) {
            LOG.warn("No TransactionTemplate available so transactions will not be enabled!");
            return processor;
        }

        TransactionInterceptor answer = new TransactionInterceptor(transactionTemplate);
        answer.setProcessor(processor);
        return answer;
    }

    public TransactionTemplate getTemplate() {
        return template;
    }

    public void setTemplate(TransactionTemplate template) {
        this.template = template;


public class DataSetEndpoint extends MockEndpoint implements Service {
    private static final transient Log LOG = LogFactory.getLog(DataSetEndpoint.class);
    private DataSet dataSet;
    private AtomicInteger receivedCounter = new AtomicInteger();
    private long produceDelay = -1;
    private long consumeDelay = -1;
    private long startTime;
    private long preloadSize;

    public DataSetEndpoint(String endpointUri, Component component, DataSet dataSet) {
        super(endpointUri, component);
        this.dataSet = dataSet;
    }

    public DataSetEndpoint(String endpointUri, DataSet dataSet) {
        super(endpointUri);
        this.dataSet = dataSet;
    }

    public static void assertEquals(String description, Object expected, Object actual, Exchange exchange) {
        if (!ObjectHelper.equal(expected, actual)) {
            throw new AssertionError(description + " does not match. Expected: " + expected + " but was: " + actual + " on " + exchange + " with headers: " + exchange.getIn().getHeaders());
        }
    }

    @Override
    public PollingConsumer<Exchange> createPollingConsumer() throws Exception {
        return new EventDrivenPollingConsumer<Exchange>(this);
    }

    @Override
    public Consumer<Exchange> createConsumer(Processor processor) throws Exception {
        return new DataSetConsumer(this, processor);
    }

    @Override
    public void reset() {
        super.reset();
        receivedCounter.set(0);
    }

    @Override
    public int getReceivedCounter() {
        return receivedCounter.get();
    }

    /**
     * Creates a message exchange for the given index in the {@link DataSet}
     */
    public Exchange createExchange(long messageIndex) throws Exception {
        Exchange exchange = createExchange();
        getDataSet().populateMessage(exchange, messageIndex);

        Message in = exchange.getIn();
        in.setHeader(DataSet.INDEX_HEADER, messageIndex);

        return exchange;
    }

    @Override
    protected void waitForCompleteLatch() throws InterruptedException {
        long size = getDataSet().getSize();
        size *= 4000;
        setResultWaitTime(size);
        super.waitForCompleteLatch();
    }

    public DataSet getDataSet() {
        return dataSet;
    }

    public void setDataSet(DataSet dataSet) {
        this.dataSet = dataSet;
    }

    public long getPreloadSize() {
        return preloadSize;
    }

    /**
     * Sets how many messages should be preloaded (sent) before the route completes its initialisation
     */
    public void setPreloadSize(long preloadSize) {
        this.preloadSize = preloadSize;
    }

    public long getConsumeDelay() {
        return consumeDelay;
    }

    /**
     * Allows a delay to be specified which causes consumers to pause - to simulate slow consumers
     */
    public void setConsumeDelay(long consumeDelay) {
        this.consumeDelay = consumeDelay;
    }

    public long getProduceDelay() {
        return produceDelay;
    }

    /**
     * Allows a delay to be specified which causes producers to pause - to simpulate slow producers
     */
    public void setProduceDelay(long produceDelay) {
        this.produceDelay = produceDelay;
    }

    @Override
    protected void performAssertions(Exchange actual) throws Exception {
        if (startTime == 0) {
            startTime = System.currentTimeMillis();
        }
        int receivedCount = receivedCounter.incrementAndGet();
        long index = receivedCount - 1;
        Exchange expected = createExchange(index);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Received message: " + index + " = " + actual);
        }

        assertMessageExpected(index, expected, actual);

        if (consumeDelay > 0) {
            Thread.sleep(consumeDelay);
        }

        long group = getDataSet().getReportCount();
        if (receivedCount % group == 0) {
            reportProgress(actual, receivedCount);
        }
    }

    protected void reportProgress(Exchange actual, int receivedCount) {
        long time = System.currentTimeMillis();
        long elapsed = time - startTime;
        startTime = time;

        LOG.info("Received: " + receivedCount + " messages so far. Last group took: " + elapsed + " millis");
    }

    protected void assertMessageExpected(long index, Exchange expected, Exchange actual) throws Exception {
        long actualCounter = ExchangeHelper.getMandatoryHeader(actual, DataSet.INDEX_HEADER, Long.class);
        assertEquals("Header: " + DataSet.INDEX_HEADER, index, actualCounter, actual);

        getDataSet().assertMessageExpected(this, expected, actual, index);
    }

    public void start() throws Exception {
        long size = getDataSet().getSize();
        expectedMessageCount((int) size);
    }

    public void stop() throws Exception {

FUNC_DECL RETURN VAR_DECL VAR_DECL PARAM CALL CALL CALL CALL CALL


org.apache.camel.model.TryType

@XmlRootElement(name = "try")
@XmlAccessorType(XmlAccessType.FIELD)
public class TryType extends OutputType<TryType> {
    @XmlTransient
    private List<CatchType> catchClauses;
    @XmlTransient
    private FinallyType finallyClause;
    @XmlTransient
    private boolean initialized;
    @XmlTransient
    private List<ProcessorType<?>> outputsWithoutCatches;

    @Override
    public String toString() {
        return "Try[ " + getOutputs() + "]";
    }

    @Override
    public Processor createProcessor(RouteContext routeContext) throws Exception {
        Processor tryProcessor = createOutputsProcessor(routeContext, getOutputsWithoutCatches());

        Processor finallyProcessor = null;
        if (finallyClause != null) {
            finallyProcessor = finallyClause.createProcessor(routeContext);
        }
        List<CatchProcessor> catchProcessors = new ArrayList<CatchProcessor>();
        if (catchClauses != null) {
            for (CatchType catchClause : catchClauses) {
                catchProcessors.add(catchClause.createProcessor(routeContext));
            }
        }
        return new TryProcessor(tryProcessor, catchProcessors, finallyProcessor);
    }

    public CatchType handle(Class<?> exceptionType) {
        CatchType answer = new CatchType(exceptionType);
        addOutput(answer);
        return answer;
    }

    public FinallyType handleAll() {
        FinallyType answer = new FinallyType();
        addOutput(answer);
        return answer;
    }

    public List<CatchType> getCatchClauses() {
        if (catchClauses == null) {
            checkInitialized();
        }
        return catchClauses;
    }

    public FinallyType getFinallyClause() {
        if (finallyClause == null) {
            checkInitialized();
        }
        return finallyClause;
    }

    public List<ProcessorType<?>> getOutputsWithoutCatches() {
        if (outputsWithoutCatches == null) {
            checkInitialized();
        }
        return outputsWithoutCatches;
    }

    public void setOutputs(List<ProcessorType<?>> outputs) {
        initialized = false;
        super.setOutputs(outputs);
    }

    public void addOutput(ProcessorType output) {
        initialized = false;
        getOutputs().add(output);
    }

    /**
     * Checks whether or not this object has been initialized
     */
    protected void checkInitialized() {
        if (!initialized) {
            initialized = true;
            outputsWithoutCatches = new ArrayList<ProcessorType<?>>();
            catchClauses = new ArrayList<CatchType>();
            finallyClause = null;

            for (ProcessorType output : outputs) {
                if (output instanceof CatchType) {
                    catchClauses.add((CatchType)output);
                } else if (output instanceof FinallyType) {
                    if (finallyClause != null) {
                        throw new IllegalArgumentException("Multiple finally clauses added: " + finallyClause
                                                           + " and " + output);
                    } else {
                        finallyClause = (FinallyType)output;
                    }
                } else {
                    outputsWithoutCatches.add(output);

FUNC_DECL PARAM CALL ASSIGN CALL LITERAL_ANCHOR


public class ProtectRecord
    extends Record
{
    public final static short sid = 0x12;
    private short             field_1_protect;

    public ProtectRecord()
    {
    }

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

    /**
     * Constructs a Protect record and sets its fields appropriately.
     *
     * @param id id must be 0x12 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 data
     */

    public ProtectRecord(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 PROTECT RECORD");
        }
    }

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

    /**
     * set whether the sheet is protected or not
     * @param protect whether to protect the sheet or not
     */

    public void setProtect(boolean protect)
    {
        if (protect)
        {
            field_1_protect = 1;
        }
        else
        {
            field_1_protect = 0;
        }
    }

    /**
     * get whether the sheet is protected or not
     * @return whether to protect the sheet or not
     */

    public boolean getProtect()
    {
        return (field_1_protect == 1);
    }

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

        buffer.append("[PROTECT]\n");
	    buffer.append("    .protect         = ").append(getProtect())
            .append("\n");
        buffer.append("[/PROTECT]\n");
        return buffer.toString();
    }

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

    public int getRecordSize()
    {
        return 6;
    }

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

    public Object clone() {
        ProtectRecord rec = new ProtectRecord();
        rec.field_1_protect = field_1_protect;
        return rec;

    public int getRecordSize()
    {
        return 6;


public class BookBoolRecord
    extends Record
{
    public final static short sid = 0xDA;
    private short             field_1_save_link_values;

    public BookBoolRecord()
    {
    }

    /**
     * Constructs a BookBoolRecord and sets its fields appropriately
     *
     * @param id     id must be 0xDA 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 BookBoolRecord(RecordInputStream in)
    {
        super(in);
    }

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

    protected void fillFields(RecordInputStream in)
    {
        field_1_save_link_values = in.readShort();
    }

    /**
     * set the save ext links flag
     *
     * @param flag flag (0/1 -off/on)
     */

    public void setSaveLinkValues(short flag)
    {
        field_1_save_link_values = flag;
    }

    /**
     * get the save ext links flag
     *
     * @return short 0/1 (off/on)
     */

    public short getSaveLinkValues()
    {
        return field_1_save_link_values;
    }

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

        buffer.append("[BOOKBOOL]\n");
        buffer.append("    .savelinkvalues  = ")
            .append(Integer.toHexString(getSaveLinkValues())).append("\n");
        buffer.append("[/BOOKBOOL]\n");
        return buffer.toString();
    }

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

    public int getRecordSize()
    {
        return 6;
    }

    public short getSid()
    {
        return sid;

    public short getSid()
    {
        return sid;


public class RenameExtensions extends MatchingTask {

    private String fromExtension = "";
    private String toExtension = "";
    private boolean replace = false;
    private File srcDir;

    private Mapper.MapperType globType;

    /** Creates new RenameExtensions */
    public RenameExtensions() {
        super();
        globType = new Mapper.MapperType();
        globType.setValue("glob");
    }

    /**
     * The string that files must end in to be renamed
     *
     * @param from the extension of files being renamed.
     */
    public void setFromExtension(String from) {
        fromExtension = from;
    }

    /**
     * The string that renamed files will end with on
     * completion
     *
     * @param to the extension of the renamed files.
     */
    public void setToExtension(String to) {
        toExtension = to;
    }

    /**
     * store replace attribute - this determines whether the target file
     * should be overwritten if present
     *
     * @param replace if true overwrite any target files that exist.
     */
    public void setReplace(boolean replace) {
        this.replace = replace;
    }

    /**
     * Set the source dir to find the files to be renamed.
     *
     * @param srcDir the source directory.
     */
    public void setSrcDir(File srcDir) {
        this.srcDir = srcDir;
    }

    /**
     * Executes the task.
     *
     * @throws BuildException is there is a problem in the task execution.
     */
    public void execute() throws BuildException {

        if (fromExtension == null || toExtension == null || srcDir == null) {
            throw new BuildException("srcDir, fromExtension and toExtension "
                + "attributes must be set!");
        }

        log("DEPRECATED - The renameext task is deprecated.  Use move instead.",
            Project.MSG_WARN);
        log("Replace this with:", Project.MSG_INFO);
        log("<move todir=\"" + srcDir + "\" overwrite=\"" + replace + "\">",
            Project.MSG_INFO);
        log("  <fileset dir=\"" + srcDir + "\" />", Project.MSG_INFO);
        log("  <mapper type=\"glob\"", Project.MSG_INFO);
        log("          from=\"*" + fromExtension + "\"", Project.MSG_INFO);
        log("          to=\"*" + toExtension + "\" />", Project.MSG_INFO);
        log("</move>", Project.MSG_INFO);
        log("using the same patterns on <fileset> as you\'ve used here",
            Project.MSG_INFO);

        Move move = new Move();
        move.bindToOwner(this);
        move.setOwningTarget(getOwningTarget());
        move.setTaskName(getTaskName());
        move.setLocation(getLocation());
        move.setTodir(srcDir);
        move.setOverwrite(replace);

        fileset.setDir(srcDir);
        move.addFileset(fileset);

        Mapper me = move.createMapper();
        me.setType(globType);
        me.setFrom("*" + fromExtension);
        me.setTo("*" + toExtension);

        move.execute();


org.gjt.sp.jedit.gui.TipOfTheDay

public class TipOfTheDay extends EnhancedDialog
{
	//{{{ TipOfTheDay constructor
	public TipOfTheDay(View view)
	{
		super(view,jEdit.getProperty("tip.title"),false);

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

		JLabel label = new JLabel(jEdit.getProperty("tip.caption"));
		label.setFont(new Font("SansSerif",Font.PLAIN,24));
		label.setForeground(UIManager.getColor("Button.foreground"));
		content.add(BorderLayout.NORTH,label);

		tipText = new JEditorPane();
		tipText.setEditable(false);
		tipText.setContentType("text/html");

		nextTip();

		JScrollPane scroller = new JScrollPane(tipText);
		scroller.setPreferredSize(new Dimension(150,150));
		content.add(BorderLayout.CENTER,scroller);

		ActionHandler actionHandler = new ActionHandler();

		Box buttons = new Box(BoxLayout.X_AXIS);

		showNextTime = new JCheckBox(jEdit.getProperty("tip.show-next-time"),
			jEdit.getBooleanProperty("tip.show"));
		showNextTime.addActionListener(actionHandler);
		buttons.add(showNextTime);

		buttons.add(Box.createHorizontalStrut(6));
		buttons.add(Box.createGlue());

		nextTip = new JButton(jEdit.getProperty("tip.next-tip"));
		nextTip.addActionListener(actionHandler);
		buttons.add(nextTip);

		buttons.add(Box.createHorizontalStrut(6));

		close = new JButton(jEdit.getProperty("common.close"));
		close.addActionListener(actionHandler);
		buttons.add(close);
		content.getRootPane().setDefaultButton(close);

		Dimension dim = nextTip.getPreferredSize();
		dim.width = Math.max(dim.width,close.getPreferredSize().width);
		nextTip.setPreferredSize(dim);
		close.setPreferredSize(dim);

		content.add(BorderLayout.SOUTH,buttons);

		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		pack();
		setLocationRelativeTo(view);
		show();
	} //}}}

	//{{{ ok() method
	public void ok()
	{
		dispose();
	} //}}}

	//{{{ cancel() method
	public void cancel()
	{
		dispose();
	} //}}}

	//{{{ Private members

	//{{{ Instance variables
	private JCheckBox showNextTime;
	private JButton nextTip, close;
	private JEditorPane tipText;
	private int currentTip = -1;
	//}}}

	//{{{ nextTip() method
	private void nextTip()
	{
		File[] tips = new File(MiscUtilities.constructPath(
			jEdit.getJEditHome(),"doc","tips")).listFiles();
		if(tips == null || tips.length == 0)
		{
			tipText.setText(jEdit.getProperty("tip.not-found"));
			return;
		}

		int count = tips.length;

		// so that we don't see the same tip again if the user
		// clicks 'Next Tip'
		int tipToShow = currentTip;
		while(tipToShow == currentTip || !tips[tipToShow].getName().endsWith(".html"))
			tipToShow = Math.abs(new Random().nextInt()) % count;
		try
		{
			tipText.setPage(tips[tipToShow].toURL());
		}
		catch(Exception e)
		{
			Log.log(Log.ERROR,this,e);
		}
	} //}}}

	//}}}

	//{{{ ActionHandler class
	class ActionHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent evt)
		{
			Object source = evt.getSource();
			if(source == showNextTime)
			{
				jEdit.setBooleanProperty("tip.show",showNextTime
					.isSelected());
			}
			else if(source == nextTip)
				nextTip();
			else if(source == close)
				dispose();

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


class SecuritySupport12 extends SecuritySupport {

    ClassLoader getContextClassLoader() {
        return (ClassLoader)
                AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                ClassLoader cl = null;
                try {
                    cl = Thread.currentThread().getContextClassLoader();
                } catch (SecurityException ex) { }
                return cl;
            }
        });
    }

    ClassLoader getSystemClassLoader() {
        return (ClassLoader)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    ClassLoader cl = null;
                    try {
                        cl = ClassLoader.getSystemClassLoader();
                    } catch (SecurityException ex) {}
                    return cl;
                }
            });
    }

    ClassLoader getParentClassLoader(final ClassLoader cl) {
        return (ClassLoader)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    ClassLoader parent = null;
                    try {
                        parent = cl.getParent();
                    } catch (SecurityException ex) {}

                    return (parent == cl) ? null : parent;
                }
            });
    }

    String getSystemProperty(final String propName) {
        return (String)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return System.getProperty(propName);
                }
            });
    }

    FileInputStream getFileInputStream(final File file)
        throws FileNotFoundException
    {
        try {
            return (FileInputStream)
                AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws FileNotFoundException {
                        return new FileInputStream(file);
                    }
                });
        } catch (PrivilegedActionException e) {
            throw (FileNotFoundException)e.getException();
        }
    }

    InputStream getResourceAsStream(final ClassLoader cl,
                                           final String name)
    {
        return (InputStream)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    InputStream ris;
                    if (cl == null) {
                        ris = ClassLoader.getSystemResourceAsStream(name);
                    } else {
                        ris = cl.getResourceAsStream(name);
                    }
                    return ris;
                }
            });
    }

    boolean getFileExists(final File f) {
    return ((Boolean)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new Boolean(f.exists());
                }
            })).booleanValue();
    }

    long getLastModified(final File f) {
    return ((Long)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new Long(f.lastModified());

FUNC_DECL RETURN CALL CALL FUNC_DECL RETURN TRY VAR_DECL CATCH ASSIGN LITERAL_ANCHOR CALL CALL

FUNC_DECL TRY PARAM CATCH RETURN THROW_RAISE CALL CALL CALL FUNC_DECL RETURN CALL

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

FUNC_DECL RETURN PARAM CALL CALL FUNC_DECL RETURN CALL CALL


org.apache.ivy.util.Configurator

public class Configurator {
    public static class Macro {
        private MacroDef macrodef;

        private Map attValues = new HashMap();

        private Map macroRecords = new HashMap();

        public Macro(MacroDef def) {
            macrodef = def;
        }

        public void defineAttribute(String attributeName, String value) {
            if (macrodef.getAttribute(attributeName) == null) {
                throw new IllegalArgumentException("undeclared attribute " + attributeName
                        + " on macro " + macrodef.getName());
            }
            attValues.put(attributeName, value);
        }

        public MacroRecord recordCreateChild(String name) {
            MacroRecord macroRecord = new MacroRecord(name);
            List records = (List) macroRecords.get(name);
            if (records == null) {
                records = new ArrayList();
                macroRecords.put(name, records);
            }
            records.add(macroRecord);
            return macroRecord;
        }

        public Object play(Configurator conf) {
            return macrodef.play(conf, attValues, macroRecords);
        }

    }

    public static class Attribute {
        private String name;

        private String defaultValue;

        public String getDefault() {
            return defaultValue;
        }

        public void setDefault(String default1) {
            defaultValue = default1;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class Element {
        private String name;

        private boolean optional = false;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isOptional() {
            return optional;
        }

        public void setOptional(boolean optional) {
            this.optional = optional;
        }
    }

    public static class MacroRecord {
        private String name;

        private Map attributes = new LinkedHashMap();

        private List children = new ArrayList();

        private Object object;

        public MacroRecord(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void recordAttribute(String name, String value) {
            attributes.put(name, value);
        }

        public MacroRecord recordChild(String name) {
            MacroRecord child = new MacroRecord(name);
            children.add(child);
            return child;
        }

        public MacroRecord recordChild(String name, Object object) {
            MacroRecord child = recordChild(name);
            child.object = object;
            return child;
        }

        public Map getAttributes() {
            return attributes;
        }

        public List getChildren() {
            return children;
        }

        public Object getObject() {
            return object;
        }
    }

    public static class MacroDef {
        private String name;

        private Map attributes = new HashMap();

        private Map elements = new HashMap();

        private MacroRecord macroRecord;

        public MacroDef(String macroName) {
            name = macroName;
        }

        public Attribute getAttribute(String attributeName) {
            return (Attribute) attributes.get(attributeName);
        }

        public Object play(Configurator conf, Map attValues, Map macroRecords) {
            for (Iterator iter = attributes.values().iterator(); iter.hasNext();) {
                Attribute att = (Attribute) iter.next();
                String val = (String) attValues.get(att.getName());
                if (val == null) {
                    if (att.getDefault() == null) {
                        throw new IllegalArgumentException("attribute " + att.getName()
                                + " is required in " + getName());
                    } else {
                        attValues.put(att.getName(), att.getDefault());
                    }
                }
            }
            return play(conf, macroRecord, attValues, macroRecords);
        }

        private Object play(Configurator conf, MacroRecord macroRecord, Map attValues,
                Map childrenRecords) {
            if (macroRecord.getObject() != null) {
                // this is a recorded reference, we can add the referenced object directly
                conf.addChild(macroRecord.getName(), macroRecord.getObject());
                conf.endCreateChild();
                return macroRecord.getObject();
            }
            conf.startCreateChild(macroRecord.getName());
            Map attributes = macroRecord.getAttributes();
            for (Iterator iter = attributes.keySet().iterator(); iter.hasNext();) {
                String attName = (String) iter.next();
                String attValue = replaceParam((String) attributes.get(attName), attValues);
                conf.setAttribute(attName, attValue);
            }
            for (Iterator iter = macroRecord.getChildren().iterator(); iter.hasNext();) {
                MacroRecord child = (MacroRecord) iter.next();
                Element elt = (Element) elements.get(child.getName());
                if (elt != null) {
                    List elements = (List) childrenRecords.get(child.getName());
                    if (elements != null) {
                        for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
                            MacroRecord element = (MacroRecord) iterator.next();
                            for (Iterator it2 = element.getChildren().iterator(); it2.hasNext();) {
                                MacroRecord r = (MacroRecord) it2.next();
                                play(conf, r, attValues, Collections.EMPTY_MAP);
                            }
                        }
                    } else if (!elt.isOptional()) {
                        throw new IllegalArgumentException(
                                "non optional element is not specified: " + elt.getName()
                                        + " in macro " + getName());
                    }
                    continue;
                }
                play(conf, child, attValues, childrenRecords);
            }
            return conf.endCreateChild();
        }

        private String replaceParam(String string, Map attValues) {
            return IvyPatternHelper.substituteParams(string, attValues);
        }

        public String getName() {
            return name;
        }

        public void addConfiguredAttribute(Attribute att) {
            attributes.put(att.getName(), att);
        }

        public void addConfiguredElement(Element elt) {
            elements.put(elt.getName(), elt);
        }

        public Macro createMacro() {
            return new Macro(this);
        }

        public void addAttribute(String attName, String attDefaultValue) {
            Attribute att = new Attribute();
            att.setName(attName);
            att.setDefault(attDefaultValue);
            addConfiguredAttribute(att);
        }

        public void addElement(String elementName, boolean optional) {
            Element elt = new Element();
            elt.setName(elementName);
            elt.setOptional(optional);
            addConfiguredElement(elt);
        }

        public MacroRecord recordCreateChild(String name) {
            macroRecord = new MacroRecord(name);
            return macroRecord;
        }
    }

    private static class ObjectDescriptor {
        private Object obj;

        private String objName;

        private Map createMethods = new HashMap();

        private Map addMethods = new HashMap();

        private Map addConfiguredMethods = new HashMap();

        private Map setMethods = new HashMap();

        private Map typeAddMethods = new HashMap();

        private Map typeAddConfiguredMethods = new HashMap();

        public ObjectDescriptor(Object object, String objName) {
            obj = object;
            this.objName = objName;
            Method[] methods = object.getClass().getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method m = methods[i];
                if (m.getName().startsWith("create") && m.getParameterTypes().length == 0
                        && !Void.TYPE.equals(m.getReturnType())) {
                    String name = StringUtils
                            .uncapitalize(m.getName().substring("create".length()));
                    if (name.length() == 0) {
                        continue;
                    }
                    addCreateMethod(name, m);
                } else if (m.getName().startsWith("addConfigured")
                        && m.getParameterTypes().length == 1
                        && Void.TYPE.equals(m.getReturnType())) {
                    String name = StringUtils.uncapitalize(m.getName().substring(
                        "addConfigured".length()));
                    if (name.length() == 0) {
                        addAddConfiguredMethod(m);
                    }
                    addAddConfiguredMethod(name, m);
                } else if (m.getName().startsWith("add")
                        && !m.getName().startsWith("addConfigured")
                        && m.getParameterTypes().length == 1
                        && Void.TYPE.equals(m.getReturnType())) {
                    String name = StringUtils.uncapitalize(m.getName().substring("add".length()));
                    if (name.length() == 0) {
                        addAddMethod(m);
                    }
                    addAddMethod(name, m);
                } else if (m.getName().startsWith("set") && m.getParameterTypes().length == 1
                        && Void.TYPE.equals(m.getReturnType())) {
                    String name = StringUtils.uncapitalize(m.getName().substring("set".length()));
                    if (name.length() == 0) {
                        continue;
                    }
                    addSetMethod(name, m);
                }
            }
        }

        public void addCreateMethod(String name, Method m) {
            createMethods.put(name, m);
        }

        public void addAddMethod(String name, Method m) {
            addMethods.put(name, m);
        }

        public void addAddConfiguredMethod(String name, Method m) {
            addConfiguredMethods.put(name, m);
        }

        private void addAddMethod(Method m) {
            typeAddMethods.put(m.getParameterTypes()[0], m);
        }

        private void addAddConfiguredMethod(Method m) {
            typeAddConfiguredMethods.put(m.getParameterTypes()[0], m);
        }

        public void addSetMethod(String name, Method m) {
            Method current = (Method) setMethods.get(name);
            if (current != null && current.getParameterTypes()[0] == String.class) {
                // setter methods with String attribute take precedence
                return;
            }
            setMethods.put(name, m);
        }

        public Object getObject() {
            return obj;
        }

        public Method getCreateMethod(String name) {
            return (Method) createMethods.get(name);
        }

        public Method getAddMethod(String name) {
            return (Method) addMethods.get(name);
        }

        public Method getAddConfiguredMethod(String name) {
            return (Method) addConfiguredMethods.get(name);
        }

        public Method getAddMethod(Class type) {
            return getTypeMatchingMethod(type, typeAddMethods);
        }

        public Method getAddConfiguredMethod(Class type) {
            return getTypeMatchingMethod(type, typeAddConfiguredMethods);
        }

        private Method getTypeMatchingMethod(Class type, Map typeMethods) {
            Method m = (Method) typeMethods.get(type);
            if (m != null) {
                return m;
            }
            for (Iterator iter = typeMethods.keySet().iterator(); iter.hasNext();) {
                Class clss = (Class) iter.next();
                if (clss.isAssignableFrom(type)) {
                    return (Method) typeMethods.get(clss);
                }
            }
            return null;
        }

        public Method getSetMethod(String name) {
            return (Method) setMethods.get(name);
        }

        public String getObjectName() {
            return objName;
        }
    }

    private FileResolver fileResolver = FileResolver.DEFAULT;

    private Map typedefs = new HashMap();

    private Map macrodefs = new HashMap();

    // stack in which the top is current configured object descriptor
    private Stack objectStack = new Stack();

    private static final List TRUE_VALUES = Arrays.asList(new String[] {"true", "yes", "on"});

    public void typeDef(String name, String className) throws ClassNotFoundException {
        typeDef(name, Class.forName(className));
    }

    public void typeDef(String name, Class clazz) {
        typedefs.put(name, clazz);
    }

    public void setRoot(Object root) {
        if (root == null) {
            throw new NullPointerException();
        }
        objectStack.clear();
        setCurrent(root, null);
    }

    public void clear() {
        objectStack.clear();
    }

    private void setCurrent(Object object, String name) {
        objectStack.push(new ObjectDescriptor(object, name));
    }

    public Object startCreateChild(String name) {
        if (objectStack.isEmpty()) {
            throw new IllegalStateException("set root before creating child");
        }
        ObjectDescriptor parentOD = (ObjectDescriptor) objectStack.peek();
        Object parent = parentOD.getObject();
        if (parent instanceof MacroDef) {
            if (!"attribute".equals(name) && !"element".equals(name)) {
                MacroRecord record = ((MacroDef) parent).recordCreateChild(name);
                setCurrent(record, name);
                return record;
            }
        }
        if (parent instanceof Macro) {
            MacroRecord record = ((Macro) parent).recordCreateChild(name);
            setCurrent(record, name);
            return record;
        }
        if (parent instanceof MacroRecord) {
            MacroRecord record = ((MacroRecord) parent).recordChild(name);
            setCurrent(record, name);
            return record;
        }
        Object child = null;
        MacroDef macrodef = (MacroDef) macrodefs.get(name);
        if (macrodef != null) {
            Macro macro = macrodef.createMacro();
            setCurrent(macro, name);
            return macro;
        }
        Class childClass = (Class) typedefs.get(name);
        Method addChild = null;
        try {
            if (childClass != null) {
                return addChild(parentOD, childClass, name, null);
            } else {
                addChild = parentOD.getCreateMethod(name);
                if (addChild != null) {
                    child = addChild.invoke(parent, new Object[0]);
                    setCurrent(child, name);
                    return child;
                }
                addChild = parentOD.getAddMethod(name);
                if (addChild != null) {
                    childClass = addChild.getParameterTypes()[0];
                    child = childClass.newInstance();
                    addChild.invoke(parent, new Object[] {child});
                    setCurrent(child, name);
                    return child;
                }
                addChild = parentOD.getAddConfiguredMethod(name);
                if (addChild != null) {
                    childClass = addChild.getParameterTypes()[0];
                    if (Map.class == childClass) {
                        child = new HashMap();
                    } else {
                        child = childClass.newInstance();
                    }
                    setCurrent(child, name);
                    return child;
                }
            }
        } catch (InstantiationException ex) {
            throw new IllegalArgumentException("no default constructor on " + childClass
                    + " for adding " + name + " on " + parent.getClass());
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException("bad method found for "
                    + name + " on " + parent.getClass());
            iae.initCause(ex);
            throw iae;
        }
        throw new IllegalArgumentException("no appropriate method found for adding " + name
                + " on " + parent.getClass());
    }

    public void addChild(String name, Object child) {
        if (objectStack.isEmpty()) {
            throw new IllegalStateException("set root before creating child");
        }
        ObjectDescriptor parentOD = (ObjectDescriptor) objectStack.peek();
        try {
            addChild(parentOD, child.getClass(), name, child);
        } catch (InstantiationException ex) {
            throw new IllegalArgumentException("no default constructor on " + child.getClass()
                    + " for adding " + name + " on " + parentOD.getObject().getClass());
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException("bad method found for "
                    + name + " on " + parentOD.getObject().getClass());
            iae.initCause(ex);
            throw iae;
        }
    }

    private Object addChild(ObjectDescriptor parentOD, Class childClass, String name, Object child)
            throws InstantiationException, IllegalAccessException, InvocationTargetException {
        Object parent = parentOD.getObject();
        if (parent instanceof MacroRecord) {
            MacroRecord record = (MacroRecord) parent;
            MacroRecord recordChild = record.recordChild(name, child);
            setCurrent(recordChild, name);
            return recordChild;
        }
        Method addChild = parentOD.getAddMethod(childClass);
        if (addChild != null) {
            if (child == null) {
                child = childClass.newInstance();
            }
            addChild.invoke(parent, new Object[] {child});
            setCurrent(child, name);
            return child;
        }
        addChild = parentOD.getAddConfiguredMethod(childClass);
        if (addChild != null) {
            if (child == null) {
                if (Map.class == childClass) {
                    child = new HashMap();
                } else {
                    child = childClass.newInstance();
                }
            }
            setCurrent(child, name);
            return child;
        }
        throw new IllegalArgumentException("no appropriate method found for adding " + name
                + " on " + parent.getClass());
    }

    public boolean isTopLevelMacroRecord() {
        if (objectStack.isEmpty()) {
            return false;
        }
        ObjectDescriptor od = (ObjectDescriptor) objectStack.peek();
        return (od.getObject() instanceof MacroDef);
    }

    public void setAttribute(String attributeName, String value) {
        if (objectStack.isEmpty()) {
            throw new IllegalStateException("set root before setting attribute");
        }
        ObjectDescriptor od = (ObjectDescriptor) objectStack.peek();
        if (od.getObject() instanceof Macro) {
            ((Macro) od.getObject()).defineAttribute(attributeName, value);
            return;
        }
        if (od.getObject() instanceof MacroRecord) {
            ((MacroRecord) od.getObject()).recordAttribute(attributeName, value);
            return;
        }
        Method m = od.getSetMethod(attributeName);
        if (m == null) {
            if (od.getObject() instanceof Map) {
                ((Map) od.getObject()).put(attributeName, value);
                return;
            }
            throw new IllegalArgumentException("no set method found for " + attributeName + " on "
                    + od.getObject().getClass());
        }
        Object convertedValue = null;
        Class paramClass = m.getParameterTypes()[0];
        try {
            if (paramClass.equals(String.class)) {
                convertedValue = value;
            } else if (paramClass.equals(Boolean.class) || paramClass.equals(boolean.class)) {
                convertedValue = Boolean.valueOf(TRUE_VALUES.contains(value));
            } else if (paramClass.equals(Character.class) || paramClass.equals(char.class)) {
                convertedValue = new Character(value.length() > 0 ? value.charAt(0) : ' ');
            } else if (paramClass.equals(Short.class) || paramClass.equals(short.class)) {
                convertedValue = Short.valueOf(value);
            } else if (paramClass.equals(Integer.class) || paramClass.equals(int.class)) {
                convertedValue = Integer.valueOf(value);
            } else if (paramClass.equals(Long.class) || paramClass.equals(long.class)) {
                convertedValue = Long.valueOf(value);
            } else if (paramClass.equals(Class.class)) {
                convertedValue = Class.forName(value);
            } else if (paramClass.equals(File.class)) {
                convertedValue = fileResolver.resolveFile(
                                        value, od.getObjectName() + "." + attributeName);
            } else {
                convertedValue = paramClass.getConstructor(new Class[] {String.class}).newInstance(
                    new Object[] {value});
            }
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException("impossible to convert "
                    + value + " to " + paramClass + " for setting " + attributeName + " on "
                    + od.getObject().getClass() + ": " + ex.getMessage());
            iae.initCause(ex);
            throw iae;
        }
        try {
            m.invoke(od.getObject(), new Object[] {convertedValue});
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException("impossible to set "
                    + attributeName + " to " + convertedValue + " on " + od.getObject().getClass());
            iae.initCause(ex);
            throw iae;
        }
    }

    public void addText(String text) {
        if (objectStack.isEmpty()) {
            throw new IllegalStateException("set root before adding text");
        }
        ObjectDescriptor od = (ObjectDescriptor) objectStack.peek();
        try {
            od.getObject().getClass().getMethod("addText", new Class[] {String.class}).invoke(
                od.getObject(), new Object[] {text});
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException(
                    "impossible to add text on " + od.getObject().getClass());
            iae.initCause(ex);
            throw iae;
        }
    }

    /**
     * @return the finished child
     */
    public Object endCreateChild() {
        if (objectStack.isEmpty()) {
            throw new IllegalStateException("set root before ending child");
        }
        ObjectDescriptor od = (ObjectDescriptor) objectStack.pop();
        if (objectStack.isEmpty()) {
            objectStack.push(od); // back to previous state
            throw new IllegalStateException("cannot end root");
        }
        if (od.getObject() instanceof Macro) {
            return ((Macro) od.getObject()).play(this);
        }
        ObjectDescriptor parentOD = (ObjectDescriptor) objectStack.peek();
        String name = od.getObjectName();
        Class childClass = (Class) typedefs.get(name);
        Method m = null;
        if (childClass != null) {
            m = parentOD.getAddConfiguredMethod(childClass);
        } else {
            m = parentOD.getAddConfiguredMethod(name);
        }
        try {
            if (m != null) {
                m.invoke(parentOD.getObject(), new Object[] {od.getObject()});
            }
            return od.getObject();
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException(
                    "impossible to add configured child for " + name + " on "
                            + parentOD.getObject().getClass()
                            + ": " + StringUtils.getErrorMessage(ex));
            iae.initCause(ex);
            throw iae;
        }
    }

    public Object getCurrent() {
        return objectStack.isEmpty() ? null : ((ObjectDescriptor) objectStack.peek()).getObject();
    }

    public int getDepth() {
        return objectStack.size();
    }

    public MacroDef startMacroDef(String macroName) {
        MacroDef macroDef = new MacroDef(macroName);
        setCurrent(macroDef, macroName);
        return macroDef;
    }

    public void addMacroAttribute(String attName, String attDefaultValue) {
        ((MacroDef) getCurrent()).addAttribute(attName, attDefaultValue);
    }

    public void addMacroElement(String elementName, boolean optional) {
        ((MacroDef) getCurrent()).addElement(elementName, optional);
    }

    public void endMacroDef() {
        addConfiguredMacrodef(((MacroDef) getCurrent()));
        objectStack.pop();
    }

    public void addConfiguredMacrodef(MacroDef macrodef) {
        macrodefs.put(macrodef.getName(), macrodef);
    }

    public Class getTypeDef(String name) {
        return (Class) typedefs.get(name);
    }

    public FileResolver getFileResolver() {
        return fileResolver;
    }

    public void setFileResolver(FileResolver fileResolver) {
        Checks.checkNotNull(fileResolver, "fileResolver");
        this.fileResolver = fileResolver;


org.apache.tools.ant.taskdefs.SendEmail

public class SendEmail extends Task {
    private String from;
    private String mailhost = "localhost";
    private String message;
    private String toList;
    private String subject;
    private Vector files = new Vector();

    /** Creates new SendEmail */
    public SendEmail() {
    }

    /**
     * Sets the toList parameter of this build task.
     *
     * @param toList Comma-separated list of email recipient addreses.
     */
    public void setToList(String toList) {
        this.toList = toList;
    }

    /**
     * Sets the from parameter of this build task.
     *
     * @param from Email address of sender.
     */
    public void setFrom(String from) {
        this.from = from;
    }

    /**
     * Sets the mailhost parameter of this build task.
     *
     * @param mailhost Mail host name.
     */
    public void setMailhost(String mailhost) {
        this.mailhost = mailhost;
    }

    /**
     * Sets the message parameter of this build task.
     *
     * @param message Message body of this email.
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * Sets the subject parameter of this build task.
     *
     * @param subject Subject of this email.
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * Sets the file parameter of this build task.
     *
     * @param filenames Filenames to include as the message body of this email.
     */
    public void setFiles(String filenames) {
        StringTokenizer t = new StringTokenizer(filenames, ", ");

        while (t.hasMoreTokens()) {
            files.addElement(project.resolveFile(t.nextToken()));
        }
    }

    /**
     * Executes this build task.
     *
     * throws org.apache.tools.ant.BuildException if there is an error during task
     *        execution.
     */
    public void execute() {
        try {
            MailMessage mailMessage = new MailMessage(mailhost);

            if (from != null) {
                mailMessage.from(from);
            } else {
                throw new BuildException("Attribute \"from\" is required.");
            }

            if (toList != null) {
                StringTokenizer t = new StringTokenizer(toList, ", ", false);

                while (t.hasMoreTokens()) {
                    mailMessage.to(t.nextToken());
                }
            } else {
                throw new BuildException("Attribute \"toList\" is required.");
            }

            if (subject != null) {
                mailMessage.setSubject(subject);
            }

            if (!files.isEmpty()) {
                PrintStream out = mailMessage.getPrintStream();

                for (Enumeration e = files.elements(); e.hasMoreElements(); ) {
                    File file = (File)e.nextElement();

                    if (file.exists() && file.canRead()) {
                        int bufsize = 1024;
                        int length;
                        byte[] buf = new byte[bufsize];

                        BufferedInputStream in = null;
                        try {
                            in = new BufferedInputStream(
                                new FileInputStream(file), bufsize);

                            while ((length = in.read(buf, 0, bufsize)) != -1) {
                                out.write(buf, 0, length);
                            }
                        } finally {
                            if (in != null) {
                                in.close();
                            }
                        }

                    } else {
                        throw new BuildException("File \"" + file.getName()
                            + "\" does not exist or is not readable.");
                    }
                }
            } else if (message != null) {
                PrintStream out = mailMessage.getPrintStream();
                out.print(message);
            } else {
                throw new BuildException("Attribute \"file\" or \"message\" is required.");
            }

            log("Sending email");
            mailMessage.sendAndClose();
        } catch (IOException ioe) {
            throw new BuildException("IO error sending mail: " + ioe.getMessage());

FUNC_DECL LOOP VAR_DECL PARAM CALL CALL CALL LITERAL_ANCHOR CALL CALL


org.gjt.sp.jedit.textarea.Selection

public abstract class Selection
{
	/**
	 * Returns the start offset of this selection.
	 */
	public int getStart()
	{
		return start;
	}

	/**
	 * Returns the end offset of this selection.
	 */
	public int getEnd()
	{
		return end;
	}

	/**
	 * Returns the starting line number of this selection.
	 */
	public int getStartLine()
	{
		return startLine;
	}

	/**
	 * Returns the ending line number of this selection.
	 */
	public int getEndLine()
	{
		return endLine;
	}

	/**
	 * Returns the start offset of this selection on the specified
	 * line.
	 * @param buffer The buffer
	 * @param line The line number
	 */
	public abstract int getStart(Buffer buffer, int line);

	/**
	 * Returns the end offset of this selection on the specified
	 * line.
	 * @param buffer The buffer
	 * @param line The line number
	 */
	public abstract int getEnd(Buffer buffer, int line);

	public String toString()
	{
		return getClass().getName() + "[start=" + start
			+ ",end=" + end + ",startLine=" + startLine
			+ ",endLine=" + endLine + "]";
	}

	// package-private members
	int start, end, startLine, endLine;

	// protected members
	protected Selection()
	{
	}

	protected Selection(Selection copy)
	{
		start = copy.start;
		end = copy.end;
	}

	protected Selection(int start, int end)
	{
		this.start = start;
		this.end = end;

		// setting these is handled by textArea._addToSelection();
		//this.startLine = startLine;
		//this.endLine = endLine;
	}

	/**
	 * An ordinary range selection.
	 * @since jEdit 3.2pre1
	 */
	public static class Range extends Selection
	{
		public Range()
		{
			super();
		}

		public Range(Selection sel)
		{
			super(sel);
		}

		public Range(int start, int end)
		{
			super(start,end);
		}

		public int getStart(Buffer buffer, int line)
		{
			if(line == startLine)
				return start;
			else
			{
				Element map = buffer.getDefaultRootElement();
				Element lineElement = map.getElement(line);
				return lineElement.getStartOffset();
			}
		}

		public int getEnd(Buffer buffer, int line)
		{
			if(line == endLine)
				return end;
			else
			{
				Element map = buffer.getDefaultRootElement();
				Element lineElement = map.getElement(line);
				return lineElement.getEndOffset() - 1;
			}
		}
	}

	/**
	 * A rectangular selection.
	 * @since jEdit 3.2pre1
	 */
	public static class Rect extends Selection
	{
		public Rect()
		{
			super();
		}

		public Rect(Selection sel)
		{
			super(sel);
		}

		public Rect(int start, int end)
		{
			super(start,end);
		}

		public int getStart(Buffer buffer, int line)
		{
			if(line == startLine)
				return start;
			else
			{
				Element map = buffer.getDefaultRootElement();
				int _start = start - map.getElement(startLine)
					.getStartOffset();
				int _end = end - map.getElement(endLine)
					.getStartOffset();

				Element lineElement = map.getElement(line);
				return Math.min(lineElement.getEndOffset() - 1,
					lineElement.getStartOffset()
					+ Math.min(_start,_end));
			}
		}

		public int getEnd(Buffer buffer, int line)
		{
			if(line == endLine)
				return end;
			else
			{
				Element map = buffer.getDefaultRootElement();
				int _start = start - map.getElement(startLine)
					.getStartOffset();
				int _end = end - map.getElement(endLine)
					.getStartOffset();

				Element lineElement = map.getElement(line);
				return Math.min(lineElement.getEndOffset() - 1,
					lineElement.getStartOffset()
					+ Math.max(_start,_end));

	public int getStart()
	{
		return start;