text
stringlengths
30
1.67M
<s> package net . sf . json . processors ; public interface PropertyNameProcessor { String processPropertyName ( Class beanClass , String name ) ; } </s>
<s> package net . sf . json . processors ; import net . sf . json . JSONException ; import net . sf . json . JsonConfig ; public interface JsonValueProcessor { Object processArrayValue ( Object value , JsonConfig jsonConfig ) ; Object processObjectValue ( String key , Object value , JsonConfig jsonConfig ) ; } </s>
<s> package net . sf . json . processors ; import java . util . Set ; public abstract class PropertyNameProcessorMatcher { public static final PropertyNameProcessorMatcher DEFAULT = new DefaultPropertyNameProcessorMatcher ( ) ; public abstract Object getMatch ( Class target , Set set ) ; private static final class DefaultPropertyNameProcessorMatcher extends PropertyNameProcessorMatcher { public Object getMatch ( Class target , Set set ) { if ( target != null && set != null && set . contains ( target ) ) { return target ; } return null ; } } } </s>
<s> package net . sf . json . processors ; import java . util . Set ; public abstract class JsonBeanProcessorMatcher { public static final JsonBeanProcessorMatcher DEFAULT = new DefaultJsonBeanProcessorMatcher ( ) ; public abstract Object getMatch ( Class target , Set set ) ; private static final class DefaultJsonBeanProcessorMatcher extends JsonBeanProcessorMatcher { public Object getMatch ( Class target , Set set ) { if ( target != null && set != null && set . contains ( target ) ) { return target ; } return null ; } } } </s>
<s> package net . sf . json . processors ; import net . sf . json . JSONException ; import net . sf . json . JSONObject ; import net . sf . json . JsonConfig ; public interface JsonBeanProcessor { JSONObject processBean ( Object bean , JsonConfig jsonConfig ) ; } </s>
<s> package net . sf . json . processors ; public interface DefaultValueProcessor { Object getDefaultValue ( Class type ) ; } </s>
<s> package net . sf . json . processors ; import java . util . Set ; public abstract class DefaultValueProcessorMatcher { public static final DefaultValueProcessorMatcher DEFAULT = new DefaultDefaultValueProcessorMatcher ( ) ; public abstract Object getMatch ( Class target , Set set ) ; private static final class DefaultDefaultValueProcessorMatcher extends DefaultValueProcessorMatcher { public Object getMatch ( Class target , Set set ) { if ( target != null && set != null && set . contains ( target ) ) { return target ; } return null ; } } } </s>
<s> package net . sf . json . processors ; import net . sf . json . JSONArray ; import net . sf . json . JSONNull ; import net . sf . json . util . JSONUtils ; public class DefaultDefaultValueProcessor implements DefaultValueProcessor { public Object getDefaultValue ( Class type ) { if ( JSONUtils . isArray ( type ) ) { return new JSONArray ( ) ; } else if ( JSONUtils . isNumber ( type ) ) { if ( JSONUtils . isDouble ( type ) ) { return new Double ( <NUM_LIT:0> ) ; } else { return new Integer ( <NUM_LIT:0> ) ; } } else if ( JSONUtils . isBoolean ( type ) ) { return Boolean . FALSE ; } else if ( JSONUtils . isString ( type ) ) { return "<STR_LIT>" ; } return JSONNull . getInstance ( ) ; } } </s>
<s> package net . sf . json . processors ; import net . sf . json . JsonConfig ; public class JsDateJsonValueProcessor implements JsonValueProcessor { private JsonBeanProcessor processor ; public JsDateJsonValueProcessor ( ) { processor = new JsDateJsonBeanProcessor ( ) ; } public Object processArrayValue ( Object value , JsonConfig jsonConfig ) { return process ( value , jsonConfig ) ; } public Object processObjectValue ( String key , Object value , JsonConfig jsonConfig ) { return process ( value , jsonConfig ) ; } private Object process ( Object value , JsonConfig jsonConfig ) { return processor . processBean ( value , jsonConfig ) ; } } </s>
<s> package net . sf . json . processors ; import java . util . Set ; public abstract class JsonValueProcessorMatcher { public static final JsonValueProcessorMatcher DEFAULT = new DefaultJsonValueProcessorMatcher ( ) ; public abstract Object getMatch ( Class target , Set set ) ; private static final class DefaultJsonValueProcessorMatcher extends JsonValueProcessorMatcher { public Object getMatch ( Class target , Set set ) { if ( target != null && set != null && set . contains ( target ) ) { return target ; } return null ; } } } </s>
<s> package net . sf . json . util ; import java . io . IOException ; import java . io . Writer ; import net . sf . json . JSONException ; public class JSONBuilder { private static final int MAXDEPTH = <NUM_LIT:20> ; private boolean comma ; protected char mode ; private char stack [ ] ; private int top ; protected Writer writer ; public JSONBuilder ( Writer w ) { this . comma = false ; this . mode = '<CHAR_LIT>' ; this . stack = new char [ MAXDEPTH ] ; this . top = <NUM_LIT:0> ; this . writer = w ; } private JSONBuilder append ( String s ) { if ( s == null ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( this . mode == '<CHAR_LIT>' || this . mode == '<CHAR_LIT:a>' ) { try { if ( this . comma && this . mode == '<CHAR_LIT:a>' ) { this . writer . write ( '<CHAR_LIT:U+002C>' ) ; } this . writer . write ( s ) ; } catch ( IOException e ) { throw new JSONException ( e ) ; } if ( this . mode == '<CHAR_LIT>' ) { this . mode = '<CHAR_LIT>' ; } this . comma = true ; return this ; } throw new JSONException ( "<STR_LIT>" ) ; } public JSONBuilder array ( ) { if ( this . mode == '<CHAR_LIT>' || this . mode == '<CHAR_LIT>' || this . mode == '<CHAR_LIT:a>' ) { this . push ( '<CHAR_LIT:a>' ) ; this . append ( "<STR_LIT:[>" ) ; this . comma = false ; return this ; } throw new JSONException ( "<STR_LIT>" ) ; } private JSONBuilder end ( char m , char c ) { if ( this . mode != m ) { throw new JSONException ( m == '<CHAR_LIT>' ? "<STR_LIT>" : "<STR_LIT>" ) ; } this . pop ( m ) ; try { this . writer . write ( c ) ; } catch ( IOException e ) { throw new JSONException ( e ) ; } this . comma = true ; return this ; } public JSONBuilder endArray ( ) { return this . end ( '<CHAR_LIT:a>' , '<CHAR_LIT:]>' ) ; } public JSONBuilder endObject ( ) { return this . end ( '<CHAR_LIT>' , '<CHAR_LIT:}>' ) ; } public JSONBuilder key ( String s ) { if ( s == null ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( this . mode == '<CHAR_LIT>' ) { try { if ( this . comma ) { this . writer . write ( '<CHAR_LIT:U+002C>' ) ; } this . writer . write ( JSONUtils . quote ( s ) ) ; this . writer . write ( '<CHAR_LIT::>' ) ; this . comma = false ; this . mode = '<CHAR_LIT>' ; return this ; } catch ( IOException e ) { throw new JSONException ( e ) ; } } throw new JSONException ( "<STR_LIT>" ) ; } public JSONBuilder object ( ) { if ( this . mode == '<CHAR_LIT>' ) { this . mode = '<CHAR_LIT>' ; } if ( this . mode == '<CHAR_LIT>' || this . mode == '<CHAR_LIT:a>' ) { this . append ( "<STR_LIT:{>" ) ; this . push ( '<CHAR_LIT>' ) ; this . comma = false ; return this ; } throw new JSONException ( "<STR_LIT>" ) ; } private void pop ( char c ) { if ( this . top <= <NUM_LIT:0> || this . stack [ this . top - <NUM_LIT:1> ] != c ) { throw new JSONException ( "<STR_LIT>" ) ; } this . top -= <NUM_LIT:1> ; this . mode = this . top == <NUM_LIT:0> ? '<CHAR_LIT>' : this . stack [ this . top - <NUM_LIT:1> ] ; } private void push ( char c ) { if ( this . top >= MAXDEPTH ) { throw new JSONException ( "<STR_LIT>" ) ; } this . stack [ this . top ] = c ; this . mode = c ; this . top += <NUM_LIT:1> ; } public JSONBuilder value ( boolean b ) { return this . append ( b ? "<STR_LIT:true>" : "<STR_LIT:false>" ) ; } public JSONBuilder value ( double d ) { return this . value ( new Double ( d ) ) ; } public JSONBuilder value ( long l ) { return this . append ( Long . toString ( l ) ) ; } public JSONBuilder value ( Object o ) { return this . append ( JSONUtils . valueToString ( o ) ) ; } } </s>
<s> package net . sf . json . util ; import net . sf . json . JSONArray ; import net . sf . json . JSONException ; import net . sf . json . JSONObject ; public abstract class CycleDetectionStrategy { public static final JSONArray IGNORE_PROPERTY_ARR = new JSONArray ( ) ; public static final JSONObject IGNORE_PROPERTY_OBJ = new JSONObject ( ) ; public static final CycleDetectionStrategy LENIENT = new LenientCycleDetectionStrategy ( ) ; public static final CycleDetectionStrategy NOPROP = new LenientNoRefCycleDetectionStrategy ( ) ; public static final CycleDetectionStrategy STRICT = new StrictCycleDetectionStrategy ( ) ; public abstract JSONArray handleRepeatedReferenceAsArray ( Object reference ) ; public abstract JSONObject handleRepeatedReferenceAsObject ( Object reference ) ; private static final class LenientCycleDetectionStrategy extends CycleDetectionStrategy { public JSONArray handleRepeatedReferenceAsArray ( Object reference ) { return new JSONArray ( ) ; } public JSONObject handleRepeatedReferenceAsObject ( Object reference ) { return new JSONObject ( true ) ; } } private static final class LenientNoRefCycleDetectionStrategy extends CycleDetectionStrategy { public JSONArray handleRepeatedReferenceAsArray ( Object reference ) { return IGNORE_PROPERTY_ARR ; } public JSONObject handleRepeatedReferenceAsObject ( Object reference ) { return IGNORE_PROPERTY_OBJ ; } } private static final class StrictCycleDetectionStrategy extends CycleDetectionStrategy { public JSONArray handleRepeatedReferenceAsArray ( Object reference ) { throw new JSONException ( "<STR_LIT>" ) ; } public JSONObject handleRepeatedReferenceAsObject ( Object reference ) { throw new JSONException ( "<STR_LIT>" ) ; } } } </s>
<s> package net . sf . json . util ; public interface PropertyFilter { boolean apply ( Object source , String name , Object value ) ; } </s>
<s> package net . sf . json . util ; import java . util . Set ; public abstract class PropertyExclusionClassMatcher { public static final PropertyExclusionClassMatcher DEFAULT = new DefaultPropertyExclusionClassMatcher ( ) ; public abstract Object getMatch ( Class target , Set set ) ; private static final class DefaultPropertyExclusionClassMatcher extends PropertyExclusionClassMatcher { public Object getMatch ( Class target , Set set ) { if ( target != null && set != null && set . contains ( target ) ) { return target ; } return null ; } } } </s>
<s> package net . sf . json . util ; import net . sf . json . JSONException ; public interface JsonEventListener { void onArrayEnd ( ) ; void onArrayStart ( ) ; void onElementAdded ( int index , Object element ) ; void onError ( JSONException jsone ) ; void onObjectEnd ( ) ; void onObjectStart ( ) ; void onPropertySet ( String key , Object value , boolean accumulated ) ; void onWarning ( String warning ) ; } </s>
<s> package net . sf . json . util ; import java . lang . reflect . Field ; import java . util . Map ; import net . sf . json . JSONException ; import net . sf . json . JsonConfig ; import org . apache . commons . beanutils . PropertyUtils ; public abstract class PropertySetStrategy { public static final PropertySetStrategy DEFAULT = new DefaultPropertySetStrategy ( ) ; public abstract void setProperty ( Object bean , String key , Object value ) throws JSONException ; public void setProperty ( Object bean , String key , Object value , JsonConfig jsonConfig ) throws JSONException { setProperty ( bean , key , value ) ; } private static final class DefaultPropertySetStrategy extends PropertySetStrategy { public void setProperty ( Object bean , String key , Object value ) throws JSONException { setProperty ( bean , key , value , new JsonConfig ( ) ) ; } public void setProperty ( Object bean , String key , Object value , JsonConfig jsonConfig ) throws JSONException { if ( bean instanceof Map ) { ( ( Map ) bean ) . put ( key , value ) ; } else { if ( ! jsonConfig . isIgnorePublicFields ( ) ) { try { Field field = bean . getClass ( ) . getField ( key ) ; if ( field != null ) field . set ( bean , value ) ; } catch ( Exception e ) { _setProperty ( bean , key , value ) ; } } else { _setProperty ( bean , key , value ) ; } } } private void _setProperty ( Object bean , String key , Object value ) { try { PropertyUtils . setSimpleProperty ( bean , key , value ) ; } catch ( Exception e ) { throw new JSONException ( e ) ; } } } } </s>
<s> package net . sf . json . util ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . Collection ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import net . sf . ezmorph . MorphUtils ; import net . sf . ezmorph . MorpherRegistry ; import net . sf . ezmorph . bean . MorphDynaBean ; import net . sf . ezmorph . bean . MorphDynaClass ; import net . sf . json . JSON ; import net . sf . json . JSONArray ; import net . sf . json . JSONException ; import net . sf . json . JSONFunction ; import net . sf . json . JSONNull ; import net . sf . json . JSONObject ; import net . sf . json . JSONString ; import net . sf . json . JsonConfig ; import net . sf . json . regexp . RegexpUtils ; import org . apache . commons . beanutils . DynaBean ; public final class JSONUtils { public static final String DOUBLE_QUOTE = "<STR_LIT:\">" ; public static final String SINGLE_QUOTE = "<STR_LIT:'>" ; private static final String FUNCTION_BODY_PATTERN = "<STR_LIT>" ; private static final String FUNCTION_HEADER_PATTERN = "<STR_LIT>" ; private static final String FUNCTION_PARAMS_PATTERN = "<STR_LIT>" ; private static final String FUNCTION_PATTERN = "<STR_LIT>" ; private static final String FUNCTION_PREFIX = "<STR_LIT>" ; private static final MorpherRegistry morpherRegistry = new MorpherRegistry ( ) ; static { MorphUtils . registerStandardMorphers ( morpherRegistry ) ; } public static String convertToJavaIdentifier ( String key ) { return convertToJavaIdentifier ( key , new JsonConfig ( ) ) ; } public static String convertToJavaIdentifier ( String key , JsonConfig jsonConfig ) { try { return jsonConfig . getJavaIdentifierTransformer ( ) . transformToJavaIdentifier ( key ) ; } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( e ) ; } } public static String doubleToString ( double d ) { if ( Double . isInfinite ( d ) || Double . isNaN ( d ) ) { return "<STR_LIT:null>" ; } String s = Double . toString ( d ) ; if ( s . indexOf ( '<CHAR_LIT:.>' ) > <NUM_LIT:0> && s . indexOf ( '<CHAR_LIT:e>' ) < <NUM_LIT:0> && s . indexOf ( '<CHAR_LIT>' ) < <NUM_LIT:0> ) { while ( s . endsWith ( "<STR_LIT:0>" ) ) { s = s . substring ( <NUM_LIT:0> , s . length ( ) - <NUM_LIT:1> ) ; } if ( s . endsWith ( "<STR_LIT:.>" ) ) { s = s . substring ( <NUM_LIT:0> , s . length ( ) - <NUM_LIT:1> ) ; } } return s ; } public static String getFunctionBody ( String function ) { return RegexpUtils . getMatcher ( FUNCTION_BODY_PATTERN , true ) . getGroupIfMatches ( function , <NUM_LIT:1> ) ; } public static String getFunctionParams ( String function ) { return RegexpUtils . getMatcher ( FUNCTION_PARAMS_PATTERN , true ) . getGroupIfMatches ( function , <NUM_LIT:1> ) ; } public static Class getInnerComponentType ( Class type ) { if ( ! type . isArray ( ) ) { return type ; } return getInnerComponentType ( type . getComponentType ( ) ) ; } public static MorpherRegistry getMorpherRegistry ( ) { return morpherRegistry ; } public static Map getProperties ( JSONObject jsonObject ) { Map properties = new HashMap ( ) ; for ( Iterator keys = jsonObject . keys ( ) ; keys . hasNext ( ) ; ) { String key = ( String ) keys . next ( ) ; properties . put ( key , getTypeClass ( jsonObject . get ( key ) ) ) ; } return properties ; } public static Class getTypeClass ( Object obj ) { if ( isNull ( obj ) ) { return Object . class ; } else if ( isArray ( obj ) ) { return List . class ; } else if ( isFunction ( obj ) ) { return JSONFunction . class ; } else if ( isBoolean ( obj ) ) { return Boolean . class ; } else if ( isNumber ( obj ) ) { Number n = ( Number ) obj ; if ( isInteger ( n ) ) { return Integer . class ; } else if ( isLong ( n ) ) { return Long . class ; } else if ( isFloat ( n ) ) { return Float . class ; } else if ( isBigInteger ( n ) ) { return BigInteger . class ; } else if ( isBigDecimal ( n ) ) { return BigDecimal . class ; } else if ( isDouble ( n ) ) { return Double . class ; } else { throw new JSONException ( "<STR_LIT>" ) ; } } else if ( isString ( obj ) ) { return String . class ; } else if ( isObject ( obj ) ) { return Object . class ; } else { throw new JSONException ( "<STR_LIT>" ) ; } } public static int hashCode ( Object value ) { if ( value == null ) { return JSONNull . getInstance ( ) . hashCode ( ) ; } else if ( value instanceof JSON || value instanceof String || value instanceof JSONFunction ) { return value . hashCode ( ) ; } else { return String . valueOf ( value ) . hashCode ( ) ; } } public static boolean isArray ( Class clazz ) { return clazz != null && ( clazz . isArray ( ) || Collection . class . isAssignableFrom ( clazz ) || ( JSONArray . class . isAssignableFrom ( clazz ) ) ) ; } public static boolean isArray ( Object obj ) { if ( ( obj != null && obj . getClass ( ) . isArray ( ) ) || ( obj instanceof Collection ) || ( obj instanceof JSONArray ) ) { return true ; } return false ; } public static boolean isBoolean ( Class clazz ) { return clazz != null && ( Boolean . TYPE . isAssignableFrom ( clazz ) || Boolean . class . isAssignableFrom ( clazz ) ) ; } public static boolean isBoolean ( Object obj ) { if ( ( obj instanceof Boolean ) || ( obj != null && obj . getClass ( ) == Boolean . TYPE ) ) { return true ; } return false ; } public static boolean isDouble ( Class clazz ) { return clazz != null && ( Double . TYPE . isAssignableFrom ( clazz ) || Double . class . isAssignableFrom ( clazz ) ) ; } public static boolean isFunction ( Object obj ) { if ( obj instanceof String ) { String str = ( String ) obj ; return str . startsWith ( FUNCTION_PREFIX ) && RegexpUtils . getMatcher ( FUNCTION_PATTERN , true ) . matches ( str ) ; } if ( obj instanceof JSONFunction ) { return true ; } return false ; } public static boolean isFunctionHeader ( Object obj ) { if ( obj instanceof String ) { String str = ( String ) obj ; return str . startsWith ( FUNCTION_PREFIX ) && RegexpUtils . getMatcher ( FUNCTION_HEADER_PATTERN , true ) . matches ( str ) ; } return false ; } public static boolean isJavaIdentifier ( String str ) { if ( str . length ( ) == <NUM_LIT:0> || ! Character . isJavaIdentifierStart ( str . charAt ( <NUM_LIT:0> ) ) ) { return false ; } for ( int i = <NUM_LIT:1> ; i < str . length ( ) ; i ++ ) { if ( ! Character . isJavaIdentifierPart ( str . charAt ( i ) ) ) { return false ; } } return true ; } public static boolean isNull ( Object obj ) { if ( obj instanceof JSONObject ) { return ( ( JSONObject ) obj ) . isNullObject ( ) ; } return JSONNull . getInstance ( ) . equals ( obj ) ; } public static boolean isNumber ( Class clazz ) { return clazz != null && ( Byte . TYPE . isAssignableFrom ( clazz ) || Short . TYPE . isAssignableFrom ( clazz ) || Integer . TYPE . isAssignableFrom ( clazz ) || Long . TYPE . isAssignableFrom ( clazz ) || Float . TYPE . isAssignableFrom ( clazz ) || Double . TYPE . isAssignableFrom ( clazz ) || Number . class . isAssignableFrom ( clazz ) ) ; } public static boolean isNumber ( Object obj ) { if ( ( obj != null && obj . getClass ( ) == Byte . TYPE ) || ( obj != null && obj . getClass ( ) == Short . TYPE ) || ( obj != null && obj . getClass ( ) == Integer . TYPE ) || ( obj != null && obj . getClass ( ) == Long . TYPE ) || ( obj != null && obj . getClass ( ) == Float . TYPE ) || ( obj != null && obj . getClass ( ) == Double . TYPE ) ) { return true ; } return obj instanceof Number ; } public static boolean isObject ( Object obj ) { return ! isNumber ( obj ) && ! isString ( obj ) && ! isBoolean ( obj ) && ! isArray ( obj ) && ! isFunction ( obj ) || isNull ( obj ) ; } public static boolean isString ( Class clazz ) { return clazz != null && ( String . class . isAssignableFrom ( clazz ) || ( Character . TYPE . isAssignableFrom ( clazz ) || Character . class . isAssignableFrom ( clazz ) ) ) ; } public static boolean isString ( Object obj ) { if ( ( obj instanceof String ) || ( obj instanceof Character ) || ( obj != null && ( obj . getClass ( ) == Character . TYPE || String . class . isAssignableFrom ( obj . getClass ( ) ) ) ) ) { return true ; } return false ; } public static boolean mayBeJSON ( String string ) { return string != null && ( "<STR_LIT:null>" . equals ( string ) || ( string . startsWith ( "<STR_LIT:[>" ) && string . endsWith ( "<STR_LIT:]>" ) ) || ( string . startsWith ( "<STR_LIT:{>" ) && string . endsWith ( "<STR_LIT:}>" ) ) ) ; } public static DynaBean newDynaBean ( JSONObject jsonObject ) { return newDynaBean ( jsonObject , new JsonConfig ( ) ) ; } public static DynaBean newDynaBean ( JSONObject jsonObject , JsonConfig jsonConfig ) { Map props = getProperties ( jsonObject ) ; for ( Iterator entries = props . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; String key = ( String ) entry . getKey ( ) ; if ( ! JSONUtils . isJavaIdentifier ( key ) ) { String parsedKey = JSONUtils . convertToJavaIdentifier ( key , jsonConfig ) ; if ( parsedKey . compareTo ( key ) != <NUM_LIT:0> ) { props . put ( parsedKey , props . remove ( key ) ) ; } } } MorphDynaClass dynaClass = new MorphDynaClass ( props ) ; MorphDynaBean dynaBean = null ; try { dynaBean = ( MorphDynaBean ) dynaClass . newInstance ( ) ; dynaBean . setDynaBeanClass ( dynaClass ) ; } catch ( Exception e ) { throw new JSONException ( e ) ; } return dynaBean ; } public static String numberToString ( Number n ) { if ( n == null ) { throw new JSONException ( "<STR_LIT>" ) ; } testValidity ( n ) ; String s = n . toString ( ) ; if ( s . indexOf ( '<CHAR_LIT:.>' ) > <NUM_LIT:0> && s . indexOf ( '<CHAR_LIT:e>' ) < <NUM_LIT:0> && s . indexOf ( '<CHAR_LIT>' ) < <NUM_LIT:0> ) { while ( s . endsWith ( "<STR_LIT:0>" ) ) { s = s . substring ( <NUM_LIT:0> , s . length ( ) - <NUM_LIT:1> ) ; } if ( s . endsWith ( "<STR_LIT:.>" ) ) { s = s . substring ( <NUM_LIT:0> , s . length ( ) - <NUM_LIT:1> ) ; } } return s ; } public static String quote ( String string ) { if ( isFunction ( string ) ) { return string ; } if ( string == null || string . length ( ) == <NUM_LIT:0> ) { return "<STR_LIT>" ; } char b ; char c = <NUM_LIT:0> ; int i ; int len = string . length ( ) ; StringBuffer sb = new StringBuffer ( len * <NUM_LIT:2> ) ; String t ; char [ ] chars = string . toCharArray ( ) ; char [ ] buffer = new char [ <NUM_LIT> ] ; int bufferIndex = <NUM_LIT:0> ; sb . append ( '<CHAR_LIT:">' ) ; for ( i = <NUM_LIT:0> ; i < len ; i += <NUM_LIT:1> ) { if ( bufferIndex > <NUM_LIT> ) { sb . append ( buffer , <NUM_LIT:0> , bufferIndex ) ; bufferIndex = <NUM_LIT:0> ; } b = c ; c = chars [ i ] ; switch ( c ) { case '<STR_LIT:\\>' : case '<CHAR_LIT:">' : buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = c ; break ; case '<CHAR_LIT:/>' : if ( b == '<CHAR_LIT>' ) { buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; } buffer [ bufferIndex ++ ] = c ; break ; default : if ( c < '<CHAR_LIT:U+0020>' ) { switch ( c ) { case '<STR_LIT>' : buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = '<CHAR_LIT:b>' ; break ; case '<STR_LIT:\t>' : buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = '<CHAR_LIT>' ; break ; case '<STR_LIT:\n>' : buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = '<CHAR_LIT>' ; break ; case '<STR_LIT>' : buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = '<CHAR_LIT>' ; break ; case '<STR_LIT>' : buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = '<CHAR_LIT>' ; break ; default : t = "<STR_LIT>" + Integer . toHexString ( c ) ; int tLength = t . length ( ) ; buffer [ bufferIndex ++ ] = '<STR_LIT:\\>' ; buffer [ bufferIndex ++ ] = '<CHAR_LIT>' ; buffer [ bufferIndex ++ ] = t . charAt ( tLength - <NUM_LIT:4> ) ; buffer [ bufferIndex ++ ] = t . charAt ( tLength - <NUM_LIT:3> ) ; buffer [ bufferIndex ++ ] = t . charAt ( tLength - <NUM_LIT:2> ) ; buffer [ bufferIndex ++ ] = t . charAt ( tLength - <NUM_LIT:1> ) ; } } else { buffer [ bufferIndex ++ ] = c ; } } } sb . append ( buffer , <NUM_LIT:0> , bufferIndex ) ; sb . append ( '<CHAR_LIT:">' ) ; return sb . toString ( ) ; } public static String quoteCanonical ( String s ) { if ( s == null || s . length ( ) == <NUM_LIT:0> ) { return "<STR_LIT>" ; } int len = s . length ( ) ; StringBuilder sb = new StringBuilder ( len + <NUM_LIT:4> ) ; sb . append ( '<CHAR_LIT:">' ) ; for ( int i = <NUM_LIT:0> ; i < len ; i += <NUM_LIT:1> ) { char c = s . charAt ( i ) ; switch ( c ) { case '<STR_LIT:\\>' : case '<CHAR_LIT:">' : sb . append ( '<STR_LIT:\\>' ) ; sb . append ( c ) ; break ; default : if ( c < '<CHAR_LIT:U+0020>' ) { String t = "<STR_LIT>" + Integer . toHexString ( c ) ; sb . append ( "<STR_LIT>" ) . append ( t . substring ( t . length ( ) - <NUM_LIT:4> ) ) ; } else { sb . append ( c ) ; } } } sb . append ( '<CHAR_LIT:">' ) ; return sb . toString ( ) ; } public static String stripQuotes ( String input ) { if ( input . length ( ) < <NUM_LIT:2> ) { return input ; } else if ( input . startsWith ( SINGLE_QUOTE ) && input . endsWith ( SINGLE_QUOTE ) ) { return input . substring ( <NUM_LIT:1> , input . length ( ) - <NUM_LIT:1> ) ; } else if ( input . startsWith ( DOUBLE_QUOTE ) && input . endsWith ( DOUBLE_QUOTE ) ) { return input . substring ( <NUM_LIT:1> , input . length ( ) - <NUM_LIT:1> ) ; } else { return input ; } } public static boolean hasQuotes ( String input ) { if ( input == null || input . length ( ) < <NUM_LIT:2> ) { return false ; } return input . startsWith ( SINGLE_QUOTE ) && input . endsWith ( SINGLE_QUOTE ) || input . startsWith ( DOUBLE_QUOTE ) && input . endsWith ( DOUBLE_QUOTE ) ; } public static boolean isJsonKeyword ( String input , JsonConfig jsonConfig ) { if ( input == null ) { return false ; } return "<STR_LIT:null>" . equals ( input ) || "<STR_LIT:true>" . equals ( input ) || "<STR_LIT:false>" . equals ( input ) || ( jsonConfig . isJavascriptCompliant ( ) && "<STR_LIT>" . equals ( input ) ) ; } public static void testValidity ( Object o ) { if ( o != null ) { if ( o instanceof Double ) { if ( ( ( Double ) o ) . isInfinite ( ) || ( ( Double ) o ) . isNaN ( ) ) { throw new JSONException ( "<STR_LIT>" ) ; } } else if ( o instanceof Float ) { if ( ( ( Float ) o ) . isInfinite ( ) || ( ( Float ) o ) . isNaN ( ) ) { throw new JSONException ( "<STR_LIT>" ) ; } } else if ( o instanceof BigDecimal || o instanceof BigInteger ) { return ; } } } public static Number transformNumber ( Number input ) { if ( input instanceof Float ) { return new Double ( input . toString ( ) ) ; } else if ( input instanceof Short ) { return new Integer ( input . intValue ( ) ) ; } else if ( input instanceof Byte ) { return new Integer ( input . intValue ( ) ) ; } else if ( input instanceof Long ) { Long max = new Long ( Integer . MAX_VALUE ) ; if ( input . longValue ( ) <= max . longValue ( ) && input . longValue ( ) >= Integer . MIN_VALUE ) { return new Integer ( input . intValue ( ) ) ; } } return input ; } public static String valueToString ( Object value ) { if ( value == null || isNull ( value ) ) { return "<STR_LIT:null>" ; } if ( value instanceof JSONFunction ) { return ( ( JSONFunction ) value ) . toString ( ) ; } if ( value instanceof JSONString ) { return ( ( JSONString ) value ) . toJSONString ( ) ; } if ( value instanceof Number ) { return numberToString ( ( Number ) value ) ; } if ( value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray ) { return value . toString ( ) ; } return quote ( value . toString ( ) ) ; } public static String valueToCanonicalString ( Object value ) { if ( value == null || isNull ( value ) ) { return "<STR_LIT:null>" ; } if ( value instanceof JSONFunction ) { return value . toString ( ) ; } if ( value instanceof JSONString ) { return ( ( JSONString ) value ) . toJSONString ( ) ; } if ( value instanceof Number ) { return numberToString ( ( Number ) value ) . toLowerCase ( ) ; } if ( value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray ) { return value . toString ( ) ; } return quoteCanonical ( value . toString ( ) ) ; } public static String valueToString ( Object value , int indentFactor , int indent ) { if ( value == null || isNull ( value ) ) { return "<STR_LIT:null>" ; } if ( value instanceof JSONFunction ) { return value . toString ( ) ; } if ( value instanceof JSONString ) { return ( ( JSONString ) value ) . toJSONString ( ) ; } if ( value instanceof Number ) { return numberToString ( ( Number ) value ) ; } if ( value instanceof Boolean ) { return value . toString ( ) ; } if ( value instanceof JSONObject ) { return ( ( JSONObject ) value ) . toString ( indentFactor , indent ) ; } if ( value instanceof JSONArray ) { return ( ( JSONArray ) value ) . toString ( indentFactor , indent ) ; } return quote ( value . toString ( ) ) ; } private static boolean isBigDecimal ( Number n ) { if ( n instanceof BigDecimal ) { return true ; } try { new BigDecimal ( String . valueOf ( n ) ) ; return true ; } catch ( NumberFormatException e ) { return false ; } } private static boolean isBigInteger ( Number n ) { if ( n instanceof BigInteger ) { return true ; } try { new BigInteger ( String . valueOf ( n ) ) ; return true ; } catch ( NumberFormatException e ) { return false ; } } private static boolean isDouble ( Number n ) { if ( n instanceof Double ) { return true ; } try { double d = Double . parseDouble ( String . valueOf ( n ) ) ; return ! Double . isInfinite ( d ) ; } catch ( NumberFormatException e ) { return false ; } } private static boolean isFloat ( Number n ) { if ( n instanceof Float ) { return true ; } try { float f = Float . parseFloat ( String . valueOf ( n ) ) ; return ! Float . isInfinite ( f ) ; } catch ( NumberFormatException e ) { return false ; } } private static boolean isInteger ( Number n ) { if ( n instanceof Integer ) { return true ; } try { Integer . parseInt ( String . valueOf ( n ) ) ; return true ; } catch ( NumberFormatException e ) { return false ; } } private static boolean isLong ( Number n ) { if ( n instanceof Long ) { return true ; } try { Long . parseLong ( String . valueOf ( n ) ) ; return true ; } catch ( NumberFormatException e ) { return false ; } } private JSONUtils ( ) { super ( ) ; } } </s>
<s> package net . sf . json . util ; import java . lang . reflect . Constructor ; import java . lang . reflect . InvocationTargetException ; import net . sf . json . JSONObject ; public abstract class NewBeanInstanceStrategy { public static final NewBeanInstanceStrategy DEFAULT = new DefaultNewBeanInstanceStrategy ( ) ; public abstract Object newInstance ( Class target , JSONObject source ) throws InstantiationException , IllegalAccessException , SecurityException , NoSuchMethodException , InvocationTargetException ; private static final class DefaultNewBeanInstanceStrategy extends NewBeanInstanceStrategy { private static final Object [ ] EMPTY_ARGS = new Object [ <NUM_LIT:0> ] ; private static final Class [ ] EMPTY_PARAM_TYPES = new Class [ <NUM_LIT:0> ] ; public Object newInstance ( Class target , JSONObject source ) throws InstantiationException , IllegalAccessException , SecurityException , NoSuchMethodException , InvocationTargetException { if ( target != null ) { Constructor c = target . getDeclaredConstructor ( EMPTY_PARAM_TYPES ) ; c . setAccessible ( true ) ; try { return c . newInstance ( EMPTY_ARGS ) ; } catch ( InstantiationException e ) { String cause = "<STR_LIT>" ; try { cause = e . getCause ( ) != null ? "<STR_LIT:n>" + e . getCause ( ) . getMessage ( ) : "<STR_LIT>" ; } catch ( Throwable t ) { } throw new InstantiationException ( "<STR_LIT>" + target + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + cause ) ; } } return null ; } } } </s>
<s> package net . sf . json . util ; import net . sf . json . JSONException ; import org . apache . commons . lang . StringUtils ; public abstract class JavaIdentifierTransformer { public static final JavaIdentifierTransformer CAMEL_CASE = new CamelCaseJavaIdentifierTransformer ( ) ; public static final JavaIdentifierTransformer NOOP = new NoopJavaIdentifierTransformer ( ) ; public static final JavaIdentifierTransformer STRICT = new StrictJavaIdentifierTransformer ( ) ; public static final JavaIdentifierTransformer UNDERSCORE = new UnderscoreJavaIdentifierTransformer ( ) ; public static final JavaIdentifierTransformer WHITESPACE = new WhiteSpaceJavaIdentifierTransformer ( ) ; public abstract String transformToJavaIdentifier ( String str ) ; protected final String shaveOffNonJavaIdentifierStartChars ( String str ) { String str2 = str ; boolean ready = false ; while ( ! ready ) { if ( ! Character . isJavaIdentifierStart ( str2 . charAt ( <NUM_LIT:0> ) ) ) { str2 = str2 . substring ( <NUM_LIT:1> ) ; if ( str2 . length ( ) == <NUM_LIT:0> ) { throw new JSONException ( "<STR_LIT>" + str + "<STR_LIT>" ) ; } } else { ready = true ; } } return str2 ; } private static final class CamelCaseJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier ( String str ) { if ( str == null ) { return null ; } String str2 = shaveOffNonJavaIdentifierStartChars ( str ) ; char [ ] chars = str2 . toCharArray ( ) ; int pos = <NUM_LIT:0> ; StringBuffer buf = new StringBuffer ( ) ; boolean toUpperCaseNextChar = false ; while ( pos < chars . length ) { if ( ! Character . isJavaIdentifierPart ( chars [ pos ] ) || Character . isWhitespace ( chars [ pos ] ) ) { toUpperCaseNextChar = true ; } else { if ( toUpperCaseNextChar ) { buf . append ( Character . toUpperCase ( chars [ pos ] ) ) ; toUpperCaseNextChar = false ; } else { buf . append ( chars [ pos ] ) ; } } pos ++ ; } return buf . toString ( ) ; } } private static final class NoopJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier ( String str ) { return str ; } } private static final class StrictJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier ( String str ) { throw new JSONException ( "<STR_LIT:'>" + str + "<STR_LIT>" ) ; } } private static final class UnderscoreJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier ( String str ) { if ( str == null ) { return null ; } String str2 = shaveOffNonJavaIdentifierStartChars ( str ) ; char [ ] chars = str2 . toCharArray ( ) ; int pos = <NUM_LIT:0> ; StringBuffer buf = new StringBuffer ( ) ; boolean toUnderScorePreviousChar = false ; while ( pos < chars . length ) { if ( ! Character . isJavaIdentifierPart ( chars [ pos ] ) || Character . isWhitespace ( chars [ pos ] ) ) { toUnderScorePreviousChar = true ; } else { if ( toUnderScorePreviousChar ) { buf . append ( "<STR_LIT:_>" ) ; toUnderScorePreviousChar = false ; } buf . append ( chars [ pos ] ) ; } pos ++ ; } if ( buf . charAt ( buf . length ( ) - <NUM_LIT:1> ) == '<CHAR_LIT:_>' ) { buf . deleteCharAt ( buf . length ( ) - <NUM_LIT:1> ) ; } return buf . toString ( ) ; } } private static final class WhiteSpaceJavaIdentifierTransformer extends JavaIdentifierTransformer { public String transformToJavaIdentifier ( String str ) { if ( str == null ) { return null ; } String str2 = shaveOffNonJavaIdentifierStartChars ( str ) ; str2 = StringUtils . deleteWhitespace ( str2 ) ; char [ ] chars = str2 . toCharArray ( ) ; int pos = <NUM_LIT:0> ; StringBuffer buf = new StringBuffer ( ) ; while ( pos < chars . length ) { if ( Character . isJavaIdentifierPart ( chars [ pos ] ) ) { buf . append ( chars [ pos ] ) ; } pos ++ ; } return buf . toString ( ) ; } } } </s>
<s> package net . sf . json . util ; import java . io . StringWriter ; public class JSONStringer extends JSONBuilder { public JSONStringer ( ) { super ( new StringWriter ( ) ) ; } public String toString ( ) { return this . mode == '<CHAR_LIT>' ? this . writer . toString ( ) : null ; } } </s>
<s> package net . sf . json . util ; import java . util . Iterator ; import net . sf . json . JSON ; import net . sf . json . JSONArray ; import net . sf . json . JSONNull ; import net . sf . json . JSONObject ; public class WebUtils { private static final WebHijackPreventionStrategy DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY = WebHijackPreventionStrategy . INFINITE_LOOP ; private static WebHijackPreventionStrategy webHijackPreventionStrategy = DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY ; public static WebHijackPreventionStrategy getWebHijackPreventionStrategy ( ) { return webHijackPreventionStrategy ; } public static String protect ( JSON json ) { return protect ( json , false ) ; } public static String protect ( JSON json , boolean shrink ) { String output = ! shrink ? json . toString ( <NUM_LIT:0> ) : toString ( json ) ; return webHijackPreventionStrategy . protect ( output ) ; } public static void setWebHijackPreventionStrategy ( WebHijackPreventionStrategy strategy ) { webHijackPreventionStrategy = strategy == null ? DEFAULT_WEB_HIJACK_PREVENTION_STRATEGY : strategy ; } public static String toString ( JSON json ) { if ( json instanceof JSONObject ) { return toString ( ( JSONObject ) json ) ; } else if ( json instanceof JSONArray ) { return toString ( ( JSONArray ) json ) ; } else { return toString ( ( JSONNull ) json ) ; } } private static String join ( JSONArray jsonArray ) { int len = jsonArray . size ( ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = <NUM_LIT:0> ; i < len ; i += <NUM_LIT:1> ) { if ( i > <NUM_LIT:0> ) { sb . append ( "<STR_LIT:U+002C>" ) ; } Object value = jsonArray . get ( i ) ; sb . append ( toString ( value ) ) ; } return sb . toString ( ) ; } private static String quote ( String str ) { if ( str . indexOf ( "<STR_LIT:U+0020>" ) > - <NUM_LIT:1> || str . indexOf ( "<STR_LIT::>" ) > - <NUM_LIT:1> ) { return JSONUtils . quote ( str ) ; } else { return str ; } } private static String toString ( JSONArray jsonArray ) { try { return '<CHAR_LIT:[>' + join ( jsonArray ) + '<CHAR_LIT:]>' ; } catch ( Exception e ) { return null ; } } private static String toString ( JSONNull jsonNull ) { return jsonNull . toString ( ) ; } private static String toString ( JSONObject jsonObject ) { if ( jsonObject . isNullObject ( ) ) { return JSONNull . getInstance ( ) . toString ( ) ; } Iterator keys = jsonObject . keys ( ) ; StringBuffer sb = new StringBuffer ( "<STR_LIT:{>" ) ; while ( keys . hasNext ( ) ) { if ( sb . length ( ) > <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+002C>' ) ; } Object o = keys . next ( ) ; sb . append ( quote ( o . toString ( ) ) ) ; sb . append ( '<CHAR_LIT::>' ) ; sb . append ( toString ( jsonObject . get ( String . valueOf ( o ) ) ) ) ; } sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } private static String toString ( Object object ) { if ( object instanceof JSON ) { return toString ( ( JSON ) object ) ; } else { return JSONUtils . valueToString ( object ) ; } } private WebUtils ( ) { } } </s>
<s> package net . sf . json . util ; import net . sf . json . JSONArray ; import net . sf . json . JSONException ; import net . sf . json . JSONNull ; import net . sf . json . JSONObject ; import net . sf . json . JsonConfig ; import net . sf . json . regexp . RegexpUtils ; import org . apache . commons . lang . math . NumberUtils ; public class JSONTokener { public static int dehexchar ( char c ) { if ( c >= '<CHAR_LIT:0>' && c <= '<CHAR_LIT:9>' ) { return c - '<CHAR_LIT:0>' ; } if ( c >= '<CHAR_LIT:A>' && c <= '<CHAR_LIT>' ) { return c - ( '<CHAR_LIT:A>' - <NUM_LIT:10> ) ; } if ( c >= '<CHAR_LIT:a>' && c <= '<CHAR_LIT>' ) { return c - ( '<CHAR_LIT:a>' - <NUM_LIT:10> ) ; } return - <NUM_LIT:1> ; } private int myIndex ; private String mySource ; public JSONTokener ( String s ) { this . myIndex = <NUM_LIT:0> ; if ( s != null ) { s = s . trim ( ) ; } else { s = "<STR_LIT>" ; } if ( s . length ( ) > <NUM_LIT:0> ) { char first = s . charAt ( <NUM_LIT:0> ) ; char last = s . charAt ( s . length ( ) - <NUM_LIT:1> ) ; if ( first == '<CHAR_LIT:[>' && last != '<CHAR_LIT:]>' ) { throw syntaxError ( "<STR_LIT>" ) ; } if ( first == '<CHAR_LIT>' && last != '<CHAR_LIT:}>' ) { throw syntaxError ( "<STR_LIT>" ) ; } } this . mySource = s ; } public void back ( ) { if ( this . myIndex > <NUM_LIT:0> ) { this . myIndex -= <NUM_LIT:1> ; } } public int length ( ) { if ( this . mySource == null ) { return <NUM_LIT:0> ; } return this . mySource . length ( ) ; } public boolean matches ( String pattern ) { String str = this . mySource . substring ( this . myIndex ) ; return RegexpUtils . getMatcher ( pattern ) . matches ( str ) ; } public boolean more ( ) { return this . myIndex < this . mySource . length ( ) ; } public char next ( ) { if ( more ( ) ) { char c = this . mySource . charAt ( this . myIndex ) ; this . myIndex += <NUM_LIT:1> ; return c ; } return <NUM_LIT:0> ; } public char next ( char c ) { char n = next ( ) ; if ( n != c ) { throw syntaxError ( "<STR_LIT>" + c + "<STR_LIT>" + n + "<STR_LIT>" ) ; } return n ; } public String next ( int n ) { int i = this . myIndex ; int j = i + n ; if ( j >= this . mySource . length ( ) ) { throw syntaxError ( "<STR_LIT>" ) ; } this . myIndex += n ; return this . mySource . substring ( i , j ) ; } public char nextClean ( ) { for ( ; ; ) { char c = next ( ) ; if ( c == '<CHAR_LIT:/>' ) { switch ( next ( ) ) { case '<CHAR_LIT:/>' : do { c = next ( ) ; } while ( c != '<STR_LIT:\n>' && c != '<STR_LIT>' && c != <NUM_LIT:0> ) ; break ; case '<CHAR_LIT>' : for ( ; ; ) { c = next ( ) ; if ( c == <NUM_LIT:0> ) { throw syntaxError ( "<STR_LIT>" ) ; } if ( c == '<CHAR_LIT>' ) { if ( next ( ) == '<CHAR_LIT:/>' ) { break ; } back ( ) ; } } break ; default : back ( ) ; return '<CHAR_LIT:/>' ; } } else if ( c == '<CHAR_LIT>' ) { do { c = next ( ) ; } while ( c != '<STR_LIT:\n>' && c != '<STR_LIT>' && c != <NUM_LIT:0> ) ; } else if ( c == <NUM_LIT:0> || c > '<CHAR_LIT:U+0020>' ) { return c ; } } } public String nextString ( char quote ) { char c ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; switch ( c ) { case <NUM_LIT:0> : case '<STR_LIT:\n>' : case '<STR_LIT>' : throw syntaxError ( "<STR_LIT>" ) ; case '<STR_LIT:\\>' : c = next ( ) ; switch ( c ) { case '<CHAR_LIT:b>' : sb . append ( '<STR_LIT>' ) ; break ; case '<CHAR_LIT>' : sb . append ( '<STR_LIT:\t>' ) ; break ; case '<CHAR_LIT>' : sb . append ( '<STR_LIT:\n>' ) ; break ; case '<CHAR_LIT>' : sb . append ( '<STR_LIT>' ) ; break ; case '<CHAR_LIT>' : sb . append ( '<STR_LIT>' ) ; break ; case '<CHAR_LIT>' : sb . append ( ( char ) Integer . parseInt ( next ( <NUM_LIT:4> ) , <NUM_LIT:16> ) ) ; break ; case '<CHAR_LIT>' : sb . append ( ( char ) Integer . parseInt ( next ( <NUM_LIT:2> ) , <NUM_LIT:16> ) ) ; break ; default : sb . append ( c ) ; } break ; default : if ( c == quote ) { return sb . toString ( ) ; } sb . append ( c ) ; } } } public String nextTo ( char d ) { StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { char c = next ( ) ; if ( c == d || c == <NUM_LIT:0> || c == '<STR_LIT:\n>' || c == '<STR_LIT>' ) { if ( c != <NUM_LIT:0> ) { back ( ) ; } return sb . toString ( ) . trim ( ) ; } sb . append ( c ) ; } } public String nextTo ( String delimiters ) { char c ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; if ( delimiters . indexOf ( c ) >= <NUM_LIT:0> || c == <NUM_LIT:0> || c == '<STR_LIT:\n>' || c == '<STR_LIT>' ) { if ( c != <NUM_LIT:0> ) { back ( ) ; } return sb . toString ( ) . trim ( ) ; } sb . append ( c ) ; } } public Object nextValue ( ) { return nextValue ( new JsonConfig ( ) ) ; } public Object nextValue ( JsonConfig jsonConfig ) { char c = nextClean ( ) ; String s ; switch ( c ) { case '<CHAR_LIT:">' : case '<STR_LIT>' : return nextString ( c ) ; case '<CHAR_LIT>' : back ( ) ; return JSONObject . fromObject ( this , jsonConfig ) ; case '<CHAR_LIT:[>' : back ( ) ; return JSONArray . fromObject ( this , jsonConfig ) ; default : } StringBuffer sb = new StringBuffer ( ) ; char b = c ; while ( c >= '<CHAR_LIT:U+0020>' && "<STR_LIT>" . indexOf ( c ) < <NUM_LIT:0> ) { sb . append ( c ) ; c = next ( ) ; } back ( ) ; s = sb . toString ( ) . trim ( ) ; if ( s . equals ( "<STR_LIT>" ) ) { throw syntaxError ( "<STR_LIT>" ) ; } if ( s . equalsIgnoreCase ( "<STR_LIT:true>" ) ) { return Boolean . TRUE ; } if ( s . equalsIgnoreCase ( "<STR_LIT:false>" ) ) { return Boolean . FALSE ; } if ( s . equals ( "<STR_LIT:null>" ) || ( jsonConfig . isJavascriptCompliant ( ) && s . equals ( "<STR_LIT>" ) ) ) { return JSONNull . getInstance ( ) ; } if ( ( b >= '<CHAR_LIT:0>' && b <= '<CHAR_LIT:9>' ) || b == '<CHAR_LIT:.>' || b == '<CHAR_LIT:->' || b == '<CHAR_LIT>' ) { if ( b == '<CHAR_LIT:0>' ) { if ( s . length ( ) > <NUM_LIT:2> && ( s . charAt ( <NUM_LIT:1> ) == '<CHAR_LIT>' || s . charAt ( <NUM_LIT:1> ) == '<CHAR_LIT>' ) ) { try { return new Integer ( Integer . parseInt ( s . substring ( <NUM_LIT:2> ) , <NUM_LIT:16> ) ) ; } catch ( Exception e ) { } } else { try { return new Integer ( Integer . parseInt ( s , <NUM_LIT:8> ) ) ; } catch ( Exception e ) { } } } try { return NumberUtils . createNumber ( s ) ; } catch ( Exception e ) { return s ; } } if ( JSONUtils . isFunctionHeader ( s ) || JSONUtils . isFunction ( s ) ) { return s ; } switch ( peek ( ) ) { case '<CHAR_LIT:U+002C>' : case '<CHAR_LIT:}>' : case '<CHAR_LIT>' : case '<CHAR_LIT:[>' : case '<CHAR_LIT:]>' : throw new JSONException ( "<STR_LIT>" + s + "<STR_LIT:'>" ) ; } return s ; } public char peek ( ) { if ( more ( ) ) { char c = this . mySource . charAt ( this . myIndex ) ; return c ; } return <NUM_LIT:0> ; } public void reset ( ) { this . myIndex = <NUM_LIT:0> ; } public void skipPast ( String to ) { this . myIndex = this . mySource . indexOf ( to , this . myIndex ) ; if ( this . myIndex < <NUM_LIT:0> ) { this . myIndex = this . mySource . length ( ) ; } else { this . myIndex += to . length ( ) ; } } public char skipTo ( char to ) { char c ; int index = this . myIndex ; do { c = next ( ) ; if ( c == <NUM_LIT:0> ) { this . myIndex = index ; return c ; } } while ( c != to ) ; back ( ) ; return c ; } public JSONException syntaxError ( String message ) { return new JSONException ( message + toString ( ) ) ; } public String toString ( ) { return "<STR_LIT>" + this . myIndex + "<STR_LIT>" + this . mySource ; } } </s>
<s> package net . sf . json . util ; public abstract class WebHijackPreventionStrategy { public static final WebHijackPreventionStrategy COMMENTS = new CommentWebHijackPreventionStrategy ( ) ; public static final WebHijackPreventionStrategy INFINITE_LOOP = new InfiniteLoopWebHijackPreventionStrategy ( ) ; public abstract String protect ( String str ) ; private static final class CommentWebHijackPreventionStrategy extends WebHijackPreventionStrategy { public String protect ( String str ) { return "<STR_LIT>" + str + "<STR_LIT>" ; } } private static final class InfiniteLoopWebHijackPreventionStrategy extends WebHijackPreventionStrategy { public String protect ( String str ) { return "<STR_LIT>" + str ; } } } </s>
<s> package net . sf . json ; import java . io . IOException ; import java . io . Writer ; import java . lang . reflect . Array ; import java . util . ArrayList ; import java . util . Collection ; import java . util . ConcurrentModificationException ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . ListIterator ; import java . util . Map ; import java . util . NoSuchElementException ; import java . util . Set ; import net . sf . ezmorph . Morpher ; import net . sf . ezmorph . object . IdentityObjectMorpher ; import net . sf . json . processors . JsonValueProcessor ; import net . sf . json . processors . JsonVerifier ; import net . sf . json . util . JSONTokener ; import net . sf . json . util . JSONUtils ; import org . apache . commons . lang . StringUtils ; public final class JSONArray extends AbstractJSON implements JSON , List , Comparable { public static JSONArray fromObject ( Object object ) { return fromObject ( object , new JsonConfig ( ) ) ; } public static JSONArray fromObject ( Object object , JsonConfig jsonConfig ) { if ( object instanceof JSONString ) { return _fromJSONString ( ( JSONString ) object , jsonConfig ) ; } else if ( object instanceof JSONArray ) { return _fromJSONArray ( ( JSONArray ) object , jsonConfig ) ; } else if ( object instanceof Collection ) { return _fromCollection ( ( Collection ) object , jsonConfig ) ; } else if ( object instanceof JSONTokener ) { return _fromJSONTokener ( ( JSONTokener ) object , jsonConfig ) ; } else if ( object instanceof String ) { return _fromString ( ( String ) object , jsonConfig ) ; } else if ( object != null && object . getClass ( ) . isArray ( ) ) { Class type = object . getClass ( ) . getComponentType ( ) ; if ( ! type . isPrimitive ( ) ) { return _fromArray ( ( Object [ ] ) object , jsonConfig ) ; } else { if ( type == Boolean . TYPE ) { return _fromArray ( ( boolean [ ] ) object , jsonConfig ) ; } else if ( type == Byte . TYPE ) { return _fromArray ( ( byte [ ] ) object , jsonConfig ) ; } else if ( type == Short . TYPE ) { return _fromArray ( ( short [ ] ) object , jsonConfig ) ; } else if ( type == Integer . TYPE ) { return _fromArray ( ( int [ ] ) object , jsonConfig ) ; } else if ( type == Long . TYPE ) { return _fromArray ( ( long [ ] ) object , jsonConfig ) ; } else if ( type == Float . TYPE ) { return _fromArray ( ( float [ ] ) object , jsonConfig ) ; } else if ( type == Double . TYPE ) { return _fromArray ( ( double [ ] ) object , jsonConfig ) ; } else if ( type == Character . TYPE ) { return _fromArray ( ( char [ ] ) object , jsonConfig ) ; } else { throw new JSONException ( "<STR_LIT>" ) ; } } } else if ( JSONUtils . isBoolean ( object ) || JSONUtils . isFunction ( object ) || JSONUtils . isNumber ( object ) || JSONUtils . isNull ( object ) || JSONUtils . isString ( object ) || object instanceof JSON ) { fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) . element ( object , jsonConfig ) ; fireElementAddedEvent ( <NUM_LIT:0> , jsonArray . get ( <NUM_LIT:0> ) , jsonConfig ) ; fireArrayStartEvent ( jsonConfig ) ; return jsonArray ; } else if ( JSONUtils . isObject ( object ) ) { fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) . element ( JSONObject . fromObject ( object , jsonConfig ) ) ; fireElementAddedEvent ( <NUM_LIT:0> , jsonArray . get ( <NUM_LIT:0> ) , jsonConfig ) ; fireArrayStartEvent ( jsonConfig ) ; return jsonArray ; } else { throw new JSONException ( "<STR_LIT>" ) ; } } public static int [ ] getDimensions ( JSONArray jsonArray ) { if ( jsonArray == null || jsonArray . isEmpty ( ) ) { return new int [ ] { <NUM_LIT:0> } ; } List dims = new ArrayList ( ) ; processArrayDimensions ( jsonArray , dims , <NUM_LIT:0> ) ; int [ ] dimensions = new int [ dims . size ( ) ] ; int j = <NUM_LIT:0> ; for ( Iterator i = dims . iterator ( ) ; i . hasNext ( ) ; ) { dimensions [ j ++ ] = ( ( Integer ) i . next ( ) ) . intValue ( ) ; } return dimensions ; } public static Object toArray ( JSONArray jsonArray ) { return toArray ( jsonArray , new JsonConfig ( ) ) ; } public static Object toArray ( JSONArray jsonArray , Class objectClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; return toArray ( jsonArray , jsonConfig ) ; } public static Object toArray ( JSONArray jsonArray , Class objectClass , Map classMap ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; jsonConfig . setClassMap ( classMap ) ; return toArray ( jsonArray , jsonConfig ) ; } public static Object toArray ( JSONArray jsonArray , JsonConfig jsonConfig ) { Class objectClass = jsonConfig . getRootClass ( ) ; Map classMap = jsonConfig . getClassMap ( ) ; if ( jsonArray . size ( ) == <NUM_LIT:0> ) { return Array . newInstance ( objectClass == null ? Object . class : objectClass , <NUM_LIT:0> ) ; } int [ ] dimensions = JSONArray . getDimensions ( jsonArray ) ; Object array = Array . newInstance ( objectClass == null ? Object . class : objectClass , dimensions ) ; int size = jsonArray . size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { Object value = jsonArray . get ( i ) ; if ( JSONUtils . isNull ( value ) ) { Array . set ( array , i , null ) ; } else { Class type = value . getClass ( ) ; if ( JSONArray . class . isAssignableFrom ( type ) ) { Array . set ( array , i , toArray ( ( JSONArray ) value , objectClass , classMap ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( objectClass != null && ! objectClass . isAssignableFrom ( type ) ) { value = JSONUtils . getMorpherRegistry ( ) . morph ( objectClass , value ) ; } Array . set ( array , i , value ) ; } else if ( JSONUtils . isNumber ( type ) ) { if ( objectClass != null && ( Byte . class . isAssignableFrom ( objectClass ) || Byte . TYPE . isAssignableFrom ( objectClass ) ) ) { Array . set ( array , i , Byte . valueOf ( String . valueOf ( value ) ) ) ; } else if ( objectClass != null && ( Short . class . isAssignableFrom ( objectClass ) || Short . TYPE . isAssignableFrom ( objectClass ) ) ) { Array . set ( array , i , Short . valueOf ( String . valueOf ( value ) ) ) ; } else { Array . set ( array , i , value ) ; } } else { if ( objectClass != null ) { JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( objectClass ) ; jsc . setClassMap ( classMap ) ; Array . set ( array , i , JSONObject . toBean ( ( JSONObject ) value , jsc ) ) ; } else { Array . set ( array , i , JSONObject . toBean ( ( JSONObject ) value ) ) ; } } } } return array ; } public static Object toArray ( JSONArray jsonArray , Object root , JsonConfig jsonConfig ) { Class objectClass = root . getClass ( ) ; if ( jsonArray . size ( ) == <NUM_LIT:0> ) { return Array . newInstance ( objectClass , <NUM_LIT:0> ) ; } int [ ] dimensions = JSONArray . getDimensions ( jsonArray ) ; Object array = Array . newInstance ( objectClass == null ? Object . class : objectClass , dimensions ) ; int size = jsonArray . size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { Object value = jsonArray . get ( i ) ; if ( JSONUtils . isNull ( value ) ) { Array . set ( array , i , null ) ; } else { Class type = value . getClass ( ) ; if ( JSONArray . class . isAssignableFrom ( type ) ) { Array . set ( array , i , toArray ( ( JSONArray ) value , root , jsonConfig ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || JSONUtils . isNumber ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( objectClass != null && ! objectClass . isAssignableFrom ( type ) ) { value = JSONUtils . getMorpherRegistry ( ) . morph ( objectClass , value ) ; } Array . set ( array , i , value ) ; } else { try { Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( root . getClass ( ) , null ) ; Array . set ( array , i , JSONObject . toBean ( ( JSONObject ) value , newRoot , jsonConfig ) ) ; } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( e ) ; } } } } return array ; } public static Collection toCollection ( JSONArray jsonArray ) { return toCollection ( jsonArray , new JsonConfig ( ) ) ; } public static Collection toCollection ( JSONArray jsonArray , Class objectClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; return toCollection ( jsonArray , jsonConfig ) ; } public static Collection toCollection ( JSONArray jsonArray , JsonConfig jsonConfig ) { Collection collection = null ; Class collectionType = jsonConfig . getCollectionType ( ) ; if ( collectionType . isInterface ( ) ) { if ( collectionType . equals ( List . class ) ) { collection = new ArrayList ( ) ; } else if ( collectionType . equals ( Set . class ) ) { collection = new HashSet ( ) ; } else { throw new JSONException ( "<STR_LIT>" + collectionType ) ; } } else { try { collection = ( Collection ) collectionType . newInstance ( ) ; } catch ( InstantiationException e ) { throw new JSONException ( e ) ; } catch ( IllegalAccessException e ) { throw new JSONException ( e ) ; } } Class objectClass = jsonConfig . getRootClass ( ) ; Map classMap = jsonConfig . getClassMap ( ) ; int size = jsonArray . size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { Object value = jsonArray . get ( i ) ; if ( JSONUtils . isNull ( value ) ) { collection . add ( null ) ; } else { Class type = value . getClass ( ) ; if ( JSONArray . class . isAssignableFrom ( value . getClass ( ) ) ) { collection . add ( toCollection ( ( JSONArray ) value , jsonConfig ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || JSONUtils . isNumber ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( objectClass != null && ! objectClass . isAssignableFrom ( type ) ) { value = JSONUtils . getMorpherRegistry ( ) . morph ( objectClass , value ) ; } collection . add ( value ) ; } else { if ( objectClass != null ) { JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( objectClass ) ; jsc . setClassMap ( classMap ) ; collection . add ( JSONObject . toBean ( ( JSONObject ) value , jsc ) ) ; } else { collection . add ( JSONObject . toBean ( ( JSONObject ) value ) ) ; } } } } return collection ; } public static List toList ( JSONArray jsonArray ) { return toList ( jsonArray , new JsonConfig ( ) ) ; } public static List toList ( JSONArray jsonArray , Class objectClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; return toList ( jsonArray , jsonConfig ) ; } public static List toList ( JSONArray jsonArray , Class objectClass , Map classMap ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; jsonConfig . setClassMap ( classMap ) ; return toList ( jsonArray , jsonConfig ) ; } public static List toList ( JSONArray jsonArray , JsonConfig jsonConfig ) { if ( jsonArray . size ( ) == <NUM_LIT:0> ) { return new ArrayList ( ) ; } Class objectClass = jsonConfig . getRootClass ( ) ; Map classMap = jsonConfig . getClassMap ( ) ; List list = new ArrayList ( ) ; int size = jsonArray . size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { Object value = jsonArray . get ( i ) ; if ( JSONUtils . isNull ( value ) ) { list . add ( null ) ; } else { Class type = value . getClass ( ) ; if ( JSONArray . class . isAssignableFrom ( type ) ) { list . add ( toList ( ( JSONArray ) value , objectClass , classMap ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || JSONUtils . isNumber ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( objectClass != null && ! objectClass . isAssignableFrom ( type ) ) { value = JSONUtils . getMorpherRegistry ( ) . morph ( objectClass , value ) ; } list . add ( value ) ; } else { if ( objectClass != null ) { JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( objectClass ) ; jsc . setClassMap ( classMap ) ; list . add ( JSONObject . toBean ( ( JSONObject ) value , jsc ) ) ; } else { list . add ( JSONObject . toBean ( ( JSONObject ) value ) ) ; } } } } return list ; } public static List toList ( JSONArray jsonArray , Object root , JsonConfig jsonConfig ) { if ( jsonArray . size ( ) == <NUM_LIT:0> || root == null ) { return new ArrayList ( ) ; } List list = new ArrayList ( ) ; int size = jsonArray . size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { Object value = jsonArray . get ( i ) ; if ( JSONUtils . isNull ( value ) ) { list . add ( null ) ; } else { Class type = value . getClass ( ) ; if ( JSONArray . class . isAssignableFrom ( type ) ) { list . add ( toList ( ( JSONArray ) value , root , jsonConfig ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || JSONUtils . isNumber ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { list . add ( value ) ; } else { try { Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( root . getClass ( ) , null ) ; list . add ( JSONObject . toBean ( ( JSONObject ) value , newRoot , jsonConfig ) ) ; } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( e ) ; } } } } return list ; } private static JSONArray _fromArray ( boolean [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Boolean b = array [ i ] ? Boolean . TRUE : Boolean . FALSE ; jsonArray . addValue ( b , jsonConfig ) ; fireElementAddedEvent ( i , b , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( byte [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Number n = JSONUtils . transformNumber ( new Byte ( array [ i ] ) ) ; jsonArray . addValue ( n , jsonConfig ) ; fireElementAddedEvent ( i , n , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( char [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Character c = new Character ( array [ i ] ) ; jsonArray . addValue ( c , jsonConfig ) ; fireElementAddedEvent ( i , c , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( double [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; try { for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Double d = new Double ( array [ i ] ) ; JSONUtils . testValidity ( d ) ; jsonArray . addValue ( d , jsonConfig ) ; fireElementAddedEvent ( i , d , jsonConfig ) ; } } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( float [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; try { for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Float f = new Float ( array [ i ] ) ; JSONUtils . testValidity ( f ) ; jsonArray . addValue ( f , jsonConfig ) ; fireElementAddedEvent ( i , f , jsonConfig ) ; } } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( int [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Number n = new Integer ( array [ i ] ) ; jsonArray . addValue ( n , jsonConfig ) ; fireElementAddedEvent ( i , n , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( long [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Number n = JSONUtils . transformNumber ( new Long ( array [ i ] ) ) ; jsonArray . addValue ( n , jsonConfig ) ; fireElementAddedEvent ( i , n , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( Object [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; try { for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Object element = array [ i ] ; jsonArray . addValue ( element , jsonConfig ) ; fireElementAddedEvent ( i , jsonArray . get ( i ) , jsonConfig ) ; } } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromArray ( short [ ] array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ; i ++ ) { Number n = JSONUtils . transformNumber ( new Short ( array [ i ] ) ) ; jsonArray . addValue ( n , jsonConfig ) ; fireElementAddedEvent ( i , n , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromCollection ( Collection collection , JsonConfig jsonConfig ) { if ( ! addInstance ( collection ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( collection ) ; } catch ( JSONException jsone ) { removeInstance ( collection ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( collection ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; try { int i = <NUM_LIT:0> ; for ( Iterator elements = collection . iterator ( ) ; elements . hasNext ( ) ; ) { Object element = elements . next ( ) ; jsonArray . addValue ( element , jsonConfig ) ; fireElementAddedEvent ( i , jsonArray . get ( i ++ ) , jsonConfig ) ; } } catch ( JSONException jsone ) { removeInstance ( collection ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( collection ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( collection ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromJSONArray ( JSONArray array , JsonConfig jsonConfig ) { if ( ! addInstance ( array ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( array ) ; } catch ( JSONException jsone ) { removeInstance ( array ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( array ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; int index = <NUM_LIT:0> ; for ( Iterator elements = array . iterator ( ) ; elements . hasNext ( ) ; ) { Object element = elements . next ( ) ; jsonArray . addValue ( element , jsonConfig ) ; fireElementAddedEvent ( index ++ , element , jsonConfig ) ; } removeInstance ( array ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } private static JSONArray _fromJSONString ( JSONString string , JsonConfig jsonConfig ) { return _fromJSONTokener ( new JSONTokener ( string . toJSONString ( ) ) , jsonConfig ) ; } private static JSONArray _fromJSONTokener ( JSONTokener tokener , JsonConfig jsonConfig ) { JSONArray jsonArray = new JSONArray ( ) ; int index = <NUM_LIT:0> ; try { if ( tokener . nextClean ( ) != '<CHAR_LIT:[>' ) { throw tokener . syntaxError ( "<STR_LIT>" ) ; } fireArrayStartEvent ( jsonConfig ) ; if ( tokener . nextClean ( ) == '<CHAR_LIT:]>' ) { fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } tokener . back ( ) ; for ( ; ; ) { if ( tokener . nextClean ( ) == '<CHAR_LIT:U+002C>' ) { tokener . back ( ) ; jsonArray . elements . add ( JSONNull . getInstance ( ) ) ; fireElementAddedEvent ( index , jsonArray . get ( index ++ ) , jsonConfig ) ; } else { tokener . back ( ) ; Object v = tokener . nextValue ( jsonConfig ) ; if ( ! JSONUtils . isFunctionHeader ( v ) ) { if ( v instanceof String && JSONUtils . mayBeJSON ( ( String ) v ) ) { jsonArray . addValue ( JSONUtils . DOUBLE_QUOTE + v + JSONUtils . DOUBLE_QUOTE , jsonConfig ) ; } else { jsonArray . addValue ( v , jsonConfig ) ; } fireElementAddedEvent ( index , jsonArray . get ( index ++ ) , jsonConfig ) ; } else { String params = JSONUtils . getFunctionParams ( ( String ) v ) ; int i = <NUM_LIT:0> ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { char ch = tokener . next ( ) ; if ( ch == <NUM_LIT:0> ) { break ; } if ( ch == '<CHAR_LIT>' ) { i ++ ; } if ( ch == '<CHAR_LIT:}>' ) { i -- ; } sb . append ( ch ) ; if ( i == <NUM_LIT:0> ) { break ; } } if ( i != <NUM_LIT:0> ) { throw tokener . syntaxError ( "<STR_LIT>" + v ) ; } String text = sb . toString ( ) ; text = text . substring ( <NUM_LIT:1> , text . length ( ) - <NUM_LIT:1> ) . trim ( ) ; jsonArray . addValue ( new JSONFunction ( ( params != null ) ? StringUtils . split ( params , "<STR_LIT:U+002C>" ) : null , text ) , jsonConfig ) ; fireElementAddedEvent ( index , jsonArray . get ( index ++ ) , jsonConfig ) ; } } switch ( tokener . nextClean ( ) ) { case '<CHAR_LIT:;>' : case '<CHAR_LIT:U+002C>' : if ( tokener . nextClean ( ) == '<CHAR_LIT:]>' ) { fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; } tokener . back ( ) ; break ; case '<CHAR_LIT:]>' : fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; default : throw tokener . syntaxError ( "<STR_LIT>" ) ; } } } catch ( JSONException jsone ) { fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } private static JSONArray _fromString ( String string , JsonConfig jsonConfig ) { return _fromJSONTokener ( new JSONTokener ( string ) , jsonConfig ) ; } private static void processArrayDimensions ( JSONArray jsonArray , List dims , int index ) { if ( dims . size ( ) <= index ) { dims . add ( new Integer ( jsonArray . size ( ) ) ) ; } else { int i = ( ( Integer ) dims . get ( index ) ) . intValue ( ) ; if ( jsonArray . size ( ) > i ) { dims . set ( index , new Integer ( jsonArray . size ( ) ) ) ; } } for ( Iterator i = jsonArray . iterator ( ) ; i . hasNext ( ) ; ) { Object item = i . next ( ) ; if ( item instanceof JSONArray ) { processArrayDimensions ( ( JSONArray ) item , dims , index + <NUM_LIT:1> ) ; } } } private List elements ; private boolean expandElements ; public JSONArray ( ) { this . elements = new ArrayList ( ) ; } public void add ( int index , Object value ) { add ( index , value , new JsonConfig ( ) ) ; } public void add ( int index , Object value , JsonConfig jsonConfig ) { this . elements . add ( index , processValue ( value , jsonConfig ) ) ; } public boolean add ( Object value ) { return add ( value , new JsonConfig ( ) ) ; } public boolean add ( Object value , JsonConfig jsonConfig ) { element ( value , jsonConfig ) ; return true ; } public boolean addAll ( Collection collection ) { return addAll ( collection , new JsonConfig ( ) ) ; } public boolean addAll ( Collection collection , JsonConfig jsonConfig ) { if ( collection == null || collection . size ( ) == <NUM_LIT:0> ) { return false ; } for ( Iterator i = collection . iterator ( ) ; i . hasNext ( ) ; ) { element ( i . next ( ) , jsonConfig ) ; } return true ; } public boolean addAll ( int index , Collection collection ) { return addAll ( index , collection , new JsonConfig ( ) ) ; } public boolean addAll ( int index , Collection collection , JsonConfig jsonConfig ) { if ( collection == null || collection . size ( ) == <NUM_LIT:0> ) { return false ; } int offset = <NUM_LIT:0> ; for ( Iterator i = collection . iterator ( ) ; i . hasNext ( ) ; ) { this . elements . add ( index + ( offset ++ ) , processValue ( i . next ( ) , jsonConfig ) ) ; } return true ; } public void clear ( ) { elements . clear ( ) ; } public int compareTo ( Object obj ) { if ( obj != null && ( obj instanceof JSONArray ) ) { JSONArray other = ( JSONArray ) obj ; int size1 = size ( ) ; int size2 = other . size ( ) ; if ( size1 < size2 ) { return - <NUM_LIT:1> ; } else if ( size1 > size2 ) { return <NUM_LIT:1> ; } else if ( this . equals ( other ) ) { return <NUM_LIT:0> ; } } return - <NUM_LIT:1> ; } public boolean contains ( Object o ) { return contains ( o , new JsonConfig ( ) ) ; } public boolean contains ( Object o , JsonConfig jsonConfig ) { return elements . contains ( processValue ( o , jsonConfig ) ) ; } public boolean containsAll ( Collection collection ) { return containsAll ( collection , new JsonConfig ( ) ) ; } public boolean containsAll ( Collection collection , JsonConfig jsonConfig ) { return elements . containsAll ( fromObject ( collection , jsonConfig ) ) ; } public JSONArray discard ( int index ) { elements . remove ( index ) ; return this ; } public JSONArray discard ( Object o ) { elements . remove ( o ) ; return this ; } public JSONArray element ( boolean value ) { return element ( value ? Boolean . TRUE : Boolean . FALSE ) ; } public JSONArray element ( Collection value ) { return element ( value , new JsonConfig ( ) ) ; } public JSONArray element ( Collection value , JsonConfig jsonConfig ) { if ( value instanceof JSONArray ) { elements . add ( value ) ; return this ; } else { return element ( _fromCollection ( value , jsonConfig ) ) ; } } public JSONArray element ( double value ) { Double d = new Double ( value ) ; JSONUtils . testValidity ( d ) ; return element ( d ) ; } public JSONArray element ( int value ) { return element ( new Integer ( value ) ) ; } public JSONArray element ( int index , boolean value ) { return element ( index , value ? Boolean . TRUE : Boolean . FALSE ) ; } public JSONArray element ( int index , Collection value ) { return element ( index , value , new JsonConfig ( ) ) ; } public JSONArray element ( int index , Collection value , JsonConfig jsonConfig ) { if ( value instanceof JSONArray ) { if ( index < <NUM_LIT:0> ) { throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } if ( index < size ( ) ) { elements . set ( index , value ) ; } else { while ( index != size ( ) ) { element ( JSONNull . getInstance ( ) ) ; } element ( value , jsonConfig ) ; } return this ; } else { return element ( index , _fromCollection ( value , jsonConfig ) ) ; } } public JSONArray element ( int index , double value ) { return element ( index , new Double ( value ) ) ; } public JSONArray element ( int index , int value ) { return element ( index , new Integer ( value ) ) ; } public JSONArray element ( int index , long value ) { return element ( index , new Long ( value ) ) ; } public JSONArray element ( int index , Map value ) { return element ( index , value , new JsonConfig ( ) ) ; } public JSONArray element ( int index , Map value , JsonConfig jsonConfig ) { if ( value instanceof JSONObject ) { if ( index < <NUM_LIT:0> ) { throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } if ( index < size ( ) ) { elements . set ( index , value ) ; } else { while ( index != size ( ) ) { element ( JSONNull . getInstance ( ) ) ; } element ( value , jsonConfig ) ; } return this ; } else { return element ( index , JSONObject . fromObject ( value , jsonConfig ) ) ; } } public JSONArray element ( int index , Object value ) { return element ( index , value , new JsonConfig ( ) ) ; } public JSONArray element ( int index , Object value , JsonConfig jsonConfig ) { JSONUtils . testValidity ( value ) ; if ( index < <NUM_LIT:0> ) { throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } if ( index < size ( ) ) { this . elements . set ( index , processValue ( value , jsonConfig ) ) ; } else { while ( index != size ( ) ) { element ( JSONNull . getInstance ( ) ) ; } element ( value , jsonConfig ) ; } return this ; } public JSONArray element ( int index , String value ) { return element ( index , value , new JsonConfig ( ) ) ; } public JSONArray element ( int index , String value , JsonConfig jsonConfig ) { if ( index < <NUM_LIT:0> ) { throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } if ( index < size ( ) ) { if ( value == null ) { this . elements . set ( index , "<STR_LIT>" ) ; } else if ( JSONUtils . mayBeJSON ( value ) ) { try { this . elements . set ( index , JSONSerializer . toJSON ( value , jsonConfig ) ) ; } catch ( JSONException jsone ) { this . elements . set ( index , JSONUtils . stripQuotes ( value ) ) ; } } else { this . elements . set ( index , JSONUtils . stripQuotes ( value ) ) ; } } else { while ( index != size ( ) ) { element ( JSONNull . getInstance ( ) ) ; } element ( value , jsonConfig ) ; } return this ; } public JSONArray element ( JSONNull value ) { this . elements . add ( value ) ; return this ; } public JSONArray element ( JSONObject value ) { this . elements . add ( value ) ; return this ; } public JSONArray element ( long value ) { return element ( JSONUtils . transformNumber ( new Long ( value ) ) ) ; } public JSONArray element ( Map value ) { return element ( value , new JsonConfig ( ) ) ; } public JSONArray element ( Map value , JsonConfig jsonConfig ) { if ( value instanceof JSONObject ) { elements . add ( value ) ; return this ; } else { return element ( JSONObject . fromObject ( value , jsonConfig ) ) ; } } public JSONArray element ( Object value ) { return element ( value , new JsonConfig ( ) ) ; } public JSONArray element ( Object value , JsonConfig jsonConfig ) { return addValue ( value , jsonConfig ) ; } public JSONArray element ( String value ) { return element ( value , new JsonConfig ( ) ) ; } public JSONArray element ( String value , JsonConfig jsonConfig ) { if ( value == null ) { this . elements . add ( "<STR_LIT>" ) ; } else if ( JSONUtils . hasQuotes ( value ) ) { this . elements . add ( value ) ; } else if ( JSONNull . getInstance ( ) . equals ( value ) ) { this . elements . add ( JSONNull . getInstance ( ) ) ; } else if ( JSONUtils . isJsonKeyword ( value , jsonConfig ) ) { if ( jsonConfig . isJavascriptCompliant ( ) && "<STR_LIT>" . equals ( value ) ) { this . elements . add ( JSONNull . getInstance ( ) ) ; } else { this . elements . add ( value ) ; } } else if ( JSONUtils . mayBeJSON ( value ) ) { try { this . elements . add ( JSONSerializer . toJSON ( value , jsonConfig ) ) ; } catch ( JSONException jsone ) { this . elements . add ( value ) ; } } else { this . elements . add ( value ) ; } return this ; } public boolean equals ( Object obj ) { if ( obj == this ) { return true ; } if ( obj == null ) { return false ; } if ( ! ( obj instanceof JSONArray ) ) { return false ; } JSONArray other = ( JSONArray ) obj ; if ( other . size ( ) != size ( ) ) { return false ; } int max = size ( ) ; for ( int i = <NUM_LIT:0> ; i < max ; i ++ ) { Object o1 = get ( i ) ; Object o2 = other . get ( i ) ; if ( JSONNull . getInstance ( ) . equals ( o1 ) ) { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { continue ; } else { return false ; } } else { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { return false ; } } if ( o1 instanceof JSONArray && o2 instanceof JSONArray ) { JSONArray e = ( JSONArray ) o1 ; JSONArray a = ( JSONArray ) o2 ; if ( ! a . equals ( e ) ) { return false ; } } else { if ( o1 instanceof String && o2 instanceof JSONFunction ) { if ( ! o1 . equals ( String . valueOf ( o2 ) ) ) { return false ; } } else if ( o1 instanceof JSONFunction && o2 instanceof String ) { if ( ! o2 . equals ( String . valueOf ( o1 ) ) ) { return false ; } } else if ( o1 instanceof JSONObject && o2 instanceof JSONObject ) { if ( ! o1 . equals ( o2 ) ) { return false ; } } else if ( o1 instanceof JSONArray && o2 instanceof JSONArray ) { if ( ! o1 . equals ( o2 ) ) { return false ; } } else if ( o1 instanceof JSONFunction && o2 instanceof JSONFunction ) { if ( ! o1 . equals ( o2 ) ) { return false ; } } else { if ( o1 instanceof String ) { if ( ! o1 . equals ( String . valueOf ( o2 ) ) ) { return false ; } } else if ( o2 instanceof String ) { if ( ! o2 . equals ( String . valueOf ( o1 ) ) ) { return false ; } } else { Morpher m1 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o1 . getClass ( ) ) ; Morpher m2 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o2 . getClass ( ) ) ; if ( m1 != null && m1 != IdentityObjectMorpher . getInstance ( ) ) { if ( ! o1 . equals ( JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o2 ) ) ) { return false ; } } else if ( m2 != null && m2 != IdentityObjectMorpher . getInstance ( ) ) { if ( ! JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o1 ) . equals ( o2 ) ) { return false ; } } else { if ( ! o1 . equals ( o2 ) ) { return false ; } } } } } } return true ; } public Object get ( int index ) { return this . elements . get ( index ) ; } public boolean getBoolean ( int index ) { Object o = get ( index ) ; if ( o != null ) { if ( o . equals ( Boolean . FALSE ) || ( o instanceof String && ( ( String ) o ) . equalsIgnoreCase ( "<STR_LIT:false>" ) ) ) { return false ; } else if ( o . equals ( Boolean . TRUE ) || ( o instanceof String && ( ( String ) o ) . equalsIgnoreCase ( "<STR_LIT:true>" ) ) ) { return true ; } } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public double getDouble ( int index ) { Object o = get ( index ) ; if ( o != null ) { try { return o instanceof Number ? ( ( Number ) o ) . doubleValue ( ) : Double . parseDouble ( ( String ) o ) ; } catch ( Exception e ) { throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public int getInt ( int index ) { Object o = get ( index ) ; if ( o != null ) { return o instanceof Number ? ( ( Number ) o ) . intValue ( ) : ( int ) getDouble ( index ) ; } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public JSONArray getJSONArray ( int index ) { Object o = get ( index ) ; if ( o != null && o instanceof JSONArray ) { return ( JSONArray ) o ; } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public JSONObject getJSONObject ( int index ) { Object o = get ( index ) ; if ( JSONNull . getInstance ( ) . equals ( o ) ) { return new JSONObject ( true ) ; } else if ( o instanceof JSONObject ) { return ( JSONObject ) o ; } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public long getLong ( int index ) { Object o = get ( index ) ; if ( o != null ) { return o instanceof Number ? ( ( Number ) o ) . longValue ( ) : ( long ) getDouble ( index ) ; } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public String getString ( int index ) { Object o = get ( index ) ; if ( o != null ) { return o . toString ( ) ; } throw new JSONException ( "<STR_LIT>" + index + "<STR_LIT>" ) ; } public int hashCode ( ) { int hashcode = <NUM_LIT> ; for ( Iterator e = elements . iterator ( ) ; e . hasNext ( ) ; ) { Object element = e . next ( ) ; hashcode += JSONUtils . hashCode ( element ) ; } return hashcode ; } public int indexOf ( Object o ) { return elements . indexOf ( o ) ; } public boolean isArray ( ) { return true ; } public boolean isEmpty ( ) { return this . elements . isEmpty ( ) ; } public boolean isExpandElements ( ) { return expandElements ; } public Iterator iterator ( ) { return new JSONArrayListIterator ( ) ; } public String join ( String separator ) { return join ( separator , false ) ; } public String join ( String separator , boolean stripQuotes ) { int len = size ( ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = <NUM_LIT:0> ; i < len ; i += <NUM_LIT:1> ) { if ( i > <NUM_LIT:0> ) { sb . append ( separator ) ; } String value = JSONUtils . valueToString ( this . elements . get ( i ) ) ; sb . append ( stripQuotes ? JSONUtils . stripQuotes ( value ) : value ) ; } return sb . toString ( ) ; } public int lastIndexOf ( Object o ) { return elements . lastIndexOf ( o ) ; } public ListIterator listIterator ( ) { return listIterator ( <NUM_LIT:0> ) ; } public ListIterator listIterator ( int index ) { if ( index < <NUM_LIT:0> || index > size ( ) ) throw new IndexOutOfBoundsException ( "<STR_LIT>" + index ) ; return new JSONArrayListIterator ( index ) ; } public Object opt ( int index ) { return ( index < <NUM_LIT:0> || index >= size ( ) ) ? null : this . elements . get ( index ) ; } public boolean optBoolean ( int index ) { return optBoolean ( index , false ) ; } public boolean optBoolean ( int index , boolean defaultValue ) { try { return getBoolean ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public double optDouble ( int index ) { return optDouble ( index , Double . NaN ) ; } public double optDouble ( int index , double defaultValue ) { try { return getDouble ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public int optInt ( int index ) { return optInt ( index , <NUM_LIT:0> ) ; } public int optInt ( int index , int defaultValue ) { try { return getInt ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public JSONArray optJSONArray ( int index ) { Object o = opt ( index ) ; return o instanceof JSONArray ? ( JSONArray ) o : null ; } public JSONObject optJSONObject ( int index ) { Object o = opt ( index ) ; return o instanceof JSONObject ? ( JSONObject ) o : null ; } public long optLong ( int index ) { return optLong ( index , <NUM_LIT:0> ) ; } public long optLong ( int index , long defaultValue ) { try { return getLong ( index ) ; } catch ( Exception e ) { return defaultValue ; } } public String optString ( int index ) { return optString ( index , "<STR_LIT>" ) ; } public String optString ( int index , String defaultValue ) { Object o = opt ( index ) ; return o != null ? o . toString ( ) : defaultValue ; } public Object remove ( int index ) { return elements . remove ( index ) ; } public boolean remove ( Object o ) { return elements . remove ( o ) ; } public boolean removeAll ( Collection collection ) { return removeAll ( collection , new JsonConfig ( ) ) ; } public boolean removeAll ( Collection collection , JsonConfig jsonConfig ) { return elements . removeAll ( fromObject ( collection , jsonConfig ) ) ; } public boolean retainAll ( Collection collection ) { return retainAll ( collection , new JsonConfig ( ) ) ; } public boolean retainAll ( Collection collection , JsonConfig jsonConfig ) { return elements . retainAll ( fromObject ( collection , jsonConfig ) ) ; } public Object set ( int index , Object value ) { return set ( index , value , new JsonConfig ( ) ) ; } public Object set ( int index , Object value , JsonConfig jsonConfig ) { Object previous = get ( index ) ; element ( index , value , jsonConfig ) ; return previous ; } public void setExpandElements ( boolean expandElements ) { this . expandElements = expandElements ; } public int size ( ) { return this . elements . size ( ) ; } public List subList ( int fromIndex , int toIndex ) { return elements . subList ( fromIndex , toIndex ) ; } public Object [ ] toArray ( ) { return this . elements . toArray ( ) ; } public Object [ ] toArray ( Object [ ] array ) { return elements . toArray ( array ) ; } public JSONObject toJSONObject ( JSONArray names ) { if ( names == null || names . size ( ) == <NUM_LIT:0> || size ( ) == <NUM_LIT:0> ) { return null ; } JSONObject jo = new JSONObject ( ) ; for ( int i = <NUM_LIT:0> ; i < names . size ( ) ; i ++ ) { jo . element ( names . getString ( i ) , this . opt ( i ) ) ; } return jo ; } public String toString ( ) { try { return '<CHAR_LIT:[>' + join ( "<STR_LIT:U+002C>" ) + '<CHAR_LIT:]>' ; } catch ( Exception e ) { return null ; } } public String toString ( int indentFactor ) { if ( indentFactor == <NUM_LIT:0> ) { return this . toString ( ) ; } return toString ( indentFactor , <NUM_LIT:0> ) ; } public String toString ( int indentFactor , int indent ) { int len = size ( ) ; if ( len == <NUM_LIT:0> ) { return "<STR_LIT:[]>" ; } if ( indentFactor == <NUM_LIT:0> ) { return this . toString ( ) ; } int i ; StringBuffer sb = new StringBuffer ( "<STR_LIT:[>" ) ; if ( len == <NUM_LIT:1> ) { sb . append ( JSONUtils . valueToString ( this . elements . get ( <NUM_LIT:0> ) , indentFactor , indent ) ) ; } else { int newindent = indent + indentFactor ; sb . append ( '<STR_LIT:\n>' ) ; for ( i = <NUM_LIT:0> ; i < len ; i += <NUM_LIT:1> ) { if ( i > <NUM_LIT:0> ) { sb . append ( "<STR_LIT>" ) ; } for ( int j = <NUM_LIT:0> ; j < newindent ; j += <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+0020>' ) ; } sb . append ( JSONUtils . valueToString ( this . elements . get ( i ) , indentFactor , newindent ) ) ; } sb . append ( '<STR_LIT:\n>' ) ; for ( i = <NUM_LIT:0> ; i < indent ; i += <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+0020>' ) ; } for ( i = <NUM_LIT:0> ; i < indent ; i += <NUM_LIT:1> ) { sb . insert ( <NUM_LIT:0> , '<CHAR_LIT:U+0020>' ) ; } } sb . append ( '<CHAR_LIT:]>' ) ; return sb . toString ( ) ; } protected void write ( Writer writer , WritingVisitor visitor ) throws IOException { try { boolean b = false ; int len = size ( ) ; writer . write ( '<CHAR_LIT:[>' ) ; for ( int i = <NUM_LIT:0> ; i < len ; i += <NUM_LIT:1> ) { if ( b ) { writer . write ( '<CHAR_LIT:U+002C>' ) ; } Object v = this . elements . get ( i ) ; if ( v instanceof JSON ) { visitor . on ( ( JSON ) v , writer ) ; } else { visitor . on ( v , writer ) ; } b = true ; } writer . write ( '<CHAR_LIT:]>' ) ; } catch ( IOException e ) { throw new JSONException ( e ) ; } } protected JSONArray addString ( String str ) { if ( str != null ) { elements . add ( str ) ; } return this ; } private JSONArray _addValue ( Object value , JsonConfig jsonConfig ) { this . elements . add ( value ) ; return this ; } protected Object _processValue ( Object value , JsonConfig jsonConfig ) { if ( value instanceof JSONTokener ) { return _fromJSONTokener ( ( JSONTokener ) value , jsonConfig ) ; } return super . _processValue ( value , jsonConfig ) ; } private JSONArray addValue ( Object value , JsonConfig jsonConfig ) { return _addValue ( processValue ( value , jsonConfig ) , jsonConfig ) ; } private Object processValue ( Object value , JsonConfig jsonConfig ) { if ( value != null ) { JsonValueProcessor jsonValueProcessor = jsonConfig . findJsonValueProcessor ( value . getClass ( ) ) ; if ( jsonValueProcessor != null ) { value = jsonValueProcessor . processArrayValue ( value , jsonConfig ) ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } } return _processValue ( value , jsonConfig ) ; } private class JSONArrayListIterator implements ListIterator { int currentIndex = <NUM_LIT:0> ; int lastIndex = - <NUM_LIT:1> ; JSONArrayListIterator ( ) { } JSONArrayListIterator ( int index ) { currentIndex = index ; } public boolean hasNext ( ) { return currentIndex != size ( ) ; } public Object next ( ) { try { Object next = get ( currentIndex ) ; lastIndex = currentIndex ++ ; return next ; } catch ( IndexOutOfBoundsException e ) { throw new NoSuchElementException ( ) ; } } public void remove ( ) { if ( lastIndex == - <NUM_LIT:1> ) throw new IllegalStateException ( ) ; try { JSONArray . this . remove ( lastIndex ) ; if ( lastIndex < currentIndex ) { currentIndex -- ; } lastIndex = - <NUM_LIT:1> ; } catch ( IndexOutOfBoundsException e ) { throw new ConcurrentModificationException ( ) ; } } public boolean hasPrevious ( ) { return currentIndex != <NUM_LIT:0> ; } public Object previous ( ) { try { int index = currentIndex - <NUM_LIT:1> ; Object previous = get ( index ) ; lastIndex = currentIndex = index ; return previous ; } catch ( IndexOutOfBoundsException e ) { throw new NoSuchElementException ( ) ; } } public int nextIndex ( ) { return currentIndex ; } public int previousIndex ( ) { return currentIndex - <NUM_LIT:1> ; } public void set ( Object obj ) { if ( lastIndex == - <NUM_LIT:1> ) { throw new IllegalStateException ( ) ; } try { JSONArray . this . set ( lastIndex , obj ) ; } catch ( IndexOutOfBoundsException ex ) { throw new ConcurrentModificationException ( ) ; } } public void add ( Object obj ) { try { JSONArray . this . add ( currentIndex ++ , obj ) ; lastIndex = - <NUM_LIT:1> ; } catch ( IndexOutOfBoundsException ex ) { throw new ConcurrentModificationException ( ) ; } } } } </s>
<s> package net . sf . json . test ; import java . util . Iterator ; import java . util . SortedSet ; import java . util . TreeSet ; import org . apache . commons . lang . StringUtils ; import junit . framework . Assert ; import net . sf . ezmorph . Morpher ; import net . sf . ezmorph . object . IdentityObjectMorpher ; import net . sf . json . JSON ; import net . sf . json . JSONArray ; import net . sf . json . JSONException ; import net . sf . json . JSONFunction ; import net . sf . json . JSONNull ; import net . sf . json . JSONObject ; import net . sf . json . JSONSerializer ; import net . sf . json . util . JSONUtils ; public class JSONAssert extends Assert { public static void assertEquals ( JSON expected , JSON actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( JSONArray expected , JSONArray actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( JSONArray expected , String actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( JSONFunction expected , String actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( JSONNull expected , String actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( JSONObject expected , JSONObject actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( JSONObject expected , String actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( String message , JSON expected , JSON actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } if ( expected == actual || expected . equals ( actual ) ) { return ; } if ( expected instanceof JSONArray ) { if ( actual instanceof JSONArray ) { assertEquals ( header , ( JSONArray ) expected , ( JSONArray ) actual ) ; } else { fail ( header + "<STR_LIT>" ) ; } } else if ( expected instanceof JSONObject ) { if ( actual instanceof JSONObject ) { assertEquals ( header , ( JSONObject ) expected , ( JSONObject ) actual ) ; } else { fail ( header + "<STR_LIT>" ) ; } } else if ( expected instanceof JSONNull ) { if ( actual instanceof JSONNull ) { return ; } else { fail ( header + "<STR_LIT>" ) ; } } } public static void assertEquals ( String expected , JSONArray actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( String message , JSONArray expected , JSONArray actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } if ( expected == actual || expected . equals ( actual ) ) { return ; } if ( actual . size ( ) != expected . size ( ) ) { fail ( header + "<STR_LIT>" + expected . size ( ) + "<STR_LIT>" + actual . size ( ) ) ; } int max = expected . size ( ) ; for ( int i = <NUM_LIT:0> ; i < max ; i ++ ) { Object o1 = expected . get ( i ) ; Object o2 = actual . get ( i ) ; if ( JSONNull . getInstance ( ) . equals ( o1 ) ) { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { continue ; } else { fail ( header + "<STR_LIT>" + i + "<STR_LIT>" ) ; } } else { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { fail ( header + "<STR_LIT>" + i + "<STR_LIT>" ) ; } } if ( o1 instanceof JSONArray && o2 instanceof JSONArray ) { JSONArray e = ( JSONArray ) o1 ; JSONArray a = ( JSONArray ) o2 ; assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT:;>" , e , a ) ; } else { if ( o1 instanceof String && o2 instanceof JSONFunction ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , ( String ) o1 , ( JSONFunction ) o2 ) ; } else if ( o1 instanceof JSONFunction && o2 instanceof String ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , ( JSONFunction ) o1 , ( String ) o2 ) ; } else if ( o1 instanceof JSONObject && o2 instanceof JSONObject ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , ( JSONObject ) o1 , ( JSONObject ) o2 ) ; } else if ( o1 instanceof JSONArray && o2 instanceof JSONArray ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , ( JSONArray ) o1 , ( JSONArray ) o2 ) ; } else if ( o1 instanceof JSONFunction && o2 instanceof JSONFunction ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , ( JSONFunction ) o1 , ( JSONFunction ) o2 ) ; } else { if ( o1 instanceof String ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , ( String ) o1 , String . valueOf ( o2 ) ) ; } else if ( o2 instanceof String ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , String . valueOf ( o1 ) , ( String ) o2 ) ; } else { Morpher m1 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o1 . getClass ( ) ) ; Morpher m2 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o2 . getClass ( ) ) ; if ( m1 != null && m1 != IdentityObjectMorpher . getInstance ( ) ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , o1 , JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o2 ) ) ; } else if ( m2 != null && m2 != IdentityObjectMorpher . getInstance ( ) ) { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o1 ) , o2 ) ; } else { assertEquals ( header + "<STR_LIT>" + i + "<STR_LIT>" , o1 , o2 ) ; } } } } } } public static void assertEquals ( String message , JSONArray expected , String actual ) { try { assertEquals ( message , expected , JSONArray . fromObject ( actual ) ) ; } catch ( JSONException e ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; fail ( header + "<STR_LIT>" ) ; } } public static void assertEquals ( String expected , JSONFunction actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( String message , JSONFunction expected , String actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } try { assertEquals ( header , expected , JSONFunction . parse ( actual ) ) ; } catch ( JSONException jsone ) { fail ( header + "<STR_LIT:'>" + actual + "<STR_LIT>" ) ; } } public static void assertEquals ( String expected , JSONNull actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( String message , JSONNull expected , String actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } else if ( expected == null ) { assertEquals ( header , "<STR_LIT:null>" , actual ) ; } else { assertEquals ( header , expected . toString ( ) , actual ) ; } } public static void assertEquals ( String expected , JSONObject actual ) { assertEquals ( null , expected , actual ) ; } public static void assertEquals ( String message , JSONObject expected , JSONObject actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } if ( expected == actual ) { return ; } if ( expected . isNullObject ( ) ) { if ( actual . isNullObject ( ) ) { return ; } else { fail ( header + "<STR_LIT>" ) ; } } else { if ( actual . isNullObject ( ) ) { fail ( header + "<STR_LIT>" ) ; } } if ( expected . names ( ) . size ( ) != actual . names ( ) . size ( ) ) { fail ( header + missingAndUnexpectedNames ( expected , actual ) ) ; } for ( Iterator keys = expected . keys ( ) ; keys . hasNext ( ) ; ) { String key = ( String ) keys . next ( ) ; Object o1 = expected . opt ( key ) ; Object o2 = actual . opt ( key ) ; if ( JSONNull . getInstance ( ) . equals ( o1 ) ) { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { continue ; } else { fail ( header + "<STR_LIT>" + key + "<STR_LIT>" ) ; } } else { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { fail ( header + "<STR_LIT>" + key + "<STR_LIT>" ) ; } } if ( o1 instanceof String && o2 instanceof JSONFunction ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , ( String ) o1 , ( JSONFunction ) o2 ) ; } else if ( o1 instanceof JSONFunction && o2 instanceof String ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , ( JSONFunction ) o1 , ( String ) o2 ) ; } else if ( o1 instanceof JSONObject && o2 instanceof JSONObject ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , ( JSONObject ) o1 , ( JSONObject ) o2 ) ; } else if ( o1 instanceof JSONArray && o2 instanceof JSONArray ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , ( JSONArray ) o1 , ( JSONArray ) o2 ) ; } else if ( o1 instanceof JSONFunction && o2 instanceof JSONFunction ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , ( JSONFunction ) o1 , ( JSONFunction ) o2 ) ; } else { if ( o1 instanceof String ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , ( String ) o1 , String . valueOf ( o2 ) ) ; } else if ( o2 instanceof String ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , String . valueOf ( o1 ) , ( String ) o2 ) ; } else { Morpher m1 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o1 . getClass ( ) ) ; Morpher m2 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o2 . getClass ( ) ) ; if ( m1 != null && m1 != IdentityObjectMorpher . getInstance ( ) ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , o1 , JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o2 ) ) ; } else if ( m2 != null && m2 != IdentityObjectMorpher . getInstance ( ) ) { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o1 ) , o2 ) ; } else { assertEquals ( header + "<STR_LIT>" + key + "<STR_LIT>" , o1 , o2 ) ; } } } } } private static String missingAndUnexpectedNames ( JSONObject expected , JSONObject actual ) { String missingExpectedNames = missingExpectedNames ( expected , actual ) ; String unexpectedNames = unexpectedNames ( expected , actual ) ; if ( missingExpectedNames != null && unexpectedNames != null ) { return missingExpectedNames + "<STR_LIT:U+002CU+0020>" + unexpectedNames ; } else if ( missingExpectedNames != null ) { return missingExpectedNames ; } else { return unexpectedNames ; } } private static String missingExpectedNames ( JSONObject expected , JSONObject actual ) { SortedSet keysInExpectedButNotInActual = new TreeSet ( expected . keySet ( ) ) ; keysInExpectedButNotInActual . removeAll ( actual . keySet ( ) ) ; if ( keysInExpectedButNotInActual . isEmpty ( ) ) { return null ; } else { return "<STR_LIT>" + StringUtils . join ( keysInExpectedButNotInActual , "<STR_LIT:U+002CU+0020>" ) + "<STR_LIT:]>" ; } } private static String unexpectedNames ( JSONObject expected , JSONObject actual ) { SortedSet keysInActualButNotInExpected = new TreeSet ( actual . keySet ( ) ) ; keysInActualButNotInExpected . removeAll ( expected . keySet ( ) ) ; if ( keysInActualButNotInExpected . isEmpty ( ) ) { return null ; } else { return "<STR_LIT>" + StringUtils . join ( keysInActualButNotInExpected , "<STR_LIT:U+002CU+0020>" ) + "<STR_LIT:]>" ; } } public static void assertEquals ( String message , JSONObject expected , String actual ) { try { assertEquals ( message , expected , JSONObject . fromObject ( actual ) ) ; } catch ( JSONException e ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; fail ( header + "<STR_LIT>" ) ; } } public static void assertEquals ( String message , String expected , JSONArray actual ) { try { assertEquals ( message , JSONArray . fromObject ( expected ) , actual ) ; } catch ( JSONException e ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; fail ( header + "<STR_LIT>" ) ; } } public static void assertEquals ( String message , String expected , JSONFunction actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } try { assertEquals ( header , JSONFunction . parse ( expected ) , actual ) ; } catch ( JSONException jsone ) { fail ( header + "<STR_LIT:'>" + expected + "<STR_LIT>" ) ; } } public static void assertEquals ( String message , String expected , JSONNull actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } else if ( actual == null ) { assertEquals ( header , expected , "<STR_LIT:null>" ) ; } else { assertEquals ( header , expected , actual . toString ( ) ) ; } } public static void assertEquals ( String message , String expected , JSONObject actual ) { try { assertEquals ( message , JSONObject . fromObject ( expected ) , actual ) ; } catch ( JSONException e ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; fail ( header + "<STR_LIT>" ) ; } } public static void assertJsonEquals ( String expected , String actual ) { assertJsonEquals ( null , expected , actual ) ; } public static void assertJsonEquals ( String message , String expected , String actual ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( expected == null ) { fail ( header + "<STR_LIT>" ) ; } if ( actual == null ) { fail ( header + "<STR_LIT>" ) ; } JSON json1 = null ; JSON json2 = null ; try { json1 = JSONSerializer . toJSON ( expected ) ; } catch ( JSONException jsone ) { fail ( header + "<STR_LIT>" ) ; } try { json2 = JSONSerializer . toJSON ( actual ) ; } catch ( JSONException jsone ) { fail ( header + "<STR_LIT>" ) ; } assertEquals ( header , json1 , json2 ) ; } public static void assertNotNull ( JSON json ) { assertNotNull ( null , json ) ; } public static void assertNotNull ( String message , JSON json ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( json instanceof JSONObject ) { assertFalse ( header + "<STR_LIT>" , ( ( JSONObject ) json ) . isNullObject ( ) ) ; } else if ( JSONNull . getInstance ( ) . equals ( json ) ) { fail ( header + "<STR_LIT>" ) ; } } public static void assertNull ( JSON json ) { assertNull ( null , json ) ; } public static void assertNull ( String message , JSON json ) { String header = message == null ? "<STR_LIT>" : message + "<STR_LIT::U+0020>" ; if ( json instanceof JSONObject ) { assertTrue ( header + "<STR_LIT>" , ( ( JSONObject ) json ) . isNullObject ( ) ) ; } else if ( ! JSONNull . getInstance ( ) . equals ( json ) ) { fail ( header + "<STR_LIT>" ) ; } } } </s>
<s> package net . sf . json . filters ; import net . sf . json . util . PropertyFilter ; public class NotPropertyFilter implements PropertyFilter { private PropertyFilter filter ; public NotPropertyFilter ( PropertyFilter filter ) { this . filter = filter ; } public boolean apply ( Object source , String name , Object value ) { if ( filter != null ) { return ! filter . apply ( source , name , value ) ; } return false ; } } </s>
<s> package net . sf . json . filters ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . List ; import net . sf . json . util . PropertyFilter ; public class CompositePropertyFilter implements PropertyFilter { private List filters = new ArrayList ( ) ; public CompositePropertyFilter ( ) { this ( null ) ; } public CompositePropertyFilter ( List filters ) { if ( filters != null ) { for ( Iterator i = filters . iterator ( ) ; i . hasNext ( ) ; ) { Object filter = i . next ( ) ; if ( filter instanceof PropertyFilter ) { this . filters . add ( filter ) ; } } } } public void addPropertyFilter ( PropertyFilter filter ) { if ( filter != null ) { filters . add ( filter ) ; } } public boolean apply ( Object source , String name , Object value ) { for ( Iterator i = filters . iterator ( ) ; i . hasNext ( ) ; ) { PropertyFilter filter = ( PropertyFilter ) i . next ( ) ; if ( filter . apply ( source , name , value ) ) { return true ; } } return false ; } public void removePropertyFilter ( PropertyFilter filter ) { if ( filter != null ) { filters . remove ( filter ) ; } } } </s>
<s> package net . sf . json . filters ; import net . sf . json . util . PropertyFilter ; public class AndPropertyFilter implements PropertyFilter { private PropertyFilter filter1 ; private PropertyFilter filter2 ; public AndPropertyFilter ( PropertyFilter filter1 , PropertyFilter filter2 ) { this . filter1 = filter1 ; this . filter2 = filter2 ; } public boolean apply ( Object source , String name , Object value ) { if ( filter1 != null && filter1 . apply ( source , name , value ) && filter2 != null && filter2 . apply ( source , name , value ) ) { return true ; } return false ; } } </s>
<s> package net . sf . json . filters ; import net . sf . json . util . PropertyFilter ; public class OrPropertyFilter implements PropertyFilter { private PropertyFilter filter1 ; private PropertyFilter filter2 ; public OrPropertyFilter ( PropertyFilter filter1 , PropertyFilter filter2 ) { this . filter1 = filter1 ; this . filter2 = filter2 ; } public boolean apply ( Object source , String name , Object value ) { if ( ( filter1 != null && filter1 . apply ( source , name , value ) ) || ( filter2 != null && filter2 . apply ( source , name , value ) ) ) { return true ; } return false ; } } </s>
<s> package net . sf . json . filters ; import net . sf . json . util . PropertyFilter ; public class TruePropertyFilter implements PropertyFilter { public boolean apply ( Object source , String name , Object value ) { return true ; } } </s>
<s> package net . sf . json . filters ; import net . sf . json . util . PropertyFilter ; public class FalsePropertyFilter implements PropertyFilter { public boolean apply ( Object source , String name , Object value ) { return false ; } } </s>
<s> package net . sf . json . filters ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import net . sf . json . util . PropertyFilter ; public abstract class MappingPropertyFilter implements PropertyFilter { private Map filters = new HashMap ( ) ; public MappingPropertyFilter ( ) { this ( null ) ; } public MappingPropertyFilter ( Map filters ) { if ( filters != null ) { for ( Iterator i = filters . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; Object key = entry . getKey ( ) ; Object filter = entry . getValue ( ) ; if ( filter instanceof PropertyFilter ) { this . filters . put ( key , filter ) ; } } } } public void addPropertyFilter ( Object target , PropertyFilter filter ) { if ( filter != null ) { filters . put ( target , filter ) ; } } public boolean apply ( Object source , String name , Object value ) { for ( Iterator i = filters . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; Object key = entry . getKey ( ) ; if ( keyMatches ( key , source , name , value ) ) { PropertyFilter filter = ( PropertyFilter ) entry . getValue ( ) ; return filter . apply ( source , name , value ) ; } } return false ; } public void removePropertyFilter ( Object target ) { if ( target != null ) { filters . remove ( target ) ; } } protected abstract boolean keyMatches ( Object key , Object source , String name , Object value ) ; } </s>
<s> package net . sf . json ; import java . io . IOException ; import java . io . Writer ; import java . lang . ref . SoftReference ; import java . util . Collection ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Set ; import java . util . TreeSet ; import net . sf . json . util . JSONUtils ; import net . sf . json . util . JsonEventListener ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; abstract class AbstractJSON implements JSON { private static class CycleSet extends ThreadLocal { protected Object initialValue ( ) { return new SoftReference ( new HashSet ( ) ) ; } public Set getSet ( ) { Set set = ( Set ) ( ( SoftReference ) get ( ) ) . get ( ) ; if ( set == null ) { set = new HashSet ( ) ; set ( new SoftReference ( set ) ) ; } return set ; } } private static CycleSet cycleSet = new CycleSet ( ) ; private static final Log log = LogFactory . getLog ( AbstractJSON . class ) ; protected static boolean addInstance ( Object instance ) { return getCycleSet ( ) . add ( instance ) ; } protected static void fireArrayEndEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onArrayEnd ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void fireArrayStartEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onArrayStart ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void fireElementAddedEvent ( int index , Object element , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onElementAdded ( index , element ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void fireErrorEvent ( JSONException jsone , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onError ( jsone ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void fireObjectEndEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onObjectEnd ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void fireObjectStartEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onObjectStart ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void firePropertySetEvent ( String key , Object value , boolean accumulated , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onPropertySet ( key , value , accumulated ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void fireWarnEvent ( String warning , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onWarning ( warning ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } } protected static void removeInstance ( Object instance ) { Set set = getCycleSet ( ) ; set . remove ( instance ) ; if ( set . size ( ) == <NUM_LIT:0> ) { cycleSet . remove ( ) ; } } protected Object _processValue ( Object value , JsonConfig jsonConfig ) { if ( JSONNull . getInstance ( ) . equals ( value ) ) { return JSONNull . getInstance ( ) ; } else if ( Class . class . isAssignableFrom ( value . getClass ( ) ) || value instanceof Class ) { return ( ( Class ) value ) . getName ( ) ; } else if ( JSONUtils . isFunction ( value ) ) { if ( value instanceof String ) { value = JSONFunction . parse ( ( String ) value ) ; } return value ; } else if ( value instanceof JSONString ) { return JSONSerializer . toJSON ( ( JSONString ) value , jsonConfig ) ; } else if ( value instanceof JSON ) { return JSONSerializer . toJSON ( value , jsonConfig ) ; } else if ( JSONUtils . isArray ( value ) ) { return JSONArray . fromObject ( value , jsonConfig ) ; } else if ( JSONUtils . isString ( value ) ) { String str = String . valueOf ( value ) ; if ( JSONUtils . hasQuotes ( str ) ) { String stripped = JSONUtils . stripQuotes ( str ) ; if ( JSONUtils . isFunction ( stripped ) ) { return JSONUtils . DOUBLE_QUOTE + stripped + JSONUtils . DOUBLE_QUOTE ; } if ( stripped . startsWith ( "<STR_LIT:[>" ) && stripped . endsWith ( "<STR_LIT:]>" ) ) { return stripped ; } if ( stripped . startsWith ( "<STR_LIT:{>" ) && stripped . endsWith ( "<STR_LIT:}>" ) ) { return stripped ; } return str ; } else if ( JSONUtils . isJsonKeyword ( str , jsonConfig ) ) { if ( jsonConfig . isJavascriptCompliant ( ) && "<STR_LIT>" . equals ( str ) ) { return JSONNull . getInstance ( ) ; } return str ; } else if ( JSONUtils . mayBeJSON ( str ) ) { try { return JSONSerializer . toJSON ( str , jsonConfig ) ; } catch ( JSONException jsone ) { return str ; } } return str ; } else if ( JSONUtils . isNumber ( value ) ) { JSONUtils . testValidity ( value ) ; return JSONUtils . transformNumber ( ( Number ) value ) ; } else if ( JSONUtils . isBoolean ( value ) ) { return value ; } else { JSONObject jsonObject = JSONObject . fromObject ( value , jsonConfig ) ; if ( jsonObject . isNullObject ( ) ) { return JSONNull . getInstance ( ) ; } else { return jsonObject ; } } } private static Set getCycleSet ( ) { return cycleSet . getSet ( ) ; } public final Writer write ( Writer writer ) throws IOException { write ( writer , NORMAL ) ; return writer ; } public final Writer writeCanonical ( Writer writer ) throws IOException { write ( writer , CANONICAL ) ; return writer ; } protected abstract void write ( Writer w , WritingVisitor v ) throws IOException ; interface WritingVisitor { Collection keySet ( JSONObject o ) ; void on ( JSON o , Writer w ) throws IOException ; void on ( Object value , Writer w ) throws IOException ; } private static final WritingVisitor NORMAL = new WritingVisitor ( ) { public Collection keySet ( JSONObject o ) { return o . keySet ( ) ; } public void on ( JSON o , Writer w ) throws IOException { o . write ( w ) ; } public void on ( Object value , Writer w ) throws IOException { w . write ( JSONUtils . valueToString ( value ) ) ; } } ; private static final WritingVisitor CANONICAL = new WritingVisitor ( ) { public Collection keySet ( JSONObject o ) { return new TreeSet ( o . keySet ( ) ) ; } public void on ( JSON o , Writer w ) throws IOException { o . writeCanonical ( w ) ; } public void on ( Object value , Writer w ) throws IOException { w . write ( JSONUtils . valueToCanonicalString ( value ) ) ; } } ; } </s>
<s> package net . sf . json ; import java . beans . PropertyDescriptor ; import java . io . IOException ; import java . io . Writer ; import java . lang . reflect . Array ; import java . lang . reflect . Field ; import java . lang . reflect . Modifier ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . LinkedHashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . ezmorph . Morpher ; import net . sf . ezmorph . array . ObjectArrayMorpher ; import net . sf . ezmorph . bean . BeanMorpher ; import net . sf . ezmorph . object . IdentityObjectMorpher ; import net . sf . json . processors . JsonBeanProcessor ; import net . sf . json . processors . JsonValueProcessor ; import net . sf . json . processors . JsonVerifier ; import net . sf . json . processors . PropertyNameProcessor ; import net . sf . json . regexp . RegexpUtils ; import net . sf . json . util . CycleDetectionStrategy ; import net . sf . json . util . JSONTokener ; import net . sf . json . util . JSONUtils ; import net . sf . json . util . PropertyFilter ; import net . sf . json . util . PropertySetStrategy ; import org . apache . commons . beanutils . DynaBean ; import org . apache . commons . beanutils . DynaProperty ; import org . apache . commons . beanutils . PropertyUtils ; import org . apache . commons . collections . map . ListOrderedMap ; import org . apache . commons . lang . StringUtils ; import org . apache . commons . logging . Log ; import org . apache . commons . logging . LogFactory ; public final class JSONObject extends AbstractJSON implements JSON , Map , Comparable { private static final Log log = LogFactory . getLog ( JSONObject . class ) ; public static JSONObject fromObject ( Object object ) { return fromObject ( object , new JsonConfig ( ) ) ; } public static JSONObject fromObject ( Object object , JsonConfig jsonConfig ) { if ( object == null || JSONUtils . isNull ( object ) ) { return new JSONObject ( true ) ; } else if ( object instanceof JSONObject ) { return _fromJSONObject ( ( JSONObject ) object , jsonConfig ) ; } else if ( object instanceof DynaBean ) { return _fromDynaBean ( ( DynaBean ) object , jsonConfig ) ; } else if ( object instanceof JSONTokener ) { return _fromJSONTokener ( ( JSONTokener ) object , jsonConfig ) ; } else if ( object instanceof JSONString ) { return _fromJSONString ( ( JSONString ) object , jsonConfig ) ; } else if ( object instanceof Map ) { return _fromMap ( ( Map ) object , jsonConfig ) ; } else if ( object instanceof String ) { return _fromString ( ( String ) object , jsonConfig ) ; } else if ( JSONUtils . isNumber ( object ) || JSONUtils . isBoolean ( object ) || JSONUtils . isString ( object ) ) { return new JSONObject ( ) ; } else if ( JSONUtils . isArray ( object ) ) { throw new JSONException ( "<STR_LIT>" ) ; } else { return _fromBean ( object , jsonConfig ) ; } } public static Object toBean ( JSONObject jsonObject ) { if ( jsonObject == null || jsonObject . isNullObject ( ) ) { return null ; } DynaBean dynaBean = null ; JsonConfig jsonConfig = new JsonConfig ( ) ; Map props = JSONUtils . getProperties ( jsonObject ) ; dynaBean = JSONUtils . newDynaBean ( jsonObject , jsonConfig ) ; for ( Iterator entries = jsonObject . names ( jsonConfig ) . iterator ( ) ; entries . hasNext ( ) ; ) { String name = ( String ) entries . next ( ) ; String key = JSONUtils . convertToJavaIdentifier ( name , jsonConfig ) ; Class type = ( Class ) props . get ( name ) ; Object value = jsonObject . get ( name ) ; try { if ( ! JSONUtils . isNull ( value ) ) { if ( value instanceof JSONArray ) { dynaBean . set ( key , JSONArray . toCollection ( ( JSONArray ) value ) ) ; } else if ( String . class . isAssignableFrom ( type ) || Boolean . class . isAssignableFrom ( type ) || JSONUtils . isNumber ( type ) || Character . class . isAssignableFrom ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { dynaBean . set ( key , value ) ; } else { dynaBean . set ( key , toBean ( ( JSONObject ) value ) ) ; } } else { if ( type . isPrimitive ( ) ) { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) ) ; dynaBean . set ( key , JSONUtils . getMorpherRegistry ( ) . morph ( type , null ) ) ; } else { dynaBean . set ( key , null ) ; } } } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( "<STR_LIT>" + name + "<STR_LIT>" + type , e ) ; } } return dynaBean ; } public static Object toBean ( JSONObject jsonObject , Class beanClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( beanClass ) ; return toBean ( jsonObject , jsonConfig ) ; } public static Object toBean ( JSONObject jsonObject , Class beanClass , Map classMap ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( beanClass ) ; jsonConfig . setClassMap ( classMap ) ; return toBean ( jsonObject , jsonConfig ) ; } public static Object toBean ( JSONObject jsonObject , JsonConfig jsonConfig ) { if ( jsonObject == null || jsonObject . isNullObject ( ) ) { return null ; } Class beanClass = jsonConfig . getRootClass ( ) ; Map classMap = jsonConfig . getClassMap ( ) ; if ( beanClass == null ) { return toBean ( jsonObject ) ; } if ( classMap == null ) { classMap = Collections . EMPTY_MAP ; } Object bean = null ; try { if ( beanClass . isInterface ( ) ) { if ( ! Map . class . isAssignableFrom ( beanClass ) ) { throw new JSONException ( "<STR_LIT>" + beanClass ) ; } else { bean = new HashMap ( ) ; } } else { bean = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( beanClass , jsonObject ) ; } } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( e ) ; } Map props = JSONUtils . getProperties ( jsonObject ) ; PropertyFilter javaPropertyFilter = jsonConfig . getJavaPropertyFilter ( ) ; for ( Iterator entries = jsonObject . names ( jsonConfig ) . iterator ( ) ; entries . hasNext ( ) ; ) { String name = ( String ) entries . next ( ) ; Class type = ( Class ) props . get ( name ) ; Object value = jsonObject . get ( name ) ; if ( javaPropertyFilter != null && javaPropertyFilter . apply ( bean , name , value ) ) { continue ; } String key = Map . class . isAssignableFrom ( beanClass ) && jsonConfig . isSkipJavaIdentifierTransformationInMapKeys ( ) ? name : JSONUtils . convertToJavaIdentifier ( name , jsonConfig ) ; PropertyNameProcessor propertyNameProcessor = jsonConfig . findJavaPropertyNameProcessor ( beanClass ) ; if ( propertyNameProcessor != null ) { key = propertyNameProcessor . processPropertyName ( beanClass , key ) ; } try { if ( Map . class . isAssignableFrom ( beanClass ) ) { if ( JSONUtils . isNull ( value ) ) { setProperty ( bean , key , value , jsonConfig ) ; } else if ( value instanceof JSONArray ) { setProperty ( bean , key , convertPropertyValueToCollection ( key , value , jsonConfig , name , classMap , List . class ) , jsonConfig ) ; } else if ( String . class . isAssignableFrom ( type ) || JSONUtils . isBoolean ( type ) || JSONUtils . isNumber ( type ) || JSONUtils . isString ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( jsonConfig . isHandleJettisonEmptyElement ( ) && "<STR_LIT>" . equals ( value ) ) { setProperty ( bean , key , null , jsonConfig ) ; } else { setProperty ( bean , key , value , jsonConfig ) ; } } else { Class targetClass = resolveClass ( classMap , key , name , type ) ; JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( targetClass ) ; jsc . setClassMap ( classMap ) ; if ( targetClass != null ) { setProperty ( bean , key , toBean ( ( JSONObject ) value , jsc ) , jsonConfig ) ; } else { setProperty ( bean , key , toBean ( ( JSONObject ) value ) , jsonConfig ) ; } } } else { PropertyDescriptor pd = PropertyUtils . getPropertyDescriptor ( bean , key ) ; if ( pd != null && pd . getWriteMethod ( ) == null ) { log . info ( "<STR_LIT>" + key + "<STR_LIT>" + bean . getClass ( ) + "<STR_LIT>" ) ; continue ; } if ( pd != null ) { Class targetType = pd . getPropertyType ( ) ; if ( ! JSONUtils . isNull ( value ) ) { if ( value instanceof JSONArray ) { if ( List . class . isAssignableFrom ( pd . getPropertyType ( ) ) ) { setProperty ( bean , key , convertPropertyValueToCollection ( key , value , jsonConfig , name , classMap , pd . getPropertyType ( ) ) , jsonConfig ) ; } else if ( Set . class . isAssignableFrom ( pd . getPropertyType ( ) ) ) { setProperty ( bean , key , convertPropertyValueToCollection ( key , value , jsonConfig , name , classMap , pd . getPropertyType ( ) ) , jsonConfig ) ; } else { setProperty ( bean , key , convertPropertyValueToArray ( key , value , targetType , jsonConfig , classMap ) , jsonConfig ) ; } } else if ( String . class . isAssignableFrom ( type ) || JSONUtils . isBoolean ( type ) || JSONUtils . isNumber ( type ) || JSONUtils . isString ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( pd != null ) { if ( jsonConfig . isHandleJettisonEmptyElement ( ) && "<STR_LIT>" . equals ( value ) ) { setProperty ( bean , key , null , jsonConfig ) ; } else if ( ! targetType . isInstance ( value ) ) { setProperty ( bean , key , morphPropertyValue ( key , value , type , targetType ) , jsonConfig ) ; } else { setProperty ( bean , key , value , jsonConfig ) ; } } else if ( beanClass == null || bean instanceof Map ) { setProperty ( bean , key , value , jsonConfig ) ; } else { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) + "<STR_LIT>" + bean . getClass ( ) . getName ( ) ) ; } } else { if ( jsonConfig . isHandleJettisonSingleElementArray ( ) ) { JSONArray array = new JSONArray ( ) . element ( value , jsonConfig ) ; Class newTargetClass = resolveClass ( classMap , key , name , type ) ; JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( newTargetClass ) ; jsc . setClassMap ( classMap ) ; if ( targetType . isArray ( ) ) { setProperty ( bean , key , JSONArray . toArray ( array , jsc ) , jsonConfig ) ; } else if ( JSONArray . class . isAssignableFrom ( targetType ) ) { setProperty ( bean , key , array , jsonConfig ) ; } else if ( List . class . isAssignableFrom ( targetType ) || Set . class . isAssignableFrom ( targetType ) ) { jsc . setCollectionType ( targetType ) ; setProperty ( bean , key , JSONArray . toCollection ( array , jsc ) , jsonConfig ) ; } else { setProperty ( bean , key , toBean ( ( JSONObject ) value , jsc ) , jsonConfig ) ; } } else { if ( targetType == Object . class || targetType . isInterface ( ) ) { Class targetTypeCopy = targetType ; targetType = findTargetClass ( key , classMap ) ; targetType = targetType == null ? findTargetClass ( name , classMap ) : targetType ; targetType = targetType == null && targetTypeCopy . isInterface ( ) ? targetTypeCopy : targetType ; } JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( targetType ) ; jsc . setClassMap ( classMap ) ; setProperty ( bean , key , toBean ( ( JSONObject ) value , jsc ) , jsonConfig ) ; } } } else { if ( type . isPrimitive ( ) ) { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) ) ; setProperty ( bean , key , JSONUtils . getMorpherRegistry ( ) . morph ( type , null ) , jsonConfig ) ; } else { setProperty ( bean , key , null , jsonConfig ) ; } } } else { if ( ! JSONUtils . isNull ( value ) ) { if ( value instanceof JSONArray ) { setProperty ( bean , key , convertPropertyValueToCollection ( key , value , jsonConfig , name , classMap , List . class ) , jsonConfig ) ; } else if ( String . class . isAssignableFrom ( type ) || JSONUtils . isBoolean ( type ) || JSONUtils . isNumber ( type ) || JSONUtils . isString ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( beanClass == null || bean instanceof Map || jsonConfig . getPropertySetStrategy ( ) != null || ! jsonConfig . isIgnorePublicFields ( ) ) { setProperty ( bean , key , value , jsonConfig ) ; } else { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) + "<STR_LIT>" + bean . getClass ( ) . getName ( ) ) ; } } else { if ( jsonConfig . isHandleJettisonSingleElementArray ( ) ) { Class newTargetClass = resolveClass ( classMap , key , name , type ) ; JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( newTargetClass ) ; jsc . setClassMap ( classMap ) ; setProperty ( bean , key , toBean ( ( JSONObject ) value , jsc ) , jsonConfig ) ; } else { setProperty ( bean , key , value , jsonConfig ) ; } } } else { if ( type . isPrimitive ( ) ) { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) ) ; setProperty ( bean , key , JSONUtils . getMorpherRegistry ( ) . morph ( type , null ) , jsonConfig ) ; } else { setProperty ( bean , key , null , jsonConfig ) ; } } } } } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( "<STR_LIT>" + name + "<STR_LIT>" + type , e ) ; } } return bean ; } public static Object toBean ( JSONObject jsonObject , Object root , JsonConfig jsonConfig ) { if ( jsonObject == null || jsonObject . isNullObject ( ) || root == null ) { return root ; } Class rootClass = root . getClass ( ) ; if ( rootClass . isInterface ( ) ) { throw new JSONException ( "<STR_LIT>" + rootClass ) ; } Map classMap = jsonConfig . getClassMap ( ) ; if ( classMap == null ) { classMap = Collections . EMPTY_MAP ; } Map props = JSONUtils . getProperties ( jsonObject ) ; PropertyFilter javaPropertyFilter = jsonConfig . getJavaPropertyFilter ( ) ; for ( Iterator entries = jsonObject . names ( jsonConfig ) . iterator ( ) ; entries . hasNext ( ) ; ) { String name = ( String ) entries . next ( ) ; Class type = ( Class ) props . get ( name ) ; Object value = jsonObject . get ( name ) ; if ( javaPropertyFilter != null && javaPropertyFilter . apply ( root , name , value ) ) { continue ; } String key = JSONUtils . convertToJavaIdentifier ( name , jsonConfig ) ; try { PropertyDescriptor pd = PropertyUtils . getPropertyDescriptor ( root , key ) ; if ( pd != null && pd . getWriteMethod ( ) == null ) { log . info ( "<STR_LIT>" + key + "<STR_LIT>" + root . getClass ( ) + "<STR_LIT>" ) ; continue ; } if ( ! JSONUtils . isNull ( value ) ) { if ( value instanceof JSONArray ) { if ( pd == null || List . class . isAssignableFrom ( pd . getPropertyType ( ) ) ) { Class targetClass = resolveClass ( classMap , key , name , type ) ; Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( targetClass , null ) ; List list = JSONArray . toList ( ( JSONArray ) value , newRoot , jsonConfig ) ; setProperty ( root , key , list , jsonConfig ) ; } else { Class innerType = JSONUtils . getInnerComponentType ( pd . getPropertyType ( ) ) ; Class targetInnerType = findTargetClass ( key , classMap ) ; if ( innerType . equals ( Object . class ) && targetInnerType != null && ! targetInnerType . equals ( Object . class ) ) { innerType = targetInnerType ; } Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( innerType , null ) ; Object array = JSONArray . toArray ( ( JSONArray ) value , newRoot , jsonConfig ) ; if ( innerType . isPrimitive ( ) || JSONUtils . isNumber ( innerType ) || Boolean . class . isAssignableFrom ( innerType ) || JSONUtils . isString ( innerType ) ) { array = JSONUtils . getMorpherRegistry ( ) . morph ( Array . newInstance ( innerType , <NUM_LIT:0> ) . getClass ( ) , array ) ; } else if ( ! array . getClass ( ) . equals ( pd . getPropertyType ( ) ) ) { if ( ! pd . getPropertyType ( ) . equals ( Object . class ) ) { Morpher morpher = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( Array . newInstance ( innerType , <NUM_LIT:0> ) . getClass ( ) ) ; if ( IdentityObjectMorpher . getInstance ( ) . equals ( morpher ) ) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher ( new BeanMorpher ( innerType , JSONUtils . getMorpherRegistry ( ) ) ) ; JSONUtils . getMorpherRegistry ( ) . registerMorpher ( beanMorpher ) ; } array = JSONUtils . getMorpherRegistry ( ) . morph ( Array . newInstance ( innerType , <NUM_LIT:0> ) . getClass ( ) , array ) ; } } setProperty ( root , key , array , jsonConfig ) ; } } else if ( String . class . isAssignableFrom ( type ) || JSONUtils . isBoolean ( type ) || JSONUtils . isNumber ( type ) || JSONUtils . isString ( type ) || JSONFunction . class . isAssignableFrom ( type ) ) { if ( pd != null ) { if ( jsonConfig . isHandleJettisonEmptyElement ( ) && "<STR_LIT>" . equals ( value ) ) { setProperty ( root , key , null , jsonConfig ) ; } else if ( ! pd . getPropertyType ( ) . isInstance ( value ) ) { Morpher morpher = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( pd . getPropertyType ( ) ) ; if ( IdentityObjectMorpher . getInstance ( ) . equals ( morpher ) ) { log . warn ( "<STR_LIT>" + key + "<STR_LIT>" + type . getName ( ) + "<STR_LIT>" + pd . getPropertyType ( ) . getName ( ) + "<STR_LIT>" ) ; JSONUtils . getMorpherRegistry ( ) . registerMorpher ( new BeanMorpher ( pd . getPropertyType ( ) , JSONUtils . getMorpherRegistry ( ) ) ) ; } setProperty ( root , key , JSONUtils . getMorpherRegistry ( ) . morph ( pd . getPropertyType ( ) , value ) , jsonConfig ) ; } else { setProperty ( root , key , value , jsonConfig ) ; } } else if ( root instanceof Map ) { setProperty ( root , key , value , jsonConfig ) ; } else { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) + "<STR_LIT>" + root . getClass ( ) . getName ( ) ) ; } } else { if ( pd != null ) { Class targetClass = pd . getPropertyType ( ) ; if ( jsonConfig . isHandleJettisonSingleElementArray ( ) ) { JSONArray array = new JSONArray ( ) . element ( value , jsonConfig ) ; Class newTargetClass = resolveClass ( classMap , key , name , type ) ; Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( newTargetClass , ( JSONObject ) value ) ; if ( targetClass . isArray ( ) ) { setProperty ( root , key , JSONArray . toArray ( array , newRoot , jsonConfig ) , jsonConfig ) ; } else if ( Collection . class . isAssignableFrom ( targetClass ) ) { setProperty ( root , key , JSONArray . toList ( array , newRoot , jsonConfig ) , jsonConfig ) ; } else if ( JSONArray . class . isAssignableFrom ( targetClass ) ) { setProperty ( root , key , array , jsonConfig ) ; } else { setProperty ( root , key , toBean ( ( JSONObject ) value , newRoot , jsonConfig ) , jsonConfig ) ; } } else { if ( targetClass == Object . class ) { targetClass = resolveClass ( classMap , key , name , type ) ; if ( targetClass == null ) { targetClass = Object . class ; } } Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( targetClass , ( JSONObject ) value ) ; setProperty ( root , key , toBean ( ( JSONObject ) value , newRoot , jsonConfig ) , jsonConfig ) ; } } else if ( root instanceof Map ) { Class targetClass = findTargetClass ( key , classMap ) ; targetClass = targetClass == null ? findTargetClass ( name , classMap ) : targetClass ; Object newRoot = jsonConfig . getNewBeanInstanceStrategy ( ) . newInstance ( targetClass , ( JSONObject ) value ) ; setProperty ( root , key , toBean ( ( JSONObject ) value , newRoot , jsonConfig ) , jsonConfig ) ; } else { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) + "<STR_LIT>" + rootClass . getName ( ) ) ; } } } else { if ( type . isPrimitive ( ) ) { log . warn ( "<STR_LIT>" + key + "<STR_LIT::>" + type . getName ( ) ) ; setProperty ( root , key , JSONUtils . getMorpherRegistry ( ) . morph ( type , null ) , jsonConfig ) ; } else { setProperty ( root , key , null , jsonConfig ) ; } } } catch ( JSONException jsone ) { throw jsone ; } catch ( Exception e ) { throw new JSONException ( "<STR_LIT>" + name + "<STR_LIT>" + type , e ) ; } } return root ; } private static JSONObject _fromBean ( Object bean , JsonConfig jsonConfig ) { if ( ! addInstance ( bean ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsObject ( bean ) ; } catch ( JSONException jsone ) { removeInstance ( bean ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( bean ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireObjectStartEvent ( jsonConfig ) ; JsonBeanProcessor processor = jsonConfig . findJsonBeanProcessor ( bean . getClass ( ) ) ; if ( processor != null ) { JSONObject json = null ; try { json = processor . processBean ( bean , jsonConfig ) ; if ( json == null ) { json = ( JSONObject ) jsonConfig . findDefaultValueProcessor ( bean . getClass ( ) ) . getDefaultValue ( bean . getClass ( ) ) ; if ( json == null ) { json = new JSONObject ( true ) ; } } removeInstance ( bean ) ; fireObjectEndEvent ( jsonConfig ) ; } catch ( JSONException jsone ) { removeInstance ( bean ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( bean ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } return json ; } JSONObject jsonObject = defaultBeanProcessing ( bean , jsonConfig ) ; removeInstance ( bean ) ; fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; } private static JSONObject defaultBeanProcessing ( Object bean , JsonConfig jsonConfig ) { Class beanClass = bean . getClass ( ) ; PropertyNameProcessor propertyNameProcessor = jsonConfig . findJsonPropertyNameProcessor ( beanClass ) ; Collection exclusions = jsonConfig . getMergedExcludes ( beanClass ) ; JSONObject jsonObject = new JSONObject ( ) ; try { PropertyDescriptor [ ] pds = PropertyUtils . getPropertyDescriptors ( bean ) ; PropertyFilter jsonPropertyFilter = jsonConfig . getJsonPropertyFilter ( ) ; for ( int i = <NUM_LIT:0> ; i < pds . length ; i ++ ) { boolean bypass = false ; String key = pds [ i ] . getName ( ) ; if ( exclusions . contains ( key ) ) { continue ; } if ( jsonConfig . isIgnoreTransientFields ( ) && isTransientField ( key , beanClass ) ) { continue ; } Class type = pds [ i ] . getPropertyType ( ) ; try { pds [ i ] . getReadMethod ( ) ; } catch ( Exception e ) { String warning = "<STR_LIT>" + key + "<STR_LIT>" + beanClass + "<STR_LIT>" ; fireWarnEvent ( warning , jsonConfig ) ; log . info ( warning ) ; continue ; } if ( pds [ i ] . getReadMethod ( ) != null ) { Object value = PropertyUtils . getProperty ( bean , key ) ; if ( jsonPropertyFilter != null && jsonPropertyFilter . apply ( bean , key , value ) ) { continue ; } JsonValueProcessor jsonValueProcessor = jsonConfig . findJsonValueProcessor ( beanClass , type , key ) ; if ( jsonValueProcessor != null ) { value = jsonValueProcessor . processObjectValue ( key , value , jsonConfig ) ; bypass = true ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } if ( propertyNameProcessor != null ) { key = propertyNameProcessor . processPropertyName ( beanClass , key ) ; } setValue ( jsonObject , key , value , type , jsonConfig , bypass ) ; } else { String warning = "<STR_LIT>" + key + "<STR_LIT>" + beanClass + "<STR_LIT>" ; fireWarnEvent ( warning , jsonConfig ) ; log . info ( warning ) ; } } try { if ( ! jsonConfig . isIgnorePublicFields ( ) ) { Field [ ] fields = beanClass . getFields ( ) ; for ( int i = <NUM_LIT:0> ; i < fields . length ; i ++ ) { boolean bypass = false ; Field field = fields [ i ] ; String key = field . getName ( ) ; if ( exclusions . contains ( key ) ) { continue ; } if ( jsonConfig . isIgnoreTransientFields ( ) && isTransientField ( field ) ) { continue ; } Class type = field . getType ( ) ; Object value = field . get ( bean ) ; if ( jsonPropertyFilter != null && jsonPropertyFilter . apply ( bean , key , value ) ) { continue ; } JsonValueProcessor jsonValueProcessor = jsonConfig . findJsonValueProcessor ( beanClass , type , key ) ; if ( jsonValueProcessor != null ) { value = jsonValueProcessor . processObjectValue ( key , value , jsonConfig ) ; bypass = true ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } if ( propertyNameProcessor != null ) { key = propertyNameProcessor . processPropertyName ( beanClass , key ) ; } setValue ( jsonObject , key , value , type , jsonConfig , bypass ) ; } } } catch ( Exception e ) { log . trace ( "<STR_LIT>" , e ) ; } } catch ( JSONException jsone ) { removeInstance ( bean ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( Exception e ) { removeInstance ( bean ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } return jsonObject ; } private static JSONObject _fromDynaBean ( DynaBean bean , JsonConfig jsonConfig ) { if ( bean == null ) { fireObjectStartEvent ( jsonConfig ) ; fireObjectEndEvent ( jsonConfig ) ; return new JSONObject ( true ) ; } if ( ! addInstance ( bean ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsObject ( bean ) ; } catch ( JSONException jsone ) { removeInstance ( bean ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( bean ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireObjectStartEvent ( jsonConfig ) ; JSONObject jsonObject = new JSONObject ( ) ; try { DynaProperty [ ] props = bean . getDynaClass ( ) . getDynaProperties ( ) ; Collection exclusions = jsonConfig . getMergedExcludes ( ) ; PropertyFilter jsonPropertyFilter = jsonConfig . getJsonPropertyFilter ( ) ; for ( int i = <NUM_LIT:0> ; i < props . length ; i ++ ) { boolean bypass = false ; DynaProperty dynaProperty = props [ i ] ; String key = dynaProperty . getName ( ) ; if ( exclusions . contains ( key ) ) { continue ; } Class type = dynaProperty . getType ( ) ; Object value = bean . get ( dynaProperty . getName ( ) ) ; if ( jsonPropertyFilter != null && jsonPropertyFilter . apply ( bean , key , value ) ) { continue ; } JsonValueProcessor jsonValueProcessor = jsonConfig . findJsonValueProcessor ( type , key ) ; if ( jsonValueProcessor != null ) { value = jsonValueProcessor . processObjectValue ( key , value , jsonConfig ) ; bypass = true ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } setValue ( jsonObject , key , value , type , jsonConfig , bypass ) ; } } catch ( JSONException jsone ) { removeInstance ( bean ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( bean ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( bean ) ; fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; } private static JSONObject _fromJSONObject ( JSONObject object , JsonConfig jsonConfig ) { if ( object == null || object . isNullObject ( ) ) { fireObjectStartEvent ( jsonConfig ) ; fireObjectEndEvent ( jsonConfig ) ; return new JSONObject ( true ) ; } if ( ! addInstance ( object ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsObject ( object ) ; } catch ( JSONException jsone ) { removeInstance ( object ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( object ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireObjectStartEvent ( jsonConfig ) ; JSONArray sa = object . names ( jsonConfig ) ; Collection exclusions = jsonConfig . getMergedExcludes ( ) ; JSONObject jsonObject = new JSONObject ( ) ; PropertyFilter jsonPropertyFilter = jsonConfig . getJsonPropertyFilter ( ) ; for ( Iterator i = sa . iterator ( ) ; i . hasNext ( ) ; ) { Object k = i . next ( ) ; if ( k == null ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( ! ( k instanceof String ) && ! jsonConfig . isAllowNonStringKeys ( ) ) { throw new ClassCastException ( "<STR_LIT>" ) ; } String key = String . valueOf ( k ) ; if ( "<STR_LIT:null>" . equals ( key ) ) { throw new NullPointerException ( "<STR_LIT>" ) ; } if ( exclusions . contains ( key ) ) { continue ; } Object value = object . opt ( key ) ; if ( jsonPropertyFilter != null && jsonPropertyFilter . apply ( object , key , value ) ) { continue ; } if ( jsonObject . properties . containsKey ( key ) ) { jsonObject . accumulate ( key , value , jsonConfig ) ; firePropertySetEvent ( key , value , true , jsonConfig ) ; } else { jsonObject . setInternal ( key , value , jsonConfig ) ; firePropertySetEvent ( key , value , false , jsonConfig ) ; } } removeInstance ( object ) ; fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; } private static JSONObject _fromJSONString ( JSONString string , JsonConfig jsonConfig ) { return _fromJSONTokener ( new JSONTokener ( string . toJSONString ( ) ) , jsonConfig ) ; } private static JSONObject _fromJSONTokener ( JSONTokener tokener , JsonConfig jsonConfig ) { try { char c ; String key ; Object value ; if ( tokener . matches ( "<STR_LIT>" ) ) { fireObjectStartEvent ( jsonConfig ) ; fireObjectEndEvent ( jsonConfig ) ; return new JSONObject ( true ) ; } if ( tokener . nextClean ( ) != '<CHAR_LIT>' ) { throw tokener . syntaxError ( "<STR_LIT>" ) ; } fireObjectStartEvent ( jsonConfig ) ; Collection exclusions = jsonConfig . getMergedExcludes ( ) ; PropertyFilter jsonPropertyFilter = jsonConfig . getJsonPropertyFilter ( ) ; JSONObject jsonObject = new JSONObject ( ) ; for ( ; ; ) { c = tokener . nextClean ( ) ; switch ( c ) { case <NUM_LIT:0> : throw tokener . syntaxError ( "<STR_LIT>" ) ; case '<CHAR_LIT:}>' : fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; default : tokener . back ( ) ; key = tokener . nextValue ( jsonConfig ) . toString ( ) ; } c = tokener . nextClean ( ) ; if ( c == '<CHAR_LIT:=>' ) { if ( tokener . next ( ) != '<CHAR_LIT:>>' ) { tokener . back ( ) ; } } else if ( c != '<CHAR_LIT::>' ) { throw tokener . syntaxError ( "<STR_LIT>" ) ; } char peek = tokener . peek ( ) ; boolean quoted = peek == '<CHAR_LIT:">' || peek == '<STR_LIT>' ; Object v = tokener . nextValue ( jsonConfig ) ; if ( quoted || ! JSONUtils . isFunctionHeader ( v ) ) { if ( exclusions . contains ( key ) ) { switch ( tokener . nextClean ( ) ) { case '<CHAR_LIT:;>' : case '<CHAR_LIT:U+002C>' : if ( tokener . nextClean ( ) == '<CHAR_LIT:}>' ) { fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; } tokener . back ( ) ; break ; case '<CHAR_LIT:}>' : fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; default : throw tokener . syntaxError ( "<STR_LIT>" ) ; } continue ; } if ( jsonPropertyFilter == null || ! jsonPropertyFilter . apply ( tokener , key , v ) ) { if ( quoted && v instanceof String && ( JSONUtils . mayBeJSON ( ( String ) v ) || JSONUtils . isFunction ( v ) ) ) { v = JSONUtils . DOUBLE_QUOTE + v + JSONUtils . DOUBLE_QUOTE ; } if ( jsonObject . properties . containsKey ( key ) ) { jsonObject . accumulate ( key , v , jsonConfig ) ; firePropertySetEvent ( key , v , true , jsonConfig ) ; } else { jsonObject . element ( key , v , jsonConfig ) ; firePropertySetEvent ( key , v , false , jsonConfig ) ; } } } else { String params = JSONUtils . getFunctionParams ( ( String ) v ) ; int i = <NUM_LIT:0> ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { char ch = tokener . next ( ) ; if ( ch == <NUM_LIT:0> ) { break ; } if ( ch == '<CHAR_LIT>' ) { i ++ ; } if ( ch == '<CHAR_LIT:}>' ) { i -- ; } sb . append ( ch ) ; if ( i == <NUM_LIT:0> ) { break ; } } if ( i != <NUM_LIT:0> ) { throw tokener . syntaxError ( "<STR_LIT>" + v ) ; } String text = sb . toString ( ) ; text = text . substring ( <NUM_LIT:1> , text . length ( ) - <NUM_LIT:1> ) . trim ( ) ; value = new JSONFunction ( ( params != null ) ? StringUtils . split ( params , "<STR_LIT:U+002C>" ) : null , text ) ; if ( jsonPropertyFilter == null || ! jsonPropertyFilter . apply ( tokener , key , value ) ) { if ( jsonObject . properties . containsKey ( key ) ) { jsonObject . accumulate ( key , value , jsonConfig ) ; firePropertySetEvent ( key , value , true , jsonConfig ) ; } else { jsonObject . element ( key , value , jsonConfig ) ; firePropertySetEvent ( key , value , false , jsonConfig ) ; } } } switch ( tokener . nextClean ( ) ) { case '<CHAR_LIT:;>' : case '<CHAR_LIT:U+002C>' : if ( tokener . nextClean ( ) == '<CHAR_LIT:}>' ) { fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; } tokener . back ( ) ; break ; case '<CHAR_LIT:}>' : fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; default : throw tokener . syntaxError ( "<STR_LIT>" ) ; } } } catch ( JSONException jsone ) { fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } private static JSONObject _fromMap ( Map map , JsonConfig jsonConfig ) { if ( map == null ) { fireObjectStartEvent ( jsonConfig ) ; fireObjectEndEvent ( jsonConfig ) ; return new JSONObject ( true ) ; } if ( ! addInstance ( map ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsObject ( map ) ; } catch ( JSONException jsone ) { removeInstance ( map ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( map ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireObjectStartEvent ( jsonConfig ) ; Collection exclusions = jsonConfig . getMergedExcludes ( ) ; JSONObject jsonObject = new JSONObject ( ) ; PropertyFilter jsonPropertyFilter = jsonConfig . getJsonPropertyFilter ( ) ; try { for ( Iterator entries = map . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { boolean bypass = false ; Map . Entry entry = ( Map . Entry ) entries . next ( ) ; Object k = entry . getKey ( ) ; if ( k == null ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( ! ( k instanceof String ) && ! jsonConfig . isAllowNonStringKeys ( ) ) { throw new ClassCastException ( "<STR_LIT>" ) ; } String key = String . valueOf ( k ) ; if ( "<STR_LIT:null>" . equals ( key ) ) { throw new NullPointerException ( "<STR_LIT>" ) ; } if ( exclusions . contains ( key ) ) { continue ; } Object value = entry . getValue ( ) ; if ( jsonPropertyFilter != null && jsonPropertyFilter . apply ( map , key , value ) ) { continue ; } if ( value != null ) { JsonValueProcessor jsonValueProcessor = jsonConfig . findJsonValueProcessor ( value . getClass ( ) , key ) ; if ( jsonValueProcessor != null ) { value = jsonValueProcessor . processObjectValue ( key , value , jsonConfig ) ; bypass = true ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } setValue ( jsonObject , key , value , value . getClass ( ) , jsonConfig , bypass ) ; } else { if ( jsonObject . properties . containsKey ( key ) ) { jsonObject . accumulate ( key , JSONNull . getInstance ( ) ) ; firePropertySetEvent ( key , JSONNull . getInstance ( ) , true , jsonConfig ) ; } else { jsonObject . element ( key , JSONNull . getInstance ( ) ) ; firePropertySetEvent ( key , JSONNull . getInstance ( ) , false , jsonConfig ) ; } } } } catch ( JSONException jsone ) { removeInstance ( map ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException e ) { removeInstance ( map ) ; JSONException jsone = new JSONException ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( map ) ; fireObjectEndEvent ( jsonConfig ) ; return jsonObject ; } private static JSONObject _fromString ( String str , JsonConfig jsonConfig ) { if ( str == null || "<STR_LIT:null>" . equals ( str ) ) { fireObjectStartEvent ( jsonConfig ) ; fireObjectEndEvent ( jsonConfig ) ; return new JSONObject ( true ) ; } return _fromJSONTokener ( new JSONTokener ( str ) , jsonConfig ) ; } private static Object convertPropertyValueToArray ( String key , Object value , Class targetType , JsonConfig jsonConfig , Map classMap ) { Class innerType = JSONUtils . getInnerComponentType ( targetType ) ; Class targetInnerType = findTargetClass ( key , classMap ) ; if ( innerType . equals ( Object . class ) && targetInnerType != null && ! targetInnerType . equals ( Object . class ) ) { innerType = targetInnerType ; } JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( innerType ) ; jsc . setClassMap ( classMap ) ; Object array = JSONArray . toArray ( ( JSONArray ) value , jsc ) ; if ( innerType . isPrimitive ( ) || JSONUtils . isNumber ( innerType ) || Boolean . class . isAssignableFrom ( innerType ) || JSONUtils . isString ( innerType ) ) { array = JSONUtils . getMorpherRegistry ( ) . morph ( Array . newInstance ( innerType , <NUM_LIT:0> ) . getClass ( ) , array ) ; } else if ( ! array . getClass ( ) . equals ( targetType ) ) { if ( ! targetType . equals ( Object . class ) ) { Morpher morpher = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( Array . newInstance ( innerType , <NUM_LIT:0> ) . getClass ( ) ) ; if ( IdentityObjectMorpher . getInstance ( ) . equals ( morpher ) ) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher ( new BeanMorpher ( innerType , JSONUtils . getMorpherRegistry ( ) ) ) ; JSONUtils . getMorpherRegistry ( ) . registerMorpher ( beanMorpher ) ; } array = JSONUtils . getMorpherRegistry ( ) . morph ( Array . newInstance ( innerType , <NUM_LIT:0> ) . getClass ( ) , array ) ; } } return array ; } private static List convertPropertyValueToList ( String key , Object value , JsonConfig jsonConfig , String name , Map classMap ) { Class targetClass = findTargetClass ( key , classMap ) ; targetClass = targetClass == null ? findTargetClass ( name , classMap ) : targetClass ; JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( targetClass ) ; jsc . setClassMap ( classMap ) ; List list = ( List ) JSONArray . toCollection ( ( JSONArray ) value , jsc ) ; return list ; } private static Collection convertPropertyValueToCollection ( String key , Object value , JsonConfig jsonConfig , String name , Map classMap , Class collectionType ) { Class targetClass = findTargetClass ( key , classMap ) ; targetClass = targetClass == null ? findTargetClass ( name , classMap ) : targetClass ; JsonConfig jsc = jsonConfig . copy ( ) ; jsc . setRootClass ( targetClass ) ; jsc . setClassMap ( classMap ) ; jsc . setCollectionType ( collectionType ) ; return JSONArray . toCollection ( ( JSONArray ) value , jsc ) ; } private static Class resolveClass ( Map classMap , String key , String name , Class type ) { Class targetClass = findTargetClass ( key , classMap ) ; if ( targetClass == null ) { targetClass = findTargetClass ( name , classMap ) ; } if ( targetClass == null && type != null ) { if ( List . class . equals ( type ) ) { targetClass = ArrayList . class ; } else if ( Map . class . equals ( type ) ) { targetClass = LinkedHashMap . class ; } else if ( Set . class . equals ( type ) ) { targetClass = LinkedHashSet . class ; } else if ( ! type . isInterface ( ) && ! Object . class . equals ( type ) ) { targetClass = type ; } } return targetClass ; } private static Class findTargetClass ( String key , Map classMap ) { Class targetClass = ( Class ) classMap . get ( key ) ; if ( targetClass == null ) { for ( Iterator i = classMap . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; if ( RegexpUtils . getMatcher ( ( String ) entry . getKey ( ) ) . matches ( key ) ) { targetClass = ( Class ) entry . getValue ( ) ; break ; } } } return targetClass ; } private static boolean isTransientField ( String name , Class beanClass ) { try { return isTransientField ( beanClass . getDeclaredField ( name ) ) ; } catch ( Exception e ) { } return false ; } private static boolean isTransientField ( Field field ) { return ( field . getModifiers ( ) & Modifier . TRANSIENT ) == Modifier . TRANSIENT ; } private static Object morphPropertyValue ( String key , Object value , Class type , Class targetType ) { Morpher morpher = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( targetType ) ; if ( IdentityObjectMorpher . getInstance ( ) . equals ( morpher ) ) { log . warn ( "<STR_LIT>" + key + "<STR_LIT>" + type . getName ( ) + "<STR_LIT>" + targetType . getName ( ) + "<STR_LIT>" ) ; JSONUtils . getMorpherRegistry ( ) . registerMorpher ( new BeanMorpher ( targetType , JSONUtils . getMorpherRegistry ( ) ) ) ; } value = JSONUtils . getMorpherRegistry ( ) . morph ( targetType , value ) ; return value ; } private static void setProperty ( Object bean , String key , Object value , JsonConfig jsonConfig ) throws Exception { PropertySetStrategy propertySetStrategy = jsonConfig . getPropertySetStrategy ( ) != null ? jsonConfig . getPropertySetStrategy ( ) : PropertySetStrategy . DEFAULT ; propertySetStrategy . setProperty ( bean , key , value , jsonConfig ) ; } private static void setValue ( JSONObject jsonObject , String key , Object value , Class type , JsonConfig jsonConfig , boolean bypass ) { boolean accumulated = false ; if ( value == null ) { value = jsonConfig . findDefaultValueProcessor ( type ) . getDefaultValue ( type ) ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } if ( jsonObject . properties . containsKey ( key ) ) { if ( String . class . isAssignableFrom ( type ) ) { Object o = jsonObject . opt ( key ) ; if ( o instanceof JSONArray ) { ( ( JSONArray ) o ) . addString ( ( String ) value ) ; } else { jsonObject . properties . put ( key , new JSONArray ( ) . element ( o ) . addString ( ( String ) value ) ) ; } } else { jsonObject . accumulate ( key , value , jsonConfig ) ; } accumulated = true ; } else { if ( bypass || String . class . isAssignableFrom ( type ) ) { jsonObject . properties . put ( key , value ) ; } else { jsonObject . setInternal ( key , value , jsonConfig ) ; } } value = jsonObject . opt ( key ) ; if ( accumulated ) { JSONArray array = ( JSONArray ) value ; value = array . get ( array . size ( ) - <NUM_LIT:1> ) ; } firePropertySetEvent ( key , value , accumulated , jsonConfig ) ; } private boolean nullObject ; private Map properties ; public JSONObject ( ) { this . properties = new ListOrderedMap ( ) ; } public JSONObject ( boolean isNull ) { this ( ) ; this . nullObject = isNull ; } public JSONObject accumulate ( String key , boolean value ) { return _accumulate ( key , value ? Boolean . TRUE : Boolean . FALSE , new JsonConfig ( ) ) ; } public JSONObject accumulate ( String key , double value ) { return _accumulate ( key , new Double ( value ) , new JsonConfig ( ) ) ; } public JSONObject accumulate ( String key , int value ) { return _accumulate ( key , new Integer ( value ) , new JsonConfig ( ) ) ; } public JSONObject accumulate ( String key , long value ) { return _accumulate ( key , new Long ( value ) , new JsonConfig ( ) ) ; } public JSONObject accumulate ( String key , Object value ) { return _accumulate ( key , value , new JsonConfig ( ) ) ; } public JSONObject accumulate ( String key , Object value , JsonConfig jsonConfig ) { return _accumulate ( key , value , jsonConfig ) ; } public void accumulateAll ( Map map ) { accumulateAll ( map , new JsonConfig ( ) ) ; } public void accumulateAll ( Map map , JsonConfig jsonConfig ) { if ( map instanceof JSONObject ) { for ( Iterator entries = map . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; String key = ( String ) entry . getKey ( ) ; Object value = entry . getValue ( ) ; accumulate ( key , value , jsonConfig ) ; } } else { for ( Iterator entries = map . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; String key = String . valueOf ( entry . getKey ( ) ) ; Object value = entry . getValue ( ) ; accumulate ( key , value , jsonConfig ) ; } } } public void clear ( ) { properties . clear ( ) ; } public int compareTo ( Object obj ) { if ( obj != null && ( obj instanceof JSONObject ) ) { JSONObject other = ( JSONObject ) obj ; int size1 = size ( ) ; int size2 = other . size ( ) ; if ( size1 < size2 ) { return - <NUM_LIT:1> ; } else if ( size1 > size2 ) { return <NUM_LIT:1> ; } else if ( this . equals ( other ) ) { return <NUM_LIT:0> ; } } return - <NUM_LIT:1> ; } public boolean containsKey ( Object key ) { return properties . containsKey ( key ) ; } public boolean containsValue ( Object value ) { return containsValue ( value , new JsonConfig ( ) ) ; } public boolean containsValue ( Object value , JsonConfig jsonConfig ) { try { value = processValue ( value , jsonConfig ) ; } catch ( JSONException e ) { return false ; } return properties . containsValue ( value ) ; } public JSONObject discard ( String key ) { verifyIsNull ( ) ; this . properties . remove ( key ) ; return this ; } public JSONObject element ( String key , boolean value ) { verifyIsNull ( ) ; return element ( key , value ? Boolean . TRUE : Boolean . FALSE ) ; } public JSONObject element ( String key , Collection value ) { return element ( key , value , new JsonConfig ( ) ) ; } public JSONObject element ( String key , Collection value , JsonConfig jsonConfig ) { verifyIsNull ( ) ; if ( ! ( value instanceof JSONArray ) ) { value = JSONArray . fromObject ( value , jsonConfig ) ; } return setInternal ( key , value , jsonConfig ) ; } public JSONObject element ( String key , double value ) { verifyIsNull ( ) ; Double d = new Double ( value ) ; JSONUtils . testValidity ( d ) ; return element ( key , d ) ; } public JSONObject element ( String key , int value ) { verifyIsNull ( ) ; return element ( key , new Integer ( value ) ) ; } public JSONObject element ( String key , long value ) { verifyIsNull ( ) ; return element ( key , new Long ( value ) ) ; } public JSONObject element ( String key , Map value ) { return element ( key , value , new JsonConfig ( ) ) ; } public JSONObject element ( String key , Map value , JsonConfig jsonConfig ) { verifyIsNull ( ) ; if ( value instanceof JSONObject ) { return setInternal ( key , value , jsonConfig ) ; } else { return element ( key , JSONObject . fromObject ( value , jsonConfig ) , jsonConfig ) ; } } public JSONObject element ( String key , Object value ) { return element ( key , value , new JsonConfig ( ) ) ; } public JSONObject element ( String key , Object value , JsonConfig jsonConfig ) { verifyIsNull ( ) ; if ( key == null ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( value != null ) { value = processValue ( key , value , jsonConfig ) ; _setInternal ( key , value , jsonConfig ) ; } else { remove ( key ) ; } return this ; } public JSONObject elementOpt ( String key , Object value ) { return elementOpt ( key , value , new JsonConfig ( ) ) ; } public JSONObject elementOpt ( String key , Object value , JsonConfig jsonConfig ) { verifyIsNull ( ) ; if ( key != null && value != null ) { element ( key , value , jsonConfig ) ; } return this ; } public Set entrySet ( ) { return Collections . unmodifiableSet ( properties . entrySet ( ) ) ; } public boolean equals ( Object obj ) { if ( obj == this ) { return true ; } if ( obj == null ) { return false ; } if ( ! ( obj instanceof JSONObject ) ) { return false ; } JSONObject other = ( JSONObject ) obj ; if ( isNullObject ( ) ) { if ( other . isNullObject ( ) ) { return true ; } else { return false ; } } else { if ( other . isNullObject ( ) ) { return false ; } } if ( other . size ( ) != size ( ) ) { return false ; } for ( Iterator keys = properties . keySet ( ) . iterator ( ) ; keys . hasNext ( ) ; ) { String key = ( String ) keys . next ( ) ; if ( ! other . properties . containsKey ( key ) ) { return false ; } Object o1 = properties . get ( key ) ; Object o2 = other . properties . get ( key ) ; if ( JSONNull . getInstance ( ) . equals ( o1 ) ) { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { continue ; } else { return false ; } } else { if ( JSONNull . getInstance ( ) . equals ( o2 ) ) { return false ; } } if ( o1 instanceof String && o2 instanceof JSONFunction ) { if ( ! o1 . equals ( String . valueOf ( o2 ) ) ) { return false ; } } else if ( o1 instanceof JSONFunction && o2 instanceof String ) { if ( ! o2 . equals ( String . valueOf ( o1 ) ) ) { return false ; } } else if ( o1 instanceof JSONObject && o2 instanceof JSONObject ) { if ( ! o1 . equals ( o2 ) ) { return false ; } } else if ( o1 instanceof JSONArray && o2 instanceof JSONArray ) { if ( ! o1 . equals ( o2 ) ) { return false ; } } else if ( o1 instanceof JSONFunction && o2 instanceof JSONFunction ) { if ( ! o1 . equals ( o2 ) ) { return false ; } } else { if ( o1 instanceof String ) { if ( ! o1 . equals ( String . valueOf ( o2 ) ) ) { return false ; } } else if ( o2 instanceof String ) { if ( ! o2 . equals ( String . valueOf ( o1 ) ) ) { return false ; } } else { Morpher m1 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o1 . getClass ( ) ) ; Morpher m2 = JSONUtils . getMorpherRegistry ( ) . getMorpherFor ( o2 . getClass ( ) ) ; if ( m1 != null && m1 != IdentityObjectMorpher . getInstance ( ) ) { if ( ! o1 . equals ( JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o2 ) ) ) { return false ; } } else if ( m2 != null && m2 != IdentityObjectMorpher . getInstance ( ) ) { if ( ! JSONUtils . getMorpherRegistry ( ) . morph ( o1 . getClass ( ) , o1 ) . equals ( o2 ) ) { return false ; } } else { if ( ! o1 . equals ( o2 ) ) { return false ; } } } } } return true ; } public Object get ( Object key ) { if ( key instanceof String ) { return get ( ( String ) key ) ; } return null ; } public Object get ( String key ) { verifyIsNull ( ) ; return this . properties . get ( key ) ; } public boolean getBoolean ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( o != null ) { if ( o . equals ( Boolean . FALSE ) || ( o instanceof String && ( ( String ) o ) . equalsIgnoreCase ( "<STR_LIT:false>" ) ) ) { return false ; } else if ( o . equals ( Boolean . TRUE ) || ( o instanceof String && ( ( String ) o ) . equalsIgnoreCase ( "<STR_LIT:true>" ) ) ) { return true ; } } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public double getDouble ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( o != null ) { try { return o instanceof Number ? ( ( Number ) o ) . doubleValue ( ) : Double . parseDouble ( ( String ) o ) ; } catch ( Exception e ) { throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public int getInt ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( o != null ) { return o instanceof Number ? ( ( Number ) o ) . intValue ( ) : ( int ) getDouble ( key ) ; } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public JSONArray getJSONArray ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( o != null && o instanceof JSONArray ) { return ( JSONArray ) o ; } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public JSONObject getJSONObject ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( JSONNull . getInstance ( ) . equals ( o ) ) { return new JSONObject ( true ) ; } else if ( o instanceof JSONObject ) { return ( JSONObject ) o ; } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public long getLong ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( o != null ) { return o instanceof Number ? ( ( Number ) o ) . longValue ( ) : ( long ) getDouble ( key ) ; } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public String getString ( String key ) { verifyIsNull ( ) ; Object o = get ( key ) ; if ( o != null ) { return o . toString ( ) ; } throw new JSONException ( "<STR_LIT>" + JSONUtils . quote ( key ) + "<STR_LIT>" ) ; } public boolean has ( String key ) { verifyIsNull ( ) ; return this . properties . containsKey ( key ) ; } public int hashCode ( ) { int hashcode = <NUM_LIT> ; if ( isNullObject ( ) ) { return hashcode + JSONNull . getInstance ( ) . hashCode ( ) ; } for ( Iterator entries = properties . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; Object key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; hashcode += key . hashCode ( ) + JSONUtils . hashCode ( value ) ; } return hashcode ; } public boolean isArray ( ) { return false ; } public boolean isEmpty ( ) { return this . properties . isEmpty ( ) ; } public boolean isNullObject ( ) { return nullObject ; } public Iterator keys ( ) { verifyIsNull ( ) ; return keySet ( ) . iterator ( ) ; } public Set keySet ( ) { return Collections . unmodifiableSet ( properties . keySet ( ) ) ; } public JSONArray names ( ) { return names ( new JsonConfig ( ) ) ; } public JSONArray names ( JsonConfig jsonConfig ) { verifyIsNull ( ) ; JSONArray ja = new JSONArray ( ) ; Iterator keys = keys ( ) ; while ( keys . hasNext ( ) ) { ja . element ( keys . next ( ) , jsonConfig ) ; } return ja ; } public Object opt ( String key ) { verifyIsNull ( ) ; return key == null ? null : this . properties . get ( key ) ; } public boolean optBoolean ( String key ) { verifyIsNull ( ) ; return optBoolean ( key , false ) ; } public boolean optBoolean ( String key , boolean defaultValue ) { verifyIsNull ( ) ; try { return getBoolean ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public double optDouble ( String key ) { verifyIsNull ( ) ; return optDouble ( key , Double . NaN ) ; } public double optDouble ( String key , double defaultValue ) { verifyIsNull ( ) ; try { Object o = opt ( key ) ; return o instanceof Number ? ( ( Number ) o ) . doubleValue ( ) : new Double ( ( String ) o ) . doubleValue ( ) ; } catch ( Exception e ) { return defaultValue ; } } public int optInt ( String key ) { verifyIsNull ( ) ; return optInt ( key , <NUM_LIT:0> ) ; } public int optInt ( String key , int defaultValue ) { verifyIsNull ( ) ; try { return getInt ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public JSONArray optJSONArray ( String key ) { verifyIsNull ( ) ; Object o = opt ( key ) ; return o instanceof JSONArray ? ( JSONArray ) o : null ; } public JSONObject optJSONObject ( String key ) { verifyIsNull ( ) ; Object o = opt ( key ) ; return o instanceof JSONObject ? ( JSONObject ) o : null ; } public long optLong ( String key ) { verifyIsNull ( ) ; return optLong ( key , <NUM_LIT:0> ) ; } public long optLong ( String key , long defaultValue ) { verifyIsNull ( ) ; try { return getLong ( key ) ; } catch ( Exception e ) { return defaultValue ; } } public String optString ( String key ) { verifyIsNull ( ) ; return optString ( key , "<STR_LIT>" ) ; } public String optString ( String key , String defaultValue ) { verifyIsNull ( ) ; Object o = opt ( key ) ; return o != null ? o . toString ( ) : defaultValue ; } public Object put ( Object key , Object value ) { if ( key == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } Object previous = properties . get ( key ) ; element ( String . valueOf ( key ) , value ) ; return previous ; } public void putAll ( Map map ) { putAll ( map , new JsonConfig ( ) ) ; } public void putAll ( Map map , JsonConfig jsonConfig ) { if ( map instanceof JSONObject ) { for ( Iterator entries = map . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; String key = ( String ) entry . getKey ( ) ; Object value = entry . getValue ( ) ; this . properties . put ( key , value ) ; } } else { for ( Iterator entries = map . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; String key = String . valueOf ( entry . getKey ( ) ) ; Object value = entry . getValue ( ) ; element ( key , value , jsonConfig ) ; } } } public Object remove ( Object key ) { return properties . remove ( key ) ; } public Object remove ( String key ) { verifyIsNull ( ) ; return this . properties . remove ( key ) ; } public int size ( ) { return this . properties . size ( ) ; } public JSONArray toJSONArray ( JSONArray names ) { verifyIsNull ( ) ; if ( names == null || names . size ( ) == <NUM_LIT:0> ) { return null ; } JSONArray ja = new JSONArray ( ) ; for ( int i = <NUM_LIT:0> ; i < names . size ( ) ; i += <NUM_LIT:1> ) { ja . element ( this . opt ( names . getString ( i ) ) ) ; } return ja ; } public String toString ( ) { if ( isNullObject ( ) ) { return JSONNull . getInstance ( ) . toString ( ) ; } try { Iterator keys = keys ( ) ; StringBuffer sb = new StringBuffer ( "<STR_LIT:{>" ) ; while ( keys . hasNext ( ) ) { if ( sb . length ( ) > <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+002C>' ) ; } Object o = keys . next ( ) ; sb . append ( JSONUtils . quote ( o . toString ( ) ) ) ; sb . append ( '<CHAR_LIT::>' ) ; sb . append ( JSONUtils . valueToString ( this . properties . get ( o ) ) ) ; } sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } catch ( Exception e ) { return null ; } } public String toString ( int indentFactor ) { if ( isNullObject ( ) ) { return JSONNull . getInstance ( ) . toString ( ) ; } if ( indentFactor == <NUM_LIT:0> ) { return this . toString ( ) ; } return toString ( indentFactor , <NUM_LIT:0> ) ; } public String toString ( int indentFactor , int indent ) { if ( isNullObject ( ) ) { return JSONNull . getInstance ( ) . toString ( ) ; } int i ; int n = size ( ) ; if ( n == <NUM_LIT:0> ) { return "<STR_LIT:{}>" ; } if ( indentFactor == <NUM_LIT:0> ) { return this . toString ( ) ; } Iterator keys = keys ( ) ; StringBuffer sb = new StringBuffer ( "<STR_LIT:{>" ) ; int newindent = indent + indentFactor ; Object o ; if ( n == <NUM_LIT:1> ) { o = keys . next ( ) ; sb . append ( JSONUtils . quote ( o . toString ( ) ) ) ; sb . append ( "<STR_LIT::U+0020>" ) ; sb . append ( JSONUtils . valueToString ( this . properties . get ( o ) , indentFactor , indent ) ) ; } else { while ( keys . hasNext ( ) ) { o = keys . next ( ) ; if ( sb . length ( ) > <NUM_LIT:1> ) { sb . append ( "<STR_LIT>" ) ; } else { sb . append ( '<STR_LIT:\n>' ) ; } for ( i = <NUM_LIT:0> ; i < newindent ; i += <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+0020>' ) ; } sb . append ( JSONUtils . quote ( o . toString ( ) ) ) ; sb . append ( "<STR_LIT::U+0020>" ) ; sb . append ( JSONUtils . valueToString ( this . properties . get ( o ) , indentFactor , newindent ) ) ; } if ( sb . length ( ) > <NUM_LIT:1> ) { sb . append ( '<STR_LIT:\n>' ) ; for ( i = <NUM_LIT:0> ; i < indent ; i += <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+0020>' ) ; } } for ( i = <NUM_LIT:0> ; i < indent ; i += <NUM_LIT:1> ) { sb . insert ( <NUM_LIT:0> , '<CHAR_LIT:U+0020>' ) ; } } sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } public Collection values ( ) { return Collections . unmodifiableCollection ( properties . values ( ) ) ; } protected void write ( Writer writer , WritingVisitor visitor ) throws IOException { if ( isNullObject ( ) ) { writer . write ( JSONNull . getInstance ( ) . toString ( ) ) ; } boolean b = false ; Iterator keys = visitor . keySet ( this ) . iterator ( ) ; writer . write ( '<CHAR_LIT>' ) ; while ( keys . hasNext ( ) ) { if ( b ) { writer . write ( '<CHAR_LIT:U+002C>' ) ; } Object k = keys . next ( ) ; writer . write ( JSONUtils . quote ( k . toString ( ) ) ) ; writer . write ( '<CHAR_LIT::>' ) ; Object v = this . properties . get ( k ) ; if ( v instanceof JSON ) { visitor . on ( ( JSON ) v , writer ) ; } else { visitor . on ( v , writer ) ; } b = true ; } writer . write ( '<CHAR_LIT:}>' ) ; } private JSONObject _accumulate ( String key , Object value , JsonConfig jsonConfig ) { if ( isNullObject ( ) ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( ! has ( key ) ) { setInternal ( key , value , jsonConfig ) ; } else { Object o = opt ( key ) ; if ( o instanceof JSONArray ) { ( ( JSONArray ) o ) . element ( value , jsonConfig ) ; } else { setInternal ( key , new JSONArray ( ) . element ( o ) . element ( value , jsonConfig ) , jsonConfig ) ; } } return this ; } protected Object _processValue ( Object value , JsonConfig jsonConfig ) { if ( value instanceof JSONTokener ) { return _fromJSONTokener ( ( JSONTokener ) value , jsonConfig ) ; } return super . _processValue ( value , jsonConfig ) ; } private JSONObject _setInternal ( String key , Object value , JsonConfig jsonConfig ) { verifyIsNull ( ) ; if ( key == null ) { throw new JSONException ( "<STR_LIT>" ) ; } if ( JSONUtils . isString ( value ) && JSONUtils . mayBeJSON ( String . valueOf ( value ) ) ) { this . properties . put ( key , value ) ; } else { if ( CycleDetectionStrategy . IGNORE_PROPERTY_OBJ == value || CycleDetectionStrategy . IGNORE_PROPERTY_ARR == value ) { } else { this . properties . put ( key , value ) ; } } return this ; } private Object processValue ( Object value , JsonConfig jsonConfig ) { if ( value != null ) { JsonValueProcessor processor = jsonConfig . findJsonValueProcessor ( value . getClass ( ) ) ; if ( processor != null ) { value = processor . processObjectValue ( null , value , jsonConfig ) ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } } return _processValue ( value , jsonConfig ) ; } private Object processValue ( String key , Object value , JsonConfig jsonConfig ) { if ( value != null ) { JsonValueProcessor processor = jsonConfig . findJsonValueProcessor ( value . getClass ( ) , key ) ; if ( processor != null ) { value = processor . processObjectValue ( null , value , jsonConfig ) ; if ( ! JsonVerifier . isValidJsonValue ( value ) ) { throw new JSONException ( "<STR_LIT>" + value ) ; } } } return _processValue ( value , jsonConfig ) ; } private JSONObject setInternal ( String key , Object value , JsonConfig jsonConfig ) { return _setInternal ( key , processValue ( key , value , jsonConfig ) , jsonConfig ) ; } private void verifyIsNull ( ) { if ( isNullObject ( ) ) { throw new JSONException ( "<STR_LIT>" ) ; } } } </s>
<s> package net . sf . json ; import java . io . Serializable ; import net . sf . json . util . JSONUtils ; import org . apache . commons . lang . StringUtils ; import org . apache . commons . lang . builder . EqualsBuilder ; import org . apache . commons . lang . builder . HashCodeBuilder ; public class JSONFunction implements Serializable { private static final String [ ] EMPTY_PARAM_ARRAY = new String [ <NUM_LIT:0> ] ; public static JSONFunction parse ( String str ) { if ( ! JSONUtils . isFunction ( str ) ) { throw new JSONException ( "<STR_LIT>" + str ) ; } else { String params = JSONUtils . getFunctionParams ( str ) ; String text = JSONUtils . getFunctionBody ( str ) ; return new JSONFunction ( ( params != null ) ? StringUtils . split ( params , "<STR_LIT:U+002C>" ) : null , text != null ? text : "<STR_LIT>" ) ; } } private String [ ] params ; private String text ; public JSONFunction ( String text ) { this ( null , text ) ; } public JSONFunction ( String [ ] params , String text ) { this . text = ( text != null ) ? text . trim ( ) : "<STR_LIT>" ; if ( params != null ) { if ( params . length == <NUM_LIT:1> && params [ <NUM_LIT:0> ] . trim ( ) . equals ( "<STR_LIT>" ) ) { this . params = EMPTY_PARAM_ARRAY ; } else { this . params = new String [ params . length ] ; System . arraycopy ( params , <NUM_LIT:0> , this . params , <NUM_LIT:0> , params . length ) ; for ( int i = <NUM_LIT:0> ; i < params . length ; i ++ ) { this . params [ i ] = this . params [ i ] . trim ( ) ; } } } else { this . params = EMPTY_PARAM_ARRAY ; } } public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( obj instanceof String ) { try { JSONFunction other = parse ( ( String ) obj ) ; return equals ( other ) ; } catch ( JSONException e ) { return false ; } } if ( ! ( obj instanceof JSONFunction ) ) { return false ; } JSONFunction other = ( JSONFunction ) obj ; if ( params . length != other . params . length ) { return false ; } EqualsBuilder builder = new EqualsBuilder ( ) ; for ( int i = <NUM_LIT:0> ; i < params . length ; i ++ ) { builder . append ( params [ i ] , other . params [ i ] ) ; } builder . append ( text , other . text ) ; return builder . isEquals ( ) ; } public String [ ] getParams ( ) { return params ; } public String getText ( ) { return text ; } public int hashCode ( ) { HashCodeBuilder builder = new HashCodeBuilder ( ) ; for ( int i = <NUM_LIT:0> ; i < params . length ; i ++ ) { builder . append ( params [ i ] ) ; } builder . append ( text ) ; return builder . toHashCode ( ) ; } public String toString ( ) { StringBuffer b = new StringBuffer ( "<STR_LIT>" ) ; if ( params . length > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < params . length - <NUM_LIT:1> ; i ++ ) { b . append ( params [ i ] ) . append ( '<CHAR_LIT:U+002C>' ) ; } b . append ( params [ params . length - <NUM_LIT:1> ] ) ; } b . append ( "<STR_LIT>" ) ; if ( text . length ( ) > <NUM_LIT:0> ) { b . append ( '<CHAR_LIT:U+0020>' ) . append ( text ) . append ( '<CHAR_LIT:U+0020>' ) ; } b . append ( '<CHAR_LIT:}>' ) ; return b . toString ( ) ; } } </s>
<s> package net . sf . json ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import net . sf . json . processors . DefaultDefaultValueProcessor ; import net . sf . json . processors . DefaultValueProcessor ; import net . sf . json . processors . DefaultValueProcessorMatcher ; import net . sf . json . processors . JsonBeanProcessor ; import net . sf . json . processors . JsonBeanProcessorMatcher ; import net . sf . json . processors . JsonValueProcessor ; import net . sf . json . processors . JsonValueProcessorMatcher ; import net . sf . json . processors . PropertyNameProcessor ; import net . sf . json . processors . PropertyNameProcessorMatcher ; import net . sf . json . util . CycleDetectionStrategy ; import net . sf . json . util . JavaIdentifierTransformer ; import net . sf . json . util . JsonEventListener ; import net . sf . json . util . NewBeanInstanceStrategy ; import net . sf . json . util . PropertyExclusionClassMatcher ; import net . sf . json . util . PropertyFilter ; import net . sf . json . util . PropertySetStrategy ; import org . apache . commons . collections . map . MultiKeyMap ; import org . apache . commons . lang . StringUtils ; public class JsonConfig { public static final DefaultValueProcessorMatcher DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER = DefaultValueProcessorMatcher . DEFAULT ; public static final JsonBeanProcessorMatcher DEFAULT_JSON_BEAN_PROCESSOR_MATCHER = JsonBeanProcessorMatcher . DEFAULT ; public static final JsonValueProcessorMatcher DEFAULT_JSON_VALUE_PROCESSOR_MATCHER = JsonValueProcessorMatcher . DEFAULT ; public static final NewBeanInstanceStrategy DEFAULT_NEW_BEAN_INSTANCE_STRATEGY = NewBeanInstanceStrategy . DEFAULT ; public static final PropertyExclusionClassMatcher DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER = PropertyExclusionClassMatcher . DEFAULT ; public static final PropertyNameProcessorMatcher DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER = PropertyNameProcessorMatcher . DEFAULT ; public static final int MODE_LIST = <NUM_LIT:1> ; public static final int MODE_OBJECT_ARRAY = <NUM_LIT:2> ; public static final int MODE_SET = <NUM_LIT:2> ; private static final Class DEFAULT_COLLECTION_TYPE = List . class ; private static final CycleDetectionStrategy DEFAULT_CYCLE_DETECTION_STRATEGY = CycleDetectionStrategy . STRICT ; private static final String [ ] DEFAULT_EXCLUDES = new String [ ] { "<STR_LIT:class>" , "<STR_LIT>" , "<STR_LIT>" } ; private static final JavaIdentifierTransformer DEFAULT_JAVA_IDENTIFIER_TRANSFORMER = JavaIdentifierTransformer . NOOP ; private static final DefaultValueProcessor DEFAULT_VALUE_PROCESSOR = new DefaultDefaultValueProcessor ( ) ; private static final String [ ] EMPTY_EXCLUDES = new String [ <NUM_LIT:0> ] ; private int arrayMode = MODE_LIST ; private MultiKeyMap beanKeyMap = new MultiKeyMap ( ) ; private Map beanProcessorMap = new HashMap ( ) ; private MultiKeyMap beanTypeMap = new MultiKeyMap ( ) ; private Map classMap ; private Class collectionType = DEFAULT_COLLECTION_TYPE ; private CycleDetectionStrategy cycleDetectionStrategy = DEFAULT_CYCLE_DETECTION_STRATEGY ; private Map defaultValueMap = new HashMap ( ) ; private DefaultValueProcessorMatcher defaultValueProcessorMatcher = DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER ; private Class enclosedType ; private List eventListeners = new ArrayList ( ) ; private String [ ] excludes = EMPTY_EXCLUDES ; private Map exclusionMap = new HashMap ( ) ; private boolean handleJettisonEmptyElement ; private boolean handleJettisonSingleElementArray ; private boolean ignoreDefaultExcludes ; private boolean ignoreTransientFields ; private boolean ignorePublicFields = true ; private boolean javascriptCompliant ; private JavaIdentifierTransformer javaIdentifierTransformer = DEFAULT_JAVA_IDENTIFIER_TRANSFORMER ; private PropertyFilter javaPropertyFilter ; private Map javaPropertyNameProcessorMap = new HashMap ( ) ; private PropertyNameProcessorMatcher javaPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER ; private JsonBeanProcessorMatcher jsonBeanProcessorMatcher = DEFAULT_JSON_BEAN_PROCESSOR_MATCHER ; private PropertyFilter jsonPropertyFilter ; private Map jsonPropertyNameProcessorMap = new HashMap ( ) ; private PropertyNameProcessorMatcher jsonPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER ; private JsonValueProcessorMatcher jsonValueProcessorMatcher = DEFAULT_JSON_VALUE_PROCESSOR_MATCHER ; private Map keyMap = new HashMap ( ) ; private NewBeanInstanceStrategy newBeanInstanceStrategy = DEFAULT_NEW_BEAN_INSTANCE_STRATEGY ; private PropertyExclusionClassMatcher propertyExclusionClassMatcher = DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER ; private PropertySetStrategy propertySetStrategy ; private Class rootClass ; private boolean skipJavaIdentifierTransformationInMapKeys ; private boolean triggerEvents ; private Map typeMap = new HashMap ( ) ; private List ignoreFieldAnnotations = new ArrayList ( ) ; private boolean allowNonStringKeys = false ; public JsonConfig ( ) { } public synchronized void addJsonEventListener ( JsonEventListener listener ) { if ( ! eventListeners . contains ( listener ) ) { eventListeners . add ( listener ) ; } } public void clearJavaPropertyNameProcessors ( ) { javaPropertyNameProcessorMap . clear ( ) ; } public void clearJsonBeanProcessors ( ) { beanProcessorMap . clear ( ) ; } public synchronized void clearJsonEventListeners ( ) { eventListeners . clear ( ) ; } public void clearJsonPropertyNameProcessors ( ) { jsonPropertyNameProcessorMap . clear ( ) ; } public void clearJsonValueProcessors ( ) { beanKeyMap . clear ( ) ; beanTypeMap . clear ( ) ; keyMap . clear ( ) ; typeMap . clear ( ) ; } public void clearPropertyExclusions ( ) { exclusionMap . clear ( ) ; } public void clearPropertyNameProcessors ( ) { clearJavaPropertyNameProcessors ( ) ; } public JsonConfig copy ( ) { JsonConfig jsc = new JsonConfig ( ) ; jsc . beanKeyMap . putAll ( beanKeyMap ) ; jsc . beanTypeMap . putAll ( beanTypeMap ) ; jsc . classMap = new HashMap ( ) ; if ( classMap != null ) { jsc . classMap . putAll ( classMap ) ; } jsc . cycleDetectionStrategy = cycleDetectionStrategy ; if ( eventListeners != null ) { jsc . eventListeners . addAll ( eventListeners ) ; } if ( excludes != null ) { jsc . excludes = new String [ excludes . length ] ; System . arraycopy ( excludes , <NUM_LIT:0> , jsc . excludes , <NUM_LIT:0> , excludes . length ) ; } jsc . handleJettisonEmptyElement = handleJettisonEmptyElement ; jsc . handleJettisonSingleElementArray = handleJettisonSingleElementArray ; jsc . ignoreDefaultExcludes = ignoreDefaultExcludes ; jsc . ignoreTransientFields = ignoreTransientFields ; jsc . ignorePublicFields = ignorePublicFields ; jsc . javaIdentifierTransformer = javaIdentifierTransformer ; jsc . javascriptCompliant = javascriptCompliant ; jsc . keyMap . putAll ( keyMap ) ; jsc . beanProcessorMap . putAll ( beanProcessorMap ) ; jsc . rootClass = rootClass ; jsc . skipJavaIdentifierTransformationInMapKeys = skipJavaIdentifierTransformationInMapKeys ; jsc . triggerEvents = triggerEvents ; jsc . typeMap . putAll ( typeMap ) ; jsc . jsonPropertyFilter = jsonPropertyFilter ; jsc . javaPropertyFilter = javaPropertyFilter ; jsc . jsonBeanProcessorMatcher = jsonBeanProcessorMatcher ; jsc . newBeanInstanceStrategy = newBeanInstanceStrategy ; jsc . defaultValueProcessorMatcher = defaultValueProcessorMatcher ; jsc . defaultValueMap . putAll ( defaultValueMap ) ; jsc . propertySetStrategy = propertySetStrategy ; jsc . collectionType = collectionType ; jsc . enclosedType = enclosedType ; jsc . jsonValueProcessorMatcher = jsonValueProcessorMatcher ; jsc . javaPropertyNameProcessorMatcher = javaPropertyNameProcessorMatcher ; jsc . javaPropertyNameProcessorMap . putAll ( javaPropertyNameProcessorMap ) ; jsc . jsonPropertyNameProcessorMatcher = jsonPropertyNameProcessorMatcher ; jsc . jsonPropertyNameProcessorMap . putAll ( jsonPropertyNameProcessorMap ) ; jsc . propertyExclusionClassMatcher = propertyExclusionClassMatcher ; jsc . exclusionMap . putAll ( exclusionMap ) ; jsc . ignoreFieldAnnotations . addAll ( ignoreFieldAnnotations ) ; jsc . allowNonStringKeys = allowNonStringKeys ; return jsc ; } public void disableEventTriggering ( ) { triggerEvents = false ; } public void enableEventTriggering ( ) { triggerEvents = true ; } public DefaultValueProcessor findDefaultValueProcessor ( Class target ) { if ( ! defaultValueMap . isEmpty ( ) ) { Object key = defaultValueProcessorMatcher . getMatch ( target , defaultValueMap . keySet ( ) ) ; DefaultValueProcessor processor = ( DefaultValueProcessor ) defaultValueMap . get ( key ) ; if ( processor != null ) { return processor ; } } return DEFAULT_VALUE_PROCESSOR ; } public PropertyNameProcessor findJavaPropertyNameProcessor ( Class beanClass ) { if ( ! javaPropertyNameProcessorMap . isEmpty ( ) ) { Object key = javaPropertyNameProcessorMatcher . getMatch ( beanClass , javaPropertyNameProcessorMap . keySet ( ) ) ; return ( PropertyNameProcessor ) javaPropertyNameProcessorMap . get ( key ) ; } return null ; } public JsonBeanProcessor findJsonBeanProcessor ( Class target ) { if ( ! beanProcessorMap . isEmpty ( ) ) { Object key = jsonBeanProcessorMatcher . getMatch ( target , beanProcessorMap . keySet ( ) ) ; return ( JsonBeanProcessor ) beanProcessorMap . get ( key ) ; } return null ; } public PropertyNameProcessor findJsonPropertyNameProcessor ( Class beanClass ) { if ( ! jsonPropertyNameProcessorMap . isEmpty ( ) ) { Object key = jsonPropertyNameProcessorMatcher . getMatch ( beanClass , jsonPropertyNameProcessorMap . keySet ( ) ) ; return ( PropertyNameProcessor ) jsonPropertyNameProcessorMap . get ( key ) ; } return null ; } public JsonValueProcessor findJsonValueProcessor ( Class propertyType ) { if ( ! typeMap . isEmpty ( ) ) { Object key = jsonValueProcessorMatcher . getMatch ( propertyType , typeMap . keySet ( ) ) ; return ( JsonValueProcessor ) typeMap . get ( key ) ; } return null ; } public JsonValueProcessor findJsonValueProcessor ( Class beanClass , Class propertyType , String key ) { JsonValueProcessor jsonValueProcessor = null ; jsonValueProcessor = ( JsonValueProcessor ) beanKeyMap . get ( beanClass , key ) ; if ( jsonValueProcessor != null ) { return jsonValueProcessor ; } jsonValueProcessor = ( JsonValueProcessor ) beanTypeMap . get ( beanClass , propertyType ) ; if ( jsonValueProcessor != null ) { return jsonValueProcessor ; } jsonValueProcessor = ( JsonValueProcessor ) keyMap . get ( key ) ; if ( jsonValueProcessor != null ) { return jsonValueProcessor ; } Object tkey = jsonValueProcessorMatcher . getMatch ( propertyType , typeMap . keySet ( ) ) ; jsonValueProcessor = ( JsonValueProcessor ) typeMap . get ( tkey ) ; if ( jsonValueProcessor != null ) { return jsonValueProcessor ; } return null ; } public JsonValueProcessor findJsonValueProcessor ( Class propertyType , String key ) { JsonValueProcessor jsonValueProcessor = null ; jsonValueProcessor = ( JsonValueProcessor ) keyMap . get ( key ) ; if ( jsonValueProcessor != null ) { return jsonValueProcessor ; } Object tkey = jsonValueProcessorMatcher . getMatch ( propertyType , typeMap . keySet ( ) ) ; jsonValueProcessor = ( JsonValueProcessor ) typeMap . get ( tkey ) ; if ( jsonValueProcessor != null ) { return jsonValueProcessor ; } return null ; } public PropertyNameProcessor findPropertyNameProcessor ( Class beanClass ) { return findJavaPropertyNameProcessor ( beanClass ) ; } public int getArrayMode ( ) { return arrayMode ; } public Map getClassMap ( ) { return classMap ; } public Class getCollectionType ( ) { return collectionType ; } public CycleDetectionStrategy getCycleDetectionStrategy ( ) { return cycleDetectionStrategy ; } public DefaultValueProcessorMatcher getDefaultValueProcessorMatcher ( ) { return defaultValueProcessorMatcher ; } public Class getEnclosedType ( ) { return enclosedType ; } public String [ ] getExcludes ( ) { return excludes ; } public JavaIdentifierTransformer getJavaIdentifierTransformer ( ) { return javaIdentifierTransformer ; } public PropertyFilter getJavaPropertyFilter ( ) { return javaPropertyFilter ; } public PropertyNameProcessorMatcher getJavaPropertyNameProcessorMatcher ( ) { return javaPropertyNameProcessorMatcher ; } public JsonBeanProcessorMatcher getJsonBeanProcessorMatcher ( ) { return jsonBeanProcessorMatcher ; } public synchronized List getJsonEventListeners ( ) { return eventListeners ; } public PropertyFilter getJsonPropertyFilter ( ) { return jsonPropertyFilter ; } public PropertyNameProcessorMatcher getJsonPropertyNameProcessorMatcher ( ) { return javaPropertyNameProcessorMatcher ; } public JsonValueProcessorMatcher getJsonValueProcessorMatcher ( ) { return jsonValueProcessorMatcher ; } public Collection getMergedExcludes ( ) { Collection exclusions = new HashSet ( ) ; for ( int i = <NUM_LIT:0> ; i < excludes . length ; i ++ ) { String exclusion = excludes [ i ] ; if ( ! StringUtils . isBlank ( excludes [ i ] ) ) { exclusions . add ( exclusion . trim ( ) ) ; } } if ( ! ignoreDefaultExcludes ) { for ( int i = <NUM_LIT:0> ; i < DEFAULT_EXCLUDES . length ; i ++ ) { if ( ! exclusions . contains ( DEFAULT_EXCLUDES [ i ] ) ) { exclusions . add ( DEFAULT_EXCLUDES [ i ] ) ; } } } return exclusions ; } public Collection getMergedExcludes ( Class target ) { if ( target == null ) { return getMergedExcludes ( ) ; } Collection exclusionSet = getMergedExcludes ( ) ; if ( ! exclusionMap . isEmpty ( ) ) { Object key = propertyExclusionClassMatcher . getMatch ( target , exclusionMap . keySet ( ) ) ; Set set = ( Set ) exclusionMap . get ( key ) ; if ( set != null && ! set . isEmpty ( ) ) { for ( Iterator i = set . iterator ( ) ; i . hasNext ( ) ; ) { Object e = i . next ( ) ; if ( ! exclusionSet . contains ( e ) ) { exclusionSet . add ( e ) ; } } } } return exclusionSet ; } public NewBeanInstanceStrategy getNewBeanInstanceStrategy ( ) { return newBeanInstanceStrategy ; } public PropertyExclusionClassMatcher getPropertyExclusionClassMatcher ( ) { return propertyExclusionClassMatcher ; } public PropertyNameProcessorMatcher getPropertyNameProcessorMatcher ( ) { return getJavaPropertyNameProcessorMatcher ( ) ; } public PropertySetStrategy getPropertySetStrategy ( ) { return propertySetStrategy ; } public Class getRootClass ( ) { return rootClass ; } public boolean isAllowNonStringKeys ( ) { return allowNonStringKeys ; } public boolean isEventTriggeringEnabled ( ) { return triggerEvents ; } public boolean isHandleJettisonEmptyElement ( ) { return handleJettisonEmptyElement ; } public boolean isHandleJettisonSingleElementArray ( ) { return handleJettisonSingleElementArray ; } public boolean isIgnoreDefaultExcludes ( ) { return ignoreDefaultExcludes ; } public boolean isIgnoreJPATransient ( ) { return ignoreFieldAnnotations . contains ( "<STR_LIT>" ) ; } public boolean isIgnoreTransientFields ( ) { return ignoreTransientFields ; } public boolean isIgnorePublicFields ( ) { return ignorePublicFields ; } public boolean isJavascriptCompliant ( ) { return javascriptCompliant ; } public boolean isSkipJavaIdentifierTransformationInMapKeys ( ) { return skipJavaIdentifierTransformationInMapKeys ; } public void registerDefaultValueProcessor ( Class target , DefaultValueProcessor defaultValueProcessor ) { if ( target != null && defaultValueProcessor != null ) { defaultValueMap . put ( target , defaultValueProcessor ) ; } } public void registerJavaPropertyNameProcessor ( Class target , PropertyNameProcessor propertyNameProcessor ) { if ( target != null && propertyNameProcessor != null ) { javaPropertyNameProcessorMap . put ( target , propertyNameProcessor ) ; } } public void registerJsonBeanProcessor ( Class target , JsonBeanProcessor jsonBeanProcessor ) { if ( target != null && jsonBeanProcessor != null ) { beanProcessorMap . put ( target , jsonBeanProcessor ) ; } } public void registerJsonPropertyNameProcessor ( Class target , PropertyNameProcessor propertyNameProcessor ) { if ( target != null && propertyNameProcessor != null ) { jsonPropertyNameProcessorMap . put ( target , propertyNameProcessor ) ; } } public void registerJsonValueProcessor ( Class beanClass , Class propertyType , JsonValueProcessor jsonValueProcessor ) { if ( beanClass != null && propertyType != null && jsonValueProcessor != null ) { beanTypeMap . put ( beanClass , propertyType , jsonValueProcessor ) ; } } public void registerJsonValueProcessor ( Class propertyType , JsonValueProcessor jsonValueProcessor ) { if ( propertyType != null && jsonValueProcessor != null ) { typeMap . put ( propertyType , jsonValueProcessor ) ; } } public void registerJsonValueProcessor ( Class beanClass , String key , JsonValueProcessor jsonValueProcessor ) { if ( beanClass != null && key != null && jsonValueProcessor != null ) { beanKeyMap . put ( beanClass , key , jsonValueProcessor ) ; } } public void registerJsonValueProcessor ( String key , JsonValueProcessor jsonValueProcessor ) { if ( key != null && jsonValueProcessor != null ) { keyMap . put ( key , jsonValueProcessor ) ; } } public void registerPropertyExclusion ( Class target , String propertyName ) { if ( target != null && propertyName != null ) { Set set = ( Set ) exclusionMap . get ( target ) ; if ( set == null ) { set = new HashSet ( ) ; exclusionMap . put ( target , set ) ; } if ( ! set . contains ( propertyName ) ) { set . add ( propertyName ) ; } } } public void registerPropertyExclusions ( Class target , String [ ] properties ) { if ( target != null && properties != null && properties . length > <NUM_LIT:0> ) { Set set = ( Set ) exclusionMap . get ( target ) ; if ( set == null ) { set = new HashSet ( ) ; exclusionMap . put ( target , set ) ; } for ( int i = <NUM_LIT:0> ; i < properties . length ; i ++ ) { if ( ! set . contains ( properties [ i ] ) ) { set . add ( properties [ i ] ) ; } } } } public void registerPropertyNameProcessor ( Class target , PropertyNameProcessor propertyNameProcessor ) { registerJavaPropertyNameProcessor ( target , propertyNameProcessor ) ; } public synchronized void removeJsonEventListener ( JsonEventListener listener ) { eventListeners . remove ( listener ) ; } public void reset ( ) { excludes = EMPTY_EXCLUDES ; ignoreDefaultExcludes = false ; ignoreTransientFields = false ; ignorePublicFields = true ; javascriptCompliant = false ; javaIdentifierTransformer = DEFAULT_JAVA_IDENTIFIER_TRANSFORMER ; cycleDetectionStrategy = DEFAULT_CYCLE_DETECTION_STRATEGY ; skipJavaIdentifierTransformationInMapKeys = false ; triggerEvents = false ; handleJettisonEmptyElement = false ; handleJettisonSingleElementArray = false ; arrayMode = MODE_LIST ; rootClass = null ; classMap = null ; keyMap . clear ( ) ; typeMap . clear ( ) ; beanKeyMap . clear ( ) ; beanTypeMap . clear ( ) ; jsonPropertyFilter = null ; javaPropertyFilter = null ; jsonBeanProcessorMatcher = DEFAULT_JSON_BEAN_PROCESSOR_MATCHER ; newBeanInstanceStrategy = DEFAULT_NEW_BEAN_INSTANCE_STRATEGY ; defaultValueProcessorMatcher = DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER ; defaultValueMap . clear ( ) ; propertySetStrategy = null ; collectionType = DEFAULT_COLLECTION_TYPE ; enclosedType = null ; jsonValueProcessorMatcher = DEFAULT_JSON_VALUE_PROCESSOR_MATCHER ; javaPropertyNameProcessorMap . clear ( ) ; javaPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER ; jsonPropertyNameProcessorMap . clear ( ) ; jsonPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER ; beanProcessorMap . clear ( ) ; propertyExclusionClassMatcher = DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER ; exclusionMap . clear ( ) ; ignoreFieldAnnotations . clear ( ) ; allowNonStringKeys = false ; } public void setAllowNonStringKeys ( boolean allowNonStringKeys ) { this . allowNonStringKeys = allowNonStringKeys ; } public void setArrayMode ( int arrayMode ) { if ( arrayMode == MODE_OBJECT_ARRAY ) { this . arrayMode = arrayMode ; } else if ( arrayMode == MODE_SET ) { this . arrayMode = arrayMode ; this . collectionType = Set . class ; } else { this . arrayMode = MODE_LIST ; this . enclosedType = DEFAULT_COLLECTION_TYPE ; } } public void setClassMap ( Map classMap ) { this . classMap = classMap ; } public void setCollectionType ( Class collectionType ) { if ( collectionType != null ) { if ( ! Collection . class . isAssignableFrom ( collectionType ) ) { throw new JSONException ( "<STR_LIT>" + collectionType . getName ( ) ) ; } this . collectionType = collectionType ; } else { collectionType = DEFAULT_COLLECTION_TYPE ; } } public void setCycleDetectionStrategy ( CycleDetectionStrategy cycleDetectionStrategy ) { this . cycleDetectionStrategy = cycleDetectionStrategy == null ? DEFAULT_CYCLE_DETECTION_STRATEGY : cycleDetectionStrategy ; } public void setDefaultValueProcessorMatcher ( DefaultValueProcessorMatcher defaultValueProcessorMatcher ) { this . defaultValueProcessorMatcher = defaultValueProcessorMatcher == null ? DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER : defaultValueProcessorMatcher ; } public void setEnclosedType ( Class enclosedType ) { this . enclosedType = enclosedType ; } public void setExcludes ( String [ ] excludes ) { this . excludes = excludes == null ? EMPTY_EXCLUDES : excludes ; } public void setHandleJettisonEmptyElement ( boolean handleJettisonEmptyElement ) { this . handleJettisonEmptyElement = handleJettisonEmptyElement ; } public void setHandleJettisonSingleElementArray ( boolean handleJettisonSingleElementArray ) { this . handleJettisonSingleElementArray = handleJettisonSingleElementArray ; } public void setIgnoreDefaultExcludes ( boolean ignoreDefaultExcludes ) { this . ignoreDefaultExcludes = ignoreDefaultExcludes ; } public void setIgnoreJPATransient ( boolean ignoreJPATransient ) { if ( ignoreJPATransient ) { addIgnoreFieldAnnotation ( "<STR_LIT>" ) ; } else { removeIgnoreFieldAnnotation ( "<STR_LIT>" ) ; } } public void addIgnoreFieldAnnotation ( String annotationClassName ) { if ( annotationClassName != null && ! ignoreFieldAnnotations . contains ( annotationClassName ) ) { ignoreFieldAnnotations . add ( annotationClassName ) ; } } public void removeIgnoreFieldAnnotation ( String annotationClassName ) { if ( annotationClassName != null ) ignoreFieldAnnotations . remove ( annotationClassName ) ; } public void addIgnoreFieldAnnotation ( Class annotationClass ) { if ( annotationClass != null && ! ignoreFieldAnnotations . contains ( annotationClass . getName ( ) ) ) { ignoreFieldAnnotations . add ( annotationClass . getName ( ) ) ; } } public void removeIgnoreFieldAnnotation ( Class annotationClass ) { if ( annotationClass != null ) ignoreFieldAnnotations . remove ( annotationClass . getName ( ) ) ; } public List getIgnoreFieldAnnotations ( ) { return Collections . unmodifiableList ( ignoreFieldAnnotations ) ; } public void setIgnoreTransientFields ( boolean ignoreTransientFields ) { this . ignoreTransientFields = ignoreTransientFields ; } public void setIgnorePublicFields ( boolean ignorePublicFields ) { this . ignorePublicFields = ignorePublicFields ; } public void setJavascriptCompliant ( boolean javascriptCompliant ) { this . javascriptCompliant = javascriptCompliant ; } public void setJavaIdentifierTransformer ( JavaIdentifierTransformer javaIdentifierTransformer ) { this . javaIdentifierTransformer = javaIdentifierTransformer == null ? DEFAULT_JAVA_IDENTIFIER_TRANSFORMER : javaIdentifierTransformer ; } public void setJavaPropertyFilter ( PropertyFilter javaPropertyFilter ) { this . javaPropertyFilter = javaPropertyFilter ; } public void setJavaPropertyNameProcessorMatcher ( PropertyNameProcessorMatcher propertyNameProcessorMatcher ) { this . javaPropertyNameProcessorMatcher = propertyNameProcessorMatcher == null ? DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER : propertyNameProcessorMatcher ; } public void setJsonBeanProcessorMatcher ( JsonBeanProcessorMatcher jsonBeanProcessorMatcher ) { this . jsonBeanProcessorMatcher = jsonBeanProcessorMatcher == null ? DEFAULT_JSON_BEAN_PROCESSOR_MATCHER : jsonBeanProcessorMatcher ; } public void setJsonPropertyFilter ( PropertyFilter jsonPropertyFilter ) { this . jsonPropertyFilter = jsonPropertyFilter ; } public void setJsonPropertyNameProcessorMatcher ( PropertyNameProcessorMatcher propertyNameProcessorMatcher ) { this . jsonPropertyNameProcessorMatcher = propertyNameProcessorMatcher == null ? DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER : propertyNameProcessorMatcher ; } public void setJsonValueProcessorMatcher ( JsonValueProcessorMatcher jsonValueProcessorMatcher ) { this . jsonValueProcessorMatcher = jsonValueProcessorMatcher == null ? DEFAULT_JSON_VALUE_PROCESSOR_MATCHER : jsonValueProcessorMatcher ; } public void setNewBeanInstanceStrategy ( NewBeanInstanceStrategy newBeanInstanceStrategy ) { this . newBeanInstanceStrategy = newBeanInstanceStrategy == null ? DEFAULT_NEW_BEAN_INSTANCE_STRATEGY : newBeanInstanceStrategy ; } public void setPropertyExclusionClassMatcher ( PropertyExclusionClassMatcher propertyExclusionClassMatcher ) { this . propertyExclusionClassMatcher = propertyExclusionClassMatcher == null ? DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER : propertyExclusionClassMatcher ; } public void setPropertyNameProcessorMatcher ( PropertyNameProcessorMatcher propertyNameProcessorMatcher ) { setJavaPropertyNameProcessorMatcher ( propertyNameProcessorMatcher ) ; } public void setPropertySetStrategy ( PropertySetStrategy propertySetStrategy ) { this . propertySetStrategy = propertySetStrategy ; } public void setRootClass ( Class rootClass ) { this . rootClass = rootClass ; } public void setSkipJavaIdentifierTransformationInMapKeys ( boolean skipJavaIdentifierTransformationInMapKeys ) { this . skipJavaIdentifierTransformationInMapKeys = skipJavaIdentifierTransformationInMapKeys ; } public void unregisterDefaultValueProcessor ( Class target ) { if ( target != null ) { defaultValueMap . remove ( target ) ; } } public void unregisterJavaPropertyNameProcessor ( Class target ) { if ( target != null ) { javaPropertyNameProcessorMap . remove ( target ) ; } } public void unregisterJsonBeanProcessor ( Class target ) { if ( target != null ) { beanProcessorMap . remove ( target ) ; } } public void unregisterJsonPropertyNameProcessor ( Class target ) { if ( target != null ) { jsonPropertyNameProcessorMap . remove ( target ) ; } } public void unregisterJsonValueProcessor ( Class propertyType ) { if ( propertyType != null ) { typeMap . remove ( propertyType ) ; } } public void unregisterJsonValueProcessor ( Class beanClass , Class propertyType ) { if ( beanClass != null && propertyType != null ) { beanTypeMap . remove ( beanClass , propertyType ) ; } } public void unregisterJsonValueProcessor ( Class beanClass , String key ) { if ( beanClass != null && key != null ) { beanKeyMap . remove ( beanClass , key ) ; } } public void unregisterJsonValueProcessor ( String key ) { if ( key != null ) { keyMap . remove ( key ) ; } } public void unregisterPropertyExclusion ( Class target , String propertyName ) { if ( target != null && propertyName != null ) { Set set = ( Set ) exclusionMap . get ( target ) ; if ( set == null ) { set = new HashSet ( ) ; exclusionMap . put ( target , set ) ; } set . remove ( propertyName ) ; } } public void unregisterPropertyExclusions ( Class target ) { if ( target != null ) { Set set = ( Set ) exclusionMap . get ( target ) ; if ( set != null ) { set . clear ( ) ; } } } public void unregisterPropertyNameProcessor ( Class target ) { unregisterJavaPropertyNameProcessor ( target ) ; } } </s>
<s> package net . sf . json ; public interface JSONString { public String toJSONString ( ) ; } </s>
<s> package net . sf . json ; import java . io . IOException ; import java . io . Writer ; public final class JSONNull implements JSON { private static JSONNull instance ; static { instance = new JSONNull ( ) ; } public static JSONNull getInstance ( ) { return instance ; } private JSONNull ( ) { } public boolean equals ( Object object ) { return object == null || object == this || object == instance || ( object instanceof JSONObject && ( ( JSONObject ) object ) . isNullObject ( ) ) || "<STR_LIT:null>" . equals ( object ) ; } public int hashCode ( ) { return <NUM_LIT> + "<STR_LIT:null>" . hashCode ( ) ; } public boolean isArray ( ) { return false ; } public boolean isEmpty ( ) { throw new JSONException ( "<STR_LIT>" ) ; } public int size ( ) { throw new JSONException ( "<STR_LIT>" ) ; } public String toString ( ) { return "<STR_LIT:null>" ; } public String toString ( int indentFactor ) { return toString ( ) ; } public String toString ( int indentFactor , int indent ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = <NUM_LIT:0> ; i < indent ; i += <NUM_LIT:1> ) { sb . append ( '<CHAR_LIT:U+0020>' ) ; } sb . append ( toString ( ) ) ; return sb . toString ( ) ; } public Writer write ( Writer writer ) throws IOException { writer . write ( toString ( ) ) ; return writer ; } public Writer writeCanonical ( Writer w ) throws IOException { return write ( w ) ; } } </s>
<s> package net . java . joglutils . lighting ; import javax . media . opengl . * ; import java . awt . Color ; import java . nio . * ; public class Material { GL2 attachedGL ; private int face ; private float [ ] ambient ; private float [ ] diffuse ; private float [ ] specular ; private float shininess ; private float [ ] emissive ; public Material ( ) { attachedGL = null ; face = GL2 . GL_FRONT_AND_BACK ; float [ ] localAmb = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1.0f> } ; ambient = localAmb ; float [ ] localDiff = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1.0f> } ; diffuse = localDiff ; float [ ] localSpec = { <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:1.0f> } ; specular = localSpec ; float [ ] localEm = { <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:1.0f> } ; emissive = localEm ; shininess = <NUM_LIT:0> ; } public Material ( GL2 gl , int face ) { this . attachedGL = gl ; this . face = face ; this . specular = new float [ <NUM_LIT:4> ] ; this . ambient = new float [ <NUM_LIT:4> ] ; this . diffuse = new float [ <NUM_LIT:4> ] ; this . emissive = new float [ <NUM_LIT:4> ] ; this . retrieve ( ) ; } public Material ( GL2 gl ) { this ( gl , GL2 . GL_FRONT_AND_BACK ) ; } public void setAttachedGL ( GL2 gl ) { this . attachedGL = gl ; } public GL getAttachedGL ( ) { return this . attachedGL ; } public void detachGL ( ) { this . attachedGL = null ; } public boolean isAttached ( ) { if ( this . attachedGL == null ) return false ; return true ; } public void apply ( GL2 gl ) { gl . glMaterialfv ( face , GL2 . GL_SPECULAR , specular , <NUM_LIT:0> ) ; gl . glMaterialfv ( face , GL2 . GL_EMISSION , emissive , <NUM_LIT:0> ) ; gl . glMaterialfv ( face , GL2 . GL_AMBIENT , ambient , <NUM_LIT:0> ) ; gl . glMaterialfv ( face , GL2 . GL_DIFFUSE , diffuse , <NUM_LIT:0> ) ; gl . glMaterialf ( face , GL2 . GL_SHININESS , shininess ) ; } public void retrieve ( GL2 gl ) { int retrievalFace = face ; if ( face == GL2 . GL_FRONT_AND_BACK ) retrievalFace = GL2 . GL_FRONT ; FloatBuffer buff = FloatBuffer . allocate ( <NUM_LIT> ) ; gl . glGetMaterialfv ( retrievalFace , gl . GL_SPECULAR , buff ) ; buff . get ( this . specular ) ; gl . glGetMaterialfv ( retrievalFace , gl . GL_EMISSION , buff ) ; buff . get ( this . emissive ) ; gl . glGetMaterialfv ( retrievalFace , gl . GL_AMBIENT , buff ) ; buff . get ( this . ambient ) ; gl . glGetMaterialfv ( retrievalFace , gl . GL_DIFFUSE , buff ) ; buff . get ( this . diffuse ) ; gl . glGetMaterialfv ( retrievalFace , gl . GL_SHININESS , buff ) ; this . shininess = buff . get ( ) ; } public void apply ( ) throws LightingException { if ( attachedGL == null ) throw new LightingException ( "<STR_LIT>" ) ; this . apply ( this . attachedGL ) ; } public void retrieve ( ) throws LightingException { if ( attachedGL == null ) throw new LightingException ( "<STR_LIT>" ) ; this . retrieve ( attachedGL ) ; } public void setFace ( int face ) throws LightingException { if ( face == GL2 . GL_FRONT_AND_BACK ) this . face = GL2 . GL_FRONT_AND_BACK ; else if ( face == GL2 . GL_FRONT ) this . face = GL2 . GL_FRONT ; else if ( face == GL2 . GL_BACK ) this . face = GL2 . GL_BACK ; else throw new LightingException ( "<STR_LIT>" ) ; } public int getFace ( ) { return face ; } public void setSpecular ( Color specular ) { if ( this . attachedGL != null ) attachedGL . glMaterialfv ( face , GL2 . GL_SPECULAR , specular . getRGBComponents ( null ) , <NUM_LIT:0> ) ; this . specular = specular . getRGBComponents ( null ) ; } public Color getSpecular ( ) { return new Color ( specular [ <NUM_LIT:0> ] , specular [ <NUM_LIT:1> ] , specular [ <NUM_LIT:2> ] , specular [ <NUM_LIT:3> ] ) ; } public void setShininess ( float shininess ) { if ( this . attachedGL != null ) attachedGL . glMaterialf ( face , GL2 . GL_SHININESS , shininess ) ; this . shininess = shininess ; } public float getShininess ( ) { return shininess ; } public void setEmissive ( Color emissive ) { if ( this . attachedGL != null ) attachedGL . glMaterialfv ( face , GL2 . GL_EMISSION , emissive . getRGBComponents ( null ) , <NUM_LIT:0> ) ; this . emissive = emissive . getRGBComponents ( null ) ; } public Color getEmissive ( ) { return new Color ( emissive [ <NUM_LIT:0> ] , emissive [ <NUM_LIT:1> ] , emissive [ <NUM_LIT:2> ] , emissive [ <NUM_LIT:3> ] ) ; } public void setAmbient ( Color ambient ) { if ( this . attachedGL != null ) attachedGL . glMaterialfv ( face , GL2 . GL_AMBIENT , ambient . getRGBComponents ( null ) , <NUM_LIT:0> ) ; this . ambient = ambient . getRGBComponents ( null ) ; } public Color getAmbient ( ) { return new Color ( ambient [ <NUM_LIT:0> ] , ambient [ <NUM_LIT:1> ] , ambient [ <NUM_LIT:2> ] , ambient [ <NUM_LIT:3> ] ) ; } public void setDiffuse ( Color diffuse ) { if ( this . attachedGL != null ) attachedGL . glMaterialfv ( face , GL2 . GL_DIFFUSE , diffuse . getRGBComponents ( null ) , <NUM_LIT:0> ) ; this . diffuse = diffuse . getRGBComponents ( null ) ; } public Color getDiffuse ( ) { return new Color ( diffuse [ <NUM_LIT:0> ] , diffuse [ <NUM_LIT:1> ] , diffuse [ <NUM_LIT:2> ] , diffuse [ <NUM_LIT:3> ] ) ; } public void applyGlobalAmbient ( Color ambient ) throws LightingException { if ( this . attachedGL == null ) throw new LightingException ( "<STR_LIT>" ) ; this . applyGlobalAmbient ( this . attachedGL , ambient ) ; } public Color getGlobalAmbient ( ) throws LightingException { if ( this . attachedGL == null ) throw new LightingException ( "<STR_LIT>" ) ; return this . getGlobalAmbient ( this . attachedGL ) ; } public static void applyGlobalAmbient ( GL2 gl , Color ambient ) { gl . glLightModelfv ( gl . GL_LIGHT_MODEL_AMBIENT , ambient . getRGBComponents ( null ) , <NUM_LIT:0> ) ; } public static Color getGlobalAmbient ( GL2 gl ) { FloatBuffer buff = FloatBuffer . allocate ( <NUM_LIT:4> ) ; gl . glGetFloatv ( gl . GL_LIGHT_MODEL_AMBIENT , buff ) ; return new Color ( buff . get ( ) , buff . get ( ) , buff . get ( ) , buff . get ( ) ) ; } } </s>
<s> package net . java . joglutils . lighting ; import javax . media . opengl . * ; import java . awt . Color ; import java . util . * ; import java . nio . * ; public class Light { static HashMap < GL , boolean [ ] > assignedLights = new HashMap < GL , boolean [ ] > ( ) ; static HashMap < GL , Boolean > shaderBuiltin = new HashMap < GL , Boolean > ( ) ; static HashMap < GL , Integer > shaderProgNums = new HashMap < GL , Integer > ( ) ; private GL2 attachedGL ; private int lightNumber ; private float [ ] ambient ; private float [ ] diffuse ; private float [ ] specular ; private float [ ] lightPosition ; private float lightW ; private float [ ] spotDirection ; private float spotCutoff ; private float spotExponent ; private float constantAttenuation ; private float linearAttenuation ; private float quadraticAttenuation ; private boolean phongShaded ; private boolean phongDiffColorMat ; private boolean phongAmbColorMat ; public Light ( ) { attachedGL = null ; lightNumber = - <NUM_LIT:1> ; float [ ] localAmb = { <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:1.0f> } ; ambient = localAmb ; float [ ] localDiff = { <NUM_LIT:1.0f> , <NUM_LIT:1.0f> , <NUM_LIT:1.0f> , <NUM_LIT:1.0f> } ; diffuse = localDiff ; float [ ] localSpec = { <NUM_LIT:1.0f> , <NUM_LIT:1.0f> , <NUM_LIT:1.0f> , <NUM_LIT:1.0f> } ; specular = localSpec ; float [ ] localPos = { <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1> } ; lightPosition = localPos ; lightW = <NUM_LIT:0> ; float [ ] localSpotDir = { <NUM_LIT:0> , <NUM_LIT:0> , - <NUM_LIT:1> } ; spotDirection = localSpotDir ; spotCutoff = <NUM_LIT> ; spotExponent = <NUM_LIT:0> ; constantAttenuation = <NUM_LIT:1> ; linearAttenuation = <NUM_LIT:0> ; quadraticAttenuation = <NUM_LIT:0> ; phongShaded = false ; phongDiffColorMat = false ; phongAmbColorMat = false ; } public Light ( GL2 gl ) throws LightingException { this ( ) ; this . attachedGL = gl ; this . lightNumber = this . findAndAssignFreeLightNumber ( gl ) ; if ( this . lightNumber == - <NUM_LIT:1> ) { this . attachedGL = null ; throw new LightingException ( "<STR_LIT>" ) ; } retrieve ( ) ; } public Light ( GL2 gl , int lightNumber ) throws LightingException { this ( ) ; if ( lightNumber < <NUM_LIT:0> || lightNumber > maxNumberOfLightsInGL ( gl ) ) throw new LightingException ( "<STR_LIT>" ) ; this . attachedGL = gl ; this . lightNumber = this . findAndAssignFreeLightNumber ( gl ) ; if ( this . lightNumber == - <NUM_LIT:1> ) { this . attachedGL = null ; throw new LightingException ( "<STR_LIT>" ) ; } retrieve ( ) ; } protected void finalize ( ) { if ( this . attachedGL != null ) this . unassignLightNumber ( this . attachedGL , this . lightNumber ) ; } public int getGLLightIdentifier ( ) { return this . numToID ( this . lightNumber ) ; } public int getLightNumber ( ) { return this . lightNumber ; } public void setLightNumber ( int lightNumber ) throws LightingException { if ( lightNumber < <NUM_LIT:0> || lightNumber > <NUM_LIT:7> ) throw new LightingException ( "<STR_LIT>" ) ; if ( this . attachedGL != null ) { if ( ! isLightNumberFree ( this . attachedGL , lightNumber ) ) throw new LightingException ( "<STR_LIT>" ) ; this . unassignLightNumber ( this . attachedGL , this . lightNumber ) ; this . assignLightNumber ( this . attachedGL , lightNumber ) ; } this . lightNumber = lightNumber ; } public void setLightID ( int lightID ) throws LightingException { setLightNumber ( this . idToNum ( lightID ) ) ; } public void setAttachedGL ( GL2 gl ) throws LightingException { this . unassignLightNumber ( this . attachedGL , this . lightNumber ) ; if ( ! this . hasFreeLights ( gl ) ) { this . attachedGL = null ; this . lightNumber = - <NUM_LIT:1> ; throw new LightingException ( "<STR_LIT>" ) ; } this . lightNumber = findAndAssignFreeLightNumber ( gl ) ; this . attachedGL = gl ; if ( this . phongShaded ) { if ( ! this . shaderBuiltin . containsKey ( gl ) ) this . initializePhongShader ( gl ) ; } } public GL getAttachedGL ( ) { return this . attachedGL ; } public void detachGL ( ) { this . unassignLightNumber ( this . attachedGL , this . lightNumber ) ; this . attachedGL = null ; } public boolean isAttached ( ) { if ( this . attachedGL == null ) return false ; return true ; } public void apply ( ) { apply ( this . attachedGL , this . lightNumber ) ; } public void retrieve ( ) { retrieve ( this . attachedGL , this . lightNumber ) ; } public void enable ( ) { enable ( this . attachedGL , this . lightNumber ) ; } public void disable ( ) { disable ( this . attachedGL , this . lightNumber ) ; } public void apply ( GL2 gl ) throws LightingException { apply ( gl , this . lightNumber ) ; } public void retrieve ( GL2 gl ) throws LightingException { retrieve ( gl , this . lightNumber ) ; } public void enable ( GL2 gl ) throws LightingException { enable ( gl , this . lightNumber ) ; } public void disable ( GL2 gl ) throws LightingException { disable ( gl , this . lightNumber ) ; } public void apply ( GL2 gl , int lightNumber ) throws LightingException { if ( ! this . isLightNumberValid ( gl , lightNumber ) ) throw new LightingException ( "<STR_LIT>" ) ; int lightID = numToID ( lightNumber ) ; gl . glLightfv ( lightID , GL2 . GL_AMBIENT , ambient , <NUM_LIT:0> ) ; gl . glLightfv ( lightID , GL2 . GL_DIFFUSE , diffuse , <NUM_LIT:0> ) ; gl . glLightfv ( lightID , GL2 . GL_SPECULAR , specular , <NUM_LIT:0> ) ; float [ ] position = new float [ <NUM_LIT:4> ] ; position [ <NUM_LIT:0> ] = lightPosition [ <NUM_LIT:0> ] ; position [ <NUM_LIT:1> ] = lightPosition [ <NUM_LIT:1> ] ; position [ <NUM_LIT:2> ] = lightPosition [ <NUM_LIT:2> ] ; position [ <NUM_LIT:3> ] = lightW ; gl . glLightfv ( lightID , GL2 . GL_POSITION , position , <NUM_LIT:0> ) ; gl . glLightfv ( lightID , GL2 . GL_SPOT_DIRECTION , spotDirection , <NUM_LIT:0> ) ; gl . glLightf ( lightID , GL2 . GL_SPOT_CUTOFF , spotCutoff ) ; gl . glLightf ( lightID , GL2 . GL_SPOT_EXPONENT , spotExponent ) ; gl . glLightf ( lightID , GL2 . GL_CONSTANT_ATTENUATION , constantAttenuation ) ; gl . glLightf ( lightID , GL2 . GL_LINEAR_ATTENUATION , linearAttenuation ) ; gl . glLightf ( lightID , GL2 . GL_QUADRATIC_ATTENUATION , quadraticAttenuation ) ; this . lightNumber = lightNumber ; } public void retrieve ( GL2 gl , int lightNumber ) throws LightingException { if ( ! this . isLightNumberValid ( gl , lightNumber ) ) throw new LightingException ( "<STR_LIT>" ) ; int lightID = numToID ( lightNumber ) ; FloatBuffer buff = FloatBuffer . allocate ( <NUM_LIT:24> ) ; gl . glGetLightfv ( lightID , GL2 . GL_AMBIENT , buff ) ; buff . get ( this . ambient ) ; gl . glGetLightfv ( lightID , GL2 . GL_DIFFUSE , buff ) ; buff . get ( this . diffuse ) ; gl . glGetLightfv ( lightID , GL2 . GL_SPECULAR , buff ) ; buff . get ( this . specular ) ; gl . glGetLightfv ( lightID , GL2 . GL_POSITION , buff ) ; buff . get ( this . lightPosition ) ; this . lightW = buff . get ( ) ; gl . glGetLightfv ( lightID , GL2 . GL_SPOT_DIRECTION , buff ) ; buff . get ( this . spotDirection ) ; gl . glGetLightfv ( lightID , GL2 . GL_SPOT_CUTOFF , buff ) ; this . spotCutoff = buff . get ( ) ; gl . glGetLightfv ( lightID , GL2 . GL_SPOT_EXPONENT , buff ) ; this . spotExponent = buff . get ( ) ; gl . glGetLightfv ( lightID , GL2 . GL_CONSTANT_ATTENUATION , buff ) ; this . constantAttenuation = buff . get ( ) ; gl . glGetLightfv ( lightID , GL2 . GL_LINEAR_ATTENUATION , buff ) ; this . linearAttenuation = buff . get ( ) ; gl . glGetLightfv ( lightID , GL2 . GL_QUADRATIC_ATTENUATION , buff ) ; this . quadraticAttenuation = buff . get ( ) ; this . lightNumber = lightNumber ; } public void enable ( GL2 gl , int lightNumber ) throws LightingException { if ( ! this . isLightNumberValid ( gl , lightNumber ) ) throw new LightingException ( "<STR_LIT>" ) ; gl . glEnable ( numToID ( lightNumber ) ) ; this . lightNumber = lightNumber ; if ( this . phongShaded ) { if ( ! shaderBuiltin . containsKey ( gl ) ) initializePhongShader ( gl ) ; if ( shaderBuiltin . get ( gl ) ) { int progID = shaderProgNums . get ( gl ) ; gl . glUseProgram ( progID + lightNumber ) ; int diffMatCol = gl . glGetUniformLocation ( progID , "<STR_LIT>" ) ; int ambMatCol = gl . glGetUniformLocation ( progID , "<STR_LIT>" ) ; gl . glUniform1i ( diffMatCol , phongDiffColorMat ? <NUM_LIT:1> : <NUM_LIT:0> ) ; gl . glUniform1i ( ambMatCol , phongAmbColorMat ? <NUM_LIT:1> : <NUM_LIT:0> ) ; } else { int progID = shaderProgNums . get ( gl ) ; int diffMatCol = gl . glGetUniformLocationARB ( progID , "<STR_LIT>" ) ; int ambMatCol = gl . glGetUniformLocationARB ( progID , "<STR_LIT>" ) ; gl . glUniform1iARB ( diffMatCol , phongDiffColorMat ? <NUM_LIT:1> : <NUM_LIT:0> ) ; gl . glUniform1iARB ( ambMatCol , phongAmbColorMat ? <NUM_LIT:1> : <NUM_LIT:0> ) ; gl . glUseProgramObjectARB ( progID + lightNumber ) ; } } else { Integer result = shaderProgNums . get ( gl ) ; if ( result != null ) { int lightID = result + lightNumber ; java . nio . IntBuffer buffer = java . nio . IntBuffer . allocate ( <NUM_LIT:1> ) ; gl . glGetIntegerv ( GL2 . GL_CURRENT_PROGRAM , buffer ) ; int currProgram = buffer . get ( ) ; if ( currProgram == lightID ) gl . glUseProgramObjectARB ( <NUM_LIT:0> ) ; } } } public void disable ( GL2 gl , int lightNumber ) throws LightingException { if ( ! this . isLightNumberValid ( gl , lightNumber ) ) throw new LightingException ( "<STR_LIT>" ) ; gl . glDisable ( numToID ( lightNumber ) ) ; this . lightNumber = lightNumber ; if ( this . phongShaded ) { if ( gl . isFunctionAvailable ( "<STR_LIT>" ) ) gl . glUseProgram ( <NUM_LIT:0> ) ; else if ( gl . isFunctionAvailable ( "<STR_LIT>" ) ) gl . glUseProgramObjectARB ( <NUM_LIT:0> ) ; } } public void setAmbient ( Color ambient ) { this . ambient = ambient . getRGBComponents ( null ) ; if ( this . attachedGL != null ) this . attachedGL . glLightfv ( numToID ( lightNumber ) , GL2 . GL_AMBIENT , this . ambient , <NUM_LIT:0> ) ; } public Color getAmbient ( ) { return new Color ( ambient [ <NUM_LIT:0> ] , ambient [ <NUM_LIT:1> ] , ambient [ <NUM_LIT:2> ] , ambient [ <NUM_LIT:3> ] ) ; } public void setDiffuse ( Color diffuse ) { this . diffuse = diffuse . getRGBComponents ( null ) ; if ( this . attachedGL != null ) this . attachedGL . glLightfv ( numToID ( lightNumber ) , GL2 . GL_DIFFUSE , this . diffuse , <NUM_LIT:0> ) ; } public Color getDiffuse ( ) { return new Color ( diffuse [ <NUM_LIT:0> ] , diffuse [ <NUM_LIT:1> ] , diffuse [ <NUM_LIT:2> ] , diffuse [ <NUM_LIT:3> ] ) ; } public void setSpecular ( Color specular ) { this . specular = specular . getRGBComponents ( null ) ; if ( this . attachedGL != null ) this . attachedGL . glLightfv ( numToID ( lightNumber ) , GL2 . GL_SPECULAR , this . specular , <NUM_LIT:0> ) ; } public Color getSpecular ( ) { return new Color ( specular [ <NUM_LIT:0> ] , specular [ <NUM_LIT:1> ] , specular [ <NUM_LIT:2> ] , specular [ <NUM_LIT:3> ] ) ; } public void setLightPosition ( float [ ] lightPosition ) { if ( this . attachedGL != null ) { float [ ] position = new float [ <NUM_LIT:4> ] ; position [ <NUM_LIT:0> ] = lightPosition [ <NUM_LIT:0> ] ; position [ <NUM_LIT:1> ] = lightPosition [ <NUM_LIT:1> ] ; position [ <NUM_LIT:2> ] = lightPosition [ <NUM_LIT:2> ] ; position [ <NUM_LIT:3> ] = this . lightW ; this . attachedGL . glLightfv ( numToID ( lightNumber ) , GL2 . GL_POSITION , position , <NUM_LIT:0> ) ; } this . lightPosition = lightPosition . clone ( ) ; } public void setLightPosition ( float lightx , float lighty , float lightz ) { float [ ] pos = { lightx , lighty , lightz } ; setLightPosition ( pos ) ; } public float [ ] getLightPosition ( ) { return this . lightPosition . clone ( ) ; } public void setSpotDirection ( float [ ] spotDirection ) { if ( this . attachedGL != null ) this . attachedGL . glLightfv ( numToID ( lightNumber ) , GL2 . GL_SPOT_DIRECTION , spotDirection , <NUM_LIT:0> ) ; this . spotDirection = spotDirection . clone ( ) ; } public void setSpotDirection ( float spotx , float spoty , float spotz ) { float [ ] spotVec = { spotx , spoty , spotz } ; setSpotDirection ( spotVec ) ; } public float [ ] getSpotDirection ( ) { return this . spotDirection . clone ( ) ; } public void setLightW ( float lightW ) { if ( this . attachedGL != null ) { float [ ] position = new float [ <NUM_LIT:4> ] ; position [ <NUM_LIT:0> ] = this . lightPosition [ <NUM_LIT:0> ] ; position [ <NUM_LIT:1> ] = this . lightPosition [ <NUM_LIT:1> ] ; position [ <NUM_LIT:2> ] = this . lightPosition [ <NUM_LIT:2> ] ; position [ <NUM_LIT:3> ] = lightW ; this . attachedGL . glLightfv ( numToID ( lightNumber ) , GL2 . GL_POSITION , position , <NUM_LIT:0> ) ; } this . lightW = lightW ; } public float getLightW ( ) { return lightW ; } public void makeDirectional ( ) { this . setLightW ( <NUM_LIT:0.0f> ) ; } public void setSpotCutoff ( float spotCutoff ) { if ( this . attachedGL != null ) this . attachedGL . glLightf ( numToID ( lightNumber ) , GL2 . GL_SPOT_CUTOFF , spotCutoff ) ; this . spotCutoff = spotCutoff ; } public float getSpotCutoff ( ) { return spotCutoff ; } public void setSpotExponent ( float spotExponent ) { if ( this . attachedGL != null ) this . attachedGL . glLightf ( numToID ( lightNumber ) , GL2 . GL_SPOT_EXPONENT , spotExponent ) ; this . spotExponent = spotExponent ; } public float getSpotExponent ( ) { return spotExponent ; } public void setConstantAttenuation ( float constantAttenuation ) { if ( this . attachedGL != null ) this . attachedGL . glLightf ( numToID ( lightNumber ) , GL2 . GL_CONSTANT_ATTENUATION , constantAttenuation ) ; this . constantAttenuation = constantAttenuation ; } public float getConstantAttenuation ( ) { return constantAttenuation ; } public void setLinearAttenuation ( float linearAttenuation ) { if ( this . attachedGL != null ) this . attachedGL . glLightf ( numToID ( lightNumber ) , GL2 . GL_LINEAR_ATTENUATION , linearAttenuation ) ; this . linearAttenuation = linearAttenuation ; } public float getLinearAttenuation ( ) { return linearAttenuation ; } public void setQuadraticAttenuation ( float quadraticAttenuation ) { if ( this . attachedGL != null ) this . attachedGL . glLightf ( numToID ( lightNumber ) , GL2 . GL_QUADRATIC_ATTENUATION , quadraticAttenuation ) ; this . quadraticAttenuation = quadraticAttenuation ; } public float getQuadraticAttenuation ( ) { return quadraticAttenuation ; } public static int maxNumberOfLightsInGL ( GL2 gl ) { java . nio . IntBuffer buff = java . nio . IntBuffer . allocate ( <NUM_LIT:1> ) ; gl . glGetIntegerv ( gl . GL_MAX_LIGHTS , buff ) ; return buff . get ( ) ; } public static int idToNum ( int lightID ) throws LightingException { int retNum = - <NUM_LIT:1> ; switch ( lightID ) { case GL2 . GL_LIGHT0 : retNum = <NUM_LIT:0> ; break ; case GL2 . GL_LIGHT1 : retNum = <NUM_LIT:1> ; break ; case GL2 . GL_LIGHT2 : retNum = <NUM_LIT:2> ; break ; case GL2 . GL_LIGHT3 : retNum = <NUM_LIT:3> ; break ; case GL2 . GL_LIGHT4 : retNum = <NUM_LIT:4> ; break ; case GL2 . GL_LIGHT5 : retNum = <NUM_LIT:5> ; break ; case GL2 . GL_LIGHT6 : retNum = <NUM_LIT:6> ; break ; case GL2 . GL_LIGHT7 : retNum = <NUM_LIT:7> ; break ; default : throw new LightingException ( "<STR_LIT>" ) ; } return retNum ; } public static int numToID ( int lightNum ) throws LightingException { int retID = - <NUM_LIT:1> ; switch ( lightNum ) { case <NUM_LIT:0> : retID = GL2 . GL_LIGHT0 ; break ; case <NUM_LIT:1> : retID = GL2 . GL_LIGHT1 ; break ; case <NUM_LIT:2> : retID = GL2 . GL_LIGHT2 ; break ; case <NUM_LIT:3> : retID = GL2 . GL_LIGHT3 ; break ; case <NUM_LIT:4> : retID = GL2 . GL_LIGHT4 ; break ; case <NUM_LIT:5> : retID = GL2 . GL_LIGHT5 ; break ; case <NUM_LIT:6> : retID = GL2 . GL_LIGHT6 ; break ; case <NUM_LIT:7> : retID = GL2 . GL_LIGHT7 ; break ; default : throw new LightingException ( "<STR_LIT>" ) ; } return retID ; } public static boolean hasFreeLights ( GL2 gl ) { boolean [ ] lights = assignedLights . get ( gl ) ; if ( lights == null ) return true ; for ( boolean b : lights ) { if ( ! b ) return true ; } return false ; } public void setPhongShaded ( boolean usePhongShading ) throws LightingException { if ( this . attachedGL != null ) initializePhongShader ( this . attachedGL ) ; this . phongShaded = usePhongShading ; } public boolean isPhongShaded ( ) { return this . phongShaded ; } public void setPhongColorMaterial ( boolean ambient , boolean diffuse ) { this . phongAmbColorMat = ambient ; this . phongDiffColorMat = diffuse ; } public boolean isAmbientPhongColorMaterial ( ) { return this . phongAmbColorMat ; } public boolean isDiffusePhongColorMaterial ( ) { return this . phongDiffColorMat ; } public static void initializePhongShader ( ) throws LightingException { initializePhongShader ( javax . media . opengl . glu . GLU . getCurrentGL ( ) . getGL2 ( ) ) ; } public static void initializePhongShader ( GL2 gl ) throws LightingException { boolean builtin ; int progID ; if ( gl . isFunctionAvailable ( "<STR_LIT>" ) ) builtin = true ; else if ( gl . isFunctionAvailable ( "<STR_LIT>" ) ) builtin = false ; else throw new LightingException ( "<STR_LIT>" ) ; if ( builtin ) { progID = gl . glCreateProgram ( ) ; for ( int currID = <NUM_LIT:1> + progID ; currID < ( progID + <NUM_LIT:8> ) ; ++ currID ) { int result = gl . glCreateProgram ( ) ; if ( result != currID ) throw new LightingException ( "<STR_LIT>" ) ; } int vertID = gl . glCreateShader ( GL2 . GL_VERTEX_SHADER ) ; String [ ] vertSource = generatePhongVertexShaderSource ( ) ; gl . glShaderSource ( vertID , vertSource . length , vertSource , generateShaderLengths ( vertSource ) , <NUM_LIT:0> ) ; for ( int currID = progID ; currID < ( <NUM_LIT:8> + progID ) ; ++ currID ) { int fragID = gl . glCreateShader ( GL2 . GL_FRAGMENT_SHADER ) ; String [ ] fragSource = generatePhongFragmentShaderSource ( currID - progID ) ; gl . glShaderSource ( fragID , fragSource . length , fragSource , generateShaderLengths ( fragSource ) , <NUM_LIT:0> ) ; gl . glCompileShader ( vertID ) ; gl . glCompileShader ( fragID ) ; gl . glAttachShader ( currID , vertID ) ; gl . glAttachShader ( currID , fragID ) ; gl . glLinkProgram ( currID ) ; int [ ] getProgArray = new int [ <NUM_LIT:1> ] ; gl . glGetProgramiv ( currID , GL2 . GL_LINK_STATUS , getProgArray , <NUM_LIT:0> ) ; if ( getProgArray [ <NUM_LIT:0> ] == GL2 . GL_FALSE ) { gl . glGetProgramiv ( currID , GL2 . GL_INFO_LOG_LENGTH , getProgArray , <NUM_LIT:0> ) ; int logLength = getProgArray [ <NUM_LIT:0> ] ; byte [ ] logArray = new byte [ logLength ] ; gl . glGetProgramInfoLog ( currID , logLength , getProgArray , <NUM_LIT:0> , logArray , <NUM_LIT:0> ) ; String log = new String ( logArray ) ; throw new LightingException ( "<STR_LIT>" + log ) ; } } } else { progID = gl . glCreateProgramObjectARB ( ) ; for ( int currID = <NUM_LIT:1> + progID ; currID < ( progID + <NUM_LIT:8> ) ; ++ currID ) { int result = gl . glCreateProgramObjectARB ( ) ; if ( result != currID ) throw new LightingException ( "<STR_LIT>" ) ; } int vertID = gl . glCreateShaderObjectARB ( GL2 . GL_VERTEX_SHADER ) ; String [ ] vertSource = generatePhongVertexShaderSource ( ) ; gl . glShaderSourceARB ( vertID , vertSource . length , vertSource , generateShaderLengths ( vertSource ) , <NUM_LIT:0> ) ; for ( int currID = progID ; currID < ( <NUM_LIT:8> + progID ) ; ++ currID ) { int fragID = gl . glCreateShaderObjectARB ( GL2 . GL_FRAGMENT_SHADER ) ; String [ ] fragSource = generatePhongFragmentShaderSource ( currID - progID ) ; gl . glShaderSourceARB ( fragID , fragSource . length , fragSource , generateShaderLengths ( fragSource ) , <NUM_LIT:0> ) ; gl . glCompileShaderARB ( vertID ) ; gl . glCompileShaderARB ( fragID ) ; gl . glAttachObjectARB ( currID , vertID ) ; gl . glAttachObjectARB ( currID , fragID ) ; gl . glLinkProgramARB ( currID ) ; int [ ] getProgArray = new int [ <NUM_LIT:1> ] ; gl . glGetObjectParameterivARB ( currID , GL2 . GL_OBJECT_LINK_STATUS_ARB , getProgArray , <NUM_LIT:0> ) ; if ( getProgArray [ <NUM_LIT:0> ] == GL2 . GL_FALSE ) { gl . glGetObjectParameterivARB ( currID , GL2 . GL_OBJECT_INFO_LOG_LENGTH_ARB , getProgArray , <NUM_LIT:0> ) ; int logLength = getProgArray [ <NUM_LIT:0> ] ; byte [ ] logArray = new byte [ logLength ] ; gl . glGetInfoLogARB ( currID , logLength , getProgArray , <NUM_LIT:0> , logArray , <NUM_LIT:0> ) ; String log = new String ( logArray ) ; throw new LightingException ( "<STR_LIT>" + log ) ; } } } shaderProgNums . put ( gl , progID ) ; shaderBuiltin . put ( gl , builtin ) ; } public static void removePhongShader ( ) throws LightingException { removePhongShader ( javax . media . opengl . glu . GLU . getCurrentGL ( ) . getGL2 ( ) ) ; } public static void removePhongShader ( GL2 gl ) throws LightingException { if ( shaderBuiltin . containsKey ( gl ) ) { int progID = shaderProgNums . remove ( gl ) ; if ( shaderBuiltin . remove ( gl ) ) { java . nio . IntBuffer intBuff = java . nio . IntBuffer . allocate ( <NUM_LIT:3> ) ; for ( int currID = progID ; currID < ( <NUM_LIT:8> + progID ) ; ++ currID ) { gl . glGetAttachedShaders ( currID , <NUM_LIT:2> , intBuff , intBuff ) ; if ( intBuff . get ( ) != <NUM_LIT:2> ) throw new LightingException ( "<STR_LIT>" + progID ) ; gl . glDeleteShader ( intBuff . get ( ) ) ; gl . glDeleteShader ( intBuff . get ( ) ) ; gl . glDeleteProgram ( currID ) ; intBuff . clear ( ) ; } } else { java . nio . IntBuffer intBuff = java . nio . IntBuffer . allocate ( <NUM_LIT:3> ) ; for ( int currID = progID ; currID < ( <NUM_LIT:8> + progID ) ; ++ currID ) { gl . glGetAttachedObjectsARB ( currID , <NUM_LIT:2> , intBuff , intBuff ) ; if ( intBuff . get ( ) != <NUM_LIT:2> ) throw new LightingException ( "<STR_LIT>" + progID ) ; gl . glDeleteObjectARB ( intBuff . get ( ) ) ; gl . glDeleteObjectARB ( intBuff . get ( ) ) ; gl . glDeleteObjectARB ( currID ) ; intBuff . clear ( ) ; } } } else throw new LightingException ( "<STR_LIT>" ) ; } private static boolean isLightNumberValid ( GL2 gl , int lightNumber ) { return ( lightNumber > - <NUM_LIT:1> && lightNumber < maxNumberOfLightsInGL ( gl ) ) ; } private static boolean isLightNumberFree ( GL2 gl , int lightNumber ) { boolean [ ] lights = assignedLights . get ( gl ) ; if ( lights == null ) return true ; if ( lightNumber >= lights . length || lightNumber < <NUM_LIT:0> ) return false ; return ( ! lights [ lightNumber ] ) ; } private static int findAndAssignFreeLightNumber ( GL2 gl ) { boolean [ ] lights = assignedLights . get ( gl ) ; if ( lights == null ) { lights = new boolean [ maxNumberOfLightsInGL ( gl ) ] ; lights [ <NUM_LIT:0> ] = true ; assignedLights . put ( gl , lights ) ; return <NUM_LIT:0> ; } int i = <NUM_LIT:0> ; while ( i < lights . length ) { if ( ! lights [ i ] ) break ; ++ i ; } if ( i < lights . length ) { lights [ i ] = true ; assignedLights . put ( gl , lights ) ; return i ; } return - <NUM_LIT:1> ; } private static void assignLightNumber ( GL2 gl , int lightNumber ) { boolean [ ] lights = assignedLights . get ( gl ) ; if ( lights == null ) { lights = new boolean [ maxNumberOfLightsInGL ( gl ) ] ; lights [ lightNumber ] = true ; } else lights [ lightNumber ] = true ; assignedLights . put ( gl , lights ) ; } private static void unassignLightNumber ( GL2 gl , int lightNumber ) { boolean [ ] lights = assignedLights . get ( gl ) ; lights [ lightNumber ] = false ; assignedLights . put ( gl , lights ) ; } private static String [ ] generatePhongFragmentShaderSource ( int lightNumber ) { String [ ] fragSource = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:n>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:n>" , "<STR_LIT>" , "<STR_LIT>" + lightNumber + "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:n>" , "<STR_LIT>" + lightNumber + "<STR_LIT>" , "<STR_LIT>" + lightNumber + "<STR_LIT>" , "<STR_LIT>" + lightNumber + "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; return fragSource ; } private static String [ ] generatePhongVertexShaderSource ( ) { final String [ ] vertSource = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:n>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; return vertSource ; } private static int [ ] generateShaderLengths ( String [ ] shaderSource ) { int [ ] vertLengths = new int [ shaderSource . length ] ; for ( int i = <NUM_LIT:0> ; i < vertLengths . length ; ++ i ) vertLengths [ i ] = shaderSource [ i ] . length ( ) ; return vertLengths ; } } </s>
<s> package net . java . joglutils . lighting ; public class LightingException extends RuntimeException { public LightingException ( ) { super ( ) ; } public LightingException ( String s ) { super ( s ) ; } } </s>
<s> package net . java . joglutils . lighting ; public class LightPanel extends javax . swing . JPanel { public LightPanel ( ) { initComponents ( ) ; lightToPanel ( new Light ( ) ) ; } public LightPanel ( Light l ) { initComponents ( ) ; lightToPanel ( l ) ; } private void initComponents ( ) { jLabel1 = new javax . swing . JLabel ( ) ; lightNumField = new javax . swing . JTextField ( ) ; ambientButton = new javax . swing . JButton ( ) ; diffuseButton = new javax . swing . JButton ( ) ; specularButton = new javax . swing . JButton ( ) ; posXField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; jLabel2 = new javax . swing . JLabel ( ) ; jLabel3 = new javax . swing . JLabel ( ) ; jLabel4 = new javax . swing . JLabel ( ) ; jLabel5 = new javax . swing . JLabel ( ) ; jLabel6 = new javax . swing . JLabel ( ) ; posYField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; posZField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; posWField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; jLabel7 = new javax . swing . JLabel ( ) ; spotXField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; spotYField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; spotZField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; spotCutoffField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; spotExponentField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; conCoeffField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; linCoeffField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; quadCoeffField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; jLabel8 = new javax . swing . JLabel ( ) ; jLabel9 = new javax . swing . JLabel ( ) ; jLabel10 = new javax . swing . JLabel ( ) ; jLabel11 = new javax . swing . JLabel ( ) ; jLabel12 = new javax . swing . JLabel ( ) ; jLabel13 = new javax . swing . JLabel ( ) ; jLabel1 . setText ( "<STR_LIT>" ) ; lightNumField . setEditable ( false ) ; lightNumField . setText ( "<STR_LIT:0>" ) ; ambientButton . setText ( "<STR_LIT>" ) ; ambientButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; diffuseButton . setText ( "<STR_LIT>" ) ; diffuseButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; specularButton . setText ( "<STR_LIT>" ) ; specularButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; posXField . setText ( "<STR_LIT>" ) ; jLabel2 . setText ( "<STR_LIT>" ) ; jLabel3 . setText ( "<STR_LIT:x>" ) ; jLabel4 . setText ( "<STR_LIT:y>" ) ; jLabel5 . setText ( "<STR_LIT>" ) ; jLabel6 . setText ( "<STR_LIT>" ) ; posYField . setText ( "<STR_LIT>" ) ; posZField . setText ( "<STR_LIT>" ) ; posWField . setText ( "<STR_LIT>" ) ; jLabel7 . setText ( "<STR_LIT>" ) ; spotXField . setText ( "<STR_LIT>" ) ; spotYField . setText ( "<STR_LIT>" ) ; spotZField . setText ( "<STR_LIT>" ) ; spotCutoffField . setText ( "<STR_LIT>" ) ; spotExponentField . setText ( "<STR_LIT>" ) ; conCoeffField . setText ( "<STR_LIT>" ) ; linCoeffField . setText ( "<STR_LIT>" ) ; quadCoeffField . setText ( "<STR_LIT>" ) ; jLabel8 . setText ( "<STR_LIT>" ) ; jLabel9 . setText ( "<STR_LIT>" ) ; jLabel10 . setText ( "<STR_LIT>" ) ; jLabel11 . setText ( "<STR_LIT>" ) ; jLabel12 . setText ( "<STR_LIT>" ) ; jLabel13 . setText ( "<STR_LIT>" ) ; org . jdesktop . layout . GroupLayout layout = new org . jdesktop . layout . GroupLayout ( this ) ; this . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( <NUM_LIT:10> , <NUM_LIT:10> , <NUM_LIT:10> ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING , false ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( <NUM_LIT:11> , <NUM_LIT:11> , <NUM_LIT:11> ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( ambientButton ) . add ( diffuseButton ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( jLabel10 ) . add ( specularButton ) ) ) ) . add ( layout . createSequentialGroup ( ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( <NUM_LIT:10> , <NUM_LIT:10> , <NUM_LIT:10> ) . add ( spotCutoffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( jLabel8 ) ) ) ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , layout . createSequentialGroup ( ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jLabel1 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( lightNumField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , <NUM_LIT> , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING , false ) . add ( jLabel4 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( jLabel3 ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel2 ) . add ( posXField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( posYField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( layout . createSequentialGroup ( ) . add ( jLabel5 ) . add ( <NUM_LIT:7> , <NUM_LIT:7> , <NUM_LIT:7> ) ) . add ( layout . createSequentialGroup ( ) . add ( jLabel6 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) ) ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( posWField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( posZField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) ) . add ( <NUM_LIT:8> , <NUM_LIT:8> , <NUM_LIT:8> ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel7 ) . add ( spotYField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( spotXField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( spotZField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) . add ( layout . createSequentialGroup ( ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel9 ) . add ( layout . createSequentialGroup ( ) . add ( <NUM_LIT:10> , <NUM_LIT:10> , <NUM_LIT:10> ) . add ( spotExponentField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) ) . add ( layout . createSequentialGroup ( ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel11 ) . add ( conCoeffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( linCoeffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jLabel12 ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel13 ) . add ( quadCoeffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) ) . add ( <NUM_LIT:10> , <NUM_LIT:10> , <NUM_LIT:10> ) ) ) ; layout . setVerticalGroup ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . addContainerGap ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( ambientButton ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( specularButton ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( diffuseButton ) ) . add ( layout . createSequentialGroup ( ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( spotXField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( layout . createSequentialGroup ( ) . add ( jLabel7 ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( spotYField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( spotZField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel8 ) . add ( jLabel9 ) ) ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( posXField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jLabel3 ) ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel2 ) . add ( lightNumField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jLabel1 ) ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel4 ) . add ( posYField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel5 ) . add ( layout . createSequentialGroup ( ) . add ( posZField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( posWField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jLabel6 ) ) ) ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( spotCutoffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( layout . createSequentialGroup ( ) . add ( spotExponentField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( jLabel12 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( linCoeffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( layout . createSequentialGroup ( ) . add ( jLabel11 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel10 ) . add ( conCoeffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) ) . add ( layout . createSequentialGroup ( ) . add ( jLabel13 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( quadCoeffField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) . addContainerGap ( ) ) ) ; } private void colorAction ( java . awt . event . ActionEvent evt ) { javax . swing . JButton src = ( javax . swing . JButton ) evt . getSource ( ) ; java . awt . Color c = javax . swing . JColorChooser . showDialog ( this , src . getText ( ) + "<STR_LIT>" , src . getForeground ( ) ) ; if ( c != null ) src . setForeground ( c ) ; } private javax . swing . JButton ambientButton ; private javax . swing . JFormattedTextField conCoeffField ; private javax . swing . JButton diffuseButton ; private javax . swing . JLabel jLabel1 ; private javax . swing . JLabel jLabel10 ; private javax . swing . JLabel jLabel11 ; private javax . swing . JLabel jLabel12 ; private javax . swing . JLabel jLabel13 ; private javax . swing . JLabel jLabel2 ; private javax . swing . JLabel jLabel3 ; private javax . swing . JLabel jLabel4 ; private javax . swing . JLabel jLabel5 ; private javax . swing . JLabel jLabel6 ; private javax . swing . JLabel jLabel7 ; private javax . swing . JLabel jLabel8 ; private javax . swing . JLabel jLabel9 ; private javax . swing . JTextField lightNumField ; private javax . swing . JFormattedTextField linCoeffField ; private javax . swing . JFormattedTextField posWField ; private javax . swing . JFormattedTextField posXField ; private javax . swing . JFormattedTextField posYField ; private javax . swing . JFormattedTextField posZField ; private javax . swing . JFormattedTextField quadCoeffField ; private javax . swing . JButton specularButton ; private javax . swing . JFormattedTextField spotCutoffField ; private javax . swing . JFormattedTextField spotExponentField ; private javax . swing . JFormattedTextField spotXField ; private javax . swing . JFormattedTextField spotYField ; private javax . swing . JFormattedTextField spotZField ; public void panelToLight ( Light l ) { l . setAmbient ( this . ambientButton . getForeground ( ) ) ; l . setDiffuse ( this . diffuseButton . getForeground ( ) ) ; l . setSpecular ( this . specularButton . getForeground ( ) ) ; float [ ] vec = new float [ <NUM_LIT:3> ] ; vec [ <NUM_LIT:0> ] = ( ( Number ) this . posXField . getValue ( ) ) . floatValue ( ) ; vec [ <NUM_LIT:1> ] = ( ( Number ) this . posYField . getValue ( ) ) . floatValue ( ) ; vec [ <NUM_LIT:2> ] = ( ( Number ) this . posZField . getValue ( ) ) . floatValue ( ) ; l . setLightPosition ( vec ) ; l . setLightW ( ( ( Number ) this . posWField . getValue ( ) ) . floatValue ( ) ) ; vec [ <NUM_LIT:0> ] = ( ( Number ) this . spotXField . getValue ( ) ) . floatValue ( ) ; vec [ <NUM_LIT:1> ] = ( ( Number ) this . spotYField . getValue ( ) ) . floatValue ( ) ; vec [ <NUM_LIT:2> ] = ( ( Number ) this . spotZField . getValue ( ) ) . floatValue ( ) ; l . setSpotDirection ( vec ) ; l . setSpotCutoff ( ( ( Number ) this . spotCutoffField . getValue ( ) ) . floatValue ( ) ) ; l . setSpotExponent ( ( ( Number ) this . spotExponentField . getValue ( ) ) . floatValue ( ) ) ; l . setConstantAttenuation ( ( ( Number ) this . conCoeffField . getValue ( ) ) . floatValue ( ) ) ; l . setLinearAttenuation ( ( ( Number ) this . linCoeffField . getValue ( ) ) . floatValue ( ) ) ; l . setQuadraticAttenuation ( ( ( Number ) this . quadCoeffField . getValue ( ) ) . floatValue ( ) ) ; } public void lightToPanel ( Light l ) { this . lightNumField . setText ( new Integer ( l . getLightNumber ( ) ) . toString ( ) ) ; this . ambientButton . setForeground ( l . getAmbient ( ) ) ; this . diffuseButton . setForeground ( l . getDiffuse ( ) ) ; this . specularButton . setForeground ( l . getSpecular ( ) ) ; float [ ] pos = l . getLightPosition ( ) ; this . posXField . setValue ( pos [ <NUM_LIT:0> ] ) ; this . posYField . setValue ( pos [ <NUM_LIT:1> ] ) ; this . posZField . setValue ( pos [ <NUM_LIT:2> ] ) ; this . posWField . setValue ( l . getLightW ( ) ) ; float [ ] spot = l . getSpotDirection ( ) ; this . spotXField . setValue ( spot [ <NUM_LIT:0> ] ) ; this . spotYField . setValue ( spot [ <NUM_LIT:1> ] ) ; this . spotZField . setValue ( spot [ <NUM_LIT:2> ] ) ; this . spotCutoffField . setValue ( l . getSpotCutoff ( ) ) ; this . spotExponentField . setValue ( l . getSpotExponent ( ) ) ; this . conCoeffField . setValue ( l . getConstantAttenuation ( ) ) ; this . linCoeffField . setValue ( l . getLinearAttenuation ( ) ) ; this . quadCoeffField . setValue ( l . getQuadraticAttenuation ( ) ) ; } } </s>
<s> package net . java . joglutils . lighting ; import java . awt . * ; import java . awt . event . * ; import javax . swing . * ; public class ColorButton extends JButton implements ActionListener { public ColorButton ( ) { super ( ) ; this . addActionListener ( this ) ; } public ColorButton ( Action a ) { super ( a ) ; this . addActionListener ( this ) ; } public ColorButton ( Icon icon ) { super ( icon ) ; this . addActionListener ( this ) ; } public ColorButton ( String text ) { super ( text ) ; this . addActionListener ( this ) ; } public ColorButton ( String text , Icon icon ) { super ( text , icon ) ; this . addActionListener ( this ) ; } public Color getColor ( ) { return this . getForeground ( ) ; } public void setColor ( Color c ) { this . setForeground ( c ) ; } public void actionPerformed ( ActionEvent e ) { JButton src = ( JButton ) e . getSource ( ) ; Color c = JColorChooser . showDialog ( this , "<STR_LIT>" , src . getForeground ( ) ) ; if ( c != null ) src . setForeground ( c ) ; } } </s>
<s> package net . java . joglutils . lighting ; public class MaterialPanel extends javax . swing . JPanel { public MaterialPanel ( ) { initComponents ( ) ; matToPanel ( new Material ( ) ) ; } public MaterialPanel ( Material m ) { initComponents ( ) ; matToPanel ( m ) ; } private void initComponents ( ) { shininessField = new javax . swing . JFormattedTextField ( java . text . NumberFormat . getInstance ( ) ) ; jLabel1 = new javax . swing . JLabel ( ) ; specularButton = new javax . swing . JButton ( ) ; diffuseButton = new javax . swing . JButton ( ) ; ambientButton = new javax . swing . JButton ( ) ; emissiveButton = new javax . swing . JButton ( ) ; shininessField . setText ( "<STR_LIT>" ) ; jLabel1 . setText ( "<STR_LIT>" ) ; specularButton . setText ( "<STR_LIT>" ) ; specularButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; diffuseButton . setText ( "<STR_LIT>" ) ; diffuseButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; ambientButton . setText ( "<STR_LIT>" ) ; ambientButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; emissiveButton . setText ( "<STR_LIT>" ) ; emissiveButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { colorAction ( evt ) ; } } ) ; org . jdesktop . layout . GroupLayout layout = new org . jdesktop . layout . GroupLayout ( this ) ; this . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING , false ) . add ( layout . createSequentialGroup ( ) . addContainerGap ( org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( diffuseButton ) ) . add ( org . jdesktop . layout . GroupLayout . LEADING , layout . createSequentialGroup ( ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) . add ( ambientButton ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( specularButton ) . add ( emissiveButton ) ) ) . add ( layout . createSequentialGroup ( ) . add ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) . add ( jLabel1 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( shininessField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) . addContainerGap ( <NUM_LIT> , Short . MAX_VALUE ) ) ) ; layout . setVerticalGroup ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( layout . createSequentialGroup ( ) . addContainerGap ( ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( ambientButton ) . add ( specularButton ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( diffuseButton ) . add ( emissiveButton ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel1 ) . add ( shininessField , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addContainerGap ( org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) ; } private void colorAction ( java . awt . event . ActionEvent evt ) { javax . swing . JButton src = ( javax . swing . JButton ) evt . getSource ( ) ; java . awt . Color c = javax . swing . JColorChooser . showDialog ( this , src . getText ( ) + "<STR_LIT>" , src . getForeground ( ) ) ; if ( c != null ) src . setForeground ( c ) ; } private javax . swing . JButton ambientButton ; private javax . swing . JButton diffuseButton ; private javax . swing . JButton emissiveButton ; private javax . swing . JLabel jLabel1 ; private javax . swing . JFormattedTextField shininessField ; private javax . swing . JButton specularButton ; public void matToPanel ( Material m ) { this . shininessField . setValue ( m . getShininess ( ) ) ; this . ambientButton . setForeground ( m . getAmbient ( ) ) ; this . diffuseButton . setForeground ( m . getDiffuse ( ) ) ; this . specularButton . setForeground ( m . getSpecular ( ) ) ; this . emissiveButton . setForeground ( m . getEmissive ( ) ) ; } public void panelToMat ( Material m ) { m . setShininess ( ( ( Number ) this . shininessField . getValue ( ) ) . floatValue ( ) ) ; m . setAmbient ( this . ambientButton . getForeground ( ) ) ; m . setDiffuse ( this . diffuseButton . getForeground ( ) ) ; m . setSpecular ( this . specularButton . getForeground ( ) ) ; m . setEmissive ( this . emissiveButton . getForeground ( ) ) ; } } </s>
<s> package net . java . joglutils . jogltext ; import java . awt . * ; import java . awt . geom . * ; import java . awt . font . * ; import java . text . * ; import javax . media . opengl . * ; import javax . media . opengl . glu . * ; public class FontDrawer { public enum NormalMode { NONE , FLAT , AVERAGED } ; private Font font ; private float depth ; private boolean edgeOnly ; private NormalMode normalMode ; public FontDrawer ( Font font ) throws NullPointerException { if ( font == null ) throw new NullPointerException ( "<STR_LIT>" ) ; this . font = font ; depth = <NUM_LIT:0> ; edgeOnly = false ; normalMode = NormalMode . FLAT ; } public void setFont ( Font font ) throws NullPointerException { if ( font == null ) throw new NullPointerException ( "<STR_LIT>" ) ; this . font = font ; } public Font getFont ( ) { return this . font ; } public void setDepth ( float depth ) { if ( depth <= <NUM_LIT:0> ) this . depth = <NUM_LIT:0> ; else this . depth = depth ; } public float getDepth ( ) { return this . depth ; } public void setFill ( boolean fill ) { this . edgeOnly = ! fill ; } public boolean isFill ( ) { return ! this . edgeOnly ; } public void setNormal ( NormalMode mode ) { this . normalMode = mode ; } public NormalMode getNormal ( ) { return this . normalMode ; } public void drawString ( String str , GL2 gl ) { drawString ( str , new GLU ( ) , gl ) ; } public void drawString ( String str , GLU glu , GL2 gl ) { GlyphVector gv = font . createGlyphVector ( new FontRenderContext ( new AffineTransform ( ) , true , true ) , new StringCharacterIterator ( str ) ) ; GeneralPath gp = ( GeneralPath ) gv . getOutline ( ) ; PathIterator pi = gp . getPathIterator ( AffineTransform . getScaleInstance ( <NUM_LIT:1.0> , - <NUM_LIT:1.0> ) , <NUM_LIT:1.0f> ) ; if ( this . normalMode != NormalMode . NONE ) gl . glNormal3f ( <NUM_LIT:0> , <NUM_LIT:0> , - <NUM_LIT:1.0f> ) ; tesselateFace ( glu , gl , pi , pi . getWindingRule ( ) , this . edgeOnly ) ; if ( this . depth != <NUM_LIT:0.0> ) { pi = gp . getPathIterator ( AffineTransform . getScaleInstance ( <NUM_LIT:1.0> , - <NUM_LIT:1.0> ) , <NUM_LIT:1.0f> ) ; if ( this . normalMode != NormalMode . NONE ) gl . glNormal3f ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1.0f> ) ; tesselateFace ( glu , gl , pi , pi . getWindingRule ( ) , this . edgeOnly , this . depth ) ; pi = gp . getPathIterator ( AffineTransform . getScaleInstance ( <NUM_LIT:1.0> , - <NUM_LIT:1.0> ) , <NUM_LIT:1.0f> ) ; switch ( this . normalMode ) { case NONE : drawSidesNoNorm ( gl , pi , this . edgeOnly , this . depth ) ; break ; case FLAT : drawSidesFlatNorm ( gl , pi , this . edgeOnly , this . depth ) ; break ; case AVERAGED : drawSidesAvgNorm ( gl , pi , this . edgeOnly , this . depth ) ; break ; } } } public void drawString ( String str , GL2 gl , float xOff , float yOff , float zOff ) { drawString ( str , new GLU ( ) , gl , xOff , yOff , zOff ) ; } public void drawString ( String str , GLU glu , GL2 gl , float xOff , float yOff , float zOff ) { gl . glPushAttrib ( GL2 . GL_TRANSFORM_BIT ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glPushMatrix ( ) ; gl . glTranslatef ( xOff , yOff , zOff ) ; this . drawString ( str , glu , gl ) ; gl . glPopMatrix ( ) ; gl . glPopAttrib ( ) ; } private void tesselateFace ( GLU glu , GL2 gl , PathIterator pi , int windingRule , boolean justBoundary ) { tesselateFace ( glu , gl , pi , windingRule , justBoundary , <NUM_LIT:0> ) ; } private void tesselateFace ( GLU glu , GL2 gl , PathIterator pi , int windingRule , boolean justBoundary , double tessZ ) { GLUtessellatorCallback aCallback = new GLUtesselatorCallbackImpl ( gl ) ; GLUtessellator tess = glu . gluNewTess ( ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_BEGIN , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_END , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_ERROR , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_VERTEX , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_COMBINE , aCallback ) ; glu . gluTessNormal ( tess , <NUM_LIT:0.0> , <NUM_LIT:0.0> , - <NUM_LIT:1.0> ) ; switch ( windingRule ) { case PathIterator . WIND_EVEN_ODD : glu . gluTessProperty ( tess , GLU . GLU_TESS_WINDING_RULE , GLU . GLU_TESS_WINDING_ODD ) ; break ; case PathIterator . WIND_NON_ZERO : glu . gluTessProperty ( tess , GLU . GLU_TESS_WINDING_RULE , GLU . GLU_TESS_WINDING_NONZERO ) ; break ; } if ( justBoundary ) { glu . gluTessProperty ( tess , GLU . GLU_TESS_BOUNDARY_ONLY , GL2 . GL_TRUE ) ; } else { glu . gluTessProperty ( tess , GLU . GLU_TESS_BOUNDARY_ONLY , GL2 . GL_FALSE ) ; } glu . gluTessBeginPolygon ( tess , ( double [ ] ) null ) ; for ( ; ! pi . isDone ( ) ; pi . next ( ) ) { double [ ] coords = new double [ <NUM_LIT:3> ] ; coords [ <NUM_LIT:2> ] = tessZ ; switch ( pi . currentSegment ( coords ) ) { case PathIterator . SEG_MOVETO : glu . gluTessBeginContour ( tess ) ; break ; case PathIterator . SEG_LINETO : glu . gluTessVertex ( tess , coords , <NUM_LIT:0> , coords ) ; break ; case PathIterator . SEG_CLOSE : glu . gluTessEndContour ( tess ) ; break ; } } glu . gluTessEndPolygon ( tess ) ; glu . gluDeleteTess ( tess ) ; } private void drawSidesNoNorm ( GL2 gl , PathIterator pi , boolean justBoundary , float tessZ ) { if ( justBoundary ) gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_LINE ) ; else gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_FILL ) ; for ( float [ ] coords = new float [ <NUM_LIT:6> ] ; ! pi . isDone ( ) ; pi . next ( ) ) { float [ ] currRender = new float [ <NUM_LIT:3> ] ; switch ( pi . currentSegment ( coords ) ) { case PathIterator . SEG_MOVETO : gl . glBegin ( GL2 . GL_QUAD_STRIP ) ; currRender [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; currRender [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; currRender [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( currRender , <NUM_LIT:0> ) ; currRender [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( currRender , <NUM_LIT:0> ) ; break ; case PathIterator . SEG_LINETO : currRender [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; currRender [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; currRender [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( currRender , <NUM_LIT:0> ) ; currRender [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( currRender , <NUM_LIT:0> ) ; break ; case PathIterator . SEG_CLOSE : currRender [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; currRender [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; currRender [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( currRender , <NUM_LIT:0> ) ; currRender [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( currRender , <NUM_LIT:0> ) ; gl . glEnd ( ) ; break ; default : throw new JogltextException ( "<STR_LIT>" ) ; } } } private void drawSidesFlatNorm ( GL2 gl , PathIterator pi , boolean justBoundary , float tessZ ) { if ( justBoundary ) gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_LINE ) ; else gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_FILL ) ; float [ ] lastCoord = new float [ <NUM_LIT:3> ] ; float [ ] firstCoord = new float [ <NUM_LIT:3> ] ; for ( float [ ] coords = new float [ <NUM_LIT:6> ] ; ! pi . isDone ( ) ; pi . next ( ) ) { switch ( pi . currentSegment ( coords ) ) { case PathIterator . SEG_MOVETO : gl . glBegin ( GL2 . GL_QUADS ) ; lastCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; lastCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; firstCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; firstCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; break ; case PathIterator . SEG_LINETO : gl . glNormal3f ( lastCoord [ <NUM_LIT:1> ] - coords [ <NUM_LIT:1> ] , coords [ <NUM_LIT:0> ] - lastCoord [ <NUM_LIT:0> ] , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; coords [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( coords , <NUM_LIT:0> ) ; coords [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( coords , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; lastCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; break ; case PathIterator . SEG_CLOSE : gl . glNormal3f ( lastCoord [ <NUM_LIT:1> ] - firstCoord [ <NUM_LIT:1> ] , firstCoord [ <NUM_LIT:0> ] - lastCoord [ <NUM_LIT:0> ] , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; firstCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( firstCoord , <NUM_LIT:0> ) ; firstCoord [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( firstCoord , <NUM_LIT:0> ) ; gl . glEnd ( ) ; break ; default : throw new JogltextException ( "<STR_LIT>" ) ; } } } private void drawSidesAvgNorm ( GL2 gl , PathIterator pi , boolean justBoundary , float tessZ ) { if ( justBoundary ) gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_LINE ) ; else gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_FILL ) ; float [ ] firstCoord = null ; float [ ] secondCoord = null ; float [ ] thirdCoord = null ; float [ ] twoBackCoord = null ; float [ ] oneBackCoord = null ; for ( float [ ] coords = new float [ <NUM_LIT:6> ] ; ! pi . isDone ( ) ; pi . next ( ) ) { switch ( pi . currentSegment ( coords ) ) { case PathIterator . SEG_MOVETO : firstCoord = new float [ <NUM_LIT:3> ] ; firstCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; firstCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; gl . glBegin ( GL2 . GL_QUAD_STRIP ) ; break ; case PathIterator . SEG_LINETO : if ( secondCoord == null ) { secondCoord = new float [ <NUM_LIT:3> ] ; secondCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; secondCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; twoBackCoord = firstCoord . clone ( ) ; oneBackCoord = secondCoord . clone ( ) ; } else { float avgdeltax = oneBackCoord [ <NUM_LIT:0> ] - twoBackCoord [ <NUM_LIT:0> ] + coords [ <NUM_LIT:0> ] - oneBackCoord [ <NUM_LIT:0> ] ; float avgdeltay = oneBackCoord [ <NUM_LIT:1> ] - twoBackCoord [ <NUM_LIT:1> ] + coords [ <NUM_LIT:1> ] - oneBackCoord [ <NUM_LIT:1> ] ; if ( thirdCoord == null ) { thirdCoord = new float [ <NUM_LIT:3> ] ; thirdCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; thirdCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; } gl . glNormal3f ( - avgdeltay , avgdeltax , <NUM_LIT:0> ) ; oneBackCoord [ <NUM_LIT:2> ] = <NUM_LIT:0.0f> ; gl . glVertex3fv ( oneBackCoord , <NUM_LIT:0> ) ; oneBackCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( oneBackCoord , <NUM_LIT:0> ) ; twoBackCoord [ <NUM_LIT:0> ] = oneBackCoord [ <NUM_LIT:0> ] ; twoBackCoord [ <NUM_LIT:1> ] = oneBackCoord [ <NUM_LIT:1> ] ; oneBackCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; oneBackCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; } break ; case PathIterator . SEG_CLOSE : float avgdeltax = oneBackCoord [ <NUM_LIT:0> ] - twoBackCoord [ <NUM_LIT:0> ] + firstCoord [ <NUM_LIT:0> ] - oneBackCoord [ <NUM_LIT:0> ] ; float avgdeltay = oneBackCoord [ <NUM_LIT:1> ] - twoBackCoord [ <NUM_LIT:1> ] + firstCoord [ <NUM_LIT:1> ] - oneBackCoord [ <NUM_LIT:1> ] ; gl . glNormal3f ( - avgdeltay , avgdeltax , <NUM_LIT:0> ) ; oneBackCoord [ <NUM_LIT:2> ] = <NUM_LIT:0.0f> ; gl . glVertex3fv ( oneBackCoord , <NUM_LIT:0> ) ; oneBackCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( oneBackCoord , <NUM_LIT:0> ) ; avgdeltax = firstCoord [ <NUM_LIT:0> ] - oneBackCoord [ <NUM_LIT:0> ] + secondCoord [ <NUM_LIT:0> ] - firstCoord [ <NUM_LIT:0> ] ; avgdeltay = firstCoord [ <NUM_LIT:1> ] - oneBackCoord [ <NUM_LIT:1> ] + secondCoord [ <NUM_LIT:1> ] - firstCoord [ <NUM_LIT:1> ] ; gl . glNormal3f ( - avgdeltay , avgdeltax , <NUM_LIT:0> ) ; firstCoord [ <NUM_LIT:2> ] = <NUM_LIT:0.0f> ; gl . glVertex3fv ( firstCoord , <NUM_LIT:0> ) ; firstCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( firstCoord , <NUM_LIT:0> ) ; avgdeltax = secondCoord [ <NUM_LIT:0> ] - firstCoord [ <NUM_LIT:0> ] + thirdCoord [ <NUM_LIT:0> ] - secondCoord [ <NUM_LIT:0> ] ; avgdeltay = secondCoord [ <NUM_LIT:1> ] - firstCoord [ <NUM_LIT:1> ] + thirdCoord [ <NUM_LIT:1> ] - secondCoord [ <NUM_LIT:1> ] ; gl . glNormal3f ( - avgdeltay , avgdeltax , <NUM_LIT:0> ) ; secondCoord [ <NUM_LIT:2> ] = <NUM_LIT:0.0f> ; gl . glVertex3fv ( secondCoord , <NUM_LIT:0> ) ; secondCoord [ <NUM_LIT:2> ] = tessZ ; gl . glVertex3fv ( secondCoord , <NUM_LIT:0> ) ; gl . glEnd ( ) ; firstCoord = null ; secondCoord = null ; thirdCoord = null ; twoBackCoord = null ; oneBackCoord = null ; break ; default : throw new JogltextException ( "<STR_LIT>" ) ; } } } private class GLUtesselatorCallbackImpl extends javax . media . opengl . glu . GLUtessellatorCallbackAdapter { private GL2 gl ; public GLUtesselatorCallbackImpl ( GL2 gl ) { this . gl = gl ; } public void begin ( int type ) { gl . glBegin ( type ) ; } public void vertex ( java . lang . Object vertexData ) { double [ ] coords = ( double [ ] ) vertexData ; gl . glVertex3dv ( coords , <NUM_LIT:0> ) ; } public void end ( ) { gl . glEnd ( ) ; } } } </s>
<s> package net . java . joglutils . jogltext ; import java . awt . Font ; import java . awt . font . FontRenderContext ; import java . awt . font . GlyphVector ; import java . awt . geom . AffineTransform ; import java . awt . geom . GeneralPath ; import java . awt . geom . PathIterator ; import java . awt . geom . Rectangle2D ; import java . text . StringCharacterIterator ; import java . util . ArrayList ; import java . util . Iterator ; import javax . media . opengl . * ; import javax . media . opengl . glu . * ; import javax . vecmath . Vector3f ; public class TextRenderer3D { private Font font ; private float depth = <NUM_LIT> ; private boolean edgeOnly = false ; private boolean calcNormals = true ; ; private float flatness = <NUM_LIT> ; private Vector3f vecA = new Vector3f ( ) ; private Vector3f vecB = new Vector3f ( ) ; private Vector3f normal = new Vector3f ( ) ; private GLU glu = new GLU ( ) ; private GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; private int lastIndex = - <NUM_LIT:1> ; private ArrayList < Integer > listIndex = new ArrayList < Integer > ( ) ; public TextRenderer3D ( Font font , float depth ) throws NullPointerException { if ( font == null ) throw new NullPointerException ( "<STR_LIT>" ) ; this . font = font ; this . depth = depth ; } public void setFont ( Font font ) throws NullPointerException { if ( font == null ) throw new NullPointerException ( "<STR_LIT>" ) ; this . font = font ; } public Font getFont ( ) { return this . font ; } public void setDepth ( float depth ) { if ( depth <= <NUM_LIT:0> ) this . depth = <NUM_LIT:0> ; else this . depth = depth ; } public float getDepth ( ) { return this . depth ; } public void setFill ( boolean fill ) { this . edgeOnly = ! fill ; } public boolean isFill ( ) { return ! this . edgeOnly ; } public float getFlatness ( ) { return flatness ; } public void setFlatness ( float flatness ) { this . flatness = flatness ; } public void setCalcNormals ( boolean normals ) { this . calcNormals = normals ; } public boolean getCalcNormals ( ) { return this . calcNormals ; } public void draw ( String str , float xOff , float yOff , float zOff , float scaleFactor ) { gl . glPushAttrib ( GL2 . GL_TRANSFORM_BIT ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glPushMatrix ( ) ; gl . glEnable ( GL2 . GL_NORMALIZE ) ; gl . glScalef ( scaleFactor , scaleFactor , scaleFactor ) ; gl . glTranslatef ( xOff , yOff , zOff ) ; this . draw ( str ) ; gl . glPopMatrix ( ) ; gl . glPopAttrib ( ) ; } public void draw ( String str ) { GlyphVector gv = font . createGlyphVector ( new FontRenderContext ( new AffineTransform ( ) , true , true ) , new StringCharacterIterator ( str ) ) ; GeneralPath gp = ( GeneralPath ) gv . getOutline ( ) ; PathIterator pi = gp . getPathIterator ( AffineTransform . getScaleInstance ( <NUM_LIT:1.0> , - <NUM_LIT:1.0> ) , flatness ) ; if ( calcNormals ) gl . glNormal3f ( <NUM_LIT:0> , <NUM_LIT:0> , - <NUM_LIT:1.0f> ) ; tesselateFace ( glu , gl , pi , this . edgeOnly , <NUM_LIT:0.0f> ) ; if ( this . depth != <NUM_LIT:0.0> ) { pi = gp . getPathIterator ( AffineTransform . getScaleInstance ( <NUM_LIT:1.0> , - <NUM_LIT:1.0> ) , flatness ) ; if ( calcNormals ) gl . glNormal3f ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1.0f> ) ; tesselateFace ( glu , gl , pi , this . edgeOnly , this . depth ) ; pi = gp . getPathIterator ( AffineTransform . getScaleInstance ( <NUM_LIT:1.0> , - <NUM_LIT:1.0> ) , flatness ) ; drawSides ( gl , pi , this . edgeOnly , this . depth ) ; } } public int compile ( String str , float xOff , float yOff , float zOff , float scaleFactor ) { int index = gl . glGenLists ( <NUM_LIT:1> ) ; gl . glNewList ( index , GL2 . GL_COMPILE ) ; draw ( str , xOff , yOff , zOff , scaleFactor ) ; gl . glEndList ( ) ; listIndex . add ( index ) ; return index ; } public int compile ( String str ) { int index = gl . glGenLists ( <NUM_LIT:1> ) ; gl . glNewList ( index , GL2 . GL_COMPILE ) ; draw ( str ) ; gl . glEndList ( ) ; listIndex . add ( index ) ; return index ; } public void call ( ) { if ( lastIndex != - <NUM_LIT:1> ) gl . glCallList ( this . lastIndex ) ; } public void call ( int index ) { gl . glCallList ( index ) ; } public void dispose ( ) { for ( Iterator iter = listIndex . iterator ( ) ; iter . hasNext ( ) ; ) { int index = ( Integer ) iter . next ( ) ; gl . glDeleteLists ( index , <NUM_LIT:1> ) ; } lastIndex = - <NUM_LIT:1> ; } public void dispose ( int index ) { for ( Iterator iter = listIndex . iterator ( ) ; iter . hasNext ( ) ; ) { int i = ( Integer ) iter . next ( ) ; if ( i == index ) { gl . glDeleteLists ( index , <NUM_LIT:1> ) ; if ( index == lastIndex ) lastIndex = - <NUM_LIT:1> ; break ; } } } public Rectangle2D getBounds ( String str ) { GlyphVector gv = font . createGlyphVector ( new FontRenderContext ( new AffineTransform ( ) , true , true ) , new StringCharacterIterator ( str ) ) ; GeneralPath gp = ( GeneralPath ) gv . getOutline ( ) ; return gp . getBounds2D ( ) ; } public Rectangle2D getBounds ( String str , float scaleFactor ) { gl . glPushAttrib ( GL2 . GL_TRANSFORM_BIT ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glPushMatrix ( ) ; gl . glScalef ( scaleFactor , scaleFactor , scaleFactor ) ; GlyphVector gv = font . createGlyphVector ( new FontRenderContext ( new AffineTransform ( ) , true , true ) , new StringCharacterIterator ( str ) ) ; GeneralPath gp = ( GeneralPath ) gv . getOutline ( ) ; Rectangle2D rect = gp . getBounds2D ( ) ; gl . glPopMatrix ( ) ; gl . glPopAttrib ( ) ; return rect ; } private void drawSides ( GL2 gl , PathIterator pi , boolean justBoundary , float depth ) { if ( justBoundary ) gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_LINE ) ; else gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_FILL ) ; float [ ] lastCoord = new float [ <NUM_LIT:3> ] ; float [ ] firstCoord = new float [ <NUM_LIT:3> ] ; float [ ] coords = new float [ <NUM_LIT:6> ] ; while ( ! pi . isDone ( ) ) { switch ( pi . currentSegment ( coords ) ) { case PathIterator . SEG_MOVETO : gl . glBegin ( GL2 . GL_QUADS ) ; lastCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; lastCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; firstCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; firstCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; break ; case PathIterator . SEG_LINETO : if ( calcNormals ) setNormal ( gl , lastCoord [ <NUM_LIT:0> ] - coords [ <NUM_LIT:0> ] , lastCoord [ <NUM_LIT:1> ] - coords [ <NUM_LIT:1> ] , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , depth ) ; lastCoord [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:2> ] = depth ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; coords [ <NUM_LIT:2> ] = depth ; gl . glVertex3fv ( coords , <NUM_LIT:0> ) ; coords [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( coords , <NUM_LIT:0> ) ; if ( calcNormals ) { lastCoord [ <NUM_LIT:0> ] = coords [ <NUM_LIT:0> ] ; lastCoord [ <NUM_LIT:1> ] = coords [ <NUM_LIT:1> ] ; } break ; case PathIterator . SEG_CLOSE : if ( calcNormals ) setNormal ( gl , lastCoord [ <NUM_LIT:0> ] - firstCoord [ <NUM_LIT:0> ] , lastCoord [ <NUM_LIT:1> ] - firstCoord [ <NUM_LIT:1> ] , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , depth ) ; lastCoord [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; lastCoord [ <NUM_LIT:2> ] = depth ; gl . glVertex3fv ( lastCoord , <NUM_LIT:0> ) ; firstCoord [ <NUM_LIT:2> ] = depth ; gl . glVertex3fv ( firstCoord , <NUM_LIT:0> ) ; firstCoord [ <NUM_LIT:2> ] = <NUM_LIT:0> ; gl . glVertex3fv ( firstCoord , <NUM_LIT:0> ) ; gl . glEnd ( ) ; break ; default : throw new RuntimeException ( "<STR_LIT>" ) ; } pi . next ( ) ; } } private void setNormal ( GL2 gl , float x1 , float y1 , float z1 , float x2 , float y2 , float z2 ) { vecA . set ( x1 , y1 , z1 ) ; vecB . set ( x2 , y2 , z2 ) ; normal . cross ( vecA , vecB ) ; normal . normalize ( ) ; gl . glNormal3f ( normal . x , normal . y , normal . z ) ; } private void tesselateFace ( GLU glu , GL2 gl , PathIterator pi , boolean justBoundary , double tessZ ) { GLUtessellatorCallback aCallback = new GLUtesselatorCallbackImpl ( gl ) ; GLUtessellator tess = glu . gluNewTess ( ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_BEGIN , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_END , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_ERROR , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_VERTEX , aCallback ) ; glu . gluTessCallback ( tess , GLU . GLU_TESS_COMBINE , aCallback ) ; glu . gluTessNormal ( tess , <NUM_LIT:0.0> , <NUM_LIT:0.0> , - <NUM_LIT:1.0> ) ; if ( pi . getWindingRule ( ) == PathIterator . WIND_EVEN_ODD ) glu . gluTessProperty ( tess , GLU . GLU_TESS_WINDING_RULE , GLU . GLU_TESS_WINDING_ODD ) ; else glu . gluTessProperty ( tess , GLU . GLU_TESS_WINDING_RULE , GLU . GLU_TESS_WINDING_NONZERO ) ; if ( justBoundary ) glu . gluTessProperty ( tess , GLU . GLU_TESS_BOUNDARY_ONLY , GL2 . GL_TRUE ) ; else glu . gluTessProperty ( tess , GLU . GLU_TESS_BOUNDARY_ONLY , GL2 . GL_FALSE ) ; glu . gluTessBeginPolygon ( tess , ( double [ ] ) null ) ; while ( ! pi . isDone ( ) ) { double [ ] coords = new double [ <NUM_LIT:3> ] ; coords [ <NUM_LIT:2> ] = tessZ ; switch ( pi . currentSegment ( coords ) ) { case PathIterator . SEG_MOVETO : glu . gluTessBeginContour ( tess ) ; break ; case PathIterator . SEG_LINETO : glu . gluTessVertex ( tess , coords , <NUM_LIT:0> , coords ) ; break ; case PathIterator . SEG_CLOSE : glu . gluTessEndContour ( tess ) ; break ; } pi . next ( ) ; } glu . gluTessEndPolygon ( tess ) ; glu . gluDeleteTess ( tess ) ; } private class GLUtesselatorCallbackImpl extends javax . media . opengl . glu . GLUtessellatorCallbackAdapter { private GL2 gl ; public GLUtesselatorCallbackImpl ( GL2 gl ) { this . gl = gl ; } public void begin ( int type ) { gl . glBegin ( type ) ; } public void vertex ( java . lang . Object vertexData ) { double [ ] coords = ( double [ ] ) vertexData ; gl . glVertex3dv ( coords , <NUM_LIT:0> ) ; } public void end ( ) { gl . glEnd ( ) ; } } } </s>
<s> package net . java . joglutils . jogltext ; public class JogltextException extends RuntimeException { public JogltextException ( ) { super ( ) ; } public JogltextException ( String str ) { super ( str ) ; } } </s>
<s> package net . java . joglutils ; import java . awt . * ; import java . awt . event . * ; import javax . swing . * ; public class JPanelDialog extends JDialog implements ActionListener { private boolean result = false ; private JButton acceptButton ; private JButton rejectButton ; private JPanel mainPanel ; private int numOfPanels = <NUM_LIT:0> ; public JPanelDialog ( JPanel inputPanel ) { super ( ) ; this . setModal ( false ) ; initLayout ( inputPanel ) ; } public JPanelDialog ( String title , JPanel inputPanel ) { super ( ) ; this . setTitle ( title ) ; this . setModal ( false ) ; initLayout ( inputPanel ) ; } public JPanelDialog ( Frame parent , JPanel inputPanel ) { super ( parent , false ) ; initLayout ( inputPanel ) ; } public JPanelDialog ( Frame parent , String title , JPanel inputPanel ) { super ( parent , title , false ) ; initLayout ( inputPanel ) ; } public boolean showAsModal ( ) { boolean startModal = this . isModal ( ) ; this . setModal ( true ) ; this . setVisible ( true ) ; this . setModal ( startModal ) ; return result ; } public boolean isAccepted ( ) { return result ; } public void setButtonTexts ( String acceptButtonText , String rejectButtonText ) { acceptButton . setText ( acceptButtonText ) ; rejectButton . setText ( rejectButtonText ) ; } private void initLayout ( JPanel inputPanel ) { GridBagConstraints gbc ; this . acceptButton = new javax . swing . JButton ( ) ; this . rejectButton = new javax . swing . JButton ( ) ; this . mainPanel = inputPanel ; getContentPane ( ) . setLayout ( new java . awt . GridBagLayout ( ) ) ; acceptButton . setText ( "<STR_LIT>" ) ; gbc = new GridBagConstraints ( ) ; gbc . gridx = <NUM_LIT:0> ; gbc . gridy = <NUM_LIT:1> ; gbc . insets = new Insets ( <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:10> ) ; gbc . anchor = gbc . EAST ; getContentPane ( ) . add ( acceptButton , gbc ) ; rejectButton . setText ( "<STR_LIT>" ) ; gbc = new GridBagConstraints ( ) ; gbc . gridx = <NUM_LIT:1> ; gbc . gridy = <NUM_LIT:1> ; gbc . insets = new Insets ( <NUM_LIT:5> , <NUM_LIT:10> , <NUM_LIT:5> , <NUM_LIT:5> ) ; gbc . anchor = gbc . WEST ; getContentPane ( ) . add ( rejectButton , gbc ) ; gbc = new GridBagConstraints ( ) ; gbc . gridx = <NUM_LIT:0> ; gbc . gridy = <NUM_LIT:0> ; gbc . gridwidth = <NUM_LIT:2> ; gbc . insets = new Insets ( <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> ) ; gbc . anchor = gbc . CENTER ; getContentPane ( ) . add ( mainPanel , gbc ) ; pack ( ) ; acceptButton . addActionListener ( this ) ; rejectButton . addActionListener ( this ) ; this . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { super . windowClosing ( e ) ; result = false ; dispose ( ) ; } } ) ; this . numOfPanels = <NUM_LIT:1> ; } public void actionPerformed ( ActionEvent e ) { if ( e . getSource ( ) == acceptButton ) { this . result = true ; this . dispose ( ) ; } else if ( e . getSource ( ) == rejectButton ) { this . result = false ; this . dispose ( ) ; } else throw new RuntimeException ( "<STR_LIT>" ) ; } public static boolean showModalDialog ( JPanel panel ) { JPanelDialog jpd = new JPanelDialog ( panel ) ; return jpd . showAsModal ( ) ; } public static boolean showModalDialog ( JPanel panel , String title ) { JPanelDialog jpd = new JPanelDialog ( title , panel ) ; return jpd . showAsModal ( ) ; } public static boolean showModalDialog ( Frame parent , JPanel panel ) { JPanelDialog jpd = new JPanelDialog ( parent , panel ) ; return jpd . showAsModal ( ) ; } public static boolean showModalDialog ( Frame parent , JPanel panel , String title ) { JPanelDialog jpd = new JPanelDialog ( parent , title , panel ) ; return jpd . showAsModal ( ) ; } public java . awt . Component add ( java . awt . Component compToAdd ) { GridBagConstraints gbc ; gbc = new GridBagConstraints ( ) ; gbc . gridx = <NUM_LIT:0> ; gbc . gridy = numOfPanels ++ ; gbc . gridwidth = <NUM_LIT:2> ; gbc . insets = new Insets ( <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> ) ; gbc . anchor = gbc . CENTER ; getContentPane ( ) . add ( compToAdd , gbc ) ; this . getContentPane ( ) . remove ( acceptButton ) ; gbc = new GridBagConstraints ( ) ; gbc . gridx = <NUM_LIT:0> ; gbc . gridy = numOfPanels ; gbc . insets = new Insets ( <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:5> , <NUM_LIT:10> ) ; gbc . anchor = gbc . EAST ; getContentPane ( ) . add ( acceptButton , gbc ) ; this . getContentPane ( ) . remove ( rejectButton ) ; gbc = new GridBagConstraints ( ) ; gbc . gridx = <NUM_LIT:1> ; gbc . gridy = numOfPanels ; gbc . insets = new Insets ( <NUM_LIT:5> , <NUM_LIT:10> , <NUM_LIT:5> , <NUM_LIT:5> ) ; gbc . anchor = gbc . WEST ; getContentPane ( ) . add ( rejectButton , gbc ) ; pack ( ) ; return compToAdd ; } } </s>
<s> package net . java . joglutils . test3ds ; import net . java . joglutils . ThreeDS . * ; import com . sun . opengl . util . texture . Texture ; import com . sun . opengl . util . texture . TextureCoords ; import com . sun . opengl . util . texture . TextureIO ; import java . io . File ; import java . io . IOException ; import javax . media . opengl . * ; public class MyModel extends Model3DS { private Texture [ ] texture ; private TextureCoords [ ] textureCoords ; private int compiledList ; private boolean loaded = false ; public MyModel ( ) { } public boolean isLoaded ( ) { return loaded ; } public boolean load ( GLAutoDrawable gLDrawable , String file ) { if ( ! super . load ( file ) ) return false ; GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; int numMaterials = materials . size ( ) ; texture = new Texture [ numMaterials ] ; for ( int i = <NUM_LIT:0> ; i < numMaterials ; i ++ ) { loadTexture ( materials . get ( i ) . strFile , i ) ; materials . get ( i ) . texureId = i ; } compiledList = gl . glGenLists ( <NUM_LIT:1> ) ; gl . glNewList ( compiledList , GL2 . GL_COMPILE ) ; genList ( gLDrawable ) ; gl . glEndList ( ) ; loaded = true ; return loaded ; } public void render ( GLAutoDrawable gLDrawable ) { GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; gl . glCallList ( compiledList ) ; } private void loadTexture ( String strFile , int id ) { File file = new File ( strFile ) ; try { texture [ id ] = TextureIO . newTexture ( file , true ) ; } catch ( IOException e ) { System . err . println ( e . getMessage ( ) ) ; return ; } } private void genList ( GLAutoDrawable gLDrawable ) { GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; TextureCoords coords ; for ( int i = <NUM_LIT:0> ; i < objects . size ( ) ; i ++ ) { Obj tempObj = objects . get ( i ) ; if ( tempObj . hasTexture ) { texture [ tempObj . materialID ] . enable ( ) ; texture [ tempObj . materialID ] . bind ( ) ; coords = texture [ tempObj . materialID ] . getImageTexCoords ( ) ; } gl . glBegin ( GL2 . GL_TRIANGLES ) ; for ( int j = <NUM_LIT:0> ; j < tempObj . numOfFaces ; j ++ ) { for ( int whichVertex = <NUM_LIT:0> ; whichVertex < <NUM_LIT:3> ; whichVertex ++ ) { int index = tempObj . faces [ j ] . vertIndex [ whichVertex ] ; gl . glNormal3f ( tempObj . normals [ index ] . x , tempObj . normals [ index ] . y , tempObj . normals [ index ] . z ) ; if ( tempObj . hasTexture ) { if ( tempObj . texVerts != null ) gl . glTexCoord2f ( tempObj . texVerts [ index ] . x , tempObj . texVerts [ index ] . y ) ; } else { if ( materials . size ( ) < tempObj . materialID ) { byte pColor [ ] = materials . get ( tempObj . materialID ) . color ; } } gl . glVertex3f ( tempObj . verts [ index ] . x , tempObj . verts [ index ] . y , tempObj . verts [ index ] . z ) ; } } gl . glEnd ( ) ; if ( tempObj . hasTexture ) texture [ tempObj . materialID ] . disable ( ) ; } } } </s>
<s> package net . java . joglutils . test3ds ; import com . sun . opengl . util . Animator ; import java . awt . Frame ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import javax . media . opengl . * ; import javax . media . opengl . awt . * ; import javax . media . opengl . glu . GLU ; public class Main { public Main ( ) { } public static void main ( String [ ] args ) { Frame frame = new Frame ( ) ; GLCanvas canvas = new GLCanvas ( ) ; canvas . addGLEventListener ( new Renderer ( ) ) ; frame . add ( canvas ) ; frame . setSize ( <NUM_LIT> , <NUM_LIT> ) ; final Animator animator = new Animator ( canvas ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { new Thread ( new Runnable ( ) { public void run ( ) { animator . stop ( ) ; System . exit ( <NUM_LIT:0> ) ; } } ) . start ( ) ; } } ) ; frame . show ( ) ; animator . start ( ) ; } static class Renderer implements GLEventListener { private MyModel model = new MyModel ( ) ; public void display ( GLAutoDrawable gLDrawable ) { final GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; gl . glClear ( GL2 . GL_COLOR_BUFFER_BIT | GL2 . GL_DEPTH_BUFFER_BIT ) ; gl . glLoadIdentity ( ) ; gl . glPushMatrix ( ) ; gl . glScalef ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ; model . render ( gLDrawable ) ; gl . glPopMatrix ( ) ; gl . glFlush ( ) ; } public void dispose ( GLAutoDrawable drawable ) { } public void init ( GLAutoDrawable gLDrawable ) { final GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; gl . glClearColor ( <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT> ) ; gl . glClearDepth ( <NUM_LIT:1.0f> ) ; gl . glEnable ( GL2 . GL_DEPTH_TEST ) ; gl . glDepthFunc ( GL2 . GL_LEQUAL ) ; gl . glHint ( GL2 . GL_PERSPECTIVE_CORRECTION_HINT , GL2 . GL_NICEST ) ; if ( ! model . isLoaded ( ) ) model . load ( gLDrawable , "<STR_LIT>" ) ; } public void reshape ( GLAutoDrawable gLDrawable , int x , int y , int width , int height ) { final GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; final GLU glu = new GLU ( ) ; if ( height <= <NUM_LIT:0> ) height = <NUM_LIT:1> ; final float h = ( float ) width / ( float ) height ; gl . glViewport ( <NUM_LIT:0> , <NUM_LIT:0> , width , height ) ; gl . glMatrixMode ( GL2 . GL_PROJECTION ) ; gl . glLoadIdentity ( ) ; gl . glOrtho ( - <NUM_LIT:1000> , <NUM_LIT:1000> , - <NUM_LIT:1000> , <NUM_LIT:1000> , - <NUM_LIT> , <NUM_LIT> ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glLoadIdentity ( ) ; } } } </s>
<s> package net . java . joglutils . model ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import java . net . MalformedURLException ; public class ResourceRetriever { public static URL getResource ( final String filename ) throws IOException { URL url = ResourceRetriever . class . getClassLoader ( ) . getResource ( filename ) ; if ( url == null ) { return new URL ( "<STR_LIT:file>" , "<STR_LIT:localhost>" , filename ) ; } else { return url ; } } public static InputStream getResourceAsStream ( final String filename ) throws IOException { String convertedFileName = filename . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) ; InputStream stream = ResourceRetriever . class . getClassLoader ( ) . getResourceAsStream ( convertedFileName ) ; if ( stream == null ) { return new FileInputStream ( convertedFileName ) ; } else { return stream ; } } public static URL getResourceAsUrl ( final String filename ) throws IOException { URL result ; try { result = new URL ( filename ) ; } catch ( MalformedURLException e ) { Object objectpart = new Object ( ) { } ; Class classpart = objectpart . getClass ( ) ; ClassLoader loaderpart = classpart . getClassLoader ( ) ; result = loaderpart . getResource ( filename ) ; if ( result == null ) { result = new URL ( "<STR_LIT:file>" , "<STR_LIT:localhost>" , filename ) ; } } return result ; } public static InputStream getResourceAsInputStream ( final String filename ) throws IOException { URL result ; try { result = getResourceAsUrl ( filename ) ; } catch ( IOException e ) { return new FileInputStream ( filename ) ; } if ( result == null ) { return new FileInputStream ( filename ) ; } else { return result . openStream ( ) ; } } } </s>
<s> package net . java . joglutils . model ; import java . util . HashMap ; import net . java . joglutils . model . geometry . Model ; import net . java . joglutils . model . loader . LoaderFactory ; public class ModelFactory { private static HashMap < Object , Model > modelCache = new HashMap < Object , Model > ( ) ; public static Model createModel ( String source ) throws ModelLoadException { Model model = modelCache . get ( source ) ; if ( model == null ) { model = LoaderFactory . load ( source ) ; modelCache . put ( source , model ) ; } if ( model == null ) throw new ModelLoadException ( ) ; return model ; } } </s>
<s> package net . java . joglutils . model ; public class ModelLoadException extends Exception { public ModelLoadException ( ) { } public ModelLoadException ( String message ) { super ( message ) ; } } </s>
<s> package net . java . joglutils . model . geometry ; public class Bounds { public static final float LARGE = Float . MAX_VALUE ; public Vec4 min = new Vec4 ( LARGE , LARGE , LARGE ) ; public Vec4 max = new Vec4 ( - LARGE , - LARGE , - LARGE ) ; public Bounds ( ) { } public Bounds ( float x1 , float y1 , float z1 , float x2 , float y2 , float z2 ) { min . x = x1 ; min . y = y1 ; min . z = z1 ; max . x = x2 ; max . y = y2 ; max . z = z2 ; } public Bounds ( Vec4 v1 , Vec4 v2 ) { min . x = v1 . x ; min . y = v1 . y ; min . z = v1 . z ; max . x = v2 . x ; max . y = v2 . y ; max . z = v2 . z ; } public void calc ( float x , float y , float z ) { if ( x > max . x ) { max . x = x ; } if ( x < min . x ) { min . x = x ; } if ( y > max . y ) { max . y = y ; } if ( y < min . y ) { min . y = y ; } if ( z > max . z ) { max . z = z ; } if ( z < min . z ) { min . z = z ; } } public void calc ( Vec4 v ) { calc ( v . x , v . y , v . z ) ; } public float getRadius ( ) { return <NUM_LIT> * ( float ) Math . sqrt ( Math . pow ( max . x - min . x , <NUM_LIT:2> ) + Math . pow ( max . y - min . y , <NUM_LIT:2> ) + Math . pow ( max . z - min . z , <NUM_LIT:2> ) ) ; } public String toString ( ) { return "<STR_LIT>" + min . x + "<STR_LIT:U+002CU+0020>" + min . y + "<STR_LIT:U+002CU+0020>" + min . z + "<STR_LIT>" + "<STR_LIT>" + max . x + "<STR_LIT:U+002CU+0020>" + max . y + "<STR_LIT:U+002CU+0020>" + max . z + "<STR_LIT:)>" ; } } </s>
<s> package net . java . joglutils . model . geometry ; public class Face { public int vertIndex [ ] ; public int coordIndex [ ] ; public int normalIndex [ ] ; public Face ( int numVertices ) { vertIndex = new int [ numVertices ] ; coordIndex = new int [ numVertices ] ; normalIndex = new int [ numVertices ] ; } public int materialID = <NUM_LIT:0> ; } </s>
<s> package net . java . joglutils . model . geometry ; import java . util . Vector ; public class Model { protected Vector < Material > materials = new Vector < Material > ( ) ; protected Vector < Mesh > mesh = new Vector < Mesh > ( ) ; protected String source ; protected boolean renderModel = true ; protected boolean centerModel = false ; protected boolean renderModelBounds = false ; protected boolean renderObjectBounds = false ; protected boolean unitizeSize = true ; protected boolean useTexture = true ; protected boolean renderAsWireframe = false ; protected boolean useLighting = true ; protected Bounds bounds = new Bounds ( ) ; private Vec4 centerPoint = new Vec4 ( <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> ) ; public Model ( String source ) { this . source = source ; } public void addMaterial ( Material mat ) { materials . add ( mat ) ; } public void addMesh ( Mesh obj ) { mesh . add ( obj ) ; } public Material getMaterial ( int index ) { return materials . get ( index ) ; } public Mesh getMesh ( int index ) { return mesh . get ( index ) ; } public int getNumberOfMeshes ( ) { return mesh . size ( ) ; } public int getNumberOfMaterials ( ) { return materials . size ( ) ; } public String getSource ( ) { return source ; } public boolean isRenderModel ( ) { return renderModel ; } public void setRenderModel ( boolean renderModel ) { this . renderModel = renderModel ; } public boolean isCentered ( ) { return centerModel ; } public void centerModelOnPosition ( boolean centerModel ) { this . centerModel = centerModel ; } public boolean isRenderModelBounds ( ) { return renderModelBounds ; } public void setRenderModelBounds ( boolean renderModelBounds ) { this . renderModelBounds = renderModelBounds ; } public boolean isRenderObjectBounds ( ) { return renderObjectBounds ; } public void setRenderObjectBounds ( boolean renderObjectBounds ) { this . renderObjectBounds = renderObjectBounds ; } public Bounds getBounds ( ) { return bounds ; } public void setBounds ( Bounds bounds ) { this . bounds = bounds ; } public Vec4 getCenterPoint ( ) { return this . centerPoint ; } public void setCenterPoint ( Vec4 center ) { this . centerPoint = center ; } public boolean isUnitizeSize ( ) { return unitizeSize ; } public void setUnitizeSize ( boolean unitizeSize ) { this . unitizeSize = unitizeSize ; } public boolean isUsingTexture ( ) { return useTexture ; } public void setUseTexture ( boolean useTexture ) { this . useTexture = useTexture ; } public boolean isRenderingAsWireframe ( ) { return renderAsWireframe ; } public void setRenderAsWireframe ( boolean renderAsWireframe ) { this . renderAsWireframe = renderAsWireframe ; } public boolean isUsingLighting ( ) { return useLighting ; } public void setUseLighting ( boolean useLighting ) { this . useLighting = useLighting ; } } </s>
<s> package net . java . joglutils . model . geometry ; public class TexCoord { public float u , v ; public TexCoord ( ) { u = v = <NUM_LIT:0> ; } public TexCoord ( float u , float v ) { this . u = u ; this . v = v ; } } </s>
<s> package net . java . joglutils . model . geometry ; import java . awt . Color ; public class Material { public String strName ; public String strFile ; public Color ambientColor ; public Color specularColor ; public Color diffuseColor ; public Color emissive = Color . BLACK ; public float shininess ; public float shininess2 ; public float transparency ; public int textureId ; public float uTile ; public float vTile ; public float uOffset ; public float vOffset ; } </s>
<s> package net . java . joglutils . model . geometry ; import java . util . Vector ; public class Mesh { public int numOfVerts = <NUM_LIT:0> ; public int numOfFaces = <NUM_LIT:0> ; public int numTexCoords = <NUM_LIT:0> ; public int materialID = <NUM_LIT:0> ; public boolean hasTexture = false ; public String name = null ; public int indices = <NUM_LIT:0> ; public Vec4 vertices [ ] = null ; public Vec4 normals [ ] = null ; public TexCoord texCoords [ ] = null ; public Face faces [ ] = null ; public Bounds bounds = null ; public Mesh ( ) { this ( "<STR_LIT:default>" ) ; } public Mesh ( String name ) { this . name = name ; bounds = new Bounds ( ) ; } } </s>
<s> package net . java . joglutils . model . geometry ; public class Vec4 { public float x , y , z , w ; public Vec4 ( ) { this ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) ; } public Vec4 ( float _x , float _y , float _z ) { x = _x ; y = _y ; z = _z ; } public Vec4 ( float _x , float _y , float _z , float _w ) { x = _x ; y = _y ; z = _z ; w = _w ; } public Vec4 ( Vec4 v ) { x = v . x ; y = v . y ; z = v . z ; w = v . w ; } } </s>
<s> package net . java . joglutils . model ; import net . java . joglutils . model . geometry . Model ; public interface iModel3DRenderer { public void render ( Object context , Model model ) ; public void debug ( boolean value ) ; } </s>
<s> package net . java . joglutils . model . examples ; import net . java . joglutils . model . * ; import com . sun . opengl . util . texture . * ; import com . sun . opengl . util . texture . awt . * ; import java . awt . image . BufferedImage ; import java . io . IOException ; import java . net . URL ; import java . util . HashMap ; import javax . imageio . ImageIO ; import javax . media . opengl . * ; import net . java . joglutils . model . ResourceRetriever ; import net . java . joglutils . model . geometry . Bounds ; import net . java . joglutils . model . geometry . Material ; import net . java . joglutils . model . geometry . Mesh ; import net . java . joglutils . model . geometry . Model ; import net . java . joglutils . model . geometry . Vec4 ; import net . java . joglutils . model . iModel3DRenderer ; public class DisplayListRenderer implements iModel3DRenderer { private static DisplayListRenderer instance = new DisplayListRenderer ( ) ; private DisplayListCache listCache = new DisplayListCache ( ) ; private HashMap < Integer , Texture > texture ; private int modelBoundsList = - <NUM_LIT:1> ; private int objectBoundsList = <NUM_LIT:1> ; private boolean isDebugging = true ; public DisplayListRenderer ( ) { } public static DisplayListRenderer getInstance ( ) { return instance ; } public void debug ( boolean value ) { this . isDebugging = value ; } public void render ( Object context , Model model ) { GL2 gl = null ; if ( context instanceof GL2 ) gl = ( GL2 ) context ; else if ( context instanceof GLAutoDrawable ) gl = ( ( GLAutoDrawable ) context ) . getGL ( ) . getGL2 ( ) ; if ( gl == null ) { return ; } if ( model == null ) { return ; } int displayList = listCache . get ( model ) ; if ( displayList < <NUM_LIT:0> ) { displayList = initialize ( gl , model ) ; if ( this . isDebugging ) System . out . println ( "<STR_LIT>" + model . getSource ( ) ) ; } boolean isTextureEnabled = gl . glIsEnabled ( GL2 . GL_TEXTURE_2D ) ; boolean isLightingEnabled = gl . glIsEnabled ( GL2 . GL_LIGHTING ) ; boolean isMaterialEnabled = gl . glIsEnabled ( GL2 . GL_COLOR_MATERIAL ) ; if ( ! model . isUsingLighting ( ) ) { gl . glDisable ( GL2 . GL_LIGHTING ) ; } if ( model . isUsingTexture ( ) ) { gl . glEnable ( GL2 . GL_TEXTURE_2D ) ; } else { gl . glDisable ( GL2 . GL_TEXTURE_2D ) ; } if ( model . isRenderingAsWireframe ( ) ) { gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_LINE ) ; } else { gl . glPolygonMode ( GL2 . GL_FRONT_AND_BACK , GL2 . GL_FILL ) ; } gl . glDisable ( GL2 . GL_COLOR_MATERIAL ) ; gl . glPushMatrix ( ) ; if ( model . isUnitizeSize ( ) ) { float scale = <NUM_LIT:1.0f> / model . getBounds ( ) . getRadius ( ) ; gl . glScalef ( scale , scale , scale ) ; } if ( model . isCentered ( ) ) { Vec4 center = model . getCenterPoint ( ) ; gl . glTranslatef ( - center . x , - center . y , - center . z ) ; } if ( model . isRenderModel ( ) ) gl . glCallList ( displayList ) ; gl . glDisable ( GL2 . GL_LIGHTING ) ; if ( model . isRenderModelBounds ( ) ) gl . glCallList ( modelBoundsList ) ; if ( model . isRenderObjectBounds ( ) ) gl . glCallList ( objectBoundsList ) ; gl . glPopMatrix ( ) ; if ( isTextureEnabled ) { gl . glEnable ( GL2 . GL_TEXTURE_2D ) ; } else { gl . glDisable ( GL2 . GL_TEXTURE_2D ) ; } if ( isLightingEnabled ) { gl . glEnable ( GL2 . GL_LIGHTING ) ; } else { gl . glDisable ( GL2 . GL_LIGHTING ) ; } if ( isMaterialEnabled ) { gl . glEnable ( GL2 . GL_COLOR_MATERIAL ) ; } else { gl . glDisable ( GL2 . GL_COLOR_MATERIAL ) ; } } private int initialize ( GL2 gl , Model model ) { if ( this . isDebugging ) System . out . println ( "<STR_LIT>" + model . getSource ( ) ) ; int numMaterials = model . getNumberOfMaterials ( ) ; if ( this . isDebugging && numMaterials > <NUM_LIT:0> ) { System . out . println ( "<STR_LIT>" + numMaterials + "<STR_LIT>" ) ; } String file = model . getSource ( ) ; texture = new HashMap < Integer , Texture > ( ) ; for ( int i = <NUM_LIT:0> ; i < numMaterials ; i ++ ) { String subFileName = "<STR_LIT>" ; int index = file . lastIndexOf ( '<CHAR_LIT:/>' ) ; if ( index != - <NUM_LIT:1> ) { subFileName = file . substring ( <NUM_LIT:0> , index + <NUM_LIT:1> ) ; } else { index = file . lastIndexOf ( '<STR_LIT:\\>' ) ; if ( index != - <NUM_LIT:1> ) { subFileName = file . substring ( <NUM_LIT:0> , index + <NUM_LIT:1> ) ; } } if ( model . getMaterial ( i ) . strFile != null ) { if ( this . isDebugging ) System . out . print ( "<STR_LIT>" + subFileName + model . getMaterial ( i ) . strFile ) ; URL result ; try { result = ResourceRetriever . getResourceAsUrl ( subFileName + model . getMaterial ( i ) . strFile ) ; } catch ( IOException e ) { if ( this . isDebugging ) System . err . println ( "<STR_LIT>" ) ; continue ; } if ( result != null && ! result . getPath ( ) . endsWith ( "<STR_LIT:/>" ) && ! result . getPath ( ) . endsWith ( "<STR_LIT:\\>" ) ) { loadTexture ( result , i ) ; model . getMaterial ( i ) . textureId = i ; if ( this . isDebugging ) System . out . println ( "<STR_LIT>" + i ) ; } else if ( this . isDebugging ) { System . out . println ( "<STR_LIT>" ) ; } } } if ( this . isDebugging && numMaterials > <NUM_LIT:0> ) { System . out . println ( "<STR_LIT>" ) ; } if ( this . isDebugging ) System . out . println ( "<STR_LIT>" ) ; int compiledList = listCache . generateList ( model , gl , <NUM_LIT:3> ) ; if ( this . isDebugging ) System . out . println ( "<STR_LIT>" ) ; gl . glNewList ( compiledList , GL2 . GL_COMPILE ) ; genList ( gl , model ) ; gl . glEndList ( ) ; modelBoundsList = compiledList + <NUM_LIT:1> ; if ( this . isDebugging ) System . out . println ( "<STR_LIT>" ) ; gl . glNewList ( modelBoundsList , GL2 . GL_COMPILE ) ; genModelBoundsList ( gl , model ) ; gl . glEndList ( ) ; objectBoundsList = compiledList + <NUM_LIT:2> ; if ( this . isDebugging ) System . out . println ( "<STR_LIT>" ) ; gl . glNewList ( objectBoundsList , GL2 . GL_COMPILE ) ; genObjectBoundsList ( gl , model ) ; gl . glEndList ( ) ; if ( this . isDebugging ) { System . out . println ( "<STR_LIT>" ) ; System . out . println ( "<STR_LIT>" ) ; } return compiledList ; } private void loadTexture ( URL url , int id ) { if ( url != null ) { BufferedImage bufferedImage = null ; try { bufferedImage = ImageIO . read ( url ) ; } catch ( Exception e ) { System . err . println ( "<STR_LIT>" + e . getMessage ( ) ) ; return ; } texture . put ( id , AWTTextureIO . newTexture ( bufferedImage , true ) ) ; } } private void genList ( GL2 gl , Model model ) { TextureCoords coords ; for ( int i = <NUM_LIT:0> ; i < model . getNumberOfMeshes ( ) ; i ++ ) { Mesh tempObj = model . getMesh ( i ) ; if ( tempObj . numOfFaces == <NUM_LIT:0> ) { System . err . println ( "<STR_LIT>" + tempObj . name + "<STR_LIT>" ) ; continue ; } if ( tempObj . hasTexture && texture . get ( tempObj . materialID ) != null ) { Texture t = texture . get ( tempObj . materialID ) ; gl . glMatrixMode ( GL2 . GL_TEXTURE ) ; gl . glPushMatrix ( ) ; if ( t . getMustFlipVertically ( ) ) { gl . glScaled ( <NUM_LIT:1> , - <NUM_LIT:1> , <NUM_LIT:1> ) ; gl . glTranslated ( <NUM_LIT:0> , - <NUM_LIT:1> , <NUM_LIT:0> ) ; } gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glPushMatrix ( ) ; gl . glTexParameteri ( GL2 . GL_TEXTURE_2D , GL2 . GL_TEXTURE_WRAP_S , GL2 . GL_REPEAT ) ; gl . glTexParameteri ( GL2 . GL_TEXTURE_2D , GL2 . GL_TEXTURE_WRAP_T , GL2 . GL_REPEAT ) ; t . enable ( ) ; t . bind ( ) ; coords = t . getImageTexCoords ( ) ; } for ( int j = <NUM_LIT:0> ; j < tempObj . numOfFaces ; j ++ ) { if ( tempObj . hasTexture ) { } else { if ( tempObj . faces [ j ] . materialID < model . getNumberOfMaterials ( ) ) { float [ ] rgba = new float [ <NUM_LIT:4> ] ; Material material = model . getMaterial ( tempObj . faces [ j ] . materialID ) ; gl . glMaterialfv ( GL2 . GL_FRONT , GL2 . GL_DIFFUSE , material . diffuseColor . getRGBComponents ( rgba ) , <NUM_LIT:0> ) ; gl . glMaterialfv ( GL2 . GL_FRONT , GL2 . GL_AMBIENT , material . ambientColor . getRGBComponents ( rgba ) , <NUM_LIT:0> ) ; gl . glMaterialfv ( GL2 . GL_FRONT , GL2 . GL_SPECULAR , material . specularColor . getRGBComponents ( rgba ) , <NUM_LIT:0> ) ; gl . glMaterialf ( GL2 . GL_FRONT , GL2 . GL_SHININESS , material . shininess ) ; gl . glMaterialfv ( GL2 . GL_FRONT , GL2 . GL_EMISSION , material . emissive . getRGBComponents ( rgba ) , <NUM_LIT:0> ) ; } } int indexType = <NUM_LIT:0> ; int vertexIndex = <NUM_LIT:0> ; int normalIndex = <NUM_LIT:0> ; int textureIndex = <NUM_LIT:0> ; gl . glBegin ( GL2 . GL_POLYGON ) ; for ( int whichVertex = <NUM_LIT:0> ; whichVertex < tempObj . faces [ j ] . vertIndex . length ; whichVertex ++ ) { vertexIndex = tempObj . faces [ j ] . vertIndex [ whichVertex ] ; try { normalIndex = tempObj . faces [ j ] . normalIndex [ whichVertex ] ; indexType = <NUM_LIT:0> ; gl . glNormal3f ( tempObj . normals [ normalIndex ] . x , tempObj . normals [ normalIndex ] . y , tempObj . normals [ normalIndex ] . z ) ; if ( tempObj . hasTexture ) { if ( tempObj . texCoords != null ) { textureIndex = tempObj . faces [ j ] . coordIndex [ whichVertex ] ; indexType = <NUM_LIT:1> ; gl . glTexCoord2f ( tempObj . texCoords [ textureIndex ] . u , tempObj . texCoords [ textureIndex ] . v ) ; } } indexType = <NUM_LIT:2> ; gl . glVertex3f ( tempObj . vertices [ vertexIndex ] . x , tempObj . vertices [ vertexIndex ] . y , tempObj . vertices [ vertexIndex ] . z ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; switch ( indexType ) { case <NUM_LIT:0> : System . err . println ( "<STR_LIT>" + normalIndex + "<STR_LIT>" ) ; break ; case <NUM_LIT:1> : System . err . println ( "<STR_LIT>" + textureIndex + "<STR_LIT>" ) ; break ; case <NUM_LIT:2> : System . err . println ( "<STR_LIT>" + vertexIndex + "<STR_LIT>" ) ; break ; } } } gl . glEnd ( ) ; } if ( tempObj . hasTexture ) { Texture t = texture . get ( tempObj . materialID ) ; if ( t != null ) t . disable ( ) ; gl . glMatrixMode ( GL2 . GL_TEXTURE ) ; gl . glPopMatrix ( ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glPopMatrix ( ) ; } } gl . glColor3f ( <NUM_LIT:1.0f> , <NUM_LIT:1.0f> , <NUM_LIT:1.0f> ) ; } public void renderBoundsOfObject ( GL2 gl , int id , Model model ) { if ( id >= <NUM_LIT:0> && id <= model . getNumberOfMeshes ( ) ) { if ( model . getMesh ( id ) . bounds != null ) { drawBounds ( gl , model . getMesh ( id ) . bounds ) ; } } } private void genModelBoundsList ( GLAutoDrawable gLDrawable , Model model ) { GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; drawBounds ( gl , model . getBounds ( ) ) ; } private void genModelBoundsList ( GL2 gl , Model model ) { drawBounds ( gl , model . getBounds ( ) ) ; } private void genObjectBoundsList ( GLAutoDrawable gLDrawable , Model model ) { GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; genObjectBoundsList ( gl , model ) ; } private void genObjectBoundsList ( GL2 gl , Model model ) { for ( int i = <NUM_LIT:0> ; i < model . getNumberOfMeshes ( ) ; i ++ ) { if ( model . getMesh ( i ) . bounds != null ) { drawBounds ( gl , model . getMesh ( i ) . bounds ) ; } } } private void drawBounds ( GL2 gl , Bounds bounds ) { gl . glBegin ( GL2 . GL_LINE_LOOP ) ; gl . glVertex3f ( bounds . min . x , bounds . min . y , bounds . min . z ) ; gl . glVertex3f ( bounds . max . x , bounds . min . y , bounds . min . z ) ; gl . glVertex3f ( bounds . max . x , bounds . max . y , bounds . min . z ) ; gl . glVertex3f ( bounds . min . x , bounds . max . y , bounds . min . z ) ; gl . glEnd ( ) ; gl . glBegin ( GL2 . GL_LINE_LOOP ) ; gl . glVertex3f ( bounds . min . x , bounds . min . y , bounds . max . z ) ; gl . glVertex3f ( bounds . max . x , bounds . min . y , bounds . max . z ) ; gl . glVertex3f ( bounds . max . x , bounds . max . y , bounds . max . z ) ; gl . glVertex3f ( bounds . min . x , bounds . max . y , bounds . max . z ) ; gl . glEnd ( ) ; gl . glBegin ( GL2 . GL_LINES ) ; gl . glVertex3f ( bounds . min . x , bounds . min . y , bounds . min . z ) ; gl . glVertex3f ( bounds . min . x , bounds . min . y , bounds . max . z ) ; gl . glVertex3f ( bounds . max . x , bounds . min . y , bounds . min . z ) ; gl . glVertex3f ( bounds . max . x , bounds . min . y , bounds . max . z ) ; gl . glVertex3f ( bounds . max . x , bounds . max . y , bounds . min . z ) ; gl . glVertex3f ( bounds . max . x , bounds . max . y , bounds . max . z ) ; gl . glVertex3f ( bounds . min . x , bounds . max . y , bounds . min . z ) ; gl . glVertex3f ( bounds . min . x , bounds . max . y , bounds . max . z ) ; gl . glEnd ( ) ; } public int unsignedByteToInt ( byte b ) { return ( int ) b & <NUM_LIT> ; } public float intToFloat ( int i ) { return ( float ) i / <NUM_LIT> ; } public class DisplayListCache { private HashMap < Object , Integer > listCache ; private DisplayListCache ( ) { listCache = new HashMap < Object , Integer > ( ) ; } public void clear ( ) { listCache . clear ( ) ; } public int get ( Object objID ) { if ( listCache . containsKey ( objID ) ) return listCache . get ( objID ) ; else return - <NUM_LIT:1> ; } public void remove ( Object objID , GL2 gl , int howMany ) { Integer list = listCache . get ( objID ) ; if ( list != null ) gl . glDeleteLists ( list , howMany ) ; listCache . remove ( objID ) ; } public int generateList ( Object objID , GL2 gl , int howMany ) { Integer list = null ; list = listCache . get ( objID ) ; if ( list == null ) { list = new Integer ( gl . glGenLists ( howMany ) ) ; listCache . put ( objID , list ) ; } return list ; } } } </s>
<s> package net . java . joglutils . model . examples ; import net . java . joglutils . model . * ; import com . sun . opengl . util . Animator ; import java . awt . Frame ; import java . awt . event . KeyEvent ; import java . awt . event . KeyListener ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import javax . media . opengl . awt . GLCanvas ; import javax . swing . * ; import javax . swing . event . MouseInputAdapter ; import java . awt . event . MouseEvent ; import javax . media . opengl . * ; import java . awt . * ; import javax . media . opengl . glu . GLU ; import net . java . joglutils . model . ModelFactory ; import net . java . joglutils . model . ModelLoadException ; import net . java . joglutils . model . geometry . Model ; import net . java . joglutils . model . iModel3DRenderer ; public class ModelTest { public ModelTest ( ) { } public static void main ( String [ ] args ) { Frame frame = new Frame ( ) ; GLCanvas canvas = new GLCanvas ( ) ; final Renderer renderer = new Renderer ( ) ; MouseHandler inputMouseHandler = new MouseHandler ( renderer ) ; canvas . addMouseListener ( inputMouseHandler ) ; canvas . addMouseMotionListener ( inputMouseHandler ) ; canvas . addKeyListener ( new KeyListener ( ) { public void keyTyped ( KeyEvent e ) { Model model = renderer . getModel ( ) ; if ( model == null ) return ; switch ( e . getKeyChar ( ) ) { case '<CHAR_LIT>' : model . setRenderAsWireframe ( ! model . isRenderingAsWireframe ( ) ) ; break ; case '<CHAR_LIT>' : model . setUseLighting ( ! model . isUsingLighting ( ) ) ; break ; } } public void keyPressed ( KeyEvent e ) { } public void keyReleased ( KeyEvent e ) { } } ) ; canvas . addGLEventListener ( renderer ) ; frame . add ( canvas ) ; frame . add ( canvas ) ; frame . setSize ( <NUM_LIT> , <NUM_LIT> ) ; final Animator animator = new Animator ( canvas ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { new Thread ( new Runnable ( ) { public void run ( ) { animator . stop ( ) ; System . exit ( <NUM_LIT:0> ) ; } } ) . start ( ) ; } } ) ; frame . setVisible ( true ) ; animator . start ( ) ; } static class Renderer implements GLEventListener { private GLU glu = new GLU ( ) ; private Model model ; private iModel3DRenderer modelRenderer ; private float scaleAll = <NUM_LIT:1.0f> ; private float rotX = <NUM_LIT:0.0f> ; private float rotY = <NUM_LIT:0.0f> ; private Point mousePoint = new Point ( ) ; private static final float MIN_SCALE = <NUM_LIT> ; private static final float MAX_SCALE = <NUM_LIT> ; private float radius = <NUM_LIT:1.0f> ; float [ ] lightAmbient = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1.0f> } ; float [ ] lightDiffuse = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1.0f> } ; float [ ] lightSpecular = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1.0f> } ; public void display ( GLAutoDrawable gLDrawable ) { final GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; gl . glClear ( GL2 . GL_COLOR_BUFFER_BIT | GL2 . GL_DEPTH_BUFFER_BIT ) ; gl . glLoadIdentity ( ) ; glu . gluLookAt ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:10> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:0> ) ; if ( Math . abs ( rotX ) >= <NUM_LIT> ) rotX = <NUM_LIT:0.0f> ; if ( Math . abs ( rotY ) >= <NUM_LIT> ) rotY = <NUM_LIT:0.0f> ; gl . glPushMatrix ( ) ; gl . glScalef ( scaleAll , scaleAll , scaleAll ) ; gl . glRotatef ( rotY , <NUM_LIT:1.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> ) ; gl . glRotatef ( rotX , <NUM_LIT:0.0f> , <NUM_LIT:1.0f> , <NUM_LIT:0.0f> ) ; modelRenderer . render ( gl , model ) ; gl . glPopMatrix ( ) ; gl . glFlush ( ) ; } public void displayChanged ( GLAutoDrawable drawable , boolean modeChanged , boolean deviceChanged ) { } public void init ( GLAutoDrawable gLDrawable ) { final GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; try { modelRenderer = DisplayListRenderer . getInstance ( ) ; modelRenderer . debug ( true ) ; model = ModelFactory . createModel ( "<STR_LIT>" ) ; model . centerModelOnPosition ( true ) ; model . setUseTexture ( true ) ; model . setRenderModelBounds ( false ) ; model . setRenderObjectBounds ( false ) ; model . setUnitizeSize ( true ) ; radius = model . getBounds ( ) . getRadius ( ) ; } catch ( ModelLoadException ex ) { ex . printStackTrace ( ) ; } float lightPosition [ ] = { <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT:1.0f> } ; float [ ] model_ambient = { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1.0f> } ; gl . glLightModelfv ( GL2 . GL_LIGHT_MODEL_AMBIENT , model_ambient , <NUM_LIT:0> ) ; gl . glLightfv ( GL2 . GL_LIGHT0 , GL2 . GL_POSITION , lightPosition , <NUM_LIT:0> ) ; gl . glLightfv ( GL2 . GL_LIGHT0 , GL2 . GL_DIFFUSE , lightDiffuse , <NUM_LIT:0> ) ; gl . glLightfv ( GL2 . GL_LIGHT0 , GL2 . GL_AMBIENT , lightAmbient , <NUM_LIT:0> ) ; gl . glLightfv ( GL2 . GL_LIGHT0 , GL2 . GL_SPECULAR , lightSpecular , <NUM_LIT:0> ) ; gl . glEnable ( GL2 . GL_LIGHT0 ) ; gl . glEnable ( GL2 . GL_LIGHTING ) ; gl . glEnable ( GL2 . GL_NORMALIZE ) ; gl . glEnable ( GL2 . GL_CULL_FACE ) ; gl . glShadeModel ( GL2 . GL_SMOOTH ) ; gl . glClearColor ( <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:1.0f> ) ; gl . glClearDepth ( <NUM_LIT:1.0f> ) ; gl . glEnable ( GL2 . GL_DEPTH_TEST ) ; gl . glDepthFunc ( GL2 . GL_LEQUAL ) ; gl . glHint ( GL2 . GL_PERSPECTIVE_CORRECTION_HINT , GL2 . GL_NICEST ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glPushMatrix ( ) ; } public void reshape ( GLAutoDrawable gLDrawable , int x , int y , int width , int height ) { final GL2 gl = gLDrawable . getGL ( ) . getGL2 ( ) ; if ( height <= <NUM_LIT:0> ) height = <NUM_LIT:1> ; final float h = ( float ) width / ( float ) height ; gl . glViewport ( <NUM_LIT:0> , <NUM_LIT:0> , width , height ) ; gl . glMatrixMode ( GL2 . GL_PROJECTION ) ; gl . glLoadIdentity ( ) ; gl . glOrtho ( - <NUM_LIT:1> , <NUM_LIT:1> , - <NUM_LIT:1> , <NUM_LIT:1> , - <NUM_LIT> , <NUM_LIT> ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glLoadIdentity ( ) ; } public void dispose ( GLAutoDrawable drawable ) { } void startDrag ( Point MousePt ) { mousePoint . x = MousePt . x ; mousePoint . y = MousePt . y ; } void drag ( Point MousePt ) { Point delta = new Point ( ) ; delta . x = MousePt . x - mousePoint . x ; delta . y = MousePt . y - mousePoint . y ; mousePoint . x = MousePt . x ; mousePoint . y = MousePt . y ; rotX += delta . x * <NUM_LIT> / scaleAll ; rotY += delta . y * <NUM_LIT> / scaleAll ; } void startZoom ( Point MousePt ) { mousePoint . x = MousePt . x ; mousePoint . y = MousePt . y ; } void zoom ( Point MousePt ) { Point delta = new Point ( ) ; delta . x = MousePt . x - mousePoint . x ; delta . y = MousePt . y - mousePoint . y ; mousePoint . x = MousePt . x ; mousePoint . y = MousePt . y ; float addition = - ( delta . x + delta . y ) / <NUM_LIT> ; if ( addition < <NUM_LIT:0.0> && ( scaleAll + addition ) > MIN_SCALE ) { scaleAll += addition ; } if ( addition > <NUM_LIT:0.0> && ( scaleAll + addition ) < MAX_SCALE ) { scaleAll += addition ; } } public Model getModel ( ) { return model ; } public void setModel ( Model model ) { this . model = model ; } } static class MouseHandler extends MouseInputAdapter { private Renderer renderer ; public MouseHandler ( Renderer renderer ) { this . renderer = renderer ; } public void mouseClicked ( MouseEvent e ) { if ( SwingUtilities . isRightMouseButton ( e ) ) { } } public void mousePressed ( MouseEvent mouseEvent ) { if ( SwingUtilities . isLeftMouseButton ( mouseEvent ) ) { renderer . startDrag ( mouseEvent . getPoint ( ) ) ; } else if ( SwingUtilities . isMiddleMouseButton ( mouseEvent ) ) { renderer . startZoom ( mouseEvent . getPoint ( ) ) ; } } public void mouseDragged ( MouseEvent mouseEvent ) { if ( SwingUtilities . isLeftMouseButton ( mouseEvent ) ) { renderer . drag ( mouseEvent . getPoint ( ) ) ; } else if ( SwingUtilities . isMiddleMouseButton ( mouseEvent ) ) { renderer . zoom ( mouseEvent . getPoint ( ) ) ; } } } } </s>
<s> package net . java . joglutils . model . loader ; interface MaxConstants { public static final int TYPE_3DS_FILE = <NUM_LIT> ; public static final int TYPE_3DS_VERSION = <NUM_LIT> ; public static final int TYPE_MESH_DATA = <NUM_LIT> ; public static final int TYPE_MESH_VERSION = <NUM_LIT> ; public static final int TYPE_COLOR_I = <NUM_LIT> ; public static final int TYPE_COLOR_F = <NUM_LIT> ; public static final int TYPE_COLOR_LIN_I = <NUM_LIT> ; public static final int TYPE_COLOR_LIN_F = <NUM_LIT> ; public static final int TYPE_PERCENT_I = <NUM_LIT> ; public static final int TYPE_PERCENT_F = <NUM_LIT> ; public static final int TYPE_BG_BITMAP = <NUM_LIT> ; public static final int TYPE_BG_USE_BITMAP = <NUM_LIT> ; public static final int TYPE_BACKGROUND_COLOR = <NUM_LIT> ; public static final int TYPE_BG_USE_SOLID = <NUM_LIT> ; public static final int TYPE_BG_GRADIENT = <NUM_LIT> ; public static final int TYPE_BG_USE_GRADIENT = <NUM_LIT> ; public static final int TYPE_AMBIENT_COLOR = <NUM_LIT> ; public static final int TYPE_FOG = <NUM_LIT> ; public static final int TYPE_USE_FOG = <NUM_LIT> ; public static final int TYPE_FOG_BGND = <NUM_LIT> ; public static final int TYPE_LAYER_FOG = <NUM_LIT> ; public static final int TYPE_USE_LAYER_FOG = <NUM_LIT> ; public static final int TYPE_NAMED_OBJECT = <NUM_LIT> ; public static final int TYPE_TRIANGLE_OBJECT = <NUM_LIT> ; public static final int TYPE_POINT_LIST = <NUM_LIT> ; public static final int TYPE_VERTEX_OPTIONS = <NUM_LIT> ; public static final int TYPE_FACE_LIST = <NUM_LIT> ; public static final int TYPE_MAT_FACE_LIST = <NUM_LIT> ; public static final int TYPE_MAT_UV = <NUM_LIT> ; public static final int TYPE_SMOOTH_GROUP = <NUM_LIT> ; public static final int TYPE_MESH_MATRIX = <NUM_LIT> ; public static final int TYPE_MESH_COLOR = <NUM_LIT> ; public static final int TYPE_DIRECT_LIGHT = <NUM_LIT> ; public static final int TYPE_SPOTLIGHT = <NUM_LIT> ; public static final int TYPE_ATTENUATION = <NUM_LIT> ; public static final int TYPE_AMBIENT_LIGHT = <NUM_LIT> ; public static final int TYPE_CAMERA = <NUM_LIT> ; public static final int TYPE_MATERIAL = <NUM_LIT> ; public static final int TYPE_MATERIAL_NAME = <NUM_LIT> ; public static final int TYPE_MAT_AMBIENT = <NUM_LIT> ; public static final int TYPE_MAT_DIFFUSE = <NUM_LIT> ; public static final int TYPE_MAT_SPECULAR = <NUM_LIT> ; public static final int TYPE_MAT_SHININESS = <NUM_LIT> ; public static final int TYPE_MAT_SHININESS2 = <NUM_LIT> ; public static final int TYPE_MAT_TRANSPARENCY = <NUM_LIT> ; public static final int TYPE_MAT_XPFALL = <NUM_LIT> ; public static final int TYPE_MAT_REFBLUR = <NUM_LIT> ; public static final int TYPE_MAT_2_SIDED = <NUM_LIT> ; public static final int TYPE_MAT_SELF_ILPCT = <NUM_LIT> ; public static final int TYPE_MAT_SHADING = <NUM_LIT> ; public static final int TYPE_MAT_TEXMAP = <NUM_LIT> ; public static final int TYPE_MAT_MAPNAME = <NUM_LIT> ; public static final int TYPE_KEY_FRAME = <NUM_LIT> ; public static final int TYPE_FRAME_INFO = <NUM_LIT> ; public static final int TYPE_FRAMES = <NUM_LIT> ; public static final int TYPE_PIVOT_POINT = <NUM_LIT> ; } </s>
<s> package net . java . joglutils . model . loader ; import java . awt . Color ; import java . io . BufferedReader ; import java . io . DataInputStream ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . util . Vector ; import net . java . joglutils . model . ModelLoadException ; import net . java . joglutils . model . ResourceRetriever ; import net . java . joglutils . model . geometry . Bounds ; import net . java . joglutils . model . geometry . Face ; import net . java . joglutils . model . geometry . Material ; import net . java . joglutils . model . geometry . Mesh ; import net . java . joglutils . model . geometry . Model ; import net . java . joglutils . model . geometry . TexCoord ; import net . java . joglutils . model . geometry . Vec4 ; public class WaveFrontLoader implements iLoader { public static final String VERTEX_DATA = "<STR_LIT>" ; public static final String NORMAL_DATA = "<STR_LIT>" ; public static final String TEXTURE_DATA = "<STR_LIT>" ; public static final String FACE_DATA = "<STR_LIT>" ; public static final String SMOOTHING_GROUP = "<STR_LIT>" ; public static final String GROUP = "<STR_LIT>" ; public static final String OBJECT = "<STR_LIT>" ; public static final String COMMENT = "<STR_LIT:#>" ; public static final String EMPTY = "<STR_LIT>" ; int vertexTotal = <NUM_LIT:0> ; int textureTotal = <NUM_LIT:0> ; int normalTotal = <NUM_LIT:0> ; private DataInputStream dataInputStream ; private Model model = null ; private Bounds bounds = new Bounds ( ) ; private Vec4 center = new Vec4 ( <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> ) ; private String baseDir = null ; public WaveFrontLoader ( ) { } int numComments = <NUM_LIT:0> ; public Model load ( String path ) throws ModelLoadException { model = new Model ( path ) ; Mesh mesh = null ; baseDir = "<STR_LIT>" ; String tokens [ ] = path . split ( "<STR_LIT:/>" ) ; for ( int i = <NUM_LIT:0> ; i < tokens . length - <NUM_LIT:1> ; i ++ ) { baseDir += tokens [ i ] + "<STR_LIT:/>" ; } InputStream stream = null ; try { stream = ResourceRetriever . getResourceAsInputStream ( model . getSource ( ) ) ; if ( stream == null ) { throw new ModelLoadException ( "<STR_LIT>" ) ; } } catch ( IOException e ) { throw new ModelLoadException ( "<STR_LIT>" + e ) ; } try { BufferedReader br = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line = null ; while ( ( line = br . readLine ( ) ) != null ) { if ( lineIs ( COMMENT , line ) ) { numComments ++ ; continue ; } if ( line . length ( ) == <NUM_LIT:0> ) { continue ; } if ( lineIs ( GROUP , line ) ) { if ( mesh == null ) { mesh = new Mesh ( ) ; } mesh . name = parseName ( line ) ; } if ( lineIs ( OBJECT , line ) ) { } if ( lineIs ( VERTEX_DATA , line ) ) { if ( mesh == null ) mesh = new Mesh ( ) ; mesh . vertices = getPoints ( VERTEX_DATA , line , br ) ; mesh . numOfVerts = mesh . vertices . length ; } if ( lineIs ( TEXTURE_DATA , line ) ) { if ( mesh == null ) mesh = new Mesh ( ) ; mesh . texCoords = getTexCoords ( TEXTURE_DATA , line , br ) ; mesh . hasTexture = true ; mesh . numTexCoords = mesh . texCoords . length ; } if ( lineIs ( NORMAL_DATA , line ) ) { if ( mesh == null ) mesh = new Mesh ( ) ; mesh . normals = getPoints ( NORMAL_DATA , line , br ) ; } if ( lineIs ( FACE_DATA , line ) ) { if ( mesh == null ) mesh = new Mesh ( ) ; mesh . faces = getFaces ( line , mesh , br ) ; mesh . numOfFaces = mesh . faces . length ; model . addMesh ( mesh ) ; mesh = new Mesh ( ) ; } if ( lineIs ( "<STR_LIT>" , line ) ) { processMaterialLib ( line ) ; } if ( lineIs ( "<STR_LIT>" , line ) ) { processMaterialType ( line , mesh ) ; } } } catch ( IOException e ) { throw new ModelLoadException ( "<STR_LIT>" + stream ) ; } model . addMesh ( mesh ) ; mesh = null ; System . out . println ( this . bounds . toString ( ) ) ; model . setBounds ( this . bounds ) ; model . setCenterPoint ( this . center ) ; return model ; } private boolean lineIs ( String type , String line ) { return line . startsWith ( type ) ; } private Vec4 [ ] getPoints ( String prefix , String currLine , BufferedReader br ) throws IOException { Vector < Vec4 > points = new Vector < Vec4 > ( ) ; boolean isVertices = prefix . equals ( VERTEX_DATA ) ; points . add ( parsePoint ( currLine ) ) ; String line = null ; while ( ( line = br . readLine ( ) ) != null ) { if ( ! lineIs ( prefix , line ) ) break ; Vec4 point = parsePoint ( line ) ; if ( isVertices ) { bounds . calc ( point ) ; } points . add ( point ) ; } if ( isVertices ) { center . x = <NUM_LIT> * ( bounds . max . x + bounds . min . x ) ; center . y = <NUM_LIT> * ( bounds . max . y + bounds . min . y ) ; center . z = <NUM_LIT> * ( bounds . max . z + bounds . min . z ) ; } Vec4 values [ ] = new Vec4 [ points . size ( ) ] ; return points . toArray ( values ) ; } private TexCoord [ ] getTexCoords ( String prefix , String currLine , BufferedReader br ) throws IOException { Vector < TexCoord > texCoords = new Vector < TexCoord > ( ) ; String s [ ] = currLine . split ( "<STR_LIT>" ) ; TexCoord texCoord = new TexCoord ( ) ; texCoord . u = Float . parseFloat ( s [ <NUM_LIT:1> ] ) ; texCoord . v = Float . parseFloat ( s [ <NUM_LIT:2> ] ) ; texCoords . add ( texCoord ) ; String line = null ; while ( ( line = br . readLine ( ) ) != null ) { if ( ! lineIs ( prefix , line ) ) break ; s = line . split ( "<STR_LIT>" ) ; texCoord = new TexCoord ( ) ; texCoord . u = Float . parseFloat ( s [ <NUM_LIT:1> ] ) ; texCoord . v = Float . parseFloat ( s [ <NUM_LIT:2> ] ) ; texCoords . add ( texCoord ) ; } TexCoord values [ ] = new TexCoord [ texCoords . size ( ) ] ; return texCoords . toArray ( values ) ; } private Face [ ] getFaces ( String currLine , Mesh mesh , BufferedReader br ) throws IOException { Vector < Face > faces = new Vector < Face > ( ) ; faces . add ( parseFace ( currLine ) ) ; String line = null ; while ( ( line = br . readLine ( ) ) != null ) { if ( lineIs ( SMOOTHING_GROUP , line ) ) { continue ; } else if ( lineIs ( "<STR_LIT>" , line ) ) { processMaterialType ( line , mesh ) ; } else if ( lineIs ( FACE_DATA , line ) ) { faces . add ( parseFace ( line ) ) ; } else break ; } Face values [ ] = new Face [ faces . size ( ) ] ; return faces . toArray ( values ) ; } private Face parseFace ( String line ) { String s [ ] = line . split ( "<STR_LIT>" ) ; if ( line . contains ( "<STR_LIT>" ) ) { for ( int loop = <NUM_LIT:1> ; loop < s . length ; loop ++ ) { s [ loop ] = s [ loop ] . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) ; } } int vdata [ ] = new int [ s . length - <NUM_LIT:1> ] ; int vtdata [ ] = new int [ s . length - <NUM_LIT:1> ] ; int vndata [ ] = new int [ s . length - <NUM_LIT:1> ] ; Face face = new Face ( s . length - <NUM_LIT:1> ) ; for ( int loop = <NUM_LIT:1> ; loop < s . length ; loop ++ ) { String s1 = s [ loop ] ; String [ ] temp = s1 . split ( "<STR_LIT:/>" ) ; if ( temp . length > <NUM_LIT:0> ) { if ( Integer . valueOf ( temp [ <NUM_LIT:0> ] ) < <NUM_LIT:0> ) { } else { face . vertIndex [ loop - <NUM_LIT:1> ] = Integer . valueOf ( temp [ <NUM_LIT:0> ] ) - <NUM_LIT:1> - this . vertexTotal ; } } if ( temp . length > <NUM_LIT:1> ) { if ( Integer . valueOf ( temp [ <NUM_LIT:1> ] ) < <NUM_LIT:0> ) { face . coordIndex [ loop - <NUM_LIT:1> ] = <NUM_LIT:0> ; } else { face . coordIndex [ loop - <NUM_LIT:1> ] = Integer . valueOf ( temp [ <NUM_LIT:1> ] ) - <NUM_LIT:1> - this . textureTotal ; } } if ( temp . length > <NUM_LIT:2> ) { face . normalIndex [ loop - <NUM_LIT:1> ] = Integer . valueOf ( temp [ <NUM_LIT:2> ] ) - <NUM_LIT:1> - this . normalTotal ; } } return face ; } private Vec4 parsePoint ( String line ) { Vec4 point = new Vec4 ( ) ; final String s [ ] = line . split ( "<STR_LIT>" ) ; point . x = Float . parseFloat ( s [ <NUM_LIT:1> ] ) ; point . y = Float . parseFloat ( s [ <NUM_LIT:2> ] ) ; point . z = Float . parseFloat ( s [ <NUM_LIT:3> ] ) ; return point ; } private String parseName ( String line ) { String name ; final String s [ ] = line . split ( "<STR_LIT>" ) ; name = s [ <NUM_LIT:1> ] ; return name ; } private void processMaterialLib ( String mtlData ) { String s [ ] = mtlData . split ( "<STR_LIT>" ) ; Material mat = new Material ( ) ; InputStream stream = null ; try { stream = ResourceRetriever . getResourceAsInputStream ( baseDir + s [ <NUM_LIT:1> ] ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } if ( stream == null ) { try { stream = new FileInputStream ( baseDir + s [ <NUM_LIT:1> ] ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; return ; } } loadMaterialFile ( stream ) ; } private void processMaterialType ( String line , Mesh mesh ) { String s [ ] = line . split ( "<STR_LIT>" ) ; int materialID = - <NUM_LIT:1> ; boolean hasTexture = false ; for ( int i = <NUM_LIT:0> ; i < model . getNumberOfMaterials ( ) ; i ++ ) { Material mat = model . getMaterial ( i ) ; if ( mat . strName . equals ( s [ <NUM_LIT:1> ] ) ) { materialID = i ; if ( mat . strFile != null ) hasTexture = true ; else hasTexture = false ; break ; } } if ( materialID != - <NUM_LIT:1> ) mesh . materialID = materialID ; } public Material loadMaterialFile ( InputStream stream ) { Material mat = null ; int texId = <NUM_LIT:0> ; try { BufferedReader br = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { String parts [ ] = line . trim ( ) . split ( "<STR_LIT>" ) ; if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) { if ( mat != null ) model . addMaterial ( mat ) ; mat = new Material ( ) ; mat . strName = parts [ <NUM_LIT:1> ] ; mat . textureId = texId ++ ; } else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) mat . specularColor = parseColor ( line ) ; else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) { if ( parts . length > <NUM_LIT:1> ) mat . shininess = Float . valueOf ( parts [ <NUM_LIT:1> ] ) ; } else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT:d>" ) ) ; else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) ; else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) mat . ambientColor = parseColor ( line ) ; else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) mat . diffuseColor = parseColor ( line ) ; else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) { if ( parts . length > <NUM_LIT:1> ) mat . strFile = parts [ <NUM_LIT:1> ] ; } else if ( parts [ <NUM_LIT:0> ] . equals ( "<STR_LIT>" ) ) { if ( parts . length > <NUM_LIT:1> ) mat . strFile = parts [ <NUM_LIT:1> ] ; } } br . close ( ) ; model . addMaterial ( mat ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } return mat ; } private Color parseColor ( String line ) { String parts [ ] = line . trim ( ) . split ( "<STR_LIT>" ) ; Color color = new Color ( Float . valueOf ( parts [ <NUM_LIT:1> ] ) , Float . valueOf ( parts [ <NUM_LIT:2> ] ) , Float . valueOf ( parts [ <NUM_LIT:3> ] ) ) ; return color ; } public static void main ( String [ ] args ) { WaveFrontLoader loader = new WaveFrontLoader ( ) ; try { loader . load ( "<STR_LIT>" ) ; } catch ( ModelLoadException ex ) { ex . printStackTrace ( ) ; } } } </s>
<s> package net . java . joglutils . model . loader ; import net . java . joglutils . model . ModelLoadException ; import net . java . joglutils . model . geometry . Model ; public interface iLoader { public Model load ( String path ) throws ModelLoadException ; } </s>
<s> package net . java . joglutils . model . loader ; import net . java . joglutils . model . ModelLoadException ; import net . java . joglutils . model . geometry . Model ; public class LoaderFactory { private static final int FILETYPE_UNKNOWN = - <NUM_LIT:1> ; private static final int FILETYPE_3DS = <NUM_LIT:1> ; private static final int FILETYPE_OBJ = <NUM_LIT:2> ; public static Model load ( String source ) throws ModelLoadException { iLoader loader = getLoader ( source ) ; if ( loader == null ) return null ; return loader . load ( source ) ; } private static iLoader getLoader ( String path ) { switch ( determineFiletype ( path ) ) { case FILETYPE_3DS : return new MaxLoader ( ) ; case FILETYPE_OBJ : return new WaveFrontLoader ( ) ; default : return null ; } } private static int determineFiletype ( String path ) { int type = FILETYPE_UNKNOWN ; String tokens [ ] = path . split ( "<STR_LIT:\\.>" ) ; if ( tokens [ tokens . length - <NUM_LIT:1> ] . equals ( "<STR_LIT>" ) ) type = FILETYPE_3DS ; else if ( tokens [ tokens . length - <NUM_LIT:1> ] . equals ( "<STR_LIT>" ) ) type = FILETYPE_OBJ ; return type ; } } </s>
<s> package net . java . joglutils . model . loader ; import java . awt . Color ; import java . io . DataInputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import net . java . joglutils . model . ResourceRetriever ; import net . java . joglutils . model . geometry . Bounds ; import net . java . joglutils . model . geometry . Face ; import net . java . joglutils . model . geometry . Material ; import net . java . joglutils . model . geometry . Mesh ; import net . java . joglutils . model . geometry . Model ; import net . java . joglutils . model . geometry . TexCoord ; import net . java . joglutils . model . geometry . Vec4 ; public class MaxLoader implements MaxConstants , iLoader { private File file ; private boolean loaded = false ; private DataInputStream dataInputStream ; private Chunk currentChunk , tempChunk ; private Bounds bounds = new Bounds ( ) ; private Vec4 center = new Vec4 ( <NUM_LIT:0.0f> , <NUM_LIT:0.0f> , <NUM_LIT:0.0f> ) ; public MaxLoader ( ) { currentChunk = new Chunk ( ) ; tempChunk = new Chunk ( ) ; } public Model load ( String source ) { Model model = new Model ( source ) ; load ( model ) ; return model ; } public boolean load ( Model model ) { try { InputStream stream = ResourceRetriever . getResourceAsInputStream ( model . getSource ( ) ) ; if ( stream == null ) { System . out . println ( "<STR_LIT>" ) ; return false ; } dataInputStream = new DataInputStream ( stream ) ; if ( dataInputStream == null ) { System . out . println ( "<STR_LIT>" ) ; return false ; } readChunkHeader ( currentChunk ) ; } catch ( IOException e ) { System . out . println ( "<STR_LIT>" + e ) ; return false ; } if ( currentChunk . id != TYPE_3DS_FILE ) { System . err . println ( "<STR_LIT>" ) ; return false ; } processNextChunk ( model , currentChunk ) ; computeNormals ( model ) ; try { dataInputStream . close ( ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return false ; } loaded = true ; model . setBounds ( this . bounds ) ; model . setCenterPoint ( this . center ) ; return loaded ; } private int readCompletely ( byte buffer [ ] , int offset , int length ) throws IOException { dataInputStream . readFully ( buffer , offset , length ) ; return length ; } void processNextChunk ( Model model , Chunk previousChunk ) { int version = <NUM_LIT:0> ; byte buffer [ ] = null ; currentChunk = new Chunk ( ) ; try { while ( previousChunk . bytesRead < previousChunk . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { case TYPE_3DS_VERSION : version = readInt ( currentChunk ) ; if ( version > <NUM_LIT> ) System . err . println ( "<STR_LIT>" ) ; break ; case TYPE_MESH_DATA : readChunkHeader ( tempChunk ) ; buffer = new byte [ tempChunk . length - tempChunk . bytesRead ] ; tempChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; currentChunk . bytesRead += tempChunk . bytesRead ; processNextChunk ( model , currentChunk ) ; break ; case TYPE_MATERIAL : Material mat = new Material ( ) ; model . addMaterial ( mat ) ; processNextMaterialChunk ( model , mat , currentChunk ) ; break ; case TYPE_NAMED_OBJECT : Mesh obj = new Mesh ( ) ; obj . name = readString ( currentChunk ) ; model . addMesh ( obj ) ; processNextObjectChunk ( model , obj , currentChunk ) ; break ; case TYPE_KEY_FRAME : processKeyFrame ( currentChunk ) ; break ; default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; break ; } previousChunk . bytesRead += currentChunk . bytesRead ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } currentChunk = previousChunk ; } private void processKeyFrame ( Chunk root ) throws IOException { currentChunk = new Chunk ( ) ; byte buffer [ ] = null ; while ( root . bytesRead < root . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; break ; } root . bytesRead += currentChunk . bytesRead ; } currentChunk = root ; } private void readChunkHeader ( Chunk chunk ) throws IOException { chunk . bytesRead = <NUM_LIT:0> ; chunk . id = this . readShort ( chunk ) ; chunk . length = this . readInt ( chunk ) ; } private void processNextObjectChunk ( Model model , Mesh object , Chunk previousChunk ) { byte buffer [ ] = null ; int bytesread ; currentChunk = new Chunk ( ) ; try { while ( previousChunk . bytesRead < previousChunk . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { case TYPE_TRIANGLE_OBJECT : processNextObjectChunk ( model , object , currentChunk ) ; break ; case TYPE_DIRECT_LIGHT : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; bytesread = readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; currentChunk . bytesRead += bytesread ; break ; case TYPE_POINT_LIST : readVertices ( object , currentChunk ) ; break ; case TYPE_FACE_LIST : readFaceList ( object , currentChunk ) ; break ; case TYPE_MAT_FACE_LIST : readObjectMaterial ( model , object , currentChunk ) ; break ; case TYPE_MAT_UV : readUVCoordinates ( object , currentChunk ) ; break ; default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; bytesread = readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; currentChunk . bytesRead += bytesread ; break ; } previousChunk . bytesRead += currentChunk . bytesRead ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } currentChunk = previousChunk ; } private void processNextMaterialChunk ( Model model , Material material , Chunk previousChunk ) { byte buffer [ ] = null ; currentChunk = new Chunk ( ) ; try { while ( previousChunk . bytesRead < previousChunk . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { case TYPE_MATERIAL_NAME : material . strName = readString ( currentChunk ) ; buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; break ; case TYPE_MAT_AMBIENT : material . ambientColor = readColor ( currentChunk ) ; break ; case TYPE_MAT_DIFFUSE : material . diffuseColor = readColor ( currentChunk ) ; break ; case TYPE_MAT_SPECULAR : material . specularColor = readColor ( currentChunk ) ; break ; case TYPE_MAT_SHININESS : material . shininess = <NUM_LIT:1.0f> + <NUM_LIT> * readPercentage ( currentChunk ) ; break ; case TYPE_MAT_SHININESS2 : material . shininess2 = <NUM_LIT:1.0f> + <NUM_LIT> * readPercentage ( currentChunk ) ; break ; case TYPE_MAT_TRANSPARENCY : material . transparency = readPercentage ( currentChunk ) ; break ; case TYPE_MAT_2_SIDED : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; break ; case TYPE_MAT_XPFALL : float xpf = readPercentage ( currentChunk ) ; break ; case TYPE_MAT_REFBLUR : float ref = readPercentage ( currentChunk ) ; break ; case TYPE_MAT_SELF_ILPCT : float il = readPercentage ( currentChunk ) ; break ; case TYPE_MAT_SHADING : int shading = readShort ( currentChunk ) ; break ; case TYPE_MAT_TEXMAP : processNextMaterialChunk ( model , material , currentChunk ) ; break ; case TYPE_MAT_MAPNAME : material . strFile = readString ( currentChunk ) ; buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; break ; default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += readCompletely ( buffer , <NUM_LIT:0> , buffer . length ) ; break ; } previousChunk . bytesRead += currentChunk . bytesRead ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } currentChunk = previousChunk ; } private void readObjectMaterial ( Model model , Mesh mesh , Chunk root ) throws IOException { String strMaterial = null ; byte buffer [ ] = null ; strMaterial = readString ( root ) ; for ( int i = <NUM_LIT:0> ; i < model . getNumberOfMaterials ( ) ; i ++ ) { if ( strMaterial . equals ( model . getMaterial ( i ) . strName ) ) { mesh . materialID = i ; Material mat = model . getMaterial ( i ) ; if ( mat . strFile != null ) mesh . hasTexture = true ; break ; } } try { int numOfFaces = this . readShort ( root ) ; for ( int i = <NUM_LIT:0> ; i < numOfFaces ; i ++ ) { int faceId = readShort ( root ) ; mesh . faces [ faceId ] . materialID = mesh . materialID ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void readUVCoordinates ( Mesh mesh , Chunk root ) throws IOException { mesh . numTexCoords = readShort ( root ) ; mesh . texCoords = new TexCoord [ mesh . numTexCoords ] ; for ( int i = <NUM_LIT:0> ; i < mesh . numTexCoords ; i ++ ) mesh . texCoords [ i ] = readPoint ( root ) ; } private void readVertices ( Mesh object , Chunk previousChunk ) { try { object . numOfVerts = readShort ( previousChunk ) ; if ( object . numOfVerts < <NUM_LIT:0> ) { throw new java . lang . RuntimeException ( "<STR_LIT>" + object . numOfVerts ) ; } object . vertices = new Vec4 [ object . numOfVerts ] ; for ( int i = <NUM_LIT:0> ; i < object . numOfVerts ; i ++ ) { object . vertices [ i ] = readVertex ( previousChunk ) ; object . bounds . calc ( object . vertices [ i ] ) ; bounds . calc ( object . vertices [ i ] ) ; } center . x = <NUM_LIT> * ( bounds . max . x + bounds . min . x ) ; center . y = <NUM_LIT> * ( bounds . max . y + bounds . min . y ) ; center . z = <NUM_LIT> * ( bounds . max . z + bounds . min . z ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void readFaceList ( Mesh object , Chunk root ) throws IOException { short index = <NUM_LIT:0> ; object . numOfFaces = readShort ( root ) ; object . faces = new Face [ object . numOfFaces ] ; for ( int i = <NUM_LIT:0> ; i < object . numOfFaces ; i ++ ) { object . faces [ i ] = new Face ( <NUM_LIT:3> ) ; object . faces [ i ] . vertIndex [ <NUM_LIT:0> ] = readShort ( root ) ; object . faces [ i ] . vertIndex [ <NUM_LIT:1> ] = readShort ( root ) ; object . faces [ i ] . vertIndex [ <NUM_LIT:2> ] = readShort ( root ) ; object . faces [ i ] . coordIndex [ <NUM_LIT:0> ] = object . faces [ i ] . vertIndex [ <NUM_LIT:0> ] ; object . faces [ i ] . coordIndex [ <NUM_LIT:1> ] = object . faces [ i ] . vertIndex [ <NUM_LIT:1> ] ; object . faces [ i ] . coordIndex [ <NUM_LIT:2> ] = object . faces [ i ] . vertIndex [ <NUM_LIT:2> ] ; readShort ( root ) ; } } protected Color readColor ( Chunk c ) throws IOException { Color color = null ; readChunkHeader ( tempChunk ) ; switch ( tempChunk . id ) { case TYPE_COLOR_F : case TYPE_COLOR_LIN_F : color = new Color ( readFloat ( c ) , readFloat ( c ) , readFloat ( c ) ) ; break ; case TYPE_COLOR_I : case TYPE_COLOR_LIN_I : color = new Color ( readUnsignedByte ( c ) , readUnsignedByte ( c ) , readUnsignedByte ( c ) ) ; } c . bytesRead += tempChunk . bytesRead ; return color ; } private void computeNormals ( Model model ) { Vec4 vVector1 = new Vec4 ( ) ; Vec4 vVector2 = new Vec4 ( ) ; Vec4 vPoly [ ] = new Vec4 [ <NUM_LIT:3> ] ; int numObjs = model . getNumberOfMeshes ( ) ; for ( int index = <NUM_LIT:0> ; index < numObjs ; index ++ ) { Mesh object = model . getMesh ( index ) ; Vec4 tempNormals [ ] = new Vec4 [ object . numOfFaces ] ; object . normals = new Vec4 [ object . numOfVerts ] ; for ( int i = <NUM_LIT:0> ; i < object . numOfFaces ; i ++ ) { vPoly [ <NUM_LIT:0> ] = new Vec4 ( object . vertices [ object . faces [ i ] . vertIndex [ <NUM_LIT:0> ] ] ) ; vPoly [ <NUM_LIT:1> ] = new Vec4 ( object . vertices [ object . faces [ i ] . vertIndex [ <NUM_LIT:1> ] ] ) ; vPoly [ <NUM_LIT:2> ] = new Vec4 ( object . vertices [ object . faces [ i ] . vertIndex [ <NUM_LIT:2> ] ] ) ; vVector1 = vPoly [ <NUM_LIT:1> ] ; vVector2 = vPoly [ <NUM_LIT:2> ] ; vVector1 . x -= vPoly [ <NUM_LIT:0> ] . x ; vVector1 . y -= vPoly [ <NUM_LIT:0> ] . y ; vVector1 . z -= vPoly [ <NUM_LIT:0> ] . z ; vVector2 . x -= vPoly [ <NUM_LIT:0> ] . x ; vVector2 . y -= vPoly [ <NUM_LIT:0> ] . y ; vVector2 . z -= vPoly [ <NUM_LIT:0> ] . z ; tempNormals [ i ] = new Vec4 ( vVector1 . y * vVector2 . z - vVector1 . z * vVector2 . y , vVector1 . z * vVector2 . x - vVector1 . x * vVector2 . z , vVector1 . x * vVector2 . y - vVector1 . y * vVector2 . x ) ; } float vSumx = <NUM_LIT:0.0f> ; float vSumy = <NUM_LIT:0.0f> ; float vSumz = <NUM_LIT:0.0f> ; int shared = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < object . numOfVerts ; i ++ ) { vSumx = <NUM_LIT:0.0f> ; vSumy = <NUM_LIT:0.0f> ; vSumz = <NUM_LIT:0.0f> ; shared = <NUM_LIT:0> ; for ( int j = <NUM_LIT:0> ; j < object . numOfFaces ; j ++ ) { if ( object . faces [ j ] . vertIndex [ <NUM_LIT:0> ] == i || object . faces [ j ] . vertIndex [ <NUM_LIT:1> ] == i || object . faces [ j ] . vertIndex [ <NUM_LIT:2> ] == i ) { object . faces [ j ] . normalIndex [ <NUM_LIT:0> ] = i ; object . faces [ j ] . normalIndex [ <NUM_LIT:1> ] = i ; object . faces [ j ] . normalIndex [ <NUM_LIT:2> ] = i ; vSumx += tempNormals [ j ] . x ; vSumy += tempNormals [ j ] . y ; vSumz += tempNormals [ j ] . z ; shared ++ ; } } vSumx /= - shared ; vSumy /= - shared ; vSumz /= - shared ; object . normals [ i ] = new Vec4 ( vSumx , vSumy , vSumz ) ; float mag = ( float ) Math . sqrt ( object . normals [ i ] . x * object . normals [ i ] . x + object . normals [ i ] . y * object . normals [ i ] . y + object . normals [ i ] . z * object . normals [ i ] . z ) ; object . normals [ i ] . x /= mag ; object . normals [ i ] . y /= mag ; object . normals [ i ] . z /= mag ; } } } protected String readString ( Chunk c ) throws IOException { DataInputStream in = dataInputStream ; StringBuffer sb = new StringBuffer ( "<STR_LIT>" ) ; c . bytesRead ++ ; byte ch = in . readByte ( ) ; while ( ch != ( byte ) <NUM_LIT:0> ) { sb . append ( ( char ) ch ) ; c . bytesRead ++ ; ch = in . readByte ( ) ; } return sb . toString ( ) ; } protected float readPercentage ( Chunk c ) throws IOException { float value = <NUM_LIT:0> ; readChunkHeader ( tempChunk ) ; if ( tempChunk . id == TYPE_PERCENT_I ) { value = ( float ) readShort ( c ) / <NUM_LIT> ; } else if ( tempChunk . id == TYPE_PERCENT_F ) { value = readFloat ( c ) ; } c . bytesRead += tempChunk . bytesRead ; return value ; } private float readFloat ( Chunk c ) throws IOException { return Float . intBitsToFloat ( readInt ( c ) ) ; } protected int readUnsignedByte ( Chunk c ) throws IOException { c . bytesRead ++ ; return dataInputStream . readUnsignedByte ( ) ; } protected int readByte ( Chunk c ) throws IOException { c . bytesRead ++ ; return dataInputStream . read ( ) & <NUM_LIT> ; } private int readInt ( Chunk c ) throws IOException { DataInputStream in = dataInputStream ; c . bytesRead += <NUM_LIT:4> ; return ( int ) ( in . read ( ) + ( in . read ( ) << <NUM_LIT:8> ) + ( in . read ( ) << <NUM_LIT:16> ) + ( in . read ( ) << <NUM_LIT:24> ) ) ; } protected int readShort ( Chunk c ) throws IOException { int b1 = readByte ( c ) ; int b2 = readByte ( c ) << <NUM_LIT:8> ; return b1 | b2 ; } private Vec4 readVertex ( Chunk c ) throws IOException { return new Vec4 ( readFloat ( c ) , readFloat ( c ) , readFloat ( c ) ) ; } private TexCoord readPoint ( Chunk c ) throws IOException { return new TexCoord ( readFloat ( c ) , readFloat ( c ) ) ; } private class Chunk { public int id = <NUM_LIT:0> ; public int length = <NUM_LIT:0> ; public int bytesRead = <NUM_LIT:0> ; } } </s>
<s> package net . java . joglutils . ThreeDS ; public class Chunk { public int id = <NUM_LIT:0> ; public int length = <NUM_LIT:0> ; public int bytesRead = <NUM_LIT:0> ; } </s>
<s> package net . java . joglutils . ThreeDS ; public class Face { public int vertIndex [ ] = new int [ <NUM_LIT:3> ] ; public int coordIndex [ ] = new int [ <NUM_LIT:3> ] ; } </s>
<s> package net . java . joglutils . ThreeDS ; public class Vec3 { public float x , y , z ; public Vec3 ( ) { } public Vec3 ( float _x , float _y , float _z ) { x = _x ; y = _y ; z = _z ; } public Vec3 ( Vec3 v ) { x = v . x ; y = v . y ; z = v . z ; } } </s>
<s> package net . java . joglutils . ThreeDS ; import java . util . Vector ; public class Model3DS { protected Loader3DS loader = new Loader3DS ( ) ; protected Vector < Material > materials = new Vector < Material > ( ) ; protected Vector < Obj > objects = new Vector < Obj > ( ) ; public Model3DS ( ) { } public boolean load ( String file ) { if ( ! loader . load ( this , file ) ) return false ; return true ; } public void addMaterial ( Material mat ) { materials . add ( mat ) ; } public void addObject ( Obj obj ) { objects . add ( obj ) ; } public Material getMaterial ( int index ) { return materials . get ( index ) ; } public Obj getObject ( int index ) { return objects . get ( index ) ; } public int getNumberOfObjects ( ) { return objects . size ( ) ; } public int getNumberOfMaterials ( ) { return materials . size ( ) ; } } </s>
<s> package net . java . joglutils . ThreeDS ; public class Material { public String strName = new String ( ) ; public String strFile = new String ( ) ; public byte color [ ] = new byte [ <NUM_LIT:3> ] ; public int texureId ; public float uTile ; public float vTile ; public float uOffset ; public float vOffset ; } </s>
<s> package net . java . joglutils . ThreeDS ; import java . io . DataInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; public class Loader3DS { private static final int PRIMARY = <NUM_LIT> ; private static final int EDITOR = <NUM_LIT> ; private static final int VERSION = <NUM_LIT> ; private static final int EDITKEYFRAME = <NUM_LIT> ; private static final int MATERIAL = <NUM_LIT> ; private static final int OBJECT = <NUM_LIT> ; private static final int MATNAME = <NUM_LIT> ; private static final int MATDIFFUSE = <NUM_LIT> ; private static final int MATMAP = <NUM_LIT> ; private static final int MATMAPFILE = <NUM_LIT> ; private static final int OBJECT_MESH = <NUM_LIT> ; private static final int OBJECT_VERTICES = <NUM_LIT> ; private static final int OBJECT_FACES = <NUM_LIT> ; private static final int OBJECT_MATERIAL = <NUM_LIT> ; private static final int OBJECT_UV = <NUM_LIT> ; private File file ; private boolean loaded = false ; private FileInputStream fileInputStream ; private DataInputStream dataInputStream ; private Chunk currentChunk , tempChunk ; public Loader3DS ( ) { currentChunk = new Chunk ( ) ; tempChunk = new Chunk ( ) ; } public boolean load ( Model3DS model , String fileName ) { String strMessage ; file = new File ( fileName ) ; try { fileInputStream = new FileInputStream ( file ) ; dataInputStream = new DataInputStream ( fileInputStream ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return false ; } readChunkHeader ( currentChunk ) ; if ( currentChunk . id != PRIMARY ) { System . err . println ( "<STR_LIT>" ) ; return false ; } processNextChunk ( model , currentChunk ) ; computeNormals ( model ) ; try { dataInputStream . close ( ) ; fileInputStream . close ( ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return false ; } loaded = true ; return loaded ; } void processNextChunk ( Model3DS model , Chunk previousChunk ) { int version = <NUM_LIT:0> ; byte buffer [ ] = null ; currentChunk = new Chunk ( ) ; try { while ( previousChunk . bytesRead < previousChunk . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { case VERSION : version = swap ( dataInputStream . readInt ( ) ) ; currentChunk . bytesRead += <NUM_LIT:4> ; if ( version > <NUM_LIT> ) System . err . println ( "<STR_LIT>" ) ; break ; case EDITOR : readChunkHeader ( tempChunk ) ; buffer = new byte [ tempChunk . length - tempChunk . bytesRead ] ; tempChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , tempChunk . length - tempChunk . bytesRead ) ; currentChunk . bytesRead += tempChunk . bytesRead ; processNextChunk ( model , currentChunk ) ; break ; case MATERIAL : Material mat = new Material ( ) ; model . addMaterial ( mat ) ; processNextMaterialChunk ( model , mat , currentChunk ) ; break ; case OBJECT : Obj obj = new Obj ( ) ; obj . strName = getString ( currentChunk ) ; model . addObject ( obj ) ; processNextObjectChunk ( model , obj , currentChunk ) ; break ; default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , currentChunk . length - currentChunk . bytesRead ) ; break ; } previousChunk . bytesRead += currentChunk . bytesRead ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } currentChunk = previousChunk ; } private void readChunkHeader ( Chunk chunk ) { byte buffer [ ] = new byte [ <NUM_LIT:2> ] ; try { chunk . id = swap ( dataInputStream . readShort ( ) ) ; chunk . id &= <NUM_LIT> ; chunk . bytesRead = <NUM_LIT:2> ; chunk . length = swap ( dataInputStream . readInt ( ) ) ; chunk . bytesRead += <NUM_LIT:4> ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void processNextObjectChunk ( Model3DS model , Obj object , Chunk previousChunk ) { byte buffer [ ] = null ; currentChunk = new Chunk ( ) ; try { while ( previousChunk . bytesRead < previousChunk . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { case OBJECT_MESH : processNextObjectChunk ( model , object , currentChunk ) ; break ; case OBJECT_VERTICES : readVertices ( object , currentChunk ) ; break ; case OBJECT_FACES : readFaceList ( object , currentChunk ) ; break ; case OBJECT_MATERIAL : readObjectMaterial ( model , object , currentChunk ) ; break ; case OBJECT_UV : readUVCoordinates ( object , currentChunk ) ; break ; default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , currentChunk . length - currentChunk . bytesRead ) ; break ; } previousChunk . bytesRead += currentChunk . bytesRead ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } currentChunk = previousChunk ; } private void processNextMaterialChunk ( Model3DS model , Material material , Chunk previousChunk ) { byte buffer [ ] = null ; currentChunk = new Chunk ( ) ; try { while ( previousChunk . bytesRead < previousChunk . length ) { readChunkHeader ( currentChunk ) ; switch ( currentChunk . id ) { case MATNAME : material . strName = getString ( currentChunk ) ; buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , currentChunk . length - currentChunk . bytesRead ) ; break ; case MATDIFFUSE : readColorChunk ( material , currentChunk ) ; break ; case MATMAP : processNextMaterialChunk ( model , material , currentChunk ) ; break ; case MATMAPFILE : material . strFile = getString ( currentChunk ) ; buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , currentChunk . length - currentChunk . bytesRead ) ; break ; default : buffer = new byte [ currentChunk . length - currentChunk . bytesRead ] ; currentChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , currentChunk . length - currentChunk . bytesRead ) ; break ; } previousChunk . bytesRead += currentChunk . bytesRead ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } currentChunk = previousChunk ; } private void readObjectMaterial ( Model3DS model , Obj object , Chunk previousChunk ) { String strMaterial = new String ( ) ; byte buffer [ ] = null ; strMaterial = getString ( previousChunk ) ; for ( int i = <NUM_LIT:0> ; i < model . getNumberOfMaterials ( ) ; i ++ ) { if ( strMaterial . equals ( model . getMaterial ( i ) . strName ) ) { object . materialID = i ; if ( model . getMaterial ( i ) . strFile . length ( ) > <NUM_LIT:0> ) object . hasTexture = true ; break ; } } try { buffer = new byte [ previousChunk . length - previousChunk . bytesRead ] ; previousChunk . bytesRead += dataInputStream . read ( buffer , <NUM_LIT:0> , previousChunk . length - previousChunk . bytesRead ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void readUVCoordinates ( Obj object , Chunk previousChunk ) { try { object . numTexVertex = swap ( dataInputStream . readShort ( ) ) ; previousChunk . bytesRead += <NUM_LIT:2> ; object . texVerts = new Vec3 [ object . numTexVertex ] ; for ( int i = <NUM_LIT:0> ; i < object . numTexVertex ; i ++ ) { object . texVerts [ i ] = new Vec3 ( swap ( dataInputStream . readFloat ( ) ) , swap ( dataInputStream . readFloat ( ) ) , <NUM_LIT:0> ) ; previousChunk . bytesRead += <NUM_LIT:8> ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void readVertices ( Obj object , Chunk previousChunk ) { try { object . numOfVerts = swap ( dataInputStream . readShort ( ) ) ; previousChunk . bytesRead += <NUM_LIT:2> ; object . verts = new Vec3 [ object . numOfVerts ] ; for ( int i = <NUM_LIT:0> ; i < object . numOfVerts ; i ++ ) { object . verts [ i ] = new Vec3 ( swap ( dataInputStream . readFloat ( ) ) , swap ( dataInputStream . readFloat ( ) ) , swap ( dataInputStream . readFloat ( ) ) ) ; previousChunk . bytesRead += <NUM_LIT:12> ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void readFaceList ( Obj object , Chunk previousChunk ) { short index = <NUM_LIT:0> ; try { object . numOfFaces = swap ( dataInputStream . readShort ( ) ) ; previousChunk . bytesRead += <NUM_LIT:2> ; object . faces = new Face [ object . numOfFaces ] ; for ( int i = <NUM_LIT:0> ; i < object . numOfFaces ; i ++ ) { object . faces [ i ] = new Face ( ) ; object . faces [ i ] . vertIndex [ <NUM_LIT:0> ] = swap ( dataInputStream . readShort ( ) ) ; object . faces [ i ] . vertIndex [ <NUM_LIT:1> ] = swap ( dataInputStream . readShort ( ) ) ; object . faces [ i ] . vertIndex [ <NUM_LIT:2> ] = swap ( dataInputStream . readShort ( ) ) ; dataInputStream . readShort ( ) ; previousChunk . bytesRead += <NUM_LIT:8> ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } } private void readColorChunk ( Material material , Chunk chunk ) { readChunkHeader ( tempChunk ) ; try { tempChunk . bytesRead += dataInputStream . read ( material . color , <NUM_LIT:0> , tempChunk . length - tempChunk . bytesRead ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return ; } chunk . bytesRead += tempChunk . bytesRead ; } private void computeNormals ( Model3DS model ) { Vec3 vVector1 = new Vec3 ( ) ; Vec3 vVector2 = new Vec3 ( ) ; Vec3 vNormal = new Vec3 ( ) ; Vec3 vPoly [ ] = new Vec3 [ <NUM_LIT:3> ] ; int numObjs = model . getNumberOfObjects ( ) ; for ( int index = <NUM_LIT:0> ; index < numObjs ; index ++ ) { Obj object = model . getObject ( index ) ; Vec3 normals [ ] = new Vec3 [ object . numOfFaces ] ; Vec3 tempNormals [ ] = new Vec3 [ object . numOfFaces ] ; object . normals = new Vec3 [ object . numOfVerts ] ; for ( int i = <NUM_LIT:0> ; i < object . numOfFaces ; i ++ ) { vPoly [ <NUM_LIT:0> ] = new Vec3 ( object . verts [ object . faces [ i ] . vertIndex [ <NUM_LIT:0> ] ] ) ; vPoly [ <NUM_LIT:1> ] = new Vec3 ( object . verts [ object . faces [ i ] . vertIndex [ <NUM_LIT:1> ] ] ) ; vPoly [ <NUM_LIT:2> ] = new Vec3 ( object . verts [ object . faces [ i ] . vertIndex [ <NUM_LIT:2> ] ] ) ; vVector1 = vPoly [ <NUM_LIT:0> ] ; vVector1 . x -= vPoly [ <NUM_LIT:2> ] . x ; vVector1 . y -= vPoly [ <NUM_LIT:2> ] . y ; vVector1 . z -= vPoly [ <NUM_LIT:2> ] . z ; vVector2 = vPoly [ <NUM_LIT:2> ] ; vVector2 . x -= vPoly [ <NUM_LIT:1> ] . x ; vVector2 . y -= vPoly [ <NUM_LIT:1> ] . y ; vVector2 . z -= vPoly [ <NUM_LIT:1> ] . z ; normals [ i ] = vVector1 ; normals [ i ] . x = normals [ i ] . y * vVector1 . z - normals [ i ] . z * vVector1 . y ; normals [ i ] . y = normals [ i ] . z * vVector1 . x - normals [ i ] . x * vVector1 . z ; normals [ i ] . z = normals [ i ] . x * vVector1 . y - normals [ i ] . y * vVector1 . x ; tempNormals [ i ] = new Vec3 ( normals [ i ] ) ; float mag = ( float ) Math . sqrt ( normals [ i ] . x * normals [ i ] . x + normals [ i ] . y * normals [ i ] . y + normals [ i ] . z * normals [ i ] . z ) ; normals [ i ] . x /= mag ; normals [ i ] . y /= mag ; normals [ i ] . z /= mag ; } Vec3 vSum = new Vec3 ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) ; Vec3 vZero = new Vec3 ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) ; int shared = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < object . numOfVerts ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < object . numOfFaces ; j ++ ) { if ( object . faces [ j ] . vertIndex [ <NUM_LIT:0> ] == i || object . faces [ j ] . vertIndex [ <NUM_LIT:1> ] == i || object . faces [ j ] . vertIndex [ <NUM_LIT:2> ] == i ) { vSum . x += tempNormals [ j ] . x ; vSum . y += tempNormals [ j ] . y ; vSum . z += tempNormals [ j ] . z ; shared ++ ; } } vSum . x /= - shared ; vSum . y /= - shared ; vSum . z /= - shared ; object . normals [ i ] = new Vec3 ( vSum ) ; float mag = ( float ) Math . sqrt ( object . normals [ i ] . x * object . normals [ i ] . x + object . normals [ i ] . y * object . normals [ i ] . y + object . normals [ i ] . z * object . normals [ i ] . z ) ; object . normals [ i ] . x /= mag ; object . normals [ i ] . y /= mag ; object . normals [ i ] . z /= mag ; vSum = vZero ; shared = <NUM_LIT:0> ; } } } private String getString ( Chunk chunk ) { int index = <NUM_LIT:0> , bytesRead = <NUM_LIT:0> ; boolean read = true ; byte buffer [ ] = new byte [ <NUM_LIT> ] ; try { while ( read ) { bytesRead += dataInputStream . read ( buffer , index , <NUM_LIT:1> ) ; if ( buffer [ index ] == <NUM_LIT:0x00> ) break ; index ++ ; } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; return "<STR_LIT>" ; } chunk . bytesRead += bytesRead ; return new String ( buffer ) . trim ( ) ; } private static short swap ( short value ) { int b1 = value & <NUM_LIT> ; int b2 = ( value > > <NUM_LIT:8> ) & <NUM_LIT> ; return ( short ) ( b1 << <NUM_LIT:8> | b2 << <NUM_LIT:0> ) ; } private static int swap ( int value ) { int b1 = ( value > > <NUM_LIT:0> ) & <NUM_LIT> ; int b2 = ( value > > <NUM_LIT:8> ) & <NUM_LIT> ; int b3 = ( value > > <NUM_LIT:16> ) & <NUM_LIT> ; int b4 = ( value > > <NUM_LIT:24> ) & <NUM_LIT> ; return b1 << <NUM_LIT:24> | b2 << <NUM_LIT:16> | b3 << <NUM_LIT:8> | b4 << <NUM_LIT:0> ; } private static long swap ( long value ) { long b1 = ( value > > <NUM_LIT:0> ) & <NUM_LIT> ; long b2 = ( value > > <NUM_LIT:8> ) & <NUM_LIT> ; long b3 = ( value > > <NUM_LIT:16> ) & <NUM_LIT> ; long b4 = ( value > > <NUM_LIT:24> ) & <NUM_LIT> ; long b5 = ( value > > <NUM_LIT:32> ) & <NUM_LIT> ; long b6 = ( value > > <NUM_LIT> ) & <NUM_LIT> ; long b7 = ( value > > <NUM_LIT> ) & <NUM_LIT> ; long b8 = ( value > > <NUM_LIT> ) & <NUM_LIT> ; return b1 << <NUM_LIT> | b2 << <NUM_LIT> | b3 << <NUM_LIT> | b4 << <NUM_LIT:32> | b5 << <NUM_LIT:24> | b6 << <NUM_LIT:16> | b7 << <NUM_LIT:8> | b8 << <NUM_LIT:0> ; } private static float swap ( float value ) { int intValue = Float . floatToIntBits ( value ) ; intValue = swap ( intValue ) ; return Float . intBitsToFloat ( intValue ) ; } private static double swap ( double value ) { long longValue = Double . doubleToLongBits ( value ) ; longValue = swap ( longValue ) ; return Double . longBitsToDouble ( longValue ) ; } } </s>
<s> package net . java . joglutils . ThreeDS ; public class Obj { public int numOfVerts = <NUM_LIT:0> ; public int numOfFaces = <NUM_LIT:0> ; public int numTexVertex = <NUM_LIT:0> ; public int materialID = <NUM_LIT:0> ; public boolean hasTexture = false ; public String strName = null ; public int indices = <NUM_LIT:0> ; public Vec3 verts [ ] = null ; public Vec3 normals [ ] = null ; public Vec3 texVerts [ ] = null ; public Face faces [ ] = null ; } </s>
<s> package net . java . joglutils ; import javax . media . opengl . * ; import javax . media . opengl . awt . * ; import javax . swing . * ; import java . awt . * ; import java . awt . event . * ; import com . sun . opengl . util . Animator ; public class GLJFrame extends JFrame { private GLEventListener listener ; private GLCapabilities caps ; private GLCapabilitiesChooser chooser ; private Animator animator ; private GLContext contextToShareWith ; public GLJFrame ( GLEventListener listener ) { this ( "<STR_LIT>" , listener ) ; } public GLJFrame ( String title , GLEventListener listener ) { super ( title ) ; this . listener = listener ; this . caps = new GLCapabilities ( GLProfile . getDefault ( ) ) ; this . chooser = null ; initComponents ( ) ; ( ( GLCanvas ) mainCanvas ) . addGLEventListener ( listener ) ; animator = null ; this . contextToShareWith = null ; } public GLJFrame ( String title , GLEventListener listener , GLCapabilities caps , GLCapabilitiesChooser chooser , GLContext contextToShareWith ) { super ( title ) ; this . listener = listener ; this . caps = caps ; this . chooser = chooser ; this . contextToShareWith = contextToShareWith ; initComponents ( ) ; ( ( GLCanvas ) mainCanvas ) . addGLEventListener ( listener ) ; animator = null ; } public GLJFrame ( String title , GLEventListener listener , GLCapabilities capabilities ) { this ( title , listener , capabilities , null , null ) ; } public GLJFrame ( String title , GLEventListener listener , GLCapabilities capabilities , GLCapabilitiesChooser chooser ) { this ( title , listener , capabilities , chooser , null ) ; } public GLJFrame ( GLEventListener listener , GLContext contextToShareWith ) { this ( listener ) ; this . contextToShareWith = contextToShareWith ; } public GLJFrame ( GLEventListener listener , GLCapabilities capabilities ) { this ( "<STR_LIT>" , listener , capabilities ) ; } public GLJFrame ( GLEventListener listener , int width , int height ) { this ( "<STR_LIT>" , listener ) ; mainCanvas . setSize ( width , height ) ; this . pack ( ) ; } public GLJFrame ( String title , GLEventListener listener , int width , int height ) { this ( title , listener ) ; mainCanvas . setSize ( width , height ) ; this . pack ( ) ; } public GLJFrame ( GLEventListener listener , boolean fullscreen ) { this ( "<STR_LIT>" , listener ) ; this . setFullscreen ( fullscreen ) ; } public GLJFrame ( String title , GLEventListener listener , boolean fullscreen ) { this ( title , listener ) ; this . setFullscreen ( fullscreen ) ; } private void initComponents ( ) { mainCanvas = new GLCanvas ( caps , chooser , contextToShareWith , null ) ; addComponentListener ( new java . awt . event . ComponentAdapter ( ) { public void componentResized ( java . awt . event . ComponentEvent evt ) { formComponentResized ( evt ) ; } } ) ; mainCanvas . setSize ( <NUM_LIT> , <NUM_LIT> ) ; getContentPane ( ) . add ( mainCanvas , java . awt . BorderLayout . CENTER ) ; pack ( ) ; } private void formComponentResized ( java . awt . event . ComponentEvent evt ) { this . mainCanvas . setSize ( this . getRootPane ( ) . getSize ( ) ) ; } private java . awt . Canvas mainCanvas ; public void setGLEventListener ( GLEventListener listener ) { ( ( GLCanvas ) this . mainCanvas ) . removeGLEventListener ( this . listener ) ; this . listener = listener ; ( ( GLCanvas ) this . mainCanvas ) . addGLEventListener ( listener ) ; } public GLEventListener getGLEventListener ( ) { return this . listener ; } public boolean setFullscreen ( boolean fs ) { GraphicsDevice dev = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) . getDefaultScreenDevice ( ) ; boolean visible = this . isVisible ( ) ; if ( fs ) { this . dispose ( ) ; this . setUndecorated ( true ) ; this . setResizable ( false ) ; try { dev . setFullScreenWindow ( this ) ; } catch ( Exception e ) { dev . setFullScreenWindow ( null ) ; e . printStackTrace ( ) ; JOptionPane . showMessageDialog ( this , "<STR_LIT>" , "<STR_LIT>" , JOptionPane . ERROR_MESSAGE ) ; } this . setVisible ( visible ) ; } else { this . dispose ( ) ; this . setUndecorated ( false ) ; this . setResizable ( true ) ; dev . setFullScreenWindow ( null ) ; this . setVisible ( visible ) ; } return dev . isFullScreenSupported ( ) ; } public void setSize ( int width , int height ) { java . awt . GraphicsDevice dev = java . awt . GraphicsEnvironment . getLocalGraphicsEnvironment ( ) . getDefaultScreenDevice ( ) ; if ( dev . getFullScreenWindow ( ) != this ) { mainCanvas . setSize ( width , height ) ; this . pack ( ) ; mainCanvas . repaint ( ) ; } } public void setSize ( java . awt . Dimension d ) { java . awt . GraphicsDevice dev = java . awt . GraphicsEnvironment . getLocalGraphicsEnvironment ( ) . getDefaultScreenDevice ( ) ; if ( dev . getFullScreenWindow ( ) != this ) { mainCanvas . setSize ( d ) ; this . pack ( ) ; } } public boolean isFullscreen ( ) { java . awt . GraphicsDevice dev = java . awt . GraphicsEnvironment . getLocalGraphicsEnvironment ( ) . getDefaultScreenDevice ( ) ; return ( dev . getFullScreenWindow ( ) == this ) ; } public GLCapabilities getGLCapabilities ( ) { return ( GLCapabilities ) this . caps . clone ( ) ; } public void setGLCapabilities ( GLCapabilities caps ) { boolean vis = this . isVisible ( ) ; this . caps = ( GLCapabilities ) caps . clone ( ) ; boolean fs = this . isFullscreen ( ) ; java . awt . Dimension d = this . mainCanvas . getSize ( ) ; this . dispose ( ) ; this . mainCanvas = new GLCanvas ( caps ) ; this . getContentPane ( ) . removeAll ( ) ; this . add ( mainCanvas ) ; mainCanvas . setSize ( d ) ; GLCanvas glc = ( GLCanvas ) mainCanvas ; glc . addGLEventListener ( listener ) ; for ( InputMethodListener l : this . getInputMethodListeners ( ) ) glc . addInputMethodListener ( l ) ; for ( KeyListener l : this . getKeyListeners ( ) ) glc . addKeyListener ( l ) ; for ( MouseListener l : this . getMouseListeners ( ) ) glc . addMouseListener ( l ) ; for ( MouseMotionListener l : this . getMouseMotionListeners ( ) ) glc . addMouseMotionListener ( l ) ; for ( MouseWheelListener l : this . getMouseWheelListeners ( ) ) glc . addMouseWheelListener ( l ) ; this . setFullscreen ( fs ) ; this . setVisible ( vis ) ; } public void repaint ( ) { super . repaint ( ) ; if ( this . animator == null ) ( ( GLCanvas ) this . mainCanvas ) . display ( ) ; else if ( ! this . animator . isAnimating ( ) ) ( ( GLCanvas ) this . mainCanvas ) . display ( ) ; } public void clearInputListeners ( ) { InputMethodListener [ ] imls = super . getInputMethodListeners ( ) ; KeyListener [ ] kls = super . getKeyListeners ( ) ; MouseListener [ ] mls = super . getMouseListeners ( ) ; MouseMotionListener [ ] mmls = super . getMouseMotionListeners ( ) ; MouseWheelListener [ ] mwls = super . getMouseWheelListeners ( ) ; for ( InputMethodListener l : imls ) { mainCanvas . removeInputMethodListener ( l ) ; super . removeInputMethodListener ( l ) ; } for ( KeyListener l : kls ) { mainCanvas . removeKeyListener ( l ) ; super . removeKeyListener ( l ) ; } for ( MouseListener l : mls ) { mainCanvas . removeMouseListener ( l ) ; super . removeMouseListener ( l ) ; } for ( MouseMotionListener l : mmls ) { mainCanvas . removeMouseMotionListener ( l ) ; super . removeMouseMotionListener ( l ) ; } for ( MouseWheelListener l : mwls ) { mainCanvas . removeMouseWheelListener ( l ) ; super . removeMouseWheelListener ( l ) ; } } public Animator generateAnimator ( ) { if ( this . animator != null ) { this . animator . stop ( ) ; this . animator . remove ( ( GLCanvas ) mainCanvas ) ; } this . animator = new Animator ( ( GLCanvas ) mainCanvas ) ; this . animator . start ( ) ; return this . animator ; } public Animator getAnimator ( ) { return this . animator ; } public void setAnimator ( Animator anim ) { this . setAnimator ( anim , true ) ; } public void setAnimator ( Animator anim , boolean start ) { if ( this . animator != null ) { this . animator . stop ( ) ; this . animator . remove ( ( GLCanvas ) mainCanvas ) ; } this . animator = anim ; this . animator . add ( ( GLCanvas ) mainCanvas ) ; if ( start ) this . animator . start ( ) ; } public void removeAnimator ( ) { this . animator . stop ( ) ; this . animator . remove ( ( GLCanvas ) mainCanvas ) ; this . animator = null ; } public boolean isAnimated ( ) { return ( animator != null ) ; } public void removeKeyListener ( KeyListener l ) { super . removeKeyListener ( l ) ; mainCanvas . removeKeyListener ( l ) ; } public void addKeyListener ( KeyListener l ) { super . addKeyListener ( l ) ; mainCanvas . addKeyListener ( l ) ; } public void removeMouseListener ( MouseListener l ) { super . removeMouseListener ( l ) ; mainCanvas . removeMouseListener ( l ) ; } public void addMouseListener ( MouseListener l ) { super . addMouseListener ( l ) ; mainCanvas . addMouseListener ( l ) ; } public void removeMouseWheelListener ( MouseWheelListener l ) { super . removeMouseWheelListener ( l ) ; mainCanvas . removeMouseWheelListener ( l ) ; } public void removeMouseMotionListener ( MouseMotionListener l ) { super . removeMouseMotionListener ( l ) ; mainCanvas . removeMouseMotionListener ( l ) ; } public void addMouseWheelListener ( MouseWheelListener l ) { super . addMouseWheelListener ( l ) ; mainCanvas . addMouseWheelListener ( l ) ; } public void addMouseMotionListener ( MouseMotionListener l ) { super . addMouseMotionListener ( l ) ; mainCanvas . addMouseMotionListener ( l ) ; } public void removeInputMethodListener ( java . awt . event . InputMethodListener l ) { super . removeInputMethodListener ( l ) ; mainCanvas . removeInputMethodListener ( l ) ; } public void addInputMethodListener ( java . awt . event . InputMethodListener l ) { super . addInputMethodListener ( l ) ; mainCanvas . addInputMethodListener ( l ) ; } public GL getGL ( ) { return ( ( GLCanvas ) mainCanvas ) . getGL ( ) ; } public void setGL ( GL gl ) { ( ( GLCanvas ) mainCanvas ) . setGL ( gl ) ; } public GLContext getContext ( ) { return ( ( GLCanvas ) mainCanvas ) . getContext ( ) ; } public GLAutoDrawable getAutoDrawable ( ) { return ( GLAutoDrawable ) mainCanvas ; } } </s>
<s> package net . java . joglutils . msg . actions ; import java . lang . reflect . * ; import net . java . joglutils . msg . misc . * ; import net . java . joglutils . msg . nodes . * ; public class GLResetAction extends Action { private static State defaults = new State ( ) ; public static State getDefaultState ( ) { return defaults ; } private static ActionTable table = new ActionTable ( GLResetAction . class ) ; public static void addActionMethod ( Class < ? extends Node > nodeType , Method m ) { table . addActionMethod ( nodeType , m ) ; } private State state = new State ( defaults ) ; public State getState ( ) { return state ; } static { try { addActionMethod ( Texture2 . class , GLResetAction . class . getMethod ( "<STR_LIT>" , GLResetAction . class , Texture2 . class ) ) ; addActionMethod ( ShaderNode . class , GLResetAction . class . getMethod ( "<STR_LIT>" , GLResetAction . class , ShaderNode . class ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "<STR_LIT>" , e ) ; } } public void apply ( Node node ) { apply ( table , node ) ; } public static void resetGL ( GLResetAction action , Texture2 node ) { node . resetGL ( action ) ; } public static void resetGL ( GLResetAction action , ShaderNode node ) { node . resetGL ( action ) ; } } </s>
<s> package net . java . joglutils . msg . actions ; import java . lang . reflect . * ; import javax . media . opengl . * ; import javax . media . opengl . glu . * ; import net . java . joglutils . msg . misc . * ; import net . java . joglutils . msg . nodes . * ; public class GLRenderAction extends Action { private static State defaults = new State ( ) ; public static State getDefaultState ( ) { return defaults ; } private static ActionTable table = new ActionTable ( GLRenderAction . class ) ; public static void addActionMethod ( Class < ? extends Node > nodeType , Method m ) { table . addActionMethod ( nodeType , m ) ; } private State state = new State ( defaults ) ; public State getState ( ) { return state ; } static { try { addActionMethod ( Node . class , GLRenderAction . class . getMethod ( "<STR_LIT>" , GLRenderAction . class , Node . class ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "<STR_LIT>" , e ) ; } } private float curAspectRatio = <NUM_LIT:1.0f> ; private int applyDepth = <NUM_LIT:0> ; private GL2 gl ; public void apply ( Node node ) { int depth = applyDepth ++ ; try { if ( depth == <NUM_LIT:0> ) { gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; gl . glPushAttrib ( GL2 . GL_ENABLE_BIT | GL2 . GL_CURRENT_BIT | GL2 . GL_DEPTH_BUFFER_BIT | GL2 . GL_TRANSFORM_BIT ) ; gl . glDisable ( GL2 . GL_LIGHTING ) ; gl . glEnable ( GL2 . GL_DEPTH_TEST ) ; gl . glColor4f ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) ; gl . glMatrixMode ( GL2 . GL_TEXTURE ) ; gl . glLoadIdentity ( ) ; gl . glMatrixMode ( GL2 . GL_MODELVIEW ) ; gl . glLoadIdentity ( ) ; gl . glPushClientAttrib ( GL2 . GL_CLIENT_VERTEX_ARRAY_BIT ) ; gl . glDisableClientState ( GL2 . GL_VERTEX_ARRAY ) ; gl . glDisableClientState ( GL2 . GL_TEXTURE_COORD_ARRAY ) ; int [ ] viewport = new int [ <NUM_LIT:4> ] ; gl . glGetIntegerv ( GL2 . GL_VIEWPORT , viewport , <NUM_LIT:0> ) ; curAspectRatio = ( float ) viewport [ <NUM_LIT:2> ] / ( float ) viewport [ <NUM_LIT:3> ] ; } apply ( table , node ) ; } finally { if ( depth == <NUM_LIT:0> ) { gl . glPopClientAttrib ( ) ; gl . glPopAttrib ( ) ; gl = null ; } -- applyDepth ; } } public GL2 getGL ( ) { return gl ; } public float getCurAspectRatio ( ) { return curAspectRatio ; } public static void render ( GLRenderAction action , Node node ) { node . render ( action ) ; } } </s>
<s> package net . java . joglutils . msg . actions ; import java . awt . Component ; import java . lang . reflect . * ; import java . util . * ; import net . java . joglutils . msg . math . * ; import net . java . joglutils . msg . misc . * ; import net . java . joglutils . msg . nodes . * ; public class RayPickAction extends Action { private static State defaults = new State ( ) ; public static State getDefaultState ( ) { return defaults ; } private static ActionTable table = new ActionTable ( RayPickAction . class ) ; public static void addActionMethod ( Class < ? extends Node > nodeType , Method m ) { table . addActionMethod ( nodeType , m ) ; } private State state = new State ( defaults ) ; public State getState ( ) { return state ; } static { try { addActionMethod ( Node . class , RayPickAction . class . getMethod ( "<STR_LIT>" , RayPickAction . class , Node . class ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "<STR_LIT>" , e ) ; } } private int applyDepth = <NUM_LIT:0> ; private Vec2f normalizedPoint ; private Line ray ; private Line computedRay ; static class RayPickedPoint implements Comparable < RayPickedPoint > { float t ; PickedPoint point ; RayPickedPoint ( float t , PickedPoint point ) { this . t = t ; this . point = point ; } public boolean equals ( Object o ) { return ( o == this ) ; } public int compareTo ( RayPickedPoint p ) { return ( int ) Math . signum ( t - p . t ) ; } } private List < RayPickedPoint > tempPickedPoints = new ArrayList < RayPickedPoint > ( ) ; private List < PickedPoint > pickedPoints = new ArrayList < PickedPoint > ( ) ; public void apply ( Node node ) { int depth = applyDepth ++ ; try { if ( depth == <NUM_LIT:0> ) { reset ( ) ; } apply ( table , node ) ; } finally { -- applyDepth ; if ( depth == <NUM_LIT:0> ) { tabulate ( ) ; } } } public void setPoint ( int x , int y , Component component ) { setNormalizedPoint ( new Vec2f ( ( float ) x / ( float ) component . getWidth ( ) , <NUM_LIT:1.0f> - ( ( float ) y / ( float ) component . getHeight ( ) ) ) ) ; } public void setNormalizedPoint ( Vec2f normalizedPoint ) { this . normalizedPoint = normalizedPoint ; ray = null ; computedRay = null ; } public void setRay ( Line ray ) { this . ray = ray ; computedRay = ray ; normalizedPoint = null ; } public List < PickedPoint > getPickedPoints ( ) { return pickedPoints ; } public PickedPoint getPickedPoint ( ) { List < PickedPoint > pickedPoints = getPickedPoints ( ) ; if ( pickedPoints == null || pickedPoints . isEmpty ( ) ) return null ; return pickedPoints . get ( <NUM_LIT:0> ) ; } public Line getComputedRay ( ) { return computedRay ; } public void recomputeRay ( Camera camera ) { if ( normalizedPoint != null && ray == null ) { if ( computedRay == null ) { computedRay = new Line ( ) ; } camera . unproject ( normalizedPoint , computedRay ) ; } } public void addPickedPoint ( PickedPoint p , float t ) { tempPickedPoints . add ( new RayPickedPoint ( t , p ) ) ; } private void reset ( ) { tempPickedPoints . clear ( ) ; pickedPoints . clear ( ) ; } private void tabulate ( ) { Collections . sort ( tempPickedPoints ) ; for ( RayPickedPoint p : tempPickedPoints ) { pickedPoints . add ( p . point ) ; } } public static void rayPick ( RayPickAction action , Node node ) { node . rayPick ( action ) ; } } </s>
<s> package net . java . joglutils . msg . actions ; import java . lang . reflect . * ; import net . java . joglutils . msg . misc . * ; import net . java . joglutils . msg . nodes . * ; public abstract class Action { public abstract void apply ( Node node ) ; public abstract State getState ( ) ; public Path getPath ( ) { return path ; } private Object [ ] argTmp = new Object [ <NUM_LIT:2> ] ; protected void apply ( ActionTable table , Node node ) { try { Method m = table . lookupActionMethod ( node ) ; if ( m != null ) { argTmp [ <NUM_LIT:0> ] = this ; argTmp [ <NUM_LIT:1> ] = node ; push ( node ) ; try { m . invoke ( null , argTmp ) ; } finally { pop ( ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } private Path path = new Path ( ) ; private void push ( Node node ) { path . add ( node ) ; } private void pop ( ) { path . remove ( path . size ( ) - <NUM_LIT:1> ) ; } } </s>
<s> package net . java . joglutils . msg . misc ; import net . java . joglutils . msg . math . * ; public class PrimitiveVertex implements Cloneable { private Vec3f coord ; private Vec2f texCoord ; private Vec4f color ; private Vec3f normal ; public PrimitiveVertex ( ) { } public Object clone ( ) { try { PrimitiveVertex vtx = ( PrimitiveVertex ) super . clone ( ) ; if ( coord != null ) { vtx . setCoord ( new Vec3f ( coord ) ) ; } if ( texCoord != null ) { vtx . setTexCoord ( new Vec2f ( texCoord ) ) ; } if ( color != null ) { vtx . setColor ( new Vec4f ( color ) ) ; } if ( normal != null ) { vtx . setNormal ( new Vec3f ( normal ) ) ; } return vtx ; } catch ( CloneNotSupportedException e ) { throw new RuntimeException ( e ) ; } } public PrimitiveVertex copy ( ) { return ( PrimitiveVertex ) clone ( ) ; } public void setCoord ( Vec3f coord ) { this . coord = coord ; } public Vec3f getCoord ( ) { return coord ; } public void setTexCoord ( Vec2f texCoord ) { this . texCoord = texCoord ; } public Vec2f getTexCoord ( ) { return texCoord ; } public void setColor ( Vec4f color ) { this . color = color ; } public Vec4f getColor ( ) { return color ; } public void setNormal ( Vec3f normal ) { this . normal = normal ; } public Vec3f getNormal ( ) { return normal ; } } </s>
<s> package net . java . joglutils . msg . misc ; import java . lang . reflect . * ; import java . util . * ; import net . java . joglutils . msg . actions . * ; import net . java . joglutils . msg . nodes . * ; public class ActionTable { private Class < ? extends Action > actionClass ; private Map < Class < ? extends Node > , Method > methodMap = new HashMap < Class < ? extends Node > , Method > ( ) ; public ActionTable ( Class < ? extends Action > actionClass ) { this . actionClass = actionClass ; } public void addActionMethod ( Class < ? extends Node > nodeType , Method actionMethod ) throws IllegalArgumentException { if ( ! Modifier . isPublic ( actionMethod . getModifiers ( ) ) ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } if ( ! Modifier . isStatic ( actionMethod . getModifiers ( ) ) ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } Class < ? > [ ] argTypes = actionMethod . getParameterTypes ( ) ; if ( argTypes . length != <NUM_LIT:2> ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } if ( ! argTypes [ <NUM_LIT:0> ] . isAssignableFrom ( actionClass ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + actionClass + "<STR_LIT>" ) ; } if ( ! argTypes [ <NUM_LIT:1> ] . isAssignableFrom ( nodeType ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + nodeType + "<STR_LIT>" ) ; } methodMap . put ( nodeType , actionMethod ) ; } public Method lookupActionMethod ( Node node ) { Class < ? extends Node > nodeType = node . getClass ( ) ; Class < ? extends Node > curType = nodeType ; do { Method m = methodMap . get ( curType ) ; if ( m != null ) { if ( curType != nodeType ) { methodMap . put ( curType , m ) ; } return m ; } Class < ? > nextType = curType . getSuperclass ( ) ; if ( Node . class . isAssignableFrom ( nextType ) ) { curType = ( Class < ? extends Node > ) nextType ; } else { curType = null ; } } while ( curType != null ) ; return null ; } } </s>
<s> package net . java . joglutils . msg . misc ; import java . util . * ; import net . java . joglutils . msg . nodes . * ; public class Path extends ArrayList < Node > { public Path copy ( ) { return ( Path ) clone ( ) ; } } </s>
<s> package net . java . joglutils . msg . misc ; public interface Time { public void update ( ) ; public double time ( ) ; public double deltaT ( ) ; } </s>
<s> package net . java . joglutils . msg . misc ; public class StateIndex { private int index ; StateIndex ( int index ) { this . index = index ; } int getIndex ( ) { return index ; } } </s>
<s> package net . java . joglutils . msg . misc ; import javax . media . opengl . * ; import javax . media . opengl . glu . GLU ; import static javax . media . opengl . GL2 . * ; public class Shader { private int id ; public Shader ( String fragmentCode ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; id = createProgram ( gl , null , fragmentCode ) ; } public Shader ( String vertexCode , String fragmentCode ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; id = createProgram ( gl , vertexCode , fragmentCode ) ; } private static int createProgram ( GL2 gl , String vertexShaderSource , String fragmentShaderSource ) throws GLException { if ( vertexShaderSource == null && fragmentShaderSource == null ) { throw new GLException ( "<STR_LIT>" + "<STR_LIT>" ) ; } int shaderProgram ; int vertexShader = <NUM_LIT:0> ; int fragmentShader = <NUM_LIT:0> ; int [ ] success = new int [ <NUM_LIT:1> ] ; int [ ] infoLogLength = new int [ <NUM_LIT:1> ] ; if ( vertexShaderSource != null ) { vertexShader = compileShader ( gl , vertexShaderSource , true ) ; if ( vertexShader == <NUM_LIT:0> ) { return <NUM_LIT:0> ; } } if ( fragmentShaderSource != null ) { fragmentShader = compileShader ( gl , fragmentShaderSource , false ) ; if ( fragmentShader == <NUM_LIT:0> ) { if ( vertexShader != <NUM_LIT:0> ) { gl . glDeleteObjectARB ( vertexShader ) ; } return <NUM_LIT:0> ; } } shaderProgram = gl . glCreateProgramObjectARB ( ) ; if ( vertexShader != <NUM_LIT:0> ) { gl . glAttachObjectARB ( shaderProgram , vertexShader ) ; gl . glDeleteObjectARB ( vertexShader ) ; } if ( fragmentShader != <NUM_LIT:0> ) { gl . glAttachObjectARB ( shaderProgram , fragmentShader ) ; gl . glDeleteObjectARB ( fragmentShader ) ; } gl . glLinkProgramARB ( shaderProgram ) ; gl . glGetObjectParameterivARB ( shaderProgram , GL_OBJECT_LINK_STATUS_ARB , success , <NUM_LIT:0> ) ; gl . glGetObjectParameterivARB ( shaderProgram , GL_OBJECT_INFO_LOG_LENGTH_ARB , infoLogLength , <NUM_LIT:0> ) ; if ( infoLogLength [ <NUM_LIT:0> ] > <NUM_LIT:1> ) { byte [ ] infoLog = new byte [ <NUM_LIT> ] ; gl . glGetInfoLogARB ( shaderProgram , <NUM_LIT> , null , <NUM_LIT:0> , infoLog , <NUM_LIT:0> ) ; System . err . println ( "<STR_LIT>" + new String ( infoLog ) ) ; } if ( success [ <NUM_LIT:0> ] == <NUM_LIT:0> ) { gl . glDeleteObjectARB ( shaderProgram ) ; return <NUM_LIT:0> ; } return shaderProgram ; } private static int compileShader ( GL2 gl , String shaderSource , boolean vertex ) throws GLException { int kind = vertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER ; int shader ; int [ ] success = new int [ <NUM_LIT:1> ] ; int [ ] infoLogLength = new int [ <NUM_LIT:1> ] ; shader = gl . glCreateShaderObjectARB ( kind ) ; gl . glShaderSourceARB ( shader , <NUM_LIT:1> , new String [ ] { shaderSource } , null , <NUM_LIT:0> ) ; gl . glCompileShaderARB ( shader ) ; gl . glGetObjectParameterivARB ( shader , GL_OBJECT_COMPILE_STATUS_ARB , success , <NUM_LIT:0> ) ; gl . glGetObjectParameterivARB ( shader , GL_OBJECT_INFO_LOG_LENGTH_ARB , infoLogLength , <NUM_LIT:0> ) ; if ( infoLogLength [ <NUM_LIT:0> ] > <NUM_LIT:1> ) { byte [ ] infoLog = new byte [ <NUM_LIT> ] ; gl . glGetInfoLogARB ( shader , <NUM_LIT> , null , <NUM_LIT:0> , infoLog , <NUM_LIT:0> ) ; System . err . println ( ( vertex ? "<STR_LIT>" : "<STR_LIT>" ) + "<STR_LIT>" + new String ( infoLog ) ) ; } if ( success [ <NUM_LIT:0> ] == <NUM_LIT:0> ) { gl . glDeleteObjectARB ( shader ) ; return <NUM_LIT:0> ; } return shader ; } public int getProgramObject ( ) { return id ; } public void enable ( ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; gl . glUseProgramObjectARB ( id ) ; } public void disable ( ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; gl . glUseProgramObjectARB ( <NUM_LIT:0> ) ; } public void dispose ( ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; gl . glDeleteObjectARB ( id ) ; id = <NUM_LIT:0> ; } public void setUniform ( String name , int i0 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform1iARB ( loc , i0 ) ; } public void setUniform ( String name , int i0 , int i1 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform2iARB ( loc , i0 , i1 ) ; } public void setUniform ( String name , int i0 , int i1 , int i2 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform3iARB ( loc , i0 , i1 , i2 ) ; } public void setUniform ( String name , int i0 , int i1 , int i2 , int i3 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform4iARB ( loc , i0 , i1 , i2 , i3 ) ; } public void setUniform ( String name , float f0 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform1fARB ( loc , f0 ) ; } public void setUniform ( String name , float f0 , float f1 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform2fARB ( loc , f0 , f1 ) ; } public void setUniform ( String name , float f0 , float f1 , float f2 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform3fARB ( loc , f0 , f1 , f2 ) ; } public void setUniform ( String name , float f0 , float f1 , float f2 , float f3 ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform4fARB ( loc , f0 , f1 , f2 , f3 ) ; } public void setUniformArray1i ( String name , int count , int [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform1ivARB ( loc , count , vals , off ) ; } public void setUniformArray2i ( String name , int count , int [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform2ivARB ( loc , count , vals , off ) ; } public void setUniformArray3i ( String name , int count , int [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform3ivARB ( loc , count , vals , off ) ; } public void setUniformArray4i ( String name , int count , int [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform4ivARB ( loc , count , vals , off ) ; } public void setUniformArray1f ( String name , int count , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform1fvARB ( loc , count , vals , off ) ; } public void setUniformArray2f ( String name , int count , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform2fvARB ( loc , count , vals , off ) ; } public void setUniformArray3f ( String name , int count , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform3fvARB ( loc , count , vals , off ) ; } public void setUniformArray4f ( String name , int count , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniform4fvARB ( loc , count , vals , off ) ; } public void setUniformMatrices2f ( String name , int count , boolean transpose , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniformMatrix2fvARB ( loc , count , transpose , vals , off ) ; } public void setUniformMatrices3f ( String name , int count , boolean transpose , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniformMatrix3fvARB ( loc , count , transpose , vals , off ) ; } public void setUniformMatrices4f ( String name , int count , boolean transpose , float [ ] vals , int off ) throws GLException { GL2 gl = GLU . getCurrentGL ( ) . getGL2 ( ) ; int loc = gl . glGetUniformLocationARB ( id , name ) ; gl . glUniformMatrix4fvARB ( loc , count , transpose , vals , off ) ; } } </s>
<s> package net . java . joglutils . msg . misc ; import java . util . * ; import net . java . joglutils . msg . elements . * ; public class State { private static int curStateIndex = <NUM_LIT:0> ; private List < Element > elements = new ArrayList < Element > ( ) ; private State defaults ; private Element topElement ; private int depth ; public State ( ) { } public State ( State defaults ) { this . defaults = defaults ; push ( ) ; } public State getDefaults ( ) { if ( defaults != null ) return defaults ; return this ; } public Element getElement ( StateIndex index ) { assert depth >= ( ( topElement == null ) ? <NUM_LIT:0> : topElement . getDepth ( ) ) : "<STR_LIT>" + elements . get ( index . getIndex ( ) ) . getClass ( ) . getName ( ) + "<STR_LIT>" ; int idx = index . getIndex ( ) ; if ( defaults == null ) { if ( idx >= elements . size ( ) ) { return null ; } return elements . get ( idx ) ; } if ( idx >= elements . size ( ) ) { while ( idx >= elements . size ( ) ) { elements . add ( null ) ; } } Element elt = elements . get ( idx ) ; if ( elt == null ) { elt = defaults . getElement ( index ) ; if ( elt == null ) { throw new RuntimeException ( "<STR_LIT>" + idx ) ; } elt = elt . newInstance ( ) ; elt . setDepth ( <NUM_LIT:0> ) ; elements . set ( idx , elt ) ; } if ( elt . getDepth ( ) < depth ) { Element newElt = elt . newInstance ( ) ; newElt . setNextInStack ( elt ) ; newElt . setDepth ( depth ) ; newElt . setNext ( topElement ) ; topElement = newElt ; elements . set ( idx , newElt ) ; newElt . push ( this ) ; elt = newElt ; } return elt ; } public void setElement ( StateIndex index , Element element ) { if ( defaults != null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } int idx = index . getIndex ( ) ; if ( idx >= elements . size ( ) ) { while ( idx >= elements . size ( ) ) { elements . add ( null ) ; } } elements . set ( idx , element ) ; } public void push ( ) { ++ depth ; } public void pop ( ) { -- depth ; Element poppedElt = null ; Element nextInStack = null ; for ( poppedElt = topElement ; poppedElt != null && poppedElt . getDepth ( ) > depth ; poppedElt = poppedElt . getNext ( ) ) { nextInStack = poppedElt . getNextInStack ( ) ; poppedElt . getNextInStack ( ) . pop ( this , poppedElt ) ; } while ( topElement != null && topElement . getDepth ( ) > depth ) { poppedElt = topElement ; topElement = topElement . getNext ( ) ; elements . set ( poppedElt . getStateIndex ( ) . getIndex ( ) , poppedElt . getNextInStack ( ) ) ; } } public static synchronized StateIndex registerElementType ( ) { return new StateIndex ( curStateIndex ++ ) ; } } </s>
<s> package net . java . joglutils . msg . misc ; public class PickedPoint extends PrimitiveVertex { private Path path ; public Object clone ( ) { PickedPoint point = ( PickedPoint ) super . clone ( ) ; if ( path != null ) { point . path = path . copy ( ) ; } return point ; } public PickedPoint copy ( ) { return ( PickedPoint ) clone ( ) ; } public void setPath ( Path path ) { this . path = path ; } public Path getPath ( ) { return path ; } } </s>
<s> package net . java . joglutils . msg . misc ; public class SystemTime implements Time { private static final int DEFAULT_NUM_SMOOTHING_SAMPLES = <NUM_LIT:10> ; private long [ ] samples = new long [ DEFAULT_NUM_SMOOTHING_SAMPLES ] ; private int numSmoothingSamples ; private int curSmoothingSample ; private long baseTime = System . currentTimeMillis ( ) ; private boolean hasCurTime ; private double curTime ; private double deltaT ; public void setNumSmoothingSamples ( int num ) { samples = new long [ num ] ; numSmoothingSamples = <NUM_LIT:0> ; curSmoothingSample = <NUM_LIT:0> ; hasCurTime = false ; } public int getNumSmoothingSamples ( ) { return samples . length ; } public void rebase ( ) { baseTime = System . currentTimeMillis ( ) ; setNumSmoothingSamples ( samples . length ) ; } public void update ( ) { long tmpTime = System . currentTimeMillis ( ) ; long diffSinceBase = tmpTime - baseTime ; samples [ curSmoothingSample ] = diffSinceBase ; curSmoothingSample = ( curSmoothingSample + <NUM_LIT:1> ) % samples . length ; numSmoothingSamples = Math . min ( <NUM_LIT:1> + numSmoothingSamples , samples . length ) ; double newCurTime = <NUM_LIT:0.0> ; for ( int i = <NUM_LIT:0> ; i < numSmoothingSamples ; i ++ ) { newCurTime += samples [ i ] ; } newCurTime /= ( <NUM_LIT> * numSmoothingSamples ) ; double lastTime = curTime ; if ( ! hasCurTime ) { lastTime = newCurTime ; hasCurTime = true ; } deltaT = newCurTime - lastTime ; curTime = newCurTime ; } public double time ( ) { return curTime ; } public double deltaT ( ) { return deltaT ; } } </s>
<s> package net . java . joglutils . msg . misc ; public interface TriangleCallback { public void triangleCB ( int triangleIndex , PrimitiveVertex v0 , int i0 , PrimitiveVertex v1 , int i1 , PrimitiveVertex v2 , int i2 ) ; } </s>
<s> package net . java . joglutils . msg . math ; public class NonSquareMatrixException extends RuntimeException { public NonSquareMatrixException ( ) { super ( ) ; } public NonSquareMatrixException ( String msg ) { super ( msg ) ; } } </s>
<s> package net . java . joglutils . msg . math ; public class Rotf { private static float EPSILON = <NUM_LIT> ; private float q0 ; private float q1 ; private float q2 ; private float q3 ; public Rotf ( ) { init ( ) ; } public Rotf ( Rotf arg ) { set ( arg ) ; } public Rotf ( Vec3f axis , float angle ) { set ( axis , angle ) ; } public Rotf ( Vec3f from , Vec3f to ) { set ( from , to ) ; } public void init ( ) { q0 = <NUM_LIT:1> ; q1 = q2 = q3 = <NUM_LIT:0> ; } public boolean withinEpsilon ( Rotf arg , float epsilon ) { return ( ( Math . abs ( q0 - arg . q0 ) < epsilon ) && ( Math . abs ( q1 - arg . q1 ) < epsilon ) && ( Math . abs ( q2 - arg . q2 ) < epsilon ) && ( Math . abs ( q3 - arg . q3 ) < epsilon ) ) ; } public void set ( Vec3f axis , float angle ) { float halfTheta = angle / <NUM_LIT> ; q0 = ( float ) Math . cos ( halfTheta ) ; float sinHalfTheta = ( float ) Math . sin ( halfTheta ) ; Vec3f realAxis = new Vec3f ( axis ) ; realAxis . normalize ( ) ; q1 = realAxis . x ( ) * sinHalfTheta ; q2 = realAxis . y ( ) * sinHalfTheta ; q3 = realAxis . z ( ) * sinHalfTheta ; } public void set ( Rotf arg ) { q0 = arg . q0 ; q1 = arg . q1 ; q2 = arg . q2 ; q3 = arg . q3 ; } public void set ( Vec3f from , Vec3f to ) { Vec3f axis = from . cross ( to ) ; if ( axis . lengthSquared ( ) < EPSILON ) { init ( ) ; return ; } float dotp = from . dot ( to ) ; float denom = from . length ( ) * to . length ( ) ; if ( denom < EPSILON ) { init ( ) ; return ; } dotp /= denom ; set ( axis , ( float ) Math . acos ( dotp ) ) ; } public float get ( Vec3f axis ) { float retval = ( float ) ( <NUM_LIT> * Math . acos ( q0 ) ) ; axis . set ( q1 , q2 , q3 ) ; float len = axis . length ( ) ; if ( len == <NUM_LIT:0.0f> ) { axis . set ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1> ) ; } else { axis . scale ( <NUM_LIT:1.0f> / len ) ; } return retval ; } public Rotf inverse ( ) { Rotf tmp = new Rotf ( this ) ; tmp . invert ( ) ; return tmp ; } public void invert ( ) { q1 = - q1 ; q2 = - q2 ; q3 = - q3 ; } public float length ( ) { return ( float ) Math . sqrt ( lengthSquared ( ) ) ; } public float lengthSquared ( ) { return ( q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3 ) ; } public void normalize ( ) { float len = length ( ) ; q0 /= len ; q1 /= len ; q2 /= len ; q3 /= len ; } public Rotf times ( Rotf b ) { Rotf tmp = new Rotf ( ) ; tmp . mul ( this , b ) ; return tmp ; } public void mul ( Rotf a , Rotf b ) { q0 = ( a . q0 * b . q0 - a . q1 * b . q1 - a . q2 * b . q2 - a . q3 * b . q3 ) ; q1 = ( a . q0 * b . q1 + a . q1 * b . q0 + a . q2 * b . q3 - a . q3 * b . q2 ) ; q2 = ( a . q0 * b . q2 + a . q2 * b . q0 - a . q1 * b . q3 + a . q3 * b . q1 ) ; q3 = ( a . q0 * b . q3 + a . q3 * b . q0 + a . q1 * b . q2 - a . q2 * b . q1 ) ; } public void toMatrix ( Mat4f mat ) { float q00 = q0 * q0 ; float q11 = q1 * q1 ; float q22 = q2 * q2 ; float q33 = q3 * q3 ; mat . set ( <NUM_LIT:0> , <NUM_LIT:0> , q00 + q11 - q22 - q33 ) ; mat . set ( <NUM_LIT:1> , <NUM_LIT:1> , q00 - q11 + q22 - q33 ) ; mat . set ( <NUM_LIT:2> , <NUM_LIT:2> , q00 - q11 - q22 + q33 ) ; float q03 = q0 * q3 ; float q12 = q1 * q2 ; mat . set ( <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT> * ( q12 - q03 ) ) ; mat . set ( <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT> * ( q03 + q12 ) ) ; float q02 = q0 * q2 ; float q13 = q1 * q3 ; mat . set ( <NUM_LIT:0> , <NUM_LIT:2> , <NUM_LIT> * ( q02 + q13 ) ) ; mat . set ( <NUM_LIT:2> , <NUM_LIT:0> , <NUM_LIT> * ( q13 - q02 ) ) ; float q01 = q0 * q1 ; float q23 = q2 * q3 ; mat . set ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT> * ( q23 - q01 ) ) ; mat . set ( <NUM_LIT:2> , <NUM_LIT:1> , <NUM_LIT> * ( q01 + q23 ) ) ; } public void fromMatrix ( Mat4f mat ) { float tr , s ; int i , j , k ; tr = mat . get ( <NUM_LIT:0> , <NUM_LIT:0> ) + mat . get ( <NUM_LIT:1> , <NUM_LIT:1> ) + mat . get ( <NUM_LIT:2> , <NUM_LIT:2> ) ; if ( tr > <NUM_LIT:0.0> ) { s = ( float ) Math . sqrt ( tr + <NUM_LIT:1.0f> ) ; q0 = s * <NUM_LIT> ; s = <NUM_LIT> / s ; q1 = ( mat . get ( <NUM_LIT:2> , <NUM_LIT:1> ) - mat . get ( <NUM_LIT:1> , <NUM_LIT:2> ) ) * s ; q2 = ( mat . get ( <NUM_LIT:0> , <NUM_LIT:2> ) - mat . get ( <NUM_LIT:2> , <NUM_LIT:0> ) ) * s ; q3 = ( mat . get ( <NUM_LIT:1> , <NUM_LIT:0> ) - mat . get ( <NUM_LIT:0> , <NUM_LIT:1> ) ) * s ; } else { i = <NUM_LIT:0> ; if ( mat . get ( <NUM_LIT:1> , <NUM_LIT:1> ) > mat . get ( <NUM_LIT:0> , <NUM_LIT:0> ) ) i = <NUM_LIT:1> ; if ( mat . get ( <NUM_LIT:2> , <NUM_LIT:2> ) > mat . get ( i , i ) ) i = <NUM_LIT:2> ; j = ( i + <NUM_LIT:1> ) % <NUM_LIT:3> ; k = ( j + <NUM_LIT:1> ) % <NUM_LIT:3> ; s = ( float ) Math . sqrt ( ( mat . get ( i , i ) - ( mat . get ( j , j ) + mat . get ( k , k ) ) ) + <NUM_LIT:1.0f> ) ; setQ ( i + <NUM_LIT:1> , s * <NUM_LIT> ) ; s = <NUM_LIT> / s ; q0 = ( mat . get ( k , j ) - mat . get ( j , k ) ) * s ; setQ ( j + <NUM_LIT:1> , ( mat . get ( j , i ) + mat . get ( i , j ) ) * s ) ; setQ ( k + <NUM_LIT:1> , ( mat . get ( k , i ) + mat . get ( i , k ) ) * s ) ; } } public void rotateVector ( Vec3f src , Vec3f dest ) { Vec3f qVec = new Vec3f ( q1 , q2 , q3 ) ; Vec3f qCrossX = qVec . cross ( src ) ; Vec3f qCrossXCrossQ = qCrossX . cross ( qVec ) ; qCrossX . scale ( <NUM_LIT> * q0 ) ; qCrossXCrossQ . scale ( - <NUM_LIT> ) ; dest . add ( src , qCrossX ) ; dest . add ( dest , qCrossXCrossQ ) ; } public Vec3f rotateVector ( Vec3f src ) { Vec3f tmp = new Vec3f ( ) ; rotateVector ( src , tmp ) ; return tmp ; } public String toString ( ) { return "<STR_LIT:(>" + q0 + "<STR_LIT:U+002CU+0020>" + q1 + "<STR_LIT:U+002CU+0020>" + q2 + "<STR_LIT:U+002CU+0020>" + q3 + "<STR_LIT:)>" ; } private void setQ ( int i , float val ) { switch ( i ) { case <NUM_LIT:0> : q0 = val ; break ; case <NUM_LIT:1> : q1 = val ; break ; case <NUM_LIT:2> : q2 = val ; break ; case <NUM_LIT:3> : q3 = val ; break ; default : throw new IndexOutOfBoundsException ( ) ; } } } </s>
<s> package net . java . joglutils . msg . math ; public class Mat2f { private float [ ] data ; public Mat2f ( ) { data = new float [ <NUM_LIT:4> ] ; } public void makeIdent ( ) { for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:2> ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < <NUM_LIT:2> ; j ++ ) { if ( i == j ) { set ( i , j , <NUM_LIT:1.0f> ) ; } else { set ( i , j , <NUM_LIT:0.0f> ) ; } } } } public float get ( int i , int j ) { return data [ <NUM_LIT:2> * i + j ] ; } public void set ( int i , int j , float val ) { data [ <NUM_LIT:2> * i + j ] = val ; } public void setCol ( int i , Vec2f v ) { set ( <NUM_LIT:0> , i , v . x ( ) ) ; set ( <NUM_LIT:1> , i , v . y ( ) ) ; } public void setRow ( int i , Vec2f v ) { set ( i , <NUM_LIT:0> , v . x ( ) ) ; set ( i , <NUM_LIT:1> , v . y ( ) ) ; } public void transpose ( ) { float t = get ( <NUM_LIT:0> , <NUM_LIT:1> ) ; set ( <NUM_LIT:0> , <NUM_LIT:1> , get ( <NUM_LIT:1> , <NUM_LIT:0> ) ) ; set ( <NUM_LIT:1> , <NUM_LIT:0> , t ) ; } public float determinant ( ) { return ( get ( <NUM_LIT:0> , <NUM_LIT:0> ) * get ( <NUM_LIT:1> , <NUM_LIT:1> ) - get ( <NUM_LIT:1> , <NUM_LIT:0> ) * get ( <NUM_LIT:0> , <NUM_LIT:1> ) ) ; } public boolean invert ( ) { float det = determinant ( ) ; if ( det == <NUM_LIT:0.0f> ) return false ; float t = get ( <NUM_LIT:0> , <NUM_LIT:0> ) ; set ( <NUM_LIT:0> , <NUM_LIT:0> , get ( <NUM_LIT:1> , <NUM_LIT:1> ) ) ; set ( <NUM_LIT:1> , <NUM_LIT:1> , t ) ; set ( <NUM_LIT:0> , <NUM_LIT:1> , - get ( <NUM_LIT:0> , <NUM_LIT:1> ) ) ; set ( <NUM_LIT:1> , <NUM_LIT:0> , - get ( <NUM_LIT:1> , <NUM_LIT:0> ) ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:4> ; i ++ ) { data [ i ] /= det ; } return true ; } public void xformVec ( Vec2f src , Vec2f dest ) { dest . set ( get ( <NUM_LIT:0> , <NUM_LIT:0> ) * src . x ( ) + get ( <NUM_LIT:0> , <NUM_LIT:1> ) * src . y ( ) , get ( <NUM_LIT:1> , <NUM_LIT:0> ) * src . x ( ) + get ( <NUM_LIT:1> , <NUM_LIT:1> ) * src . y ( ) ) ; } public Mat2f mul ( Mat2f b ) { Mat2f tmp = new Mat2f ( ) ; tmp . mul ( this , b ) ; return tmp ; } public void mul ( Mat2f a , Mat2f b ) { for ( int rc = <NUM_LIT:0> ; rc < <NUM_LIT:2> ; rc ++ ) for ( int cc = <NUM_LIT:0> ; cc < <NUM_LIT:2> ; cc ++ ) { float tmp = <NUM_LIT:0.0f> ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:2> ; i ++ ) tmp += a . get ( rc , i ) * b . get ( i , cc ) ; set ( rc , cc , tmp ) ; } } public Matf toMatf ( ) { Matf out = new Matf ( <NUM_LIT:2> , <NUM_LIT:2> ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:2> ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < <NUM_LIT:2> ; j ++ ) { out . set ( i , j , get ( i , j ) ) ; } } return out ; } public String toString ( ) { String endl = System . getProperty ( "<STR_LIT>" ) ; return "<STR_LIT:(>" + get ( <NUM_LIT:0> , <NUM_LIT:0> ) + "<STR_LIT:U+002CU+0020>" + get ( <NUM_LIT:0> , <NUM_LIT:1> ) + endl + get ( <NUM_LIT:1> , <NUM_LIT:0> ) + "<STR_LIT:U+002CU+0020>" + get ( <NUM_LIT:1> , <NUM_LIT:1> ) + "<STR_LIT:)>" ; } } </s>
<s> package net . java . joglutils . msg . math ; public class SingularMatrixException extends RuntimeException { public SingularMatrixException ( ) { super ( ) ; } public SingularMatrixException ( String msg ) { super ( msg ) ; } } </s>
<s> package net . java . joglutils . msg . math ; public class Vecf { private float [ ] data ; public Vecf ( int n ) { data = new float [ n ] ; } public Vecf ( Vecf arg ) { data = new float [ arg . data . length ] ; System . arraycopy ( arg . data , <NUM_LIT:0> , data , <NUM_LIT:0> , data . length ) ; } public int length ( ) { return data . length ; } public float get ( int i ) { return data [ i ] ; } public void set ( int i , float val ) { data [ i ] = val ; } public Vec2f toVec2f ( ) throws DimensionMismatchException { if ( length ( ) != <NUM_LIT:2> ) throw new DimensionMismatchException ( ) ; Vec2f out = new Vec2f ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:2> ; i ++ ) { out . set ( i , get ( i ) ) ; } return out ; } public Vec3f toVec3f ( ) throws DimensionMismatchException { if ( length ( ) != <NUM_LIT:3> ) throw new DimensionMismatchException ( ) ; Vec3f out = new Vec3f ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:3> ; i ++ ) { out . set ( i , get ( i ) ) ; } return out ; } public Veci toInt ( ) { Veci out = new Veci ( length ( ) ) ; for ( int i = <NUM_LIT:0> ; i < length ( ) ; i ++ ) { out . set ( i , ( int ) get ( i ) ) ; } return out ; } } </s>
<s> package net . java . joglutils . msg . math ; public class Box3f { private Vec3f min = new Vec3f ( ) ; private Vec3f max = new Vec3f ( ) ; public Box3f ( ) { } public Box3f ( Vec3f min , Vec3f max ) { setMin ( min ) ; setMax ( max ) ; } public void setMin ( Vec3f min ) { this . min . set ( min ) ; } public Vec3f getMin ( ) { return min ; } public void setMax ( Vec3f max ) { this . max . set ( max ) ; } public Vec3f getMax ( ) { return max ; } public Vec3f getCenter ( ) { return new Vec3f ( <NUM_LIT> * ( min . x ( ) + max . x ( ) ) , <NUM_LIT> * ( min . y ( ) + max . y ( ) ) , <NUM_LIT> * ( min . z ( ) + max . z ( ) ) ) ; } public void extendBy ( Vec3f point ) { if ( point . x ( ) < min . x ( ) ) min . setX ( point . x ( ) ) ; if ( point . y ( ) < min . y ( ) ) min . setY ( point . y ( ) ) ; if ( point . z ( ) < min . z ( ) ) min . setZ ( point . z ( ) ) ; if ( point . x ( ) > max . x ( ) ) max . setX ( point . x ( ) ) ; if ( point . y ( ) > max . y ( ) ) max . setY ( point . y ( ) ) ; if ( point . z ( ) > max . z ( ) ) max . setZ ( point . z ( ) ) ; } public void extendBy ( Box3f box ) { if ( box . min . x ( ) < min . x ( ) ) min . setX ( box . min . x ( ) ) ; if ( box . min . y ( ) < min . y ( ) ) min . setY ( box . min . y ( ) ) ; if ( box . min . z ( ) < min . z ( ) ) min . setZ ( box . min . z ( ) ) ; if ( box . max . x ( ) > max . x ( ) ) max . setX ( box . max . x ( ) ) ; if ( box . max . y ( ) > max . y ( ) ) max . setY ( box . max . y ( ) ) ; if ( box . max . z ( ) > max . z ( ) ) max . setZ ( box . max . z ( ) ) ; } } </s>
<s> package net . java . joglutils . msg . math ; public class Vec3d { private double x ; private double y ; private double z ; public Vec3d ( ) { } public Vec3d ( Vec3d arg ) { set ( arg ) ; } public Vec3d ( double x , double y , double z ) { set ( x , y , z ) ; } public Vec3d copy ( ) { return new Vec3d ( this ) ; } public Vec3f toFloat ( ) { return new Vec3f ( ( float ) x , ( float ) y , ( float ) z ) ; } public void set ( Vec3d arg ) { set ( arg . x , arg . y , arg . z ) ; } public void set ( double x , double y , double z ) { this . x = x ; this . y = y ; this . z = z ; } public void set ( int i , double val ) { switch ( i ) { case <NUM_LIT:0> : x = val ; break ; case <NUM_LIT:1> : y = val ; break ; case <NUM_LIT:2> : z = val ; break ; default : throw new IndexOutOfBoundsException ( ) ; } } public double get ( int i ) { switch ( i ) { case <NUM_LIT:0> : return x ; case <NUM_LIT:1> : return y ; case <NUM_LIT:2> : return z ; default : throw new IndexOutOfBoundsException ( ) ; } } public double x ( ) { return x ; } public double y ( ) { return y ; } public double z ( ) { return z ; } public void setX ( double x ) { this . x = x ; } public void setY ( double y ) { this . y = y ; } public void setZ ( double z ) { this . z = z ; } public double dot ( Vec3d arg ) { return x * arg . x + y * arg . y + z * arg . z ; } public double length ( ) { return Math . sqrt ( lengthSquared ( ) ) ; } public double lengthSquared ( ) { return this . dot ( this ) ; } public void normalize ( ) { double len = length ( ) ; if ( len == <NUM_LIT:0.0> ) return ; scale ( <NUM_LIT:1.0f> / len ) ; } public Vec3d times ( double val ) { Vec3d tmp = new Vec3d ( this ) ; tmp . scale ( val ) ; return tmp ; } public void scale ( double val ) { x *= val ; y *= val ; z *= val ; } public Vec3d plus ( Vec3d arg ) { Vec3d tmp = new Vec3d ( ) ; tmp . add ( this , arg ) ; return tmp ; } public void add ( Vec3d b ) { add ( this , b ) ; } public void add ( Vec3d a , Vec3d b ) { x = a . x + b . x ; y = a . y + b . y ; z = a . z + b . z ; } public Vec3d addScaled ( double s , Vec3d arg ) { Vec3d tmp = new Vec3d ( ) ; tmp . addScaled ( this , s , arg ) ; return tmp ; } public void addScaled ( Vec3d a , double s , Vec3d b ) { x = a . x + s * b . x ; y = a . y + s * b . y ; z = a . z + s * b . z ; } public Vec3d minus ( Vec3d arg ) { Vec3d tmp = new Vec3d ( ) ; tmp . sub ( this , arg ) ; return tmp ; } public void sub ( Vec3d b ) { sub ( this , b ) ; } public void sub ( Vec3d a , Vec3d b ) { x = a . x - b . x ; y = a . y - b . y ; z = a . z - b . z ; } public Vec3d cross ( Vec3d arg ) { Vec3d tmp = new Vec3d ( ) ; tmp . cross ( this , arg ) ; return tmp ; } public void cross ( Vec3d a , Vec3d b ) { x = a . y * b . z - a . z * b . y ; y = a . z * b . x - a . x * b . z ; z = a . x * b . y - a . y * b . x ; } public String toString ( ) { return "<STR_LIT:(>" + x + "<STR_LIT:U+002CU+0020>" + y + "<STR_LIT:U+002CU+0020>" + z + "<STR_LIT:)>" ; } } </s>
<s> package net . java . joglutils . msg . math ; public class Vec4f { private float x ; private float y ; private float z ; private float w ; public Vec4f ( ) { } public Vec4f ( Vec4f arg ) { set ( arg ) ; } public Vec4f ( float x , float y , float z , float w ) { set ( x , y , z , w ) ; } public Vec4f copy ( ) { return new Vec4f ( this ) ; } public void set ( Vec4f arg ) { set ( arg . x , arg . y , arg . z , arg . w ) ; } public void set ( float x , float y , float z , float w ) { this . x = x ; this . y = y ; this . z = z ; this . w = w ; } public void set ( int i , float val ) { switch ( i ) { case <NUM_LIT:0> : x = val ; break ; case <NUM_LIT:1> : y = val ; break ; case <NUM_LIT:2> : z = val ; break ; case <NUM_LIT:3> : w = val ; break ; default : throw new IndexOutOfBoundsException ( ) ; } } public float get ( int i ) { switch ( i ) { case <NUM_LIT:0> : return x ; case <NUM_LIT:1> : return y ; case <NUM_LIT:2> : return z ; case <NUM_LIT:3> : return w ; default : throw new IndexOutOfBoundsException ( ) ; } } public float x ( ) { return x ; } public float y ( ) { return y ; } public float z ( ) { return z ; } public float w ( ) { return w ; } public void setX ( float x ) { this . x = x ; } public void setY ( float y ) { this . y = y ; } public void setZ ( float z ) { this . z = z ; } public void setW ( float w ) { this . w = w ; } public float dot ( Vec4f arg ) { return x * arg . x + y * arg . y + z * arg . z + w * arg . w ; } public float length ( ) { return ( float ) Math . sqrt ( lengthSquared ( ) ) ; } public float lengthSquared ( ) { return this . dot ( this ) ; } public void normalize ( ) { float len = length ( ) ; if ( len == <NUM_LIT:0.0f> ) return ; scale ( <NUM_LIT:1.0f> / len ) ; } public Vec4f times ( float val ) { Vec4f tmp = new Vec4f ( this ) ; tmp . scale ( val ) ; return tmp ; } public void scale ( float val ) { x *= val ; y *= val ; z *= val ; w *= val ; } public Vec4f plus ( Vec4f arg ) { Vec4f tmp = new Vec4f ( ) ; tmp . add ( this , arg ) ; return tmp ; } public void add ( Vec4f b ) { add ( this , b ) ; } public void add ( Vec4f a , Vec4f b ) { x = a . x + b . x ; y = a . y + b . y ; z = a . z + b . z ; w = a . w + b . w ; } public Vec4f addScaled ( float s , Vec4f arg ) { Vec4f tmp = new Vec4f ( ) ; tmp . addScaled ( this , s , arg ) ; return tmp ; } public void addScaled ( Vec4f a , float s , Vec4f b ) { x = a . x + s * b . x ; y = a . y + s * b . y ; z = a . z + s * b . z ; w = a . w + s * b . w ; } public Vec4f minus ( Vec4f arg ) { Vec4f tmp = new Vec4f ( ) ; tmp . sub ( this , arg ) ; return tmp ; } public void sub ( Vec4f b ) { sub ( this , b ) ; } public void sub ( Vec4f a , Vec4f b ) { x = a . x - b . x ; y = a . y - b . y ; z = a . z - b . z ; w = a . w - b . w ; } public void componentMul ( Vec4f arg ) { x *= arg . x ; y *= arg . y ; z *= arg . z ; w *= arg . w ; } public Vecf toVecf ( ) { Vecf out = new Vecf ( <NUM_LIT:4> ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:4> ; i ++ ) { out . set ( i , get ( i ) ) ; } return out ; } public String toString ( ) { return "<STR_LIT:(>" + x + "<STR_LIT:U+002CU+0020>" + y + "<STR_LIT:U+002CU+0020>" + z + "<STR_LIT:U+002CU+0020>" + w + "<STR_LIT:)>" ; } } </s>
<s> package net . java . joglutils . msg . math ; public class Plane { private Vec3f normal ; private Vec3f point ; float c ; public Plane ( ) { normal = new Vec3f ( <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:0> ) ; point = new Vec3f ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> ) ; recalc ( ) ; } public Plane ( Vec3f normal , Vec3f point ) { this . normal = new Vec3f ( normal ) ; this . normal . normalize ( ) ; this . point = new Vec3f ( point ) ; recalc ( ) ; } public void setNormal ( Vec3f normal ) { this . normal . set ( normal ) ; this . normal . normalize ( ) ; recalc ( ) ; } public Vec3f getNormal ( ) { return normal ; } public void setPoint ( Vec3f point ) { this . point . set ( point ) ; recalc ( ) ; } public Vec3f getPoint ( ) { return point ; } public void projectPoint ( Vec3f pt , Vec3f projPt ) { float scale = normal . dot ( pt ) - c ; projPt . set ( pt . minus ( normal . times ( normal . dot ( point ) - c ) ) ) ; } public boolean intersectRay ( Vec3f rayStart , Vec3f rayDirection , IntersectionPoint intPt ) { float denom = normal . dot ( rayDirection ) ; if ( denom == <NUM_LIT:0> ) return false ; intPt . setT ( ( c - normal . dot ( rayStart ) ) / denom ) ; intPt . setIntersectionPoint ( rayStart . plus ( rayDirection . times ( intPt . getT ( ) ) ) ) ; return true ; } private void recalc ( ) { c = normal . dot ( point ) ; } } </s>
<s> package net . java . joglutils . msg . math ; public class IntersectionPoint { private Vec3f intPt = new Vec3f ( ) ; private float t ; public Vec3f getIntersectionPoint ( ) { return intPt ; } public void setIntersectionPoint ( Vec3f newPt ) { intPt . set ( newPt ) ; } public float getT ( ) { return t ; } public void setT ( float t ) { this . t = t ; } } </s>