idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
30,400
private NameSpace getNonBlockParent ( ) { NameSpace parent = super . getParent ( ) ; if ( parent instanceof BlockNameSpace ) return ( ( BlockNameSpace ) parent ) . getNonBlockParent ( ) ; else return parent ; }
do we need this?
30,401
public Object eval ( CallStack callstack , Interpreter interpreter ) throws EvalError { if ( jjtGetNumChildren ( ) > 0 ) type = ( ( BSHType ) jjtGetChild ( 0 ) ) . getType ( callstack , interpreter ) ; else type = UNTYPED ; if ( isVarArgs ) type = Array . newInstance ( type , 0 ) . getClass ( ) ; return type ; }
Evaluate the type .
30,402
public EvalError toEvalError ( String msg , SimpleNode node , CallStack callstack ) { if ( Interpreter . DEBUG . get ( ) ) printStackTrace ( ) ; if ( msg == null ) msg = "" ; else msg += ": " ; return new EvalError ( msg + this . getMessage ( ) , node , callstack , this ) ; }
Re - throw as an eval error prefixing msg to the message and specifying the node . If a node already exists the addNode is ignored .
30,403
public static String typeString ( Object value ) { return null == value || Primitive . NULL == value ? "null" : value instanceof Primitive ? ( ( Primitive ) value ) . getType ( ) . getSimpleName ( ) : typeString ( value . getClass ( ) ) ; }
Type from value to string .
30,404
public static String typeString ( Class < ? > clas ) { if ( Map . class . isAssignableFrom ( clas ) ) clas = Map . class ; else if ( List . class . isAssignableFrom ( clas ) ) if ( Queue . class . isAssignableFrom ( clas ) ) clas = Queue . class ; else clas = List . class ; else if ( Deque . class . isAssignableFrom ( clas ) ) clas = Deque . class ; else if ( Set . class . isAssignableFrom ( clas ) ) clas = Set . class ; else if ( Entry . class . isAssignableFrom ( clas ) ) clas = Entry . class ; return clas . isArray ( ) ? typeString ( clas . getComponentType ( ) ) + "[]" : clas . getName ( ) . startsWith ( "java" ) ? clas . getSimpleName ( ) : clas . getName ( ) ; }
Type from class to string .
30,405
public static String typeValueString ( final Object value ) { StringBuilder sb = new StringBuilder ( valueString ( value ) ) ; return sb . append ( " :" ) . append ( typeString ( value ) ) . toString ( ) ; }
Generate string of value and type .
30,406
private Object doProperty ( boolean toLHS , Object obj , CallStack callstack , Interpreter interpreter ) throws EvalError { if ( obj == Primitive . VOID ) throw new EvalError ( "Attempt to access property on undefined variable or class name" , this , callstack ) ; if ( obj instanceof Primitive ) throw new EvalError ( "Attempt to access property on a primitive" , this , callstack ) ; Object value = ( ( SimpleNode ) jjtGetChild ( 0 ) ) . eval ( callstack , interpreter ) ; if ( ! ( value instanceof String ) ) throw new EvalError ( "Property expression must be a String or identifier." , this , callstack ) ; if ( toLHS ) return new LHS ( obj , ( String ) value ) ; try { Object val = Reflect . getObjectProperty ( obj , ( String ) value ) ; return null == val ? Primitive . NULL : Primitive . unwrap ( val ) ; } catch ( ReflectError e ) { throw new EvalError ( "No such property: " + value , this , callstack , e ) ; } }
Property access . Must handle toLHS case .
30,407
private synchronized void writeObject ( final ObjectOutputStream s ) throws IOException { if ( null != field ) { this . object = field . getDeclaringClass ( ) ; this . varName = field . getName ( ) ; this . field = null ; } s . defaultWriteObject ( ) ; }
Reflect Field is not serializable hide it .
30,408
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; if ( null == this . object ) return ; Class < ? > cls = this . object . getClass ( ) ; if ( this . object instanceof Class ) cls = ( Class < ? > ) this . object ; this . field = BshClassManager . memberCache . get ( cls ) . findField ( varName ) ; }
Fetch field removed from serializer .
30,409
public static Object getIndex ( Object array , int index ) throws UtilTargetError { Interpreter . debug ( "getIndex: " , array , ", index=" , index ) ; try { if ( array instanceof List ) return ( ( List < ? > ) array ) . get ( index ) ; Object val = Array . get ( array , index ) ; return Primitive . wrap ( val , Types . arrayElementType ( array . getClass ( ) ) ) ; } catch ( IndexOutOfBoundsException e1 ) { int len = array instanceof List ? ( ( List < ? > ) array ) . size ( ) : Array . getLength ( array ) ; throw new UtilTargetError ( "Index " + index + " out-of-bounds for length " + len , e1 ) ; } }
Get object from array or list at index .
30,410
@ SuppressWarnings ( "unchecked" ) public static void setIndex ( Object array , int index , Object val ) throws ReflectError , UtilTargetError { try { val = Primitive . unwrap ( val ) ; if ( array instanceof List ) ( ( List < Object > ) array ) . set ( index , val ) ; else Array . set ( array , index , val ) ; } catch ( IllegalArgumentException e1 ) { throw new UtilTargetError ( new ArrayStoreException ( e1 . getMessage ( ) ) ) ; } catch ( IndexOutOfBoundsException e1 ) { int len = array instanceof List ? ( ( List < ? > ) array ) . size ( ) : Array . getLength ( array ) ; throw new UtilTargetError ( "Index " + index + " out-of-bounds for length " + len , e1 ) ; } }
Set element value of array or list at index . Array . set for array or List . set for list .
30,411
public static Object slice ( List < Object > list , int from , int to , int step ) { int length = list . size ( ) ; if ( to > length ) to = length ; if ( 0 > from ) from = 0 ; length = to - from ; if ( 0 >= length ) return list . subList ( 0 , 0 ) ; if ( step == 0 || step == 1 ) return list . subList ( from , to ) ; List < Integer > slices = new ArrayList < > ( ) ; for ( int i = 0 ; i < length ; i ++ ) if ( i % step == 0 ) slices . add ( step < 0 ? length - 1 - i : i + from ) ; return new SteppedSubList ( list , slices ) ; }
Slice the supplied list for range and step .
30,412
public static Object slice ( Object arr , int from , int to , int step ) { Class < ? > toType = Types . arrayElementType ( arr . getClass ( ) ) ; int length = Array . getLength ( arr ) ; if ( to > length ) to = length ; if ( 0 > from ) from = 0 ; length = to - from ; if ( 0 >= length ) return Array . newInstance ( toType , 0 ) ; if ( step == 0 || step == 1 ) { Object toArray = Array . newInstance ( toType , length ) ; System . arraycopy ( arr , from , toArray , 0 , length ) ; return toArray ; } Object [ ] tmp = new Object [ ( int ) Math . ceil ( ( 0.0 + length ) / Math . abs ( step ) ) ] ; for ( int i = 0 , j = 0 ; i < length ; i ++ ) if ( i % step == 0 ) tmp [ j ++ ] = Array . get ( arr , step < 0 ? length - 1 - i : i + from ) ; Object toArray = Array . newInstance ( toType , tmp . length ) ; copy ( toType , toArray , ( Object ) tmp ) ; return toArray ; }
Slice the supplied array for range and step .
30,413
public static Object repeat ( List < Object > list , int times ) { if ( times < 1 ) if ( list instanceof Queue ) return new LinkedList < > ( ) ; else return new ArrayList < > ( 0 ) ; List < Object > lst = list instanceof Queue ? new LinkedList < > ( list ) : new ArrayList < > ( list ) ; if ( times == 1 ) return lst ; while ( times -- > 1 ) lst . addAll ( list ) ; return lst ; }
Repeat the contents of a list a number of times .
30,414
public static Object repeat ( Object arr , int times ) { Class < ? > toType = Types . arrayElementType ( arr . getClass ( ) ) ; if ( times < 1 ) return Array . newInstance ( toType , 0 ) ; int [ ] dims = dimensions ( arr ) ; int length = dims [ 0 ] ; dims [ 0 ] *= times ; int i = 0 , total = dims [ 0 ] ; Object toArray = Array . newInstance ( toType , dims ) ; while ( i < total ) { System . arraycopy ( arr , 0 , toArray , i , length ) ; i += length ; } return toArray ; }
Repeat the contents of an array a number of times .
30,415
public static Object concat ( List < ? > lhs , List < ? > rhs ) { List < Object > list = lhs instanceof Queue ? new LinkedList < > ( lhs ) : new ArrayList < > ( lhs ) ; list . addAll ( rhs ) ; return list ; }
Concatenate two lists .
30,416
public static int [ ] dimensions ( Object arr ) { int [ ] dims = new int [ Types . arrayDimensions ( arr . getClass ( ) ) ] ; if ( 0 == dims . length || 0 == ( dims [ 0 ] = Array . getLength ( arr ) ) ) return dims ; for ( int i = 1 ; i < dims . length ; i ++ ) if ( null != ( arr = Array . get ( arr , 0 ) ) ) dims [ i ] = Array . getLength ( arr ) ; else break ; return dims ; }
Collect dimensions array of supplied array object . Returns the integer array used for Array . newInstance .
30,417
private static Map < ? , ? > mapOfEntries ( Entry < ? , ? > ... entries ) { Map < Object , Object > looseTypedMap = new LinkedHashMap < > ( entries . length ) ; for ( Entry < ? , ? > entry : entries ) looseTypedMap . put ( entry . getKey ( ) , entry . getValue ( ) ) ; return looseTypedMap ; }
Relaxed implementation of the java 9 Map . ofEntries . LinkedHashMap ensures element order remains as supplied .
30,418
public static Class < ? > commonType ( Class < ? > baseType , Object fromValue , IntSupplier length ) { if ( Object . class != baseType ) return baseType ; Class < ? > common = null ; int len = length . getAsInt ( ) ; for ( int i = 0 ; i < len ; i ++ ) if ( Object . class == ( common = Types . getCommonType ( common , Types . getType ( Array . get ( fromValue , 0 ) ) ) ) ) break ; if ( null != common && common != baseType ) return common ; return baseType ; }
Find a more specific type if the element type is Object . class .
30,419
public Object toObject ( CallStack callstack , Interpreter interpreter ) throws UtilEvalError { return toObject ( callstack , interpreter , false ) ; }
Resolve possibly complex name to an object value .
30,420
Object resolveThisFieldReference ( CallStack callstack , NameSpace thisNameSpace , Interpreter interpreter , String varName , boolean specialFieldsVisible ) throws UtilEvalError { if ( varName . equals ( "this" ) ) { if ( specialFieldsVisible ) throw new UtilEvalError ( "Redundant to call .this on This type" ) ; This ths = thisNameSpace . getThis ( interpreter ) ; thisNameSpace = ths . getNameSpace ( ) ; Object result = ths ; NameSpace classNameSpace = getClassNameSpace ( thisNameSpace ) ; if ( classNameSpace != null ) { if ( isCompound ( evalName ) ) result = classNameSpace . getThis ( interpreter ) ; else result = classNameSpace . getClassInstance ( ) ; } return result ; } if ( varName . equals ( "super" ) ) { This ths = thisNameSpace . getSuper ( interpreter ) ; thisNameSpace = ths . getNameSpace ( ) ; if ( thisNameSpace . getParent ( ) != null && thisNameSpace . getParent ( ) . isClass ) ths = thisNameSpace . getParent ( ) . getThis ( interpreter ) ; return ths ; } Object obj = null ; if ( varName . equals ( "global" ) ) obj = thisNameSpace . getGlobal ( interpreter ) ; if ( obj == null && specialFieldsVisible ) { if ( varName . equals ( "namespace" ) ) obj = thisNameSpace ; else if ( varName . equals ( "variables" ) ) obj = thisNameSpace . getVariableNames ( ) ; else if ( varName . equals ( "methods" ) ) obj = thisNameSpace . getMethodNames ( ) ; else if ( varName . equals ( "interpreter" ) ) if ( lastEvalName . equals ( "this" ) ) obj = interpreter ; else throw new UtilEvalError ( "Can only call .interpreter on literal 'this'" ) ; } if ( obj == null && specialFieldsVisible && varName . equals ( "caller" ) ) { if ( lastEvalName . equals ( "this" ) || lastEvalName . equals ( "caller" ) ) { if ( callstack == null ) throw new InterpreterError ( "no callstack" ) ; obj = callstack . get ( ++ callstackDepth ) . getThis ( interpreter ) ; } else throw new UtilEvalError ( "Can only call .caller on literal 'this' or literal '.caller'" ) ; return obj ; } if ( obj == null && specialFieldsVisible && varName . equals ( "callstack" ) ) { if ( lastEvalName . equals ( "this" ) ) { if ( callstack == null ) throw new InterpreterError ( "no callstack" ) ; obj = callstack ; } else throw new UtilEvalError ( "Can only call .callstack on literal 'this'" ) ; } if ( obj == null ) obj = thisNameSpace . getVariable ( varName , evalBaseObject == null ) ; if ( obj == null ) obj = Primitive . NULL ; return obj ; }
Resolve a variable relative to a This reference .
30,421
public static String escape ( String value ) { String search = "&<>" ; String [ ] replace = { "&amp;" , "&lt;" , "&gt;" } ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; int pos = search . indexOf ( c ) ; if ( pos < 0 ) buf . append ( c ) ; else buf . append ( replace [ pos ] ) ; } return buf . toString ( ) ; }
Convert special characters to entities for XML output
30,422
public V get ( K key ) { if ( null == key ) return null ; CacheReference < K > refKey = lookupFactory . createKey ( key , queue ) ; if ( cache . containsKey ( refKey ) ) { V value = dereferenceValue ( cache . get ( refKey ) ) ; if ( null != value ) return value ; cache . remove ( refKey ) ; } init ( key ) ; return dereferenceValue ( cache . get ( refKey ) ) ; }
Get a value from the cache for associated with the supplied key . New entries will be initialized if they don t exist or if they were cleared and will block to wait for a value to return . For asynchronous non blocking value creation use init .
30,423
public void init ( K key ) { if ( null == key ) return ; CacheReference < K > refKey = keyFactory . createKey ( key , queue ) ; if ( cache . containsKey ( refKey ) ) return ; FutureTask < CacheReference < V > > task = new FutureTask < > ( ( ) -> { V created = requireNonNull ( create ( key ) ) ; return valueFactory . createValue ( created , queue ) ; } ) ; cache . put ( refKey , task ) ; task . run ( ) ; }
Asynchronously initialize a new cache value to associate with key . If key is null or key already exist will do nothing . Wraps the create method in a future task and starts a new process .
30,424
public boolean remove ( K key ) { if ( null == key ) return false ; CacheReference < K > keyRef = lookupFactory . createKey ( key , queue ) ; return CacheKey . class . cast ( keyRef ) . removeCacheEntry ( ) ; }
Remove cache entry associated with the given key .
30,425
private final ReferenceFactory < K , V > toFactory ( Type type ) { switch ( type ) { case Hard : return new HardReferenceFactory ( ) ; case Weak : return new WeakReferenceFactory ( ) ; case Soft : return new SoftReferenceFactory ( ) ; default : return null ; } }
Create a reference factory of the given type .
30,426
private V dereferenceValue ( Future < CacheReference < V > > futureValue ) { try { return dereferenceValue ( futureValue . get ( ) ) ; } catch ( final Throwable e ) { return null ; } }
Retrieve a referenced value from a future and dereference it .
30,427
public static Class < ? > [ ] getTypes ( Object [ ] args ) { if ( args == null ) return Reflect . ZERO_TYPES ; Class < ? > [ ] types = new Class [ args . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) types [ i ] = getType ( args [ i ] ) ; return types ; }
Get the Java types of the arguments .
30,428
public static Class < ? > getType ( Object arg , boolean boxed ) { if ( null == arg || Primitive . NULL == arg ) return null ; if ( arg instanceof Primitive && ! boxed ) return ( ( Primitive ) arg ) . getType ( ) ; return Primitive . unwrap ( arg ) . getClass ( ) ; }
Find the type of an object boxed or not .
30,429
static boolean areSignaturesEqual ( Class [ ] from , Class [ ] to ) { if ( from . length != to . length ) return false ; for ( int i = 0 ; i < from . length ; i ++ ) if ( from [ i ] != to [ i ] ) return false ; return true ; }
Are the two signatures exactly equal? This is checked for a special case in overload resolution .
30,430
public static Class < ? > arrayElementType ( Class < ? > arrType ) { if ( null == arrType ) return null ; while ( arrType . isArray ( ) ) arrType = arrType . getComponentType ( ) ; return arrType ; }
Find array element type for class . Roll back component type until class is not an array anymore .
30,431
public static int arrayDimensions ( Class < ? > arrType ) { if ( null == arrType || ! arrType . isArray ( ) ) return 0 ; return arrType . getName ( ) . lastIndexOf ( '[' ) + 1 ; }
Find the number of array dimensions for class . By counting the number of [ prefixing the class name .
30,432
public static Class < ? > getCommonType ( Class < ? > common , Class < ? > compare ) { if ( null == common ) return compare ; if ( null == compare || common . isAssignableFrom ( compare ) ) return common ; if ( NUMBER_ORDER . containsKey ( common ) && NUMBER_ORDER . containsKey ( compare ) ) if ( NUMBER_ORDER . get ( common ) >= NUMBER_ORDER . get ( compare ) ) return common ; else return compare ; Class < ? > supr = common ; while ( null != ( supr = supr . getSuperclass ( ) ) && Object . class != supr ) if ( supr . isAssignableFrom ( compare ) ) return supr ; return Object . class ; }
Find the common type between two classes .
30,433
static UtilEvalError castError ( Class lhsType , Class rhsType , int operation ) { return castError ( StringUtil . typeString ( lhsType ) , StringUtil . typeString ( rhsType ) , operation ) ; }
Return a UtilEvalError or UtilTargetError wrapping a ClassCastException describing an illegal assignment or illegal cast respectively .
30,434
public static String getBaseName ( String className ) { int i = className . indexOf ( "$" ) ; if ( i == - 1 ) return className ; return className . substring ( i + 1 ) ; }
Return the baseName of an inner class . This should live in utilities somewhere .
30,435
public Object eval ( CallStack callstack , Interpreter interpreter ) throws EvalError { if ( paramTypes != null ) return paramTypes ; insureParsed ( ) ; Class [ ] paramTypes = new Class [ numArgs ] ; for ( int i = 0 ; i < numArgs ; i ++ ) { BSHFormalParameter param = ( BSHFormalParameter ) jjtGetChild ( i ) ; paramTypes [ i ] = ( Class ) param . eval ( callstack , interpreter ) ; } this . paramTypes = paramTypes ; return paramTypes ; }
Evaluate the types . Note that type resolution does not require the interpreter instance .
30,436
int computeMethodInfoSize ( ) { if ( sourceOffset != 0 ) { return 6 + sourceLength ; } int size = 8 ; if ( code . length > 0 ) { if ( code . length > 65535 ) { throw new IndexOutOfBoundsException ( "Method code too large!" ) ; } symbolTable . addConstantUtf8 ( Constants . CODE ) ; size += 16 + code . length + Handler . getExceptionTableSize ( firstHandler ) ; if ( stackMapTableEntries != null ) { boolean useStackMapTable = symbolTable . getMajorVersion ( ) >= Opcodes . V1_6 ; symbolTable . addConstantUtf8 ( useStackMapTable ? Constants . STACK_MAP_TABLE : "StackMap" ) ; size += 8 + stackMapTableEntries . length ; } if ( lineNumberTable != null ) { symbolTable . addConstantUtf8 ( Constants . LINE_NUMBER_TABLE ) ; size += 8 + lineNumberTable . length ; } if ( localVariableTable != null ) { symbolTable . addConstantUtf8 ( Constants . LOCAL_VARIABLE_TABLE ) ; size += 8 + localVariableTable . length ; } if ( localVariableTypeTable != null ) { symbolTable . addConstantUtf8 ( Constants . LOCAL_VARIABLE_TYPE_TABLE ) ; size += 8 + localVariableTypeTable . length ; } if ( firstCodeAttribute != null ) { size += firstCodeAttribute . computeAttributesSize ( symbolTable , code . data , code . length , maxStack , maxLocals ) ; } } if ( numberOfExceptions > 0 ) { symbolTable . addConstantUtf8 ( Constants . EXCEPTIONS ) ; size += 8 + 2 * numberOfExceptions ; } boolean useSyntheticAttribute = symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ; if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ; size += 6 ; } if ( signatureIndex != 0 ) { symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ; size += 8 ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ; size += 6 ; } if ( defaultValue != null ) { symbolTable . addConstantUtf8 ( Constants . ANNOTATION_DEFAULT ) ; size += 6 + defaultValue . length ; } if ( parameters != null ) { symbolTable . addConstantUtf8 ( Constants . METHOD_PARAMETERS ) ; size += 7 + parameters . length ; } if ( firstAttribute != null ) { size += firstAttribute . computeAttributesSize ( symbolTable ) ; } return size ; }
Returns the size of the method_info JVMS structure generated by this MethodWriter . Also add the names of the attributes of this method in the constant pool .
30,437
public Object put ( String key , Object value ) { Object oldValue = context . getAttribute ( key , ENGINE_SCOPE ) ; context . setAttribute ( key , value , ENGINE_SCOPE ) ; return oldValue ; }
Set the key value binding in the ENGINE_SCOPE of the context .
30,438
public void putAll ( Map < ? extends String , ? extends Object > t ) { context . getBindings ( ENGINE_SCOPE ) . putAll ( t ) ; }
Put the bindings into the ENGINE_SCOPE of the context .
30,439
public String getDescriptor ( ) { if ( sort == OBJECT ) { return valueBuffer . substring ( valueBegin - 1 , valueEnd + 1 ) ; } else if ( sort == INTERNAL ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( 'L' ) ; stringBuilder . append ( valueBuffer , valueBegin , valueEnd ) ; stringBuilder . append ( ';' ) ; return stringBuilder . toString ( ) ; } else { return valueBuffer . substring ( valueBegin , valueEnd ) ; } }
Returns the descriptor corresponding to this type .
30,440
private static void appendDescriptor ( final StringBuilder stringBuilder , final Class < ? > clazz ) { Class < ? > currentClass = clazz ; while ( currentClass . isArray ( ) ) { stringBuilder . append ( '[' ) ; currentClass = currentClass . getComponentType ( ) ; } if ( currentClass . isPrimitive ( ) ) { char descriptor ; if ( currentClass == Integer . TYPE ) { descriptor = 'I' ; } else if ( currentClass == Void . TYPE ) { descriptor = 'V' ; } else if ( currentClass == Boolean . TYPE ) { descriptor = 'Z' ; } else if ( currentClass == Byte . TYPE ) { descriptor = 'B' ; } else if ( currentClass == Character . TYPE ) { descriptor = 'C' ; } else if ( currentClass == Short . TYPE ) { descriptor = 'S' ; } else if ( currentClass == Double . TYPE ) { descriptor = 'D' ; } else if ( currentClass == Float . TYPE ) { descriptor = 'F' ; } else if ( currentClass == Long . TYPE ) { descriptor = 'J' ; } else { throw new AssertionError ( ) ; } stringBuilder . append ( descriptor ) ; } else { stringBuilder . append ( 'L' ) ; String name = currentClass . getName ( ) ; int nameLength = name . length ( ) ; for ( int i = 0 ; i < nameLength ; ++ i ) { char car = name . charAt ( i ) ; stringBuilder . append ( car == '.' ? '/' : car ) ; } stringBuilder . append ( ';' ) ; } }
Appends the descriptor of the given class to the given string builder .
30,441
final void setInputFrameFromApiFormat ( final SymbolTable symbolTable , final int nLocal , final Object [ ] local , final int nStack , final Object [ ] stack ) { int inputLocalIndex = 0 ; for ( int i = 0 ; i < nLocal ; ++ i ) { inputLocals [ inputLocalIndex ++ ] = getAbstractTypeFromApiFormat ( symbolTable , local [ i ] ) ; if ( local [ i ] == Opcodes . LONG || local [ i ] == Opcodes . DOUBLE ) { inputLocals [ inputLocalIndex ++ ] = TOP ; } } while ( inputLocalIndex < inputLocals . length ) { inputLocals [ inputLocalIndex ++ ] = TOP ; } int nStackTop = 0 ; for ( int i = 0 ; i < nStack ; ++ i ) { if ( stack [ i ] == Opcodes . LONG || stack [ i ] == Opcodes . DOUBLE ) { ++ nStackTop ; } } inputStack = new int [ nStack + nStackTop ] ; int inputStackIndex = 0 ; for ( int i = 0 ; i < nStack ; ++ i ) { inputStack [ inputStackIndex ++ ] = getAbstractTypeFromApiFormat ( symbolTable , stack [ i ] ) ; if ( stack [ i ] == Opcodes . LONG || stack [ i ] == Opcodes . DOUBLE ) { inputStack [ inputStackIndex ++ ] = TOP ; } } outputStackTop = 0 ; initializationCount = 0 ; }
Sets the input frame from the given public API frame description .
30,442
public static Object invokeStaticMethod ( BshClassManager bcm , Class < ? > clas , String methodName , Object [ ] args , SimpleNode callerInfo ) throws ReflectError , UtilEvalError , InvocationTargetException { Interpreter . debug ( "invoke static Method" ) ; NameSpace ns = getThisNS ( clas ) ; if ( null != ns ) ns . setNode ( callerInfo ) ; Invocable method = resolveExpectedJavaMethod ( bcm , clas , null , methodName , args , true ) ; return method . invoke ( null , args ) ; }
Invoke a method known to be static . No object instance is needed and there is no possibility of the method being a bsh scripted method .
30,443
public static Object getObjectFieldValue ( Object object , String fieldName ) throws UtilEvalError , ReflectError { if ( object instanceof This ) { return ( ( This ) object ) . namespace . getVariable ( fieldName ) ; } else if ( object == Primitive . NULL ) { throw new UtilTargetError ( new NullPointerException ( "Attempt to access field '" + fieldName + "' on null value" ) ) ; } else { try { return getFieldValue ( object . getClass ( ) , object , fieldName , false ) ; } catch ( ReflectError e ) { if ( hasObjectPropertyGetter ( object . getClass ( ) , fieldName ) ) return getObjectProperty ( object , fieldName ) ; else throw e ; } } }
Check for a field with the given name in a java object or scripted object if the field exists fetch the value if not check for a property value . If neither is found return Primitive . VOID .
30,444
static LHS getLHSObjectField ( Object object , String fieldName ) throws UtilEvalError , ReflectError { if ( object instanceof This ) return new LHS ( ( ( This ) object ) . namespace , fieldName , false ) ; try { Invocable f = resolveExpectedJavaField ( object . getClass ( ) , fieldName , false ) ; return new LHS ( object , f ) ; } catch ( ReflectError e ) { NameSpace ns = getThisNS ( object ) ; if ( isGeneratedClass ( object . getClass ( ) ) && null != ns && ns . isClass ) { Variable var = ns . getVariableImpl ( fieldName , true ) ; if ( null != var && ( ! var . hasModifier ( "private" ) || haveAccessibility ( ) ) ) return new LHS ( ns , fieldName ) ; } if ( hasObjectPropertySetter ( object . getClass ( ) , fieldName ) ) return new LHS ( object , fieldName ) ; else throw e ; } }
Get an LHS reference to an object field .
30,445
static BshMethod staticMethodImport ( Class < ? > baseClass , String methodName ) { Invocable method = BshClassManager . memberCache . get ( baseClass ) . findStaticMethod ( methodName ) ; if ( null != method ) return new BshMethod ( method , null ) ; return null ; }
Find a static method member of baseClass for the given name .
30,446
public static This getClassStaticThis ( Class < ? > clas , String className ) { try { return ( This ) getStaticFieldValue ( clas , BSHSTATIC + className ) ; } catch ( Exception e ) { throw new InterpreterError ( "Unable to get class static space: " + e , e ) ; } }
Get the static bsh namespace field from the class .
30,447
public static This getClassInstanceThis ( Object instance , String className ) { try { Object o = getObjectFieldValue ( instance , BSHTHIS + className ) ; return ( This ) Primitive . unwrap ( o ) ; } catch ( Exception e ) { throw new InterpreterError ( "Generated class: Error getting This" + e , e ) ; } }
Get the instance bsh namespace field from the object instance .
30,448
public static BshClassManager createClassManager ( Interpreter interpreter ) { BshClassManager manager ; if ( Capabilities . classExists ( "bsh.classpath.ClassManagerImpl" ) ) try { Class < ? > clazz = Capabilities . getExisting ( "bsh.classpath.ClassManagerImpl" ) ; manager = ( BshClassManager ) clazz . getConstructor ( ) . newInstance ( ) ; } catch ( IllegalArgumentException | ReflectiveOperationException | SecurityException e ) { throw new InterpreterError ( "Error loading classmanager" , e ) ; } else manager = new BshClassManager ( ) ; manager . declaringInterpreter = interpreter ; return manager ; }
Create a new instance of the class manager . Class manager instnaces are now associated with the interpreter .
30,449
public void cacheClassInfo ( String name , Class < ? > value ) { if ( value != null ) { absoluteClassCache . put ( name , value ) ; memberCache . init ( value ) ; } else absoluteNonClasses . add ( name ) ; }
Cache info about whether name is a class or not .
30,450
protected String getClassBeingDefined ( String className ) { String baseName = Name . suffix ( className , 1 ) ; return definingClassesBaseNames . get ( baseName ) ; }
This method is a temporary workaround used with definingClass . It is to be removed at some point .
30,451
protected void doneDefiningClass ( String className ) { String baseName = Name . suffix ( className , 1 ) ; definingClasses . remove ( className ) ; definingClassesBaseNames . remove ( baseName ) ; }
Indicate that the specified class name has been defined and may be loaded normally .
30,452
void setArrayExpression ( BSHArrayInitializer init ) { this . isArrayExpression = true ; if ( parent instanceof BSHAssignment ) { BSHAssignment ass = ( BSHAssignment ) parent ; if ( null != ass . operator && ass . operator == ParserConstants . ASSIGN ) this . isMapExpression = true ; if ( this . isMapExpression && init . jjtGetParent ( ) instanceof BSHArrayInitializer ) init . setMapInArray ( true ) ; } }
Called from BSHArrayInitializer during node creation informing us that we are an array expression . If parent BSHAssignment has an ASSIGN operation then this is a map expression . If the initializer reference has multiple dimensions it gets configure as being a map in array .
30,453
public LHS toLHS ( CallStack callstack , Interpreter interpreter ) throws EvalError { return ( LHS ) eval ( interpreter . getStrictJava ( ) || ! isMapExpression , callstack , interpreter ) ; }
Evaluate to a value object .
30,454
static void putTarget ( final int targetTypeAndInfo , final ByteVector output ) { switch ( targetTypeAndInfo >>> 24 ) { case CLASS_TYPE_PARAMETER : case METHOD_TYPE_PARAMETER : case METHOD_FORMAL_PARAMETER : output . putShort ( targetTypeAndInfo >>> 16 ) ; break ; case FIELD : case METHOD_RETURN : case METHOD_RECEIVER : output . putByte ( targetTypeAndInfo >>> 24 ) ; break ; case CAST : case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT : case METHOD_INVOCATION_TYPE_ARGUMENT : case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT : case METHOD_REFERENCE_TYPE_ARGUMENT : output . putInt ( targetTypeAndInfo ) ; break ; case CLASS_EXTENDS : case CLASS_TYPE_PARAMETER_BOUND : case METHOD_TYPE_PARAMETER_BOUND : case THROWS : case EXCEPTION_PARAMETER : case INSTANCEOF : case NEW : case CONSTRUCTOR_REFERENCE : case METHOD_REFERENCE : output . put12 ( targetTypeAndInfo >>> 24 , ( targetTypeAndInfo & 0xFFFF00 ) >> 8 ) ; break ; default : throw new IllegalArgumentException ( ) ; } }
Puts the given target_type and target_info JVMS structures into the given ByteVector .
30,455
public Object call ( Object object , String name , Object [ ] args ) throws BSFException { if ( object == null ) try { object = interpreter . get ( "global" ) ; } catch ( EvalError e ) { throw new BSFException ( BSFException . REASON_OTHER_ERROR , "bsh internal error: " + e , e ) ; } if ( object instanceof bsh . This ) try { Object value = ( ( bsh . This ) object ) . invokeMethod ( name , args ) ; return Primitive . unwrap ( value ) ; } catch ( InterpreterError e ) { throw new BSFException ( BSFException . REASON_UNKNOWN_LANGUAGE , "BeanShell interpreter internal error: " + e , e ) ; } catch ( TargetError e2 ) { throw new BSFException ( BSFException . REASON_EXECUTION_ERROR , "The application script threw an exception: " + e2 . getTarget ( ) , e2 ) ; } catch ( EvalError e3 ) { throw new BSFException ( BSFException . REASON_OTHER_ERROR , "BeanShell script error: " + e3 , e3 ) ; } else throw new BSFException ( "Cannot invoke method: " + name + ". Object: " + object + " is not a BeanShell scripted object." ) ; }
Invoke method name on the specified bsh scripted object . The object may be null to indicate the global namespace of the interpreter .
30,456
public void driveToClass ( String classname ) { String [ ] sa = BshClassPath . splitClassname ( classname ) ; String packn = sa [ 0 ] ; String classn = sa [ 1 ] ; if ( classPath . getClassesForPackage ( packn ) . size ( ) == 0 ) return ; ptree . setSelectedPackage ( packn ) ; for ( int i = 0 ; i < classesList . length ; i ++ ) { if ( classesList [ i ] . equals ( classn ) ) { classlist . setSelectedIndex ( i ) ; classlist . ensureIndexIsVisible ( i ) ; break ; } } }
fully qualified classname
30,457
public Object getValue ( ) { if ( value == Special . NULL_VALUE ) return null ; if ( value == Special . VOID_TYPE ) throw new InterpreterError ( "attempt to unwrap void type" ) ; return value ; }
Return the primitive value stored in its java . lang wrapper class
30,458
public Class < ? > getType ( ) { if ( this == Primitive . VOID ) return Void . TYPE ; if ( this == Primitive . NULL ) return null ; return unboxType ( value . getClass ( ) ) ; }
Get the corresponding Java primitive TYPE class for this Primitive .
30,459
public static Object unwrap ( Object obj ) { if ( obj == Primitive . VOID ) return null ; if ( obj instanceof Primitive ) return ( ( Primitive ) obj ) . getValue ( ) ; return obj ; }
Unwrap primitive values and map voids to nulls . Non Primitive types remain unchanged .
30,460
public static Primitive getDefaultValue ( Class < ? > type ) { if ( type == null ) return Primitive . NULL ; if ( Boolean . TYPE == type || Boolean . class == type ) return Primitive . FALSE ; if ( Character . TYPE == type || Character . class == type ) return Primitive . ZERO_CHAR ; if ( Byte . TYPE == type || Byte . class == type ) return Primitive . ZERO_BYTE ; if ( Short . TYPE == type || Short . class == type ) return Primitive . ZERO_SHORT ; if ( Integer . TYPE == type || Integer . class == type ) return Primitive . ZERO_INT ; if ( Long . TYPE == type || Long . class == type ) return Primitive . ZERO_LONG ; if ( Float . TYPE == type || Float . class == type ) return Primitive . ZERO_FLOAT ; if ( Double . TYPE == type || Double . class == type ) return Primitive . ZERO_DOUBLE ; if ( BigInteger . class == type ) return Primitive . ZERO_BIG_INTEGER ; if ( BigDecimal . class == type ) return Primitive . ZERO_BIG_DECIMAL ; return Primitive . NULL ; }
Get the appropriate default value per JLS 4 . 5 . 4
30,461
int computeFieldInfoSize ( ) { int size = 8 ; if ( constantValueIndex != 0 ) { symbolTable . addConstantUtf8 ( Constants . CONSTANT_VALUE ) ; size += 8 ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ) { symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ; size += 6 ; } if ( signatureIndex != 0 ) { symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ; size += 8 ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ; size += 6 ; } if ( firstAttribute != null ) { size += firstAttribute . computeAttributesSize ( symbolTable ) ; } return size ; }
Returns the size of the field_info JVMS structure generated by this FieldWriter . Also adds the names of the attributes of this field in the constant pool .
30,462
void putFieldInfo ( final ByteVector output ) { boolean useSyntheticAttribute = symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ; int mask = useSyntheticAttribute ? Opcodes . ACC_SYNTHETIC : 0 ; output . putShort ( accessFlags & ~ mask ) . putShort ( nameIndex ) . putShort ( descriptorIndex ) ; int attributesCount = 0 ; if ( constantValueIndex != 0 ) { ++ attributesCount ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { ++ attributesCount ; } if ( signatureIndex != 0 ) { ++ attributesCount ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { ++ attributesCount ; } if ( firstAttribute != null ) { attributesCount += firstAttribute . getAttributeCount ( ) ; } output . putShort ( attributesCount ) ; if ( constantValueIndex != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . CONSTANT_VALUE ) ) . putInt ( 2 ) . putShort ( constantValueIndex ) ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ) . putInt ( 0 ) ; } if ( signatureIndex != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ) . putInt ( 2 ) . putShort ( signatureIndex ) ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ) . putInt ( 0 ) ; } if ( firstAttribute != null ) { firstAttribute . putAttributes ( symbolTable , output ) ; } }
Puts the content of the field_info JVMS structure generated by this FieldWriter into the given ByteVector .
30,463
public EvalError toEvalError ( String msg , SimpleNode node , CallStack callstack ) { if ( null == msg ) msg = this . getMessage ( ) ; else msg += ": " + this . getMessage ( ) ; return new TargetError ( msg , this . getCause ( ) , node , callstack , false ) ; }
Override toEvalError to throw TargetError type .
30,464
synchronized void insureNodesParsed ( ) { if ( paramsNode != null ) return ; Object firstNode = jjtGetChild ( 0 ) ; firstThrowsClause = 1 ; if ( firstNode instanceof BSHReturnType ) { returnTypeNode = ( BSHReturnType ) firstNode ; paramsNode = ( BSHFormalParameters ) jjtGetChild ( 1 ) ; if ( jjtGetNumChildren ( ) > 2 + numThrows ) blockNode = ( BSHBlock ) jjtGetChild ( 2 + numThrows ) ; ++ firstThrowsClause ; } else { paramsNode = ( BSHFormalParameters ) jjtGetChild ( 0 ) ; blockNode = ( BSHBlock ) jjtGetChild ( 1 + numThrows ) ; } paramsNode . insureParsed ( ) ; isVarArgs = paramsNode . isVarArgs ; }
Set the returnTypeNode paramsNode and blockNode based on child node structure . No evaluation is done here .
30,465
Class evalReturnType ( CallStack callstack , Interpreter interpreter ) throws EvalError { insureNodesParsed ( ) ; if ( returnTypeNode != null ) return returnTypeNode . evalReturnType ( callstack , interpreter ) ; else return null ; }
Evaluate the return type node .
30,466
public Object eval ( CallStack callstack , Interpreter interpreter ) throws EvalError { returnType = evalReturnType ( callstack , interpreter ) ; evalNodes ( callstack , interpreter ) ; NameSpace namespace = callstack . top ( ) ; BshMethod bshMethod = new BshMethod ( this , namespace , modifiers ) ; namespace . setMethod ( bshMethod ) ; return Primitive . VOID ; }
Evaluate the declaration of the method . That is determine the structure of the method and install it into the caller s namespace .
30,467
public static ArrayList < ACL > createAcl ( FailoverWatcher failoverWatcher , String znode ) { if ( znode . equals ( "/chronos" ) ) { return Ids . OPEN_ACL_UNSAFE ; } if ( failoverWatcher . isZkSecure ( ) ) { ArrayList < ACL > acls = new ArrayList < ACL > ( ) ; acls . add ( new ACL ( ZooDefs . Perms . READ , ZooDefs . Ids . ANYONE_ID_UNSAFE ) ) ; acls . add ( new ACL ( ZooDefs . Perms . ALL , new Id ( "sasl" , failoverWatcher . getZkAdmin ( ) ) ) ) ; return acls ; } else { return Ids . OPEN_ACL_UNSAFE ; } }
Create acl for znodes anyone could read but only admin can operate if set scure .
30,468
public static byte [ ] longToBytes ( long val ) { byte [ ] b = new byte [ 8 ] ; for ( int i = 7 ; i > 0 ; i -- ) { b [ i ] = ( byte ) val ; val >>>= 8 ; } b [ 0 ] = ( byte ) val ; return b ; }
Convert long value to byte array .
30,469
public static long bytesToLong ( byte [ ] bytes ) { long l = 0 ; for ( int i = 0 ; i < 0 + 8 ; i ++ ) { l <<= 8 ; l ^= bytes [ i ] & 0xFF ; } return l ; }
Convert byte array to original long value .
30,470
private void reconnectZooKeeper ( ) throws InterruptedException , IOException { LOG . info ( "Try to reconnect ZooKeeper " + zkQuorum ) ; if ( zooKeeper != null ) { zooKeeper . close ( ) ; } connectZooKeeper ( ) ; }
Reconnect with ZooKeeper .
30,471
private void connectChronosServer ( ) throws IOException { LOG . info ( "Try to connect chronos server" ) ; byte [ ] hostPortBytes = getData ( this , masterZnode ) ; if ( hostPortBytes != null ) { String hostPort = new String ( hostPortBytes ) ; LOG . info ( "Find the active chronos server in " + hostPort ) ; try { transport = new TSocket ( hostPort . split ( "_" ) [ 0 ] , Integer . parseInt ( hostPort . split ( "_" ) [ 1 ] ) ) ; transport . open ( ) ; protocol = new TBinaryProtocol ( transport ) ; client = new ChronosService . Client ( protocol ) ; } catch ( TException e ) { new IOException ( "Exception to connect chronos server in " + hostPort ) ; } } else { throw new IOException ( "The data of " + masterZnode + " is null" ) ; } }
Access ZooKeeper to get current master ChronosServer and connect with it .
30,472
public long getTimestamps ( int range ) throws IOException { long timestamp ; try { timestamp = client . getTimestamps ( range ) ; } catch ( TException e ) { LOG . info ( "Can't get timestamp, try to connect the active chronos server" ) ; try { reconnectChronosServer ( ) ; return client . getTimestamps ( range ) ; } catch ( Exception e1 ) { LOG . info ( "Can't connect chronos server, try to connect ZooKeeper firstly" ) ; try { reconnectZooKeeper ( ) ; reconnectChronosServer ( ) ; return client . getTimestamps ( range ) ; } catch ( Exception e2 ) { throw new IOException ( "Error to get timestamp after reconnecting ZooKeeper and chronos server" , e2 ) ; } } } return timestamp ; }
Send RPC request to get timestamp from ChronosServer . Use lazy strategy to detect failure . If request fails reconnect ChronosServer . If request fails again reconnect ZooKeeper .
30,473
public void process ( WatchedEvent event ) { if ( LOG . isDebugEnabled ( ) ) { LOG . info ( "Received ZooKeeper Event, " + "type=" + event . getType ( ) + ", " + "state=" + event . getState ( ) + ", " + "path=" + event . getPath ( ) ) ; } switch ( event . getType ( ) ) { case None : { switch ( event . getState ( ) ) { case SyncConnected : { try { waitToInitZooKeeper ( 2000 ) ; } catch ( Exception e ) { LOG . error ( "Error to init ZooKeeper object after sleeping 2000 ms, reconnect ZooKeeper" ) ; try { reconnectZooKeeper ( ) ; } catch ( Exception e1 ) { LOG . error ( "Error to reconnect with ZooKeeper" , e1 ) ; } } break ; } default : break ; } break ; } default : break ; } }
Deal with connection event just wait for a while when connected .
30,474
public void waitToInitZooKeeper ( long maxWaitMillis ) throws Exception { long finished = System . currentTimeMillis ( ) + maxWaitMillis ; while ( System . currentTimeMillis ( ) < finished ) { if ( this . zooKeeper != null ) { return ; } try { Thread . sleep ( 1 ) ; } catch ( InterruptedException e ) { throw new Exception ( e ) ; } } throw new Exception ( ) ; }
Wait to init ZooKeeper object only sleep when it s null .
30,475
public byte [ ] getData ( ChronosClientWatcher chronosClientWatcher , String znode ) throws IOException { byte [ ] data = null ; for ( int i = 0 ; i <= connectRetryTimes ; i ++ ) { try { data = chronosClientWatcher . getZooKeeper ( ) . getData ( znode , null , null ) ; break ; } catch ( Exception e ) { LOG . info ( "Exceptioin to get data from ZooKeeper, retry " + i + " times" ) ; if ( i == connectRetryTimes ) { throw new IOException ( "Error when getting data from " + znode + " after retrying" ) ; } } } return data ; }
Get the data from znode .
30,476
private void initThriftServer ( ) throws TTransportException , FatalChronosException , ChronosException { int maxThread = Integer . parseInt ( properties . getProperty ( MAX_THREAD , String . valueOf ( Integer . MAX_VALUE ) ) ) ; String serverHost = properties . getProperty ( FailoverServer . SERVER_HOST ) ; int serverPort = Integer . parseInt ( properties . getProperty ( FailoverServer . SERVER_PORT ) ) ; TServerSocket serverTransport = new TServerSocket ( new InetSocketAddress ( serverHost , serverPort ) ) ; Factory proFactory = new TBinaryProtocol . Factory ( ) ; chronosImplement = new ChronosImplement ( properties , chronosServerWatcher ) ; TProcessor processor = new ChronosService . Processor ( chronosImplement ) ; Args rpcArgs = new Args ( serverTransport ) ; rpcArgs . processor ( processor ) ; rpcArgs . protocolFactory ( proFactory ) ; rpcArgs . maxWorkerThreads ( maxThread ) ; thriftServer = new TThreadPoolServer ( rpcArgs ) ; }
Initialize Thrift server of ChronosServer .
30,477
public void doAsActiveServer ( ) { try { LOG . info ( "As active master, init timestamp from ZooKeeper" ) ; chronosImplement . initTimestamp ( ) ; } catch ( Exception e ) { LOG . fatal ( "Exception to init timestamp from ZooKeeper, exit immediately" ) ; System . exit ( 0 ) ; } chronosServerWatcher . setBeenActiveMaster ( true ) ; LOG . info ( "Start to accept thrift request" ) ; startThriftServer ( ) ; }
Initialize persistent timestamp and start to serve as active master .
30,478
public static void main ( String [ ] args ) { Properties properties = new Properties ( ) ; LOG . info ( "Load chronos.cfg configuration from class path" ) ; try { properties . load ( ChronosServer . class . getClassLoader ( ) . getResourceAsStream ( "chronos.cfg" ) ) ; properties . setProperty ( FailoverServer . BASE_ZNODE , "/chronos" + "/" + properties . getProperty ( CLUSTER_NAME ) ) ; } catch ( IOException e ) { LOG . fatal ( "Error to load chronos.cfg configuration, exit immediately" , e ) ; System . exit ( 0 ) ; } ChronosServer chronosServer = null ; LOG . info ( "Init chronos server and connect ZooKeeper" ) ; try { chronosServer = new ChronosServer ( properties ) ; } catch ( Exception e ) { LOG . fatal ( "Exception to init chronos server, exit immediately" , e ) ; System . exit ( 0 ) ; } chronosServer . run ( ) ; }
The main entrance of ChronosServer to start the service .
30,479
protected void initZnode ( ) { try { ZooKeeperUtil . createAndFailSilent ( this , "/chronos" ) ; super . initZnode ( ) ; ZooKeeperUtil . createAndFailSilent ( this , baseZnode + "/persistent-timestamp" ) ; } catch ( Exception e ) { LOG . fatal ( "Error to create znode of chronos, exit immediately" ) ; System . exit ( 0 ) ; } }
Create the base znode of chronos .
30,480
public long getPersistentTimestamp ( ) throws ChronosException { byte [ ] persistentTimesampBytes = null ; for ( int i = 0 ; i <= connectRetryTimes ; ++ i ) { try { persistentTimesampBytes = ZooKeeperUtil . getDataAndWatch ( this , persistentTimestampZnode ) ; break ; } catch ( KeeperException e ) { if ( i == connectRetryTimes ) { throw new ChronosException ( "Can't get persistent timestamp from ZooKeeper after retrying" , e ) ; } LOG . info ( "Exception to get persistent timestamp from ZooKeeper, retry " + ( i + 1 ) + " times" ) ; } } if ( Arrays . equals ( persistentTimesampBytes , new byte [ 0 ] ) ) { persistentTimestamp = 0 ; } else { persistentTimestamp = ZooKeeperUtil . bytesToLong ( persistentTimesampBytes ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Return persistent timestamp " + persistentTimestamp + " to timestamp server" ) ; } return persistentTimestamp ; }
Get persistent timestamp in ZooKeeper with retries .
30,481
public void setPersistentTimestamp ( long newTimestamp ) throws FatalChronosException , ChronosException { if ( newTimestamp <= persistentTimestamp ) { throw new FatalChronosException ( "Fatal error to set a smaller timestamp" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Setting persistent timestamp " + newTimestamp + " in ZooKeeper" ) ; } for ( int i = 0 ; i <= connectRetryTimes ; ++ i ) { try { ZooKeeperUtil . setData ( this , persistentTimestampZnode , ZooKeeperUtil . longToBytes ( newTimestamp ) ) ; persistentTimestamp = newTimestamp ; break ; } catch ( KeeperException e ) { if ( i == connectRetryTimes ) { throw new ChronosException ( "Error to set persistent timestamp in ZooKeeper after retrying" , e ) ; } LOG . info ( "Exception to set persistent timestamp in ZooKeeper, retry " + ( i + 1 ) + " times" ) ; } } }
Set persistent timestamp in ZooKeeper .
30,482
protected void processConnection ( WatchedEvent event ) { super . processConnection ( event ) ; switch ( event . getState ( ) ) { case Disconnected : if ( beenActiveMaster ) { LOG . fatal ( hostPort . getHostPort ( ) + " disconnected from ZooKeeper, stop serving and exit immediately" ) ; System . exit ( 0 ) ; } else { LOG . warn ( hostPort . getHostPort ( ) + " disconnected from ZooKeeper, wait to sync and try to become active master" ) ; } break ; default : break ; } }
Deal with the connection event .
30,483
protected void connectZooKeeper ( ) throws IOException { LOG . info ( "Connecting ZooKeeper " + zkQuorum ) ; for ( int i = 0 ; i <= connectRetryTimes ; i ++ ) { try { zooKeeper = new ZooKeeper ( zkQuorum , sessionTimeout , this ) ; break ; } catch ( IOException e ) { if ( i == connectRetryTimes ) { throw new IOException ( "Can't connect ZooKeeper after retrying" , e ) ; } LOG . error ( "Exception to connect ZooKeeper, retry " + ( i + 1 ) + " times" ) ; } } }
Connect with ZooKeeper with retries .
30,484
protected void initZnode ( ) { try { ZooKeeperUtil . createAndFailSilent ( this , baseZnode ) ; ZooKeeperUtil . createAndFailSilent ( this , backupServersZnode ) ; } catch ( Exception e ) { LOG . fatal ( "Error to create znode " + baseZnode + " and " + backupServersZnode + ", exit immediately" , e ) ; System . exit ( 0 ) ; } }
Initialize the base znodes of chronos .
30,485
public void process ( WatchedEvent event ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Received ZooKeeper Event, " + "type=" + event . getType ( ) + ", " + "state=" + event . getState ( ) + ", " + "path=" + event . getPath ( ) ) ; } switch ( event . getType ( ) ) { case None : { processConnection ( event ) ; break ; } case NodeCreated : { processNodeCreated ( event . getPath ( ) ) ; break ; } case NodeDeleted : { processNodeDeleted ( event . getPath ( ) ) ; break ; } case NodeDataChanged : { processDataChanged ( event . getPath ( ) ) ; break ; } case NodeChildrenChanged : { processNodeChildrenChanged ( event . getPath ( ) ) ; break ; } default : break ; } }
Override this mothod to deal with events for leader election .
30,486
protected void processConnection ( WatchedEvent event ) { switch ( event . getState ( ) ) { case SyncConnected : LOG . info ( hostPort . getHostPort ( ) + " sync connect from ZooKeeper" ) ; try { waitToInitZooKeeper ( 2000 ) ; } catch ( Exception e ) { LOG . fatal ( "Error to init ZooKeeper object after sleeping 2000 ms, exit immediately" ) ; System . exit ( 0 ) ; } break ; case Disconnected : LOG . warn ( hostPort . getHostPort ( ) + " received disconnected from ZooKeeper" ) ; break ; case AuthFailed : LOG . fatal ( hostPort . getHostPort ( ) + " auth fail, exit immediately" ) ; System . exit ( 0 ) ; case Expired : LOG . fatal ( hostPort . getHostPort ( ) + " received expired from ZooKeeper, exit immediately" ) ; System . exit ( 0 ) ; break ; default : break ; } }
Deal with connection event exit current process if auth fails or session expires .
30,487
protected void processNodeCreated ( String path ) { if ( path . equals ( masterZnode ) ) { LOG . info ( masterZnode + " created and try to become active master" ) ; handleMasterNodeChange ( ) ; } }
Deal with create node event just call the leader election .
30,488
protected void processNodeDeleted ( String path ) { if ( path . equals ( masterZnode ) ) { LOG . info ( masterZnode + " deleted and try to become active master" ) ; handleMasterNodeChange ( ) ; } }
Deal with delete node event just call the leader election .
30,489
private void handleMasterNodeChange ( ) { try { synchronized ( hasActiveServer ) { if ( ZooKeeperUtil . watchAndCheckExists ( this , masterZnode ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "A master is now available" ) ; } hasActiveServer . set ( true ) ; } else { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "No master available. Notifying waiting threads" ) ; } hasActiveServer . set ( false ) ; hasActiveServer . notifyAll ( ) ; } } } catch ( KeeperException ke ) { LOG . error ( "Received an unexpected KeeperException, aborting" , ke ) ; } }
Implement the logic of leader election .
30,490
public boolean blockUntilActive ( ) { while ( true ) { try { if ( ZooKeeperUtil . createEphemeralNodeAndWatch ( this , masterZnode , hostPort . getHostPort ( ) . getBytes ( ) ) ) { LOG . info ( "Deleting ZNode for " + backupServersZnode + "/" + hostPort . getHostPort ( ) + " from backup master directory" ) ; ZooKeeperUtil . deleteNodeFailSilent ( this , backupServersZnode + "/" + hostPort . getHostPort ( ) ) ; hasActiveServer . set ( true ) ; LOG . info ( "Become active master in " + hostPort . getHostPort ( ) ) ; return true ; } hasActiveServer . set ( true ) ; LOG . info ( "Adding ZNode for " + backupServersZnode + "/" + hostPort . getHostPort ( ) + " in backup master directory" ) ; ZooKeeperUtil . createEphemeralNodeAndWatch ( this , backupServersZnode + "/" + hostPort . getHostPort ( ) , hostPort . getHostPort ( ) . getBytes ( ) ) ; String msg ; byte [ ] bytes = ZooKeeperUtil . getDataAndWatch ( this , masterZnode ) ; if ( bytes == null ) { msg = ( "A master was detected, but went down before its address " + "could be read. Attempting to become the next active master" ) ; } else { if ( hostPort . getHostPort ( ) . equals ( new String ( bytes ) ) ) { msg = ( "Current master has this master's address, " + hostPort . getHostPort ( ) + "; master was restarted? Deleting node." ) ; ZooKeeperUtil . deleteNode ( this , masterZnode ) ; } else { msg = "Another master " + new String ( bytes ) + " is the active master, " + hostPort . getHostPort ( ) + "; waiting to become the next active master" ; } } LOG . info ( msg ) ; } catch ( KeeperException ke ) { LOG . error ( "Received an unexpected KeeperException when block to become active, aborting" , ke ) ; return false ; } synchronized ( hasActiveServer ) { while ( hasActiveServer . get ( ) ) { try { hasActiveServer . wait ( ) ; } catch ( InterruptedException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Interrupted while waiting to be master" ) ; } return false ; } } } } }
Implement the logic of server to wait to become active master .
30,491
public void close ( ) { if ( zooKeeper != null ) { try { zooKeeper . close ( ) ; } catch ( InterruptedException e ) { LOG . error ( "Interrupt when closing zookeeper connection" , e ) ; } } }
Close the ZooKeeper object .
30,492
public static HostPort parseHostPort ( String string ) { String [ ] strings = string . split ( "_" ) ; return new HostPort ( strings [ 0 ] , Integer . parseInt ( strings [ 1 ] ) ) ; }
Parse a host_port string to construct the HostPost object .
30,493
public long getTimestamps ( int range ) throws TException { long currentTime = System . currentTimeMillis ( ) << 18 ; synchronized ( this ) { if ( currentTime > maxAssignedTimestamp ) { maxAssignedTimestamp = currentTime + range - 1 ; } else { maxAssignedTimestamp += range ; } if ( maxAssignedTimestamp >= chronosServerWatcher . getCachedPersistentTimestamp ( ) ) { sleepUntilAsyncSet ( ) ; if ( maxAssignedTimestamp >= chronosServerWatcher . getCachedPersistentTimestamp ( ) ) { long newPersistentTimestamp = maxAssignedTimestamp + zkAdvanceTimestamp ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Try to sync set persistent timestamp " + newPersistentTimestamp ) ; } try { chronosServerWatcher . setPersistentTimestamp ( newPersistentTimestamp ) ; } catch ( ChronosException e ) { LOG . fatal ( "Error to set persistent timestamp, exit immediately" ) ; System . exit ( 0 ) ; } } } if ( ! isAsyncSetPersistentTimestamp && maxAssignedTimestamp >= chronosServerWatcher . getCachedPersistentTimestamp ( ) - zkAdvanceTimestamp * 0.5 ) { long newPersistentTimestamp = chronosServerWatcher . getCachedPersistentTimestamp ( ) + zkAdvanceTimestamp ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Try to async set persistent timestamp " + newPersistentTimestamp ) ; } isAsyncSetPersistentTimestamp = true ; asyncSetPersistentTimestamp ( newPersistentTimestamp ) ; } return maxAssignedTimestamp - range + 1 ; } }
Assign required number of timestamps client can use [ timestamp timestamp + range ) .
30,494
private void sleepUntilAsyncSet ( ) { LOG . info ( "Sleep a while until asynchronously set persistent timestamp" ) ; while ( isAsyncSetPersistentTimestamp ) { try { Thread . sleep ( 1 ) ; } catch ( InterruptedException e ) { LOG . fatal ( "Interrupt when sleep to set persistent timestamp, exit immediately" ) ; System . exit ( 0 ) ; } } }
Sleep until asynchronously set persistent timestamp successfully .
30,495
public void initTimestamp ( ) throws ChronosException , FatalChronosException { maxAssignedTimestamp = chronosServerWatcher . getPersistentTimestamp ( ) ; long newPersistentTimestamp = maxAssignedTimestamp + zkAdvanceTimestamp ; chronosServerWatcher . setPersistentTimestamp ( newPersistentTimestamp ) ; LOG . info ( "Get persistent timestamp " + maxAssignedTimestamp + " and set " + newPersistentTimestamp + " in ZooKeeper" ) ; }
Get the persistent timestamp in ZooKeeper and initialize the new one in ZooKeeper .
30,496
public synchronized void asyncSetPersistentTimestamp ( final long newPersistentTimestamp ) { new Thread ( ) { public void run ( ) { try { chronosServerWatcher . setPersistentTimestamp ( newPersistentTimestamp ) ; isAsyncSetPersistentTimestamp = false ; } catch ( Exception e ) { LOG . fatal ( "Error to set persistent timestamp, exit immediately" ) ; System . exit ( 0 ) ; } } } . start ( ) ; }
Create a new thread to asynchronously set persistent timestamp in ZooKeeper .
30,497
public void doAsActiveServer ( ) { while ( true ) { LOG . info ( "No business logic, sleep for " + Integer . MAX_VALUE ) ; try { Thread . sleep ( Integer . MAX_VALUE ) ; } catch ( InterruptedException e ) { LOG . error ( "Interrupt when sleeping as active master" , e ) ; } } }
The method you should override to do your business logic after becoming active master .
30,498
public void startBenchmark ( ) { startTime = System . currentTimeMillis ( ) ; LOG . info ( "Start to benchmark chronos server" ) ; Thread t = new Thread ( ) { public void run ( ) { final long collectPeriod = 10000 ; LOG . info ( "Start another thread to export benchmark metrics every " + collectPeriod / 1000.0 + " second" ) ; int totalCount ; int totalLatency ; long exportTime ; int lastTotalCount = 0 ; int lastTotalLatency = 0 ; long lastExportTime = startTime ; while ( true ) { try { Thread . sleep ( collectPeriod ) ; } catch ( InterruptedException e ) { LOG . error ( "Interrupt when sleep to get benchmark metrics, exit immediately" ) ; System . exit ( 0 ) ; } exportTime = System . currentTimeMillis ( ) ; totalCount = totalCountInteger . get ( ) ; totalLatency = totalLatencyInteger . get ( ) ; double totalCostTime = ( exportTime - startTime ) / 1000.0 ; double costTime = ( exportTime - lastExportTime ) / 1000.0 ; double qps = ( totalCount - lastTotalCount ) / costTime ; double latency = ( totalLatency - lastTotalLatency ) * 1.0 / ( totalCount - lastTotalCount ) ; System . out . println ( "Total " + totalCostTime + ", in " + costTime + " seconds, qps: " + qps + ", latency: " + latency + "ms" ) ; lastTotalCount = totalCount ; lastTotalLatency = totalLatency ; lastExportTime = exportTime ; } } } ; t . setDaemon ( true ) ; t . start ( ) ; while ( true ) { try { long start = System . currentTimeMillis ( ) ; currentTimestamp = chronosClient . getTimestamp ( ) ; totalCountInteger . incrementAndGet ( ) ; totalLatencyInteger . addAndGet ( ( int ) ( System . currentTimeMillis ( ) - start ) ) ; if ( currentTimestamp <= previousTimestamp ) { LOG . error ( "Fatal error to get a lower timestamp " + currentTimestamp + "(previous is " + previousTimestamp + "), exit immediately" ) ; System . exit ( 0 ) ; } previousTimestamp = currentTimestamp ; if ( isFailover == true ) { double failoverTime = ( System . currentTimeMillis ( ) - failoverStartTime ) / 1000.0 ; System . out . println ( "After " + failoverStartTimeString + ", the total failover time is " + failoverTime + " seconds" ) ; } isFailover = false ; } catch ( IOException e ) { LOG . error ( "Exception to get timestamp" ) ; if ( isFailover == false ) { failoverStartTime = System . currentTimeMillis ( ) ; failoverStartTimeString = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) . format ( new Date ( failoverStartTime ) ) ; LOG . info ( "Failover occurs at " + failoverStartTimeString ) ; } isFailover = true ; } } }
Benchmark ChronosServer and print metrics in another thread .
30,499
public void set ( long startIndex , long endIndex ) { if ( endIndex <= startIndex ) return ; int startWord = ( int ) ( startIndex >> 6 ) ; int endWord = expandingWordNum ( endIndex - 1 ) ; long startmask = - 1L << startIndex ; long endmask = - 1L >>> - endIndex ; if ( startWord == endWord ) { bits [ startWord ] |= ( startmask & endmask ) ; return ; } bits [ startWord ] |= startmask ; Arrays . fill ( bits , startWord + 1 , endWord , - 1L ) ; bits [ endWord ] |= endmask ; }
Sets a range of bits expanding the set size if necessary