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 ( ...
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 ( "...
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 . ...
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 ...
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 ...
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 ) ; Li...
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 ( toTy...
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 ; w...
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...
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 ...
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 , ...
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 t...
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 )...
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 dere...
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 . cr...
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 ( c...
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 ) ; paramType...
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 ....
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 ) ; stringBuil...
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...
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 ...
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 . s...
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 ( "Atte...
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 ( obj...
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...
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...
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 ...
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 )...
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 ...
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 . ...
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 ...
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 =...
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 +...
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 . setMeth...
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 . ...
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 { tra...
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 ) ; } ca...
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 ( ) ) { ...
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 Except...
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 ( "Ex...
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 server...
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...
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_Z...
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 == connectRe...
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 " + newTi...
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 { ...
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 IOExceptio...
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 ) ; bre...
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 m...
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...
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" ) ; ZooKeeperU...
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 >= chronosServer...
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 ....
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 ( "Ge...
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 ti...
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 + " seco...
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 ] |= ( st...
Sets a range of bits expanding the set size if necessary