idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
37,600 | public void invokeMethods ( String queryName , GDATDecoder decoder ) throws InvocationTargetException , IllegalAccessException { for ( MethodInvoker methodInvoker : methodListMap . get ( queryName ) ) { decoder . reset ( ) ; methodInvoker . invoke ( decoder ) ; } } | This function invokes all the methods associated with the provided query name |
37,601 | public Map . Entry < String , GDATDecoder > getNext ( ) { Map . Entry < String , GDATDecoder > element = dataQueue . poll ( ) ; pendingRecords . add ( element ) ; return element ; } | This function returns the next entry in the data queue and adds it to a queue of pending items . This pendingRecords serves as a place holder for all the items of the current transaction . |
37,602 | public String getActualTableName ( QueueName queueName ) { if ( queueName . isQueue ( ) ) { return getTableNameForFlow ( queueName . getFirstComponent ( ) , queueName . getSecondComponent ( ) ) ; } else { throw new IllegalArgumentException ( "'" + queueName + "' is not a valid name for a queue." ) ; } } | This determines the actual table name from the table name prefix and the name of the queue . |
37,603 | public static long generateConsumerGroupId ( String flowId , String flowletId ) { return Hashing . md5 ( ) . newHasher ( ) . putString ( flowId ) . putString ( flowletId ) . hash ( ) . asLong ( ) ; } | Generates a queue consumer groupId for the given flowlet in the given program id . |
37,604 | public static Multimap < String , QueueName > configureQueue ( Program program , FlowSpecification flowSpec , QueueAdmin queueAdmin ) { Table < QueueSpecificationGenerator . Node , String , Set < QueueSpecification > > queueSpecs = new SimpleQueueSpecificationGenerator ( ) . create ( flowSpec ) ; Table < QueueName , Long , Integer > queueConfigs = HashBasedTable . create ( ) ; ImmutableSetMultimap . Builder < String , QueueName > resultBuilder = ImmutableSetMultimap . builder ( ) ; for ( Map . Entry < String , FlowletDefinition > entry : flowSpec . getFlowlets ( ) . entrySet ( ) ) { String flowletId = entry . getKey ( ) ; long groupId = FlowUtils . generateConsumerGroupId ( program , flowletId ) ; int instances = entry . getValue ( ) . getInstances ( ) ; for ( QueueSpecification queueSpec : Iterables . concat ( queueSpecs . column ( flowletId ) . values ( ) ) ) { queueConfigs . put ( queueSpec . getQueueName ( ) , groupId , instances ) ; resultBuilder . put ( flowletId , queueSpec . getQueueName ( ) ) ; } } try { for ( Map . Entry < QueueName , Map < Long , Integer > > row : queueConfigs . rowMap ( ) . entrySet ( ) ) { LOG . info ( "Queue config for {} : {}" , row . getKey ( ) , row . getValue ( ) ) ; queueAdmin . configureGroups ( row . getKey ( ) , row . getValue ( ) ) ; } return resultBuilder . build ( ) ; } catch ( Exception e ) { LOG . error ( "Failed to configure queues" , e ) ; throw Throwables . propagate ( e ) ; } } | Configures all queues being used in a flow . |
37,605 | public void invoke ( Decoder decoder ) throws InvocationTargetException , IllegalAccessException { try { method . invoke ( callingObject , pojoCreator . decode ( decoder ) ) ; } catch ( IOException e ) { LOG . error ( "Skipping invocation of method {}. Cannot instantiate parameter object of type {}" , getMethodName ( ) , methodParameterClass . getName ( ) , e ) ; } } | This method instantiates an object of the method parameter type using the incoming decoder object and then invokes the associated method . |
37,606 | private void writeLengthToStream ( int length , OutputStream out ) throws IOException { sharedByteBuffer . clear ( ) ; sharedByteBuffer . order ( ByteOrder . BIG_ENDIAN ) . putInt ( length ) ; sharedByteBuffer . flip ( ) ; out . write ( sharedByteBuffer . array ( ) , 0 , Ints . BYTES ) ; sharedByteBuffer . order ( byteOrder ) ; } | Write Length in Big Endian Order as per GDAT format specification . |
37,607 | public static QueueName from ( byte [ ] bytes ) { return new QueueName ( URI . create ( new String ( bytes , Charsets . US_ASCII ) ) ) ; } | Constructs this class from byte array of queue URI . |
37,608 | public static QueueName fromStream ( String stream ) { URI uri = URI . create ( String . format ( "stream:///%s" , stream ) ) ; return new QueueName ( uri ) ; } | Generates an QueueName for the stream . |
37,609 | private void generateGetter ( Field field ) { if ( isPrivate ) { invokeReflection ( getMethod ( Object . class , "get" , Object . class ) , getterSignature ( ) ) ; } else { directGetter ( field ) ; } if ( field . getType ( ) . isPrimitive ( ) ) { primitiveGetter ( field ) ; } } | Generates the getter method and optionally the primitive getter . |
37,610 | private void generateSetter ( Field field ) { if ( isPrivate ) { invokeReflection ( getMethod ( void . class , "set" , Object . class , Object . class ) , setterSignature ( ) ) ; } else { directSetter ( field ) ; } if ( field . getType ( ) . isPrimitive ( ) ) { primitiveSetter ( field ) ; } } | Generates the setter method and optionally the primitive setter . |
37,611 | private void invokeReflection ( Method method , String signature ) { GeneratorAdapter mg = new GeneratorAdapter ( Opcodes . ACC_PUBLIC , method , signature , new Type [ 0 ] , classWriter ) ; Label beginTry = mg . newLabel ( ) ; Label endTry = mg . newLabel ( ) ; Label catchHandle = mg . newLabel ( ) ; mg . visitTryCatchBlock ( beginTry , endTry , catchHandle , Type . getInternalName ( IllegalAccessException . class ) ) ; mg . mark ( beginTry ) ; mg . loadThis ( ) ; mg . getField ( Type . getObjectType ( className ) , "field" , Type . getType ( Field . class ) ) ; mg . loadArgs ( ) ; mg . invokeVirtual ( Type . getType ( Field . class ) , method ) ; mg . mark ( endTry ) ; mg . returnValue ( ) ; mg . mark ( catchHandle ) ; int exception = mg . newLocal ( Type . getType ( IllegalAccessException . class ) ) ; mg . storeLocal ( exception ) ; mg . loadLocal ( exception ) ; mg . invokeStatic ( Type . getType ( Throwables . class ) , getMethod ( RuntimeException . class , "propagate" , Throwable . class ) ) ; mg . throwException ( ) ; mg . endMethod ( ) ; } | Generates the try - catch block that wrap around the given reflection method call . |
37,612 | private void directGetter ( Field field ) { GeneratorAdapter mg = new GeneratorAdapter ( Opcodes . ACC_PUBLIC , getMethod ( Object . class , "get" , Object . class ) , getterSignature ( ) , new Type [ 0 ] , classWriter ) ; mg . loadArg ( 0 ) ; mg . checkCast ( Type . getType ( field . getDeclaringClass ( ) ) ) ; mg . getField ( Type . getType ( field . getDeclaringClass ( ) ) , field . getName ( ) , Type . getType ( field . getType ( ) ) ) ; if ( field . getType ( ) . isPrimitive ( ) ) { mg . valueOf ( Type . getType ( field . getType ( ) ) ) ; } mg . returnValue ( ) ; mg . endMethod ( ) ; } | Generates a getter that get the value by directly accessing the class field . |
37,613 | private void directSetter ( Field field ) { GeneratorAdapter mg = new GeneratorAdapter ( Opcodes . ACC_PUBLIC , getMethod ( void . class , "set" , Object . class , Object . class ) , setterSignature ( ) , new Type [ 0 ] , classWriter ) ; mg . loadArg ( 0 ) ; mg . checkCast ( Type . getType ( field . getDeclaringClass ( ) ) ) ; mg . loadArg ( 1 ) ; if ( field . getType ( ) . isPrimitive ( ) ) { mg . unbox ( Type . getType ( field . getType ( ) ) ) ; } else { mg . checkCast ( Type . getType ( field . getType ( ) ) ) ; } mg . putField ( Type . getType ( field . getDeclaringClass ( ) ) , field . getName ( ) , Type . getType ( field . getType ( ) ) ) ; mg . returnValue ( ) ; mg . endMethod ( ) ; } | Generates a setter that set the value by directly accessing the class field . |
37,614 | public TransactionStateCache get ( ) { if ( instance == null ) { synchronized ( lock ) { if ( instance == null ) { instance = new DefaultTransactionStateCache ( namespace ) ; instance . setConf ( conf ) ; instance . start ( ) ; } } } return instance ; } | Returns a singleton instance of the transaction state cache performing lazy initialization if necessary . |
37,615 | private MessageDigest updateHash ( MessageDigest md5 , Schema schema , Set < String > knownRecords ) { switch ( schema . getType ( ) ) { case NULL : md5 . update ( ( byte ) 0 ) ; break ; case BOOLEAN : md5 . update ( ( byte ) 1 ) ; break ; case INT : md5 . update ( ( byte ) 2 ) ; break ; case LONG : md5 . update ( ( byte ) 3 ) ; break ; case FLOAT : md5 . update ( ( byte ) 4 ) ; break ; case DOUBLE : md5 . update ( ( byte ) 5 ) ; break ; case BYTES : md5 . update ( ( byte ) 6 ) ; break ; case STRING : md5 . update ( ( byte ) 7 ) ; break ; case ENUM : md5 . update ( ( byte ) 8 ) ; for ( String value : schema . getEnumValues ( ) ) { md5 . update ( Charsets . UTF_8 . encode ( value ) ) ; } break ; case ARRAY : md5 . update ( ( byte ) 9 ) ; updateHash ( md5 , schema . getComponentSchema ( ) , knownRecords ) ; break ; case MAP : md5 . update ( ( byte ) 10 ) ; updateHash ( md5 , schema . getMapSchema ( ) . getKey ( ) , knownRecords ) ; updateHash ( md5 , schema . getMapSchema ( ) . getValue ( ) , knownRecords ) ; break ; case RECORD : md5 . update ( ( byte ) 11 ) ; boolean notKnown = knownRecords . add ( schema . getRecordName ( ) ) ; for ( Schema . Field field : schema . getFields ( ) ) { md5 . update ( Charsets . UTF_8 . encode ( field . getName ( ) ) ) ; if ( notKnown ) { updateHash ( md5 , field . getSchema ( ) , knownRecords ) ; } } break ; case UNION : md5 . update ( ( byte ) 12 ) ; for ( Schema unionSchema : schema . getUnionSchemas ( ) ) { updateHash ( md5 , unionSchema , knownRecords ) ; } break ; } return md5 ; } | Updates md5 based on the given schema . |
37,616 | private Method getEncodeMethod ( TypeToken < ? > outputType , Schema schema ) { String key = String . format ( "%s%s" , normalizeTypeName ( outputType ) , schema . getSchemaHash ( ) ) ; Method method = encodeMethods . get ( key ) ; if ( method != null ) { return method ; } TypeToken < ? > callOutputType = getCallTypeToken ( outputType , schema ) ; String methodName = String . format ( "encode%s" , key ) ; method = getMethod ( void . class , methodName , callOutputType . getRawType ( ) , Encoder . class , Schema . class , Set . class ) ; encodeMethods . put ( key , method ) ; String methodSignature = Signatures . getMethodSignature ( method , new TypeToken [ ] { callOutputType , null , null , new TypeToken < Set < Object > > ( ) { } } ) ; GeneratorAdapter mg = new GeneratorAdapter ( Opcodes . ACC_PRIVATE , method , methodSignature , new Type [ ] { Type . getType ( IOException . class ) } , classWriter ) ; generateEncodeBody ( mg , schema , outputType , 0 , 1 , 2 , 3 ) ; mg . returnValue ( ) ; mg . endMethod ( ) ; return method ; } | Returns the encode method for the given type and schema . The same method will be returned if the same type and schema has been passed to the method before . |
37,617 | private void generateEncodeBody ( GeneratorAdapter mg , Schema schema , TypeToken < ? > outputType , int value , int encoder , int schemaLocal , int seenRefs ) { Schema . Type schemaType = schema . getType ( ) ; switch ( schemaType ) { case NULL : break ; case BOOLEAN : encodeSimple ( mg , outputType , schema , "writeBool" , value , encoder ) ; break ; case INT : case LONG : case FLOAT : case DOUBLE : case BYTES : case STRING : String encodeMethod = "write" + schemaType . name ( ) . charAt ( 0 ) + schemaType . name ( ) . substring ( 1 ) . toLowerCase ( ) ; encodeSimple ( mg , outputType , schema , encodeMethod , value , encoder ) ; break ; case ENUM : encodeEnum ( mg , outputType , value , encoder , schemaLocal ) ; break ; case ARRAY : if ( Collection . class . isAssignableFrom ( outputType . getRawType ( ) ) ) { Preconditions . checkArgument ( outputType . getType ( ) instanceof ParameterizedType , "Only support parameterized collection type." ) ; TypeToken < ? > componentType = TypeToken . of ( ( ( ParameterizedType ) outputType . getType ( ) ) . getActualTypeArguments ( ) [ 0 ] ) ; encodeCollection ( mg , componentType , schema . getComponentSchema ( ) , value , encoder , schemaLocal , seenRefs ) ; } else if ( outputType . isArray ( ) ) { TypeToken < ? > componentType = outputType . getComponentType ( ) ; encodeArray ( mg , componentType , schema . getComponentSchema ( ) , value , encoder , schemaLocal , seenRefs ) ; } break ; case MAP : Preconditions . checkArgument ( Map . class . isAssignableFrom ( outputType . getRawType ( ) ) , "Only %s type is supported." , Map . class . getName ( ) ) ; Preconditions . checkArgument ( outputType . getType ( ) instanceof ParameterizedType , "Only support parameterized map type." ) ; java . lang . reflect . Type [ ] mapArgs = ( ( ParameterizedType ) outputType . getType ( ) ) . getActualTypeArguments ( ) ; Map . Entry < Schema , Schema > mapSchema = schema . getMapSchema ( ) ; encodeMap ( mg , TypeToken . of ( mapArgs [ 0 ] ) , TypeToken . of ( mapArgs [ 1 ] ) , mapSchema . getKey ( ) , mapSchema . getValue ( ) , value , encoder , schemaLocal , seenRefs ) ; break ; case RECORD : encodeRecord ( mg , schema , outputType , value , encoder , schemaLocal , seenRefs ) ; break ; case UNION : encodeUnion ( mg , outputType , schema , value , encoder , schemaLocal , seenRefs ) ; break ; } } | Generates the encode method body with the binary encoder given in the local variable . |
37,618 | private void encodeInt ( GeneratorAdapter mg , int intValue , int encoder ) { mg . loadArg ( encoder ) ; mg . push ( intValue ) ; mg . invokeInterface ( Type . getType ( Encoder . class ) , getMethod ( Encoder . class , "writeInt" , int . class ) ) ; mg . pop ( ) ; } | Generates method body for encoding an compile time int value . |
37,619 | private void encodeSimple ( GeneratorAdapter mg , TypeToken < ? > type , Schema schema , String encodeMethod , int value , int encoder ) { TypeToken < ? > encodeType = type ; mg . loadArg ( encoder ) ; mg . loadArg ( value ) ; if ( Primitives . isWrapperType ( encodeType . getRawType ( ) ) ) { encodeType = TypeToken . of ( Primitives . unwrap ( encodeType . getRawType ( ) ) ) ; mg . unbox ( Type . getType ( encodeType . getRawType ( ) ) ) ; if ( schema . getType ( ) == Schema . Type . INT && ! int . class . equals ( encodeType . getRawType ( ) ) ) { encodeType = TypeToken . of ( int . class ) ; } } else if ( schema . getType ( ) == Schema . Type . STRING && ! String . class . equals ( encodeType . getRawType ( ) ) ) { mg . invokeVirtual ( Type . getType ( encodeType . getRawType ( ) ) , getMethod ( String . class , "toString" ) ) ; encodeType = TypeToken . of ( String . class ) ; } else if ( schema . getType ( ) == Schema . Type . BYTES && UUID . class . equals ( encodeType . getRawType ( ) ) ) { Type byteBufferType = Type . getType ( ByteBuffer . class ) ; Type uuidType = Type . getType ( UUID . class ) ; mg . push ( Longs . BYTES * 2 ) ; mg . invokeStatic ( byteBufferType , getMethod ( ByteBuffer . class , "allocate" , int . class ) ) ; mg . swap ( ) ; mg . invokeVirtual ( uuidType , getMethod ( long . class , "getMostSignificantBits" ) ) ; mg . invokeVirtual ( byteBufferType , getMethod ( ByteBuffer . class , "putLong" , long . class ) ) ; mg . loadArg ( value ) ; mg . invokeVirtual ( uuidType , getMethod ( long . class , "getLeastSignificantBits" ) ) ; mg . invokeVirtual ( byteBufferType , getMethod ( ByteBuffer . class , "putLong" , long . class ) ) ; mg . invokeVirtual ( Type . getType ( Buffer . class ) , getMethod ( Buffer . class , "flip" ) ) ; mg . checkCast ( byteBufferType ) ; encodeType = TypeToken . of ( ByteBuffer . class ) ; } mg . invokeInterface ( Type . getType ( Encoder . class ) , getMethod ( Encoder . class , encodeMethod , encodeType . getRawType ( ) ) ) ; mg . pop ( ) ; } | Generates method body for encoding simple schema type by calling corresponding write method in Encoder . |
37,620 | private void encodeEnum ( GeneratorAdapter mg , TypeToken < ? > outputType , int value , int encoder , int schemaLocal ) { mg . loadArg ( encoder ) ; mg . loadArg ( schemaLocal ) ; mg . loadArg ( value ) ; mg . invokeVirtual ( Type . getType ( outputType . getRawType ( ) ) , getMethod ( String . class , "name" ) ) ; mg . invokeVirtual ( Type . getType ( Schema . class ) , getMethod ( int . class , "getEnumIndex" , String . class ) ) ; mg . invokeInterface ( Type . getType ( Encoder . class ) , getMethod ( Encoder . class , "writeInt" , int . class ) ) ; mg . pop ( ) ; } | Generates method body for encoding enum value . |
37,621 | private TypeToken < ? > getCallTypeToken ( TypeToken < ? > outputType , Schema schema ) { Schema . Type schemaType = schema . getType ( ) ; if ( schemaType == Schema . Type . RECORD || schemaType == Schema . Type . UNION ) { return TypeToken . of ( Object . class ) ; } if ( schemaType == Schema . Type . ARRAY && outputType . isArray ( ) ) { return getArrayType ( getCallTypeToken ( outputType . getComponentType ( ) , schema . getComponentSchema ( ) ) ) ; } return outputType ; } | Returns the type to be used on the encode method . This is needed to work with private classes that the generated DatumWriter doesn t have access to . |
37,622 | private synchronized void changeInstances ( String flowletId , int newInstanceCount , int oldInstanceCount ) throws Exception { instanceUpdater . update ( flowletId , newInstanceCount , oldInstanceCount ) ; } | Change the number of instances of the running flowlet . Notice that this method needs to be synchronized as change of instances involves multiple steps that need to be completed all at once . |
37,623 | public ImmutableSet < ClassInfo > getTopLevelClasses ( ) { return FluentIterable . from ( resources ) . filter ( ClassInfo . class ) . filter ( IS_TOP_LEVEL ) . toImmutableSet ( ) ; } | Returns all top level classes loadable from the current class path . |
37,624 | private Service createServiceHook ( String flowletName , Iterable < ConsumerSupplier < ? > > consumerSuppliers , AtomicReference < FlowletProgramController > controller ) { final List < String > streams = Lists . newArrayList ( ) ; for ( ConsumerSupplier < ? > consumerSupplier : consumerSuppliers ) { QueueName queueName = consumerSupplier . getQueueName ( ) ; if ( queueName . isStream ( ) ) { streams . add ( queueName . getSimpleName ( ) ) ; } } if ( streams . isEmpty ( ) ) { return new AbstractService ( ) { protected void doStart ( ) { notifyStarted ( ) ; } protected void doStop ( ) { notifyStopped ( ) ; } } ; } return new FlowletServiceHook ( flowletName , streams , controller ) ; } | Create a initializer to be executed during the flowlet driver initialization . |
37,625 | public static Manifest getManifestWithMainClass ( Class < ? > klass ) { Manifest manifest = new Manifest ( ) ; manifest . getMainAttributes ( ) . put ( ManifestFields . MANIFEST_VERSION , "1.0" ) ; manifest . getMainAttributes ( ) . put ( ManifestFields . MAIN_CLASS , klass . getName ( ) ) ; return manifest ; } | Given a class generates a manifest file with main - class as class . |
37,626 | public static Map < String , String > fromPosixArray ( Iterable < String > args ) { Map < String , String > kvMap = Maps . newHashMap ( ) ; for ( String arg : args ) { kvMap . putAll ( Splitter . on ( "--" ) . omitEmptyStrings ( ) . trimResults ( ) . withKeyValueSeparator ( "=" ) . split ( arg ) ) ; } return kvMap ; } | Converts a POSIX compliant program argument array to a String - to - String Map . |
37,627 | public CConfiguration read ( Type type , String namespace ) throws IOException { String tableName = getTableName ( namespace ) ; CConfiguration conf = null ; HTable table = null ; try { table = new HTable ( hbaseConf , tableName ) ; Get get = new Get ( Bytes . toBytes ( type . name ( ) ) ) ; get . addFamily ( FAMILY ) ; Result result = table . get ( get ) ; int propertyCnt = 0 ; if ( result != null && ! result . isEmpty ( ) ) { conf = CConfiguration . create ( ) ; conf . clear ( ) ; Map < byte [ ] , byte [ ] > kvs = result . getFamilyMap ( FAMILY ) ; for ( Map . Entry < byte [ ] , byte [ ] > e : kvs . entrySet ( ) ) { conf . set ( Bytes . toString ( e . getKey ( ) ) , Bytes . toString ( e . getValue ( ) ) ) ; propertyCnt ++ ; } } LOG . info ( "Read " + propertyCnt + " properties from configuration table = " + tableName + ", row = " + type . name ( ) ) ; } catch ( TableNotFoundException e ) { LOG . warn ( "Configuration table " + tableName + " does not yet exist." ) ; } finally { if ( table != null ) { try { table . close ( ) ; } catch ( IOException ioe ) { LOG . error ( "Error closing HTable for " + tableName , ioe ) ; } } } return conf ; } | Reads the given configuration type from the HBase table looking for the HBase table name under the given namespace . |
37,628 | protected final void setSystemTag ( String name , String value ) { systemTags . put ( name , new SystemTagImpl ( name , value ) ) ; } | Sets system tag . |
37,629 | public static int getRandomPort ( ) { try { ServerSocket socket = new ServerSocket ( 0 ) ; try { return socket . getLocalPort ( ) ; } finally { socket . close ( ) ; } } catch ( IOException e ) { return - 1 ; } } | Find a random free port in localhost for binding . |
37,630 | public synchronized void updateCache ( ) { Map < byte [ ] , QueueConsumerConfig > newCache = Maps . newTreeMap ( Bytes . BYTES_COMPARATOR ) ; long now = System . currentTimeMillis ( ) ; HTable table = null ; try { table = new HTable ( hConf , configTableName ) ; Scan scan = new Scan ( ) ; scan . addFamily ( QueueEntryRow . COLUMN_FAMILY ) ; ResultScanner scanner = table . getScanner ( scan ) ; int configCnt = 0 ; for ( Result result : scanner ) { if ( ! result . isEmpty ( ) ) { NavigableMap < byte [ ] , byte [ ] > familyMap = result . getFamilyMap ( QueueEntryRow . COLUMN_FAMILY ) ; if ( familyMap != null ) { configCnt ++ ; Map < ConsumerInstance , byte [ ] > consumerInstances = new HashMap < ConsumerInstance , byte [ ] > ( ) ; int numGroups = 0 ; Long groupId = null ; for ( Map . Entry < byte [ ] , byte [ ] > entry : familyMap . entrySet ( ) ) { long gid = Bytes . toLong ( entry . getKey ( ) ) ; int instanceId = Bytes . toInt ( entry . getKey ( ) , LONG_BYTES ) ; consumerInstances . put ( new ConsumerInstance ( gid , instanceId ) , entry . getValue ( ) ) ; if ( groupId == null || groupId != gid ) { numGroups ++ ; groupId = gid ; } } byte [ ] queueName = result . getRow ( ) ; newCache . put ( queueName , new QueueConsumerConfig ( consumerInstances , numGroups ) ) ; } } } long elapsed = System . currentTimeMillis ( ) - now ; this . configCache = newCache ; this . lastUpdated = now ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Updated consumer config cache with {} entries, took {} msec" , configCnt , elapsed ) ; } } catch ( IOException ioe ) { LOG . warn ( "Error updating queue consumer config cache: {}" , ioe . getMessage ( ) ) ; } finally { if ( table != null ) { try { table . close ( ) ; } catch ( IOException ioe ) { LOG . error ( "Error closing table {}" , Bytes . toString ( configTableName ) , ioe ) ; } } } } | This forces an immediate update of the config cache . It should only be called from the refresh thread or from tests to avoid having to add a sleep for the duration of the refresh interval . |
37,631 | @ SuppressWarnings ( "unchecked" ) private void setValue ( Object instance , Field field , String value ) throws IllegalAccessException { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } Class < ? > fieldType = field . getType ( ) ; if ( String . class . equals ( fieldType ) ) { field . set ( instance , value ) ; return ; } if ( fieldType . isEnum ( ) ) { field . set ( instance , Enum . valueOf ( ( Class < ? extends Enum > ) fieldType , value ) ) ; return ; } if ( fieldType . isPrimitive ( ) ) { fieldType = com . google . common . primitives . Primitives . wrap ( fieldType ) ; } try { field . set ( instance , fieldType . getMethod ( "valueOf" , String . class ) . invoke ( null , value ) ) ; } catch ( NoSuchMethodException e ) { throw Throwables . propagate ( e ) ; } catch ( InvocationTargetException e ) { throw Throwables . propagate ( e ) ; } } | Sets the value of the field in the given instance by converting the value from String to the field type . Currently only allows primitive types boxed types String and Enum . |
37,632 | protected void startUp ( ) { try { startRTS ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Cannot initiate RTS. Missing or bad arguments" ) ; } try { startHFTA ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Cannot initiate HFTA processes. Missing or bad arguments" ) ; } try { startGSEXIT ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Cannot initiate GSEXIT processes. Missing or bad arguments" ) ; } } | Sequentially invokes the required Streaming Engine processes . |
37,633 | public void startRTS ( ) throws IOException { List < HubDataSource > dataSources = hubDataStore . getHubDataSources ( ) ; List < String > com = Lists . newArrayList ( ) ; com . add ( getHostPort ( hubDataStore . getHubAddress ( ) ) ) ; com . add ( hubDataStore . getInstanceName ( ) ) ; for ( HubDataSource source : dataSources ) { com . add ( source . getName ( ) ) ; } ExternalProgramExecutor executorService = new ExternalProgramExecutor ( "RTS" , new File ( binLocation , "rts" ) , com . toArray ( new String [ com . size ( ) ] ) ) ; rtsExecutor . add ( executorService ) ; LOG . info ( "Starting RTS : {}" , executorService ) ; executorService . startAndWait ( ) ; } | Starts RTS process . |
37,634 | public void startHFTA ( ) throws IOException { int hftaCount = MetaInformationParser . getHFTACount ( new File ( this . hubDataStore . getBinaryLocation ( ) . toURI ( ) ) ) ; for ( int i = 0 ; i < hftaCount ; i ++ ) { List < String > com = Lists . newArrayList ( ) ; com . add ( getHostPort ( hubDataStore . getHubAddress ( ) ) ) ; com . add ( hubDataStore . getInstanceName ( ) ) ; ExternalProgramExecutor executorService = new ExternalProgramExecutor ( "HFTA-" + i , new File ( binLocation , "hfta_" + i ) , com . toArray ( new String [ com . size ( ) ] ) ) ; hftaExecutor . add ( executorService ) ; LOG . info ( "Starting HFTA : {}" , executorService ) ; executorService . startAndWait ( ) ; } } | Starts HFTA processes . |
37,635 | public void startGSEXIT ( ) throws IOException { List < HubDataSink > dataSinks = hubDataStore . getHubDataSinks ( ) ; for ( HubDataSink hubDataSink : dataSinks ) { List < String > com = Lists . newArrayList ( ) ; com . add ( getHostPort ( hubDataStore . getHubAddress ( ) ) ) ; com . add ( hubDataStore . getInstanceName ( ) ) ; com . add ( hubDataSink . getFTAName ( ) ) ; com . add ( hubDataSink . getName ( ) ) ; ExternalProgramExecutor executorService = new ExternalProgramExecutor ( "GSEXIT" , new File ( binLocation , "GSEXIT" ) , com . toArray ( new String [ com . size ( ) ] ) ) ; gsExitExecutor . add ( executorService ) ; LOG . info ( "Starting GSEXIT : {}" , executorService ) ; executorService . startAndWait ( ) ; } } | Starts GSEXIT processes . |
37,636 | private String getStringValue ( Object instance , Field field ) throws IllegalAccessException { Class < ? > fieldType = field . getType ( ) ; Preconditions . checkArgument ( fieldType . isPrimitive ( ) || Primitives . isWrapperType ( fieldType ) || String . class . equals ( fieldType ) || fieldType . isEnum ( ) , "Unsupported property type %s of field %s in class %s." , fieldType . getName ( ) , field . getName ( ) , field . getDeclaringClass ( ) . getName ( ) ) ; if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } Object value = field . get ( instance ) ; if ( value == null ) { return null ; } return fieldType . isEnum ( ) ? ( ( Enum < ? > ) value ) . name ( ) : value . toString ( ) ; } | Gets the value of the field in the given instance as String . Currently only allows primitive types boxed types String and Enum . |
37,637 | public static boolean checkSchema ( Set < Schema > output , Set < Schema > input ) { return findSchema ( output , input ) != null ; } | Given two schema s checks if there exists compatibility or equality . |
37,638 | private static byte [ ] serializeEmptyHashKeys ( ) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; Encoder encoder = new BinaryEncoder ( bos ) ; encoder . writeInt ( 0 ) ; return bos . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "encoding empty hash keys went wrong - bailing out: " + e . getMessage ( ) , e ) ; } } | many entries will have no hash keys . Serialize that once and for good |
37,639 | public Encoder writeRaw ( byte [ ] rawBytes , int off , int len ) throws IOException { output . write ( rawBytes , off , len ) ; return this ; } | Writes raw bytes to the buffer without encoding . |
37,640 | private static ClassPath getAPIClassPath ( ) throws IOException { ClassLoader classLoader = Flow . class . getClassLoader ( ) ; String resourceName = Flow . class . getName ( ) . replace ( '.' , '/' ) + ".class" ; URL url = classLoader . getResource ( resourceName ) ; if ( url == null ) { throw new IOException ( "Resource not found for " + resourceName ) ; } try { URI classPathURI = getClassPathURL ( resourceName , url ) . toURI ( ) ; return ClassPath . from ( classPathURI , classLoader ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } } | Gathers all resources for api classes . |
37,641 | private static URL getClassPathURL ( String resourceName , URL resourceURL ) { try { if ( "file" . equals ( resourceURL . getProtocol ( ) ) ) { String path = resourceURL . getFile ( ) ; int endIdx = path . length ( ) - resourceName . length ( ) ; if ( endIdx > 1 ) { endIdx -- ; } return new URL ( "file" , "" , - 1 , path . substring ( 0 , endIdx ) ) ; } if ( "jar" . equals ( resourceURL . getProtocol ( ) ) ) { String path = resourceURL . getFile ( ) ; return URI . create ( path . substring ( 0 , path . indexOf ( "!/" ) ) ) . toURL ( ) ; } } catch ( MalformedURLException e ) { throw Throwables . propagate ( e ) ; } throw new IllegalStateException ( "Unsupported class URL: " + resourceURL ) ; } | Find the classpath that contains the given resource . |
37,642 | private HBaseQueueAdmin ensureTableExists ( QueueName queueName ) throws IOException { HBaseQueueAdmin admin = queueAdmin ; try { if ( ! admin . exists ( queueName ) ) { admin . create ( queueName ) ; } } catch ( Exception e ) { throw new IOException ( "Failed to open table " + admin . getActualTableName ( queueName ) , e ) ; } return admin ; } | Helper method to select the queue or stream admin and to ensure it s table exists . |
37,643 | public static String getSerializedSchema ( String gdatHeader ) { int startBracketIndex = gdatHeader . indexOf ( "{" ) ; startBracketIndex = gdatHeader . indexOf ( "{" , startBracketIndex + 1 ) ; int endBracketIndex = gdatHeader . indexOf ( "}" ) ; Preconditions . checkArgument ( endBracketIndex > startBracketIndex ) ; return gdatHeader . substring ( startBracketIndex + 1 , endBracketIndex ) ; } | Given a gdatHeader extract serialized Schema String . |
37,644 | public static int getHFTACount ( File fileLocation ) { Document qtree = getQTree ( fileLocation ) ; int count ; count = qtree . getElementsByTagName ( "HFTA" ) . getLength ( ) ; return count ; } | This method returns the number of HFTA processes to be instantiated by parsing the qtree . xml file |
37,645 | public Delete delete ( Delete delete ) { delete . deleteColumns ( QueueEntryRow . COLUMN_FAMILY , consumerStateColumn ) ; return delete ; } | Adds a delete of this consumer state to the given Delete object . |
37,646 | public Object decode ( Decoder decoder ) throws IOException { try { return outputGenerator . read ( decoder , schema ) ; } catch ( IOException e ) { LOG . error ( "Cannot instantiate object of type {}" , outputClass . getName ( ) , e ) ; throw e ; } } | This function is called for each incoming byte record . |
37,647 | private Table < String , Integer , ProgramController > createFlowlets ( Program program , RunId runId , FlowSpecification flowSpec ) { Table < String , Integer , ProgramController > flowlets = HashBasedTable . create ( ) ; try { for ( Map . Entry < String , FlowletDefinition > entry : flowSpec . getFlowlets ( ) . entrySet ( ) ) { int instanceCount = entry . getValue ( ) . getInstances ( ) ; for ( int instanceId = 0 ; instanceId < instanceCount ; instanceId ++ ) { flowlets . put ( entry . getKey ( ) , instanceId , startFlowlet ( program , createFlowletOptions ( entry . getKey ( ) , instanceId , instanceCount , runId ) ) ) ; } } } catch ( Throwable t ) { try { Futures . successfulAsList ( Iterables . transform ( flowlets . values ( ) , new Function < ProgramController , ListenableFuture < ? > > ( ) { public ListenableFuture < ? > apply ( ProgramController controller ) { return controller . stop ( ) ; } } ) ) . get ( ) ; } catch ( Exception e ) { LOG . error ( "Fail to stop all flowlets on failure." ) ; } throw Throwables . propagate ( t ) ; } return flowlets ; } | Starts all flowlets in the flow program . |
37,648 | public final void initialize ( FlowletContext ctx ) throws Exception { super . initialize ( ctx ) ; portsAnnouncementList = Lists . newArrayList ( ) ; DefaultInputFlowletConfigurer configurer = new DefaultInputFlowletConfigurer ( this ) ; create ( configurer ) ; InputFlowletSpecification spec = configurer . createInputFlowletSpec ( ) ; dataIngestionPortsMap = Maps . newHashMap ( ) ; int httpPort = 0 ; if ( ctx . getRuntimeArguments ( ) . get ( Constants . HTTP_PORT ) != null ) { httpPort = Integer . parseInt ( ctx . getRuntimeArguments ( ) . get ( Constants . HTTP_PORT ) ) ; } dataIngestionPortsMap . put ( Constants . HTTP_PORT , httpPort ) ; for ( String inputName : spec . getInputSchemas ( ) . keySet ( ) ) { int tcpPort = 0 ; if ( ctx . getRuntimeArguments ( ) . get ( Constants . TCP_INGESTION_PORT_PREFIX + inputName ) != null ) { tcpPort = Integer . parseInt ( ctx . getRuntimeArguments ( ) . get ( Constants . TCP_INGESTION_PORT_PREFIX + inputName ) ) ; } dataIngestionPortsMap . put ( Constants . TCP_INGESTION_PORT_PREFIX + inputName , tcpPort ) ; } tmpFolder = Files . createTempDir ( ) ; File baseDir = new File ( tmpFolder , "baseDir" ) ; baseDir . mkdirs ( ) ; InputFlowletConfiguration inputFlowletConfiguration = new LocalInputFlowletConfiguration ( baseDir , spec ) ; File binDir = inputFlowletConfiguration . createStreamEngineProcesses ( ) ; healthInspector = new HealthInspector ( this ) ; metricsRecorder = new MetricsRecorder ( metrics ) ; recordQueue = new GDATRecordQueue ( ) ; inputFlowletService = new InputFlowletService ( binDir , spec , healthInspector , metricsRecorder , recordQueue , dataIngestionPortsMap , this ) ; inputFlowletService . startAndWait ( ) ; healthInspector . startAndWait ( ) ; Map < String , StreamSchema > schemaMap = MetaInformationParser . getSchemaMap ( new File ( binDir . toURI ( ) ) ) ; methodsDriver = new MethodsDriver ( this , schemaMap ) ; stopwatch = new Stopwatch ( ) ; retryCounter = 0 ; } | This method initializes all the components required to setup the SQL Compiler environment . |
37,649 | @ Tick ( delay = 200L , unit = TimeUnit . MILLISECONDS ) protected void processGDATRecords ( ) throws InvocationTargetException , IllegalAccessException { stopwatch . reset ( ) ; stopwatch . start ( ) ; while ( ! recordQueue . isEmpty ( ) ) { long elapsedTime = stopwatch . elapsedTime ( TimeUnit . SECONDS ) ; if ( elapsedTime >= Constants . TICKER_TIMEOUT ) { break ; } Map . Entry < String , GDATDecoder > record = recordQueue . getNext ( ) ; methodsDriver . invokeMethods ( record . getKey ( ) , record . getValue ( ) ) ; } stopwatch . stop ( ) ; } | This process method consumes the records queued in dataManager and invokes the associated process methods for each output query |
37,650 | public void notifyFailure ( Set < String > errorProcessNames ) { if ( errorProcessNames != null ) { LOG . warn ( "Missing pings from : " + errorProcessNames . toString ( ) ) ; } else { LOG . warn ( "No heartbeats registered" ) ; } healthInspector . stopAndWait ( ) ; healthInspector = new HealthInspector ( this ) ; inputFlowletService . restartService ( healthInspector ) ; healthInspector . startAndWait ( ) ; } | ProcessMonitor callback function Restarts SQL Compiler processes |
37,651 | protected void updateVersionInPreferences ( ) { SharedPreferences sp = PreferenceManager . getDefaultSharedPreferences ( mContext ) ; SharedPreferences . Editor editor = sp . edit ( ) ; editor . putInt ( VERSION_KEY , mCurrentVersionCode ) ; editor . commit ( ) ; } | Write current version code to the preferences . |
37,652 | public List < ReleaseItem > getChangeLog ( boolean full ) { SparseArray < ReleaseItem > masterChangelog = getMasterChangeLog ( full ) ; SparseArray < ReleaseItem > changelog = getLocalizedChangeLog ( full ) ; List < ReleaseItem > mergedChangeLog = new ArrayList < ReleaseItem > ( masterChangelog . size ( ) ) ; for ( int i = 0 , len = masterChangelog . size ( ) ; i < len ; i ++ ) { int key = masterChangelog . keyAt ( i ) ; ReleaseItem release = changelog . get ( key , masterChangelog . get ( key ) ) ; mergedChangeLog . add ( release ) ; } Collections . sort ( mergedChangeLog , getChangeLogComparator ( ) ) ; return mergedChangeLog ; } | Returns the merged change log . |
37,653 | protected final SparseArray < ReleaseItem > readChangeLogFromResource ( int resId , boolean full ) { XmlResourceParser xml = mContext . getResources ( ) . getXml ( resId ) ; try { return readChangeLog ( xml , full ) ; } finally { xml . close ( ) ; } } | Read change log from XML resource file . |
37,654 | protected SparseArray < ReleaseItem > readChangeLog ( XmlPullParser xml , boolean full ) { SparseArray < ReleaseItem > result = new SparseArray < ReleaseItem > ( ) ; try { int eventType = xml . getEventType ( ) ; while ( eventType != XmlPullParser . END_DOCUMENT ) { if ( eventType == XmlPullParser . START_TAG && xml . getName ( ) . equals ( ReleaseTag . NAME ) ) { if ( parseReleaseTag ( xml , full , result ) ) { break ; } } eventType = xml . next ( ) ; } } catch ( XmlPullParserException e ) { Log . e ( LOG_TAG , e . getMessage ( ) , e ) ; } catch ( IOException e ) { Log . e ( LOG_TAG , e . getMessage ( ) , e ) ; } return result ; } | Read the change log from an XML file . |
37,655 | public List < String > orderedGroups ( ) { int groupCount = groupCount ( ) ; List < String > groups = new ArrayList < String > ( groupCount ) ; for ( int i = 1 ; i <= groupCount ; i ++ ) { groups . add ( group ( i ) ) ; } return groups ; } | Gets a list of the matches in the order in which they occur in a matching input string |
37,656 | public String group ( String groupName ) { int idx = groupIndex ( groupName ) ; if ( idx < 0 ) { throw new IndexOutOfBoundsException ( "No group \"" + groupName + "\"" ) ; } return group ( idx ) ; } | Returns the input subsequence captured by the named group during the previous match operation . |
37,657 | public List < Map < String , String > > namedGroups ( ) { List < Map < String , String > > result = new ArrayList < Map < String , String > > ( ) ; List < String > groupNames = parentPattern . groupNames ( ) ; if ( groupNames . isEmpty ( ) ) { return result ; } int nextIndex = 0 ; while ( matcher . find ( nextIndex ) ) { Map < String , String > matches = new LinkedHashMap < String , String > ( ) ; for ( String groupName : groupNames ) { String groupValue = matcher . group ( groupIndex ( groupName ) ) ; matches . put ( groupName , groupValue ) ; nextIndex = matcher . end ( ) ; } result . add ( matches ) ; } return result ; } | Finds all named groups that exist in the input string . This resets the matcher and attempts to match the input against the pre - specified pattern . |
37,658 | public List < String > groupNames ( ) { if ( groupNames == null ) { groupNames = new ArrayList < String > ( groupInfo . keySet ( ) ) ; } return Collections . unmodifiableList ( groupNames ) ; } | Gets the names of all capture groups |
37,659 | private boolean groupInfoMatches ( Map < String , List < GroupInfo > > a , Map < String , List < GroupInfo > > b ) { if ( a == null && b == null ) { return true ; } boolean isMatch = false ; if ( a != null && b != null ) { if ( a . isEmpty ( ) && b . isEmpty ( ) ) { isMatch = true ; } else if ( a . size ( ) == b . size ( ) ) { for ( Entry < String , List < GroupInfo > > entry : a . entrySet ( ) ) { List < GroupInfo > otherList = b . get ( entry . getKey ( ) ) ; isMatch = ( otherList != null ) ; if ( ! isMatch ) { break ; } List < GroupInfo > thisList = entry . getValue ( ) ; isMatch = otherList . containsAll ( thisList ) && thisList . containsAll ( otherList ) ; if ( ! isMatch ) { break ; } } } } return isMatch ; } | Compares the keys and values of two group - info maps |
37,660 | private static double limitHprime ( double hPrime ) { hPrime /= 360.0 ; final double limited = 360.0 * ( hPrime - floor ( hPrime ) ) ; if ( limited < - 180.0 ) { return limited + 360.0 ; } else if ( limited > 180.0 ) { return limited - 360.0 ; } else { return limited ; } } | limit H values according to A . 2 . 11 |
37,661 | public String lookupHttpCrossDomain ( String httpsDomainName ) { Iterator iter = crossDomainMappings . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String httpDomainName = ( String ) iter . next ( ) ; if ( crossDomainMappings . get ( httpDomainName ) . equals ( httpsDomainName ) ) { return httpDomainName ; } } return null ; } | returns the HTTP domain Name |
37,662 | private void badRequest ( HttpServletResponse res ) throws IOException { res . setContentType ( "text/html" ) ; PrintWriter pw = res . getWriter ( ) ; pw . write ( BAD_REQUEST ) ; pw . close ( ) ; } | writes the Bad Request String in the Servlet response if condition falis |
37,663 | public static String getMD5 ( String md5Salt ) { try { MessageDigest md = MessageDigest . getInstance ( MD5 ) ; byte [ ] array = md . digest ( md5Salt . getBytes ( UTF8 ) ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < array . length ; ++ i ) { sb . append ( Integer . toHexString ( ( array [ i ] & 0xFF ) | 0x100 ) . substring ( 1 , 3 ) ) ; } return sb . toString ( ) ; } catch ( java . security . NoSuchAlgorithmException e ) { LOG . error ( e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { LOG . error ( e . getMessage ( ) ) ; } return null ; } | generates the MD5 Hash value from given salt value |
37,664 | public static float compare ( final int numOfBits , final String str1 , final String str2 ) { return compare ( numOfBits , BaseEncoding . base64 ( ) . decode ( str1 ) , BaseEncoding . base64 ( ) . decode ( str2 ) ) ; } | Compare base64 strings for MinHash . |
37,665 | public static float compare ( final int numOfBits , final byte [ ] data1 , final byte [ ] data2 ) { if ( data1 . length != data2 . length ) { return 0 ; } final int count = countSameBits ( data1 , data2 ) ; return ( float ) count / ( float ) numOfBits ; } | Compare bytes for MinHash . |
37,666 | public static HashFunction [ ] createHashFunctions ( final int seed , final int num ) { final HashFunction [ ] hashFunctions = new HashFunction [ num ] ; for ( int i = 0 ; i < num ; i ++ ) { hashFunctions [ i ] = Hashing . murmur3_128 ( seed + i ) ; } return hashFunctions ; } | Create hash functions . |
37,667 | public static String toBinaryString ( final byte [ ] data ) { if ( data == null ) { return null ; } final StringBuilder buf = new StringBuilder ( data . length * 8 ) ; for ( final byte element : data ) { byte bits = element ; for ( int j = 0 ; j < 8 ; j ++ ) { if ( ( bits & 0x80 ) == 0x80 ) { buf . append ( '1' ) ; } else { buf . append ( '0' ) ; } bits <<= 1 ; } } return buf . toString ( ) ; } | Returns a string formatted by bits . |
37,668 | public static int bitCount ( final byte [ ] data ) { int count = 0 ; for ( final byte element : data ) { byte bits = element ; for ( int j = 0 ; j < 8 ; j ++ ) { if ( ( bits & 1 ) == 1 ) { count ++ ; } bits >>= 1 ; } } return count ; } | Count the number of true bits . |
37,669 | public static Analyzer createAnalyzer ( final Tokenizer tokenizer , final int hashBit , final int seed , final int num ) { final HashFunction [ ] hashFunctions = MinHash . createHashFunctions ( seed , num ) ; final Analyzer minhashAnalyzer = new Analyzer ( ) { protected TokenStreamComponents createComponents ( final String fieldName ) { final TokenStream stream = new MinHashTokenFilter ( tokenizer , hashFunctions , hashBit ) ; return new TokenStreamComponents ( tokenizer , stream ) ; } } ; return minhashAnalyzer ; } | Create an analyzer to calculate a minhash . |
37,670 | public static Data newData ( final Analyzer analyzer , final String text , final int numOfBits ) { return new Data ( analyzer , text , numOfBits ) ; } | Create a target data which has analyzer text and the number of bits . |
37,671 | public void defineMethod ( String methodName , int modifiers , String signature , CodeBlock methodBody ) { this . methods . add ( new MethodDefinition ( methodName , modifiers , signature , methodBody ) ) ; } | Defines a new method on the target class |
37,672 | public FieldDefinition defineField ( String fieldName , int modifiers , String signature , Object value ) { FieldDefinition field = new FieldDefinition ( fieldName , modifiers , signature , value ) ; this . fields . add ( field ) ; return field ; } | Defines a new field on the target class |
37,673 | public byte [ ] toBytes ( JDKVersion version ) { ClassNode node = new ClassNode ( ) ; node . version = version . getVer ( ) ; node . access = this . access | ACC_SUPER ; node . name = this . className ; node . superName = this . superClassName ; node . sourceFile = this . sourceFile ; node . sourceDebug = this . sourceDebug ; if ( parentClassName != null ) { node . visitOuterClass ( parentClassName , null , null ) ; } for ( ChildEntry child : childClasses ) { node . visitInnerClass ( child . getClassName ( ) , className , child . getInnerName ( ) , child . getAccess ( ) ) ; } if ( ! this . interfaces . isEmpty ( ) ) { node . interfaces . addAll ( this . interfaces ) ; } for ( MethodDefinition def : methods ) { node . methods . add ( def . getMethodNode ( ) ) ; } for ( FieldDefinition def : fields ) { node . fields . add ( def . getFieldNode ( ) ) ; } if ( node . visibleAnnotations == null ) { node . visibleAnnotations = new ArrayList < AnnotationNode > ( ) ; } for ( VisibleAnnotation a : annotations ) { node . visibleAnnotations . add ( a . getNode ( ) ) ; } ClassWriter cw = new ClassWriter ( ClassWriter . COMPUTE_FRAMES ) ; node . accept ( cw ) ; return cw . toByteArray ( ) ; } | Convert this class representation to JDK bytecode |
37,674 | public CodeBlock frame_same ( final Object ... stackArguments ) { final int type ; switch ( stackArguments . length ) { case 0 : type = Opcodes . F_SAME ; break ; case 1 : type = Opcodes . F_SAME1 ; break ; default : throw new IllegalArgumentException ( "same frame should have 0" + " or 1 arguments on stack" ) ; } instructionList . add ( new FrameNode ( type , 0 , null , stackArguments . length , stackArguments ) ) ; return this ; } | adds a compressed frame to the stack |
37,675 | public void registerServiceConfiguration ( String id , String configFile , DescribeService service ) throws POIProxyException { if ( service == null || configFile == null || service . getId ( ) == null ) { throw new POIProxyException ( "Null service configuration" ) ; } this . registeredConfigurations . put ( id , configFile ) ; this . parsedConfigurations . put ( id , service ) ; try { this . save ( id , configFile ) ; } catch ( IOException e ) { throw new POIProxyException ( "Unable to write service configuration" ) ; } } | Registers a new service into the library |
37,676 | public String getServiceAsJSON ( String id ) { String path = this . registeredConfigurations . get ( id ) ; if ( path == null ) { return null ; } File f = new File ( CONFIGURATION_DIR + File . separator + path ) ; FileInputStream fis = null ; InputStream in = null ; OutputStream out = null ; String res = null ; try { fis = new FileInputStream ( f ) ; in = new BufferedInputStream ( fis , Constants . IO_BUFFER_SIZE ) ; final ByteArrayOutputStream dataStream = new ByteArrayOutputStream ( ) ; out = new BufferedOutputStream ( dataStream , Constants . IO_BUFFER_SIZE ) ; byte [ ] b = new byte [ 8 * 1024 ] ; int read ; while ( ( read = in . read ( b ) ) != - 1 ) { out . write ( b , 0 , read ) ; } out . flush ( ) ; res = new String ( dataStream . toByteArray ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } finally { Constants . closeStream ( fis ) ; Constants . closeStream ( in ) ; Constants . closeStream ( out ) ; } return res ; } | Returns the content of the json document describing a service given its id |
37,677 | static void printClassPath ( ) { URLClassLoader sysLoader = ( URLClassLoader ) ClassLoader . getSystemClassLoader ( ) ; if ( sysLoader == null ) { System . out . println ( "No system class loader. (Maybe means bootstrap class loader is being used?)" ) ; } else { System . out . println ( "Classpath:" ) ; for ( URL url : sysLoader . getURLs ( ) ) { System . out . println ( url . getFile ( ) ) ; } } } | Print the classpath . |
37,678 | public String [ ] parse ( String [ ] args ) throws ArgException { List < String > nonOptions = new ArrayList < > ( ) ; boolean ignoreOptions = false ; String tail = "" ; String arg ; for ( int ii = 0 ; ii < args . length ; ) { if ( tail . length ( ) > 0 ) { arg = tail ; tail = "" ; } else { arg = args [ ii ] ; } if ( arg . equals ( "--" ) ) { ignoreOptions = true ; } else if ( ( arg . startsWith ( "--" ) || arg . startsWith ( "-" ) ) && ! ignoreOptions ) { String argName ; String argValue ; int splitPos = arg . indexOf ( ",-" ) ; if ( splitPos == 0 ) { arg = arg . substring ( 1 ) ; splitPos = arg . indexOf ( ",-" ) ; } if ( splitPos > 0 ) { tail = arg . substring ( splitPos + 1 ) ; arg = arg . substring ( 0 , splitPos ) ; } int eqPos = arg . indexOf ( '=' ) ; if ( eqPos == - 1 ) { argName = arg ; argValue = null ; } else { argName = arg . substring ( 0 , eqPos ) ; argValue = arg . substring ( eqPos + 1 ) ; } OptionInfo oi = nameMap . get ( argName ) ; if ( oi == null ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( String . format ( "unknown option name '%s' in arg '%s'" , argName , arg ) ) ; if ( false ) { msg . append ( "; known options:" ) ; for ( String optionName : sortedKeySet ( nameMap ) ) { msg . append ( " " ) ; msg . append ( optionName ) ; } } throw new ArgException ( msg . toString ( ) ) ; } if ( oi . argumentRequired ( ) && ( argValue == null ) ) { ii ++ ; if ( ii >= args . length ) { throw new ArgException ( "option %s requires an argument" , arg ) ; } argValue = args [ ii ] ; } setArg ( oi , argName , argValue ) ; } else { if ( ! parseAfterArg ) { ignoreOptions = true ; } nonOptions . add ( arg ) ; } if ( tail . length ( ) == 0 ) { ii ++ ; } } String [ ] result = nonOptions . toArray ( new String [ nonOptions . size ( ) ] ) ; return result ; } | Sets option variables from the given command line . |
37,679 | public String [ ] parse ( String message , String [ ] args ) { String [ ] nonOptions = null ; try { nonOptions = parse ( args ) ; } catch ( ArgException ae ) { String exceptionMessage = ae . getMessage ( ) ; if ( exceptionMessage != null ) { System . out . println ( exceptionMessage ) ; } System . out . println ( message ) ; System . exit ( - 1 ) ; } return nonOptions ; } | Sets option variables from the given command line ; if any command - line argument is illegal prints the given message and terminates the program . |
37,680 | public void printUsage ( PrintStream ps ) { hasListOption = false ; if ( usageSynopsis != null ) { ps . printf ( "Usage: %s%n" , usageSynopsis ) ; } ps . println ( usage ( ) ) ; if ( hasListOption ) { ps . println ( ) ; ps . println ( LIST_HELP ) ; } } | Prints usage information to the given PrintStream . Uses the usage synopsis passed into the constructor if any . |
37,681 | public String usage ( boolean showUnpublicized , String ... groupNames ) { if ( ! hasGroups ) { if ( groupNames . length > 0 ) { throw new IllegalArgumentException ( "This instance of Options does not have any option groups defined" ) ; } return formatOptions ( options , maxOptionLength ( options , showUnpublicized ) , showUnpublicized ) ; } List < OptionGroupInfo > groups = new ArrayList < > ( ) ; if ( groupNames . length > 0 ) { for ( String groupName : groupNames ) { if ( ! groupMap . containsKey ( groupName ) ) { throw new IllegalArgumentException ( "invalid option group: " + groupName ) ; } OptionGroupInfo gi = groupMap . get ( groupName ) ; if ( ! showUnpublicized && ! gi . anyPublicized ( ) ) { throw new IllegalArgumentException ( "group does not contain any publicized options: " + groupName ) ; } else { groups . add ( groupMap . get ( groupName ) ) ; } } } else { for ( OptionGroupInfo gi : groupMap . values ( ) ) { if ( ( gi . unpublicized || ! gi . anyPublicized ( ) ) && ! showUnpublicized ) { continue ; } groups . add ( gi ) ; } } List < Integer > lengths = new ArrayList < > ( ) ; for ( OptionGroupInfo gi : groups ) { lengths . add ( maxOptionLength ( gi . optionList , showUnpublicized ) ) ; } int maxLength = Collections . max ( lengths ) ; StringJoiner buf = new StringJoiner ( lineSeparator ) ; for ( OptionGroupInfo gi : groups ) { buf . add ( String . format ( "%n%s:" , gi . name ) ) ; buf . add ( formatOptions ( gi . optionList , maxLength , showUnpublicized ) ) ; } return buf . toString ( ) ; } | Returns a usage message for command - line options . |
37,682 | private int maxOptionLength ( List < OptionInfo > optList , boolean showUnpublicized ) { int maxLength = 0 ; for ( OptionInfo oi : optList ) { if ( oi . unpublicized && ! showUnpublicized ) { continue ; } int len = oi . synopsis ( ) . length ( ) ; if ( len > maxLength ) { maxLength = len ; } } return maxLength ; } | Return the length of the longest synopsis message in a list of options . Useful for aligning options in usage strings . |
37,683 | @ SuppressWarnings ( "nullness" ) private Object getRefArg ( OptionInfo oi , String argName , String argValue ) throws ArgException { Object val ; try { if ( oi . constructor != null ) { val = oi . constructor . newInstance ( new Object [ ] { argValue } ) ; } else if ( oi . baseType . isEnum ( ) ) { @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) Object tmpVal = getEnumValue ( ( Class < Enum > ) oi . baseType , argValue ) ; val = tmpVal ; } else { if ( oi . factory == null ) { throw new Error ( "No constructor or factory for argument " + argName ) ; } if ( oi . factoryArg2 == null ) { val = oi . factory . invoke ( null , argValue ) ; } else { val = oi . factory . invoke ( null , argValue , oi . factoryArg2 ) ; } } } catch ( Exception e ) { throw new ArgException ( "Invalid argument (%s) for argument %s" , argValue , argName ) ; } return val ; } | Given a value string supplied on the command line create an object . The only expected error is some sort of parse error from the constructor . |
37,684 | public String settings ( boolean showUnpublicized ) { StringJoiner out = new StringJoiner ( lineSeparator ) ; int maxLength = maxOptionLength ( options , showUnpublicized ) ; for ( OptionInfo oi : options ) { @ SuppressWarnings ( "formatter" ) String use = String . format ( "%-" + maxLength + "s = " , oi . longName ) ; try { use += oi . field . get ( oi . obj ) ; } catch ( Exception e ) { throw new Error ( "unexpected exception reading field " + oi . field , e ) ; } out . add ( use ) ; } return out . toString ( ) ; } | Returns a string containing the current setting for each option in command - line format that can be parsed by Options . Contains every known option even if the option was not specified on the command line . Never contains duplicates . |
37,685 | public String payload ( int index ) { return payload . size ( ) > index ? payload . get ( index ) : null ; } | Returns a payload at index or null if no payload found there |
37,686 | public static String generateToken ( byte [ ] secret , long seconds , String oid , String ... payload ) { long due = Life . due ( seconds ) ; List < String > l = new ArrayList < String > ( 2 + payload . length ) ; l . add ( oid ) ; l . add ( String . valueOf ( due ) ) ; l . addAll ( C . listOf ( payload ) ) ; String s = S . join ( "|" , l ) ; return Crypto . encryptAES ( s , secret ) ; } | Generate a token string with secret key ID and optionally payloads |
37,687 | @ SuppressWarnings ( "unused" ) public static boolean isTokenValid ( byte [ ] secret , String oid , String token ) { if ( S . anyBlank ( oid , token ) ) { return false ; } String s = Crypto . decryptAES ( token , secret ) ; String [ ] sa = s . split ( "\\|" ) ; if ( sa . length < 2 ) return false ; if ( ! S . isEqual ( oid , sa [ 0 ] ) ) return false ; try { long due = Long . parseLong ( sa [ 1 ] ) ; return ( due < 1 || due > System . currentTimeMillis ( ) ) ; } catch ( Exception e ) { return false ; } } | Check if a string is a valid token |
37,688 | public DescribeService parse ( String json ) { Gson gson = createGSON ( ) ; return gson . fromJson ( json , DescribeService . class ) ; } | Parses a describe service json document passed as a String |
37,689 | public List < List < List < Double > > > getCoordinates ( ) { List < List < List < Double > > > polygon = new ArrayList < List < List < Double > > > ( ) ; for ( LineString lineString : coordinates ) { polygon . add ( lineString . getCoordinates ( ) ) ; } return polygon ; } | Should throw is not a polygon exception |
37,690 | public List < String > getServicesIDByCategory ( String category ) { Set < String > servicesID = services . keySet ( ) ; Iterator < String > it = servicesID . iterator ( ) ; List < String > ids = new ArrayList < String > ( ) ; if ( category == null ) { return ids ; } String key ; while ( it . hasNext ( ) ) { key = it . next ( ) ; DescribeService service = services . get ( key ) ; if ( service . containsCategory ( category ) ) { ids . add ( key ) ; } } return ids ; } | Iterates the list of registered services and for those that support the category passed as a parameter return their ID |
37,691 | public boolean supportsCategory ( String category ) { if ( category == null ) { return false ; } List < String > categories = this . getCategories ( ) ; for ( String cat : categories ) { if ( cat . compareToIgnoreCase ( category ) == 0 ) { return true ; } } return false ; } | Returns true if there is any service registered that supports the category parameter |
37,692 | private Param getQueryParam ( List < Param > optionalParams ) { for ( Param p : optionalParams ) { if ( p == null ) { continue ; } if ( p . getType ( ) . equals ( ParamEnum . QUERY . name ) ) { return p ; } } return null ; } | FIXME Extract the ArrayList to a Class |
37,693 | public static boolean start ( RootDoc root ) { List < Object > objs = new ArrayList < > ( ) ; for ( ClassDoc doc : root . specifiedClasses ( ) ) { if ( doc . containingClass ( ) != null ) { continue ; } Class < ? > clazz ; try { @ SuppressWarnings ( "signature" ) String className = doc . qualifiedName ( ) ; clazz = Class . forName ( className , true , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; Options . printClassPath ( ) ; return false ; } if ( needsInstantiation ( clazz ) ) { try { Constructor < ? > c = clazz . getDeclaredConstructor ( ) ; c . setAccessible ( true ) ; objs . add ( c . newInstance ( new Object [ 0 ] ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return false ; } } else { objs . add ( clazz ) ; } } if ( objs . isEmpty ( ) ) { System . out . println ( "Error: no classes found" ) ; return false ; } Object [ ] objarray = objs . toArray ( ) ; Options options = new Options ( objarray ) ; if ( options . getOptions ( ) . size ( ) < 1 ) { System . out . println ( "Error: no @Option-annotated fields found" ) ; return false ; } OptionsDoclet o = new OptionsDoclet ( root , options ) ; o . setOptions ( root . options ( ) ) ; o . processJavadoc ( ) ; try { o . write ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return false ; } return true ; } | Entry point for the doclet . |
37,694 | public static int optionLength ( String option ) { if ( option . equals ( "-help" ) ) { System . out . printf ( USAGE ) ; return 1 ; } if ( option . equals ( "-i" ) || option . equals ( "-classdoc" ) || option . equals ( "-singledash" ) ) { return 1 ; } if ( option . equals ( "-docfile" ) || option . equals ( "-outfile" ) || option . equals ( "-format" ) || option . equals ( "-d" ) ) { return 2 ; } return 0 ; } | Given a command - line option of this doclet returns the number of arguments you must specify on the command line for the given option . Returns 0 if the argument is not recognized . This method is automatically invoked by Javadoc . |
37,695 | @ SuppressWarnings ( "index" ) public static boolean validOptions ( String [ ] @ MinLen ( 1 ) [ ] options , DocErrorReporter reporter ) { boolean hasDocFile = false ; boolean hasOutFile = false ; boolean hasDestDir = false ; boolean hasFormat = false ; boolean inPlace = false ; String docFile = null ; String outFile = null ; for ( int oi = 0 ; oi < options . length ; oi ++ ) { String [ ] os = options [ oi ] ; String opt = os [ 0 ] . toLowerCase ( ) ; if ( opt . equals ( "-docfile" ) ) { if ( hasDocFile ) { reporter . printError ( "-docfile option specified twice" ) ; return false ; } docFile = os [ 1 ] ; File f = new File ( docFile ) ; if ( ! f . exists ( ) ) { reporter . printError ( "-docfile file not found: " + docFile ) ; return false ; } hasDocFile = true ; } if ( opt . equals ( "-outfile" ) ) { if ( hasOutFile ) { reporter . printError ( "-outfile option specified twice" ) ; return false ; } if ( inPlace ) { reporter . printError ( "-i and -outfile can not be used at the same time" ) ; return false ; } outFile = os [ 1 ] ; hasOutFile = true ; } if ( opt . equals ( "-i" ) ) { if ( hasOutFile ) { reporter . printError ( "-i and -outfile can not be used at the same time" ) ; return false ; } inPlace = true ; } if ( opt . equals ( "-format" ) ) { if ( hasFormat ) { reporter . printError ( "-format option specified twice" ) ; return false ; } String format = os [ 1 ] ; if ( ! format . equals ( "javadoc" ) && ! format . equals ( "html" ) ) { reporter . printError ( "unrecognized output format: " + format ) ; return false ; } hasFormat = true ; } if ( opt . equals ( "-d" ) ) { if ( hasDestDir ) { reporter . printError ( "-d specified twice" ) ; return false ; } hasDestDir = true ; } } if ( docFile != null && outFile != null && outFile . equals ( docFile ) ) { reporter . printError ( "docfile must be different from outfile" ) ; return false ; } if ( inPlace && docFile == null ) { reporter . printError ( "-i supplied but -docfile was not" ) ; return false ; } return true ; } | Tests the validity of command - line arguments passed to this doclet . Returns true if the option usage is valid and false otherwise . This method is automatically invoked by Javadoc . |
37,696 | public void write ( ) throws Exception { PrintWriter out ; String output = output ( ) ; if ( outFile != null ) { out = new PrintWriter ( Files . newBufferedWriter ( outFile . toPath ( ) , UTF_8 ) ) ; } else if ( inPlace ) { assert docFile != null : "@AssumeAssertion(nullness): dependent: docFile is non-null if inPlace is true" ; out = new PrintWriter ( Files . newBufferedWriter ( docFile . toPath ( ) , UTF_8 ) ) ; } else { out = new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( System . out , UTF_8 ) ) ) ; } out . println ( output ) ; out . flush ( ) ; out . close ( ) ; } | Write the output of this doclet to the correct file . |
37,697 | @ RequiresNonNull ( "docFile" ) private String newDocFileText ( ) throws Exception { StringJoiner b = new StringJoiner ( lineSep ) ; BufferedReader doc = Files . newBufferedReader ( docFile . toPath ( ) , UTF_8 ) ; String docline ; boolean replacing = false ; boolean replacedOnce = false ; String prefix = null ; while ( ( docline = doc . readLine ( ) ) != null ) { if ( replacing ) { if ( docline . trim ( ) . equals ( endDelim ) ) { replacing = false ; } else { continue ; } } b . add ( docline ) ; if ( ! replacedOnce && docline . trim ( ) . equals ( startDelim ) ) { if ( formatJavadoc ) { int starIndex = docline . indexOf ( '*' ) ; b . add ( docline . substring ( 0 , starIndex + 1 ) ) ; String jdoc = optionsToJavadoc ( starIndex , 100 ) ; b . add ( jdoc ) ; if ( jdoc . endsWith ( "</ul>" ) ) { b . add ( docline . substring ( 0 , starIndex + 1 ) ) ; } } else { b . add ( optionsToHtml ( 0 ) ) ; } replacedOnce = true ; replacing = true ; } } doc . close ( ) ; return b . toString ( ) ; } | Get the result of inserting the options documentation into the docfile . |
37,698 | public String optionsToHtml ( int refillWidth ) { StringJoiner b = new StringJoiner ( lineSep ) ; if ( includeClassDoc && root . classes ( ) . length > 0 ) { b . add ( OptionsDoclet . javadocToHtml ( root . classes ( ) [ 0 ] ) ) ; b . add ( "<p>Command line options:</p>" ) ; } b . add ( "<ul>" ) ; if ( ! options . hasGroups ( ) ) { b . add ( optionListToHtml ( options . getOptions ( ) , 6 , 2 , refillWidth ) ) ; } else { for ( Options . OptionGroupInfo gi : options . getOptionGroups ( ) ) { if ( ! gi . anyPublicized ( ) ) { continue ; } String ogroupHeader = " <li id=\"optiongroup:" + gi . name . replace ( " " , "-" ) . replace ( "/" , "-" ) + "\">" + gi . name ; b . add ( refill ( ogroupHeader , 6 , 2 , refillWidth ) ) ; b . add ( " <ul>" ) ; b . add ( optionListToHtml ( gi . optionList , 12 , 8 , refillWidth ) ) ; b . add ( " </ul>" ) ; } } b . add ( "</ul>" ) ; for ( Options . OptionInfo oi : options . getOptions ( ) ) { if ( oi . list != null && ! oi . unpublicized ) { b . add ( "" ) ; b . add ( LIST_HELP ) ; break ; } } return b . toString ( ) ; } | Get the HTML documentation for the underlying Options instance . |
37,699 | public String optionsToJavadoc ( int padding , int refillWidth ) { StringJoiner b = new StringJoiner ( lineSep ) ; Scanner s = new Scanner ( optionsToHtml ( refillWidth - padding - 2 ) ) ; while ( s . hasNextLine ( ) ) { String line = s . nextLine ( ) ; StringBuilder bb = new StringBuilder ( ) ; bb . append ( StringUtils . repeat ( " " , padding ) ) ; if ( line . trim ( ) . equals ( "" ) ) { bb . append ( "*" ) ; } else { bb . append ( "* " ) . append ( line ) ; } b . add ( bb ) ; } return b . toString ( ) ; } | Get the HTML documentation for the underlying Options instance formatted as a Javadoc comment . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.