idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
11,300
public static String toHexString ( byte [ ] raw ) { byte [ ] hex = new byte [ 2 * raw . length ] ; int index = 0 ; for ( byte b : raw ) { int v = b & 0x00ff ; hex [ index ++ ] = HEX_CHARS [ v >>> 4 ] ; hex [ index ++ ] = HEX_CHARS [ v & 0xf ] ; } try { return new String ( hex , "ASCII" ) ; } catch ( java . io . UnsupportedEncodingException x ) { throw new RuntimeException ( x . getMessage ( ) , x ) ; } }
Converts an array of bytes into a hexadecimal representation .
11,301
public static String toCamelCase ( String text , char separator , boolean strict ) { char [ ] chars = text . toCharArray ( ) ; int base = 0 , top = 0 ; while ( top < chars . length ) { while ( top < chars . length && chars [ top ] == separator ) { ++ top ; } if ( top < chars . length ) { chars [ base ++ ] = Character . toUpperCase ( chars [ top ++ ] ) ; } if ( strict ) { while ( top < chars . length && chars [ top ] != separator ) { chars [ base ++ ] = Character . toLowerCase ( chars [ top ++ ] ) ; } } else { while ( top < chars . length && chars [ top ] != separator ) { chars [ base ++ ] = chars [ top ++ ] ; } } } return new String ( chars , 0 , base ) ; }
Converts a word sequence into a single camel - case sequence .
11,302
public static String toLowerCamelCase ( String text , char separator ) { char [ ] chars = text . toCharArray ( ) ; int base = 0 , top = 0 ; do { while ( top < chars . length && chars [ top ] != separator ) { chars [ base ++ ] = Character . toLowerCase ( chars [ top ++ ] ) ; } while ( top < chars . length && chars [ top ] == separator ) { ++ top ; } if ( top < chars . length ) { chars [ base ++ ] = Character . toUpperCase ( chars [ top ++ ] ) ; } } while ( top < chars . length ) ; return new String ( chars , 0 , base ) ; }
Converts a word sequence into a single camel - case word that starts with a lowercase letter .
11,303
public static String splitCamelCase ( String text , String separator ) { return CAMEL_REGEX . matcher ( text ) . replaceAll ( separator ) ; }
Splits a single camel - case word into a word sequence .
11,304
public static String hash ( String text ) throws NoSuchAlgorithmException , UnsupportedEncodingException { return Strings . toHexString ( MessageDigest . getInstance ( "SHA" ) . digest ( text . getBytes ( "UTF-8" ) ) ) ; }
Generates a secure hash from a given text .
11,305
public static String extend ( String text , char filler , int length ) { if ( text . length ( ) < length ) { char [ ] buffer = new char [ length ] ; Arrays . fill ( buffer , 0 , length , filler ) ; System . arraycopy ( text . toCharArray ( ) , 0 , buffer , 0 , text . length ( ) ) ; return new String ( buffer ) ; } else { return text ; } }
Extends a string to have at least the given length . If the original string is already as long it is returned without modification .
11,306
public static String substringBefore ( String text , char stopper ) { int p = text . indexOf ( stopper ) ; return p < 0 ? text : text . substring ( 0 , p ) ; }
Returns a substring from position 0 up to just before the stopper character .
11,307
public static String substringAfter ( String text , char match ) { return text . substring ( text . indexOf ( match ) + 1 ) ; }
Returns the substring following a given character or the original if the character is not found .
11,308
public static String join ( Object array , char separator , Object ... pieces ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 , ii = Array . getLength ( array ) ; i < ii ; ++ i ) { Object element = Array . get ( array , i ) ; sb . append ( element != null ? element . toString ( ) : "null" ) . append ( separator ) ; } for ( int i = 0 ; i < pieces . length ; ++ i ) { sb . append ( pieces [ i ] != null ? pieces [ i ] . toString ( ) : "null" ) . append ( separator ) ; } if ( sb . length ( ) > 0 ) sb . setLength ( sb . length ( ) - 1 ) ; return sb . toString ( ) ; }
Concatenates elements in an array into a single String with elements separated by the given separator .
11,309
public static < T > String join ( Iterable < T > iterable , char separator , T ... pieces ) { StringBuilder sb = new StringBuilder ( ) ; for ( T element : iterable ) { sb . append ( element != null ? element . toString ( ) : "null" ) . append ( separator ) ; } for ( int i = 0 ; i < pieces . length ; ++ i ) { sb . append ( pieces [ i ] != null ? pieces [ i ] . toString ( ) : "null" ) . append ( separator ) ; } if ( sb . length ( ) > 0 ) sb . setLength ( sb . length ( ) - 1 ) ; return sb . toString ( ) ; }
Concatenates elements in an Iterable into a single String with elements separated by the given separator .
11,310
public static Class < ? > rawClassOf ( Type type ) { if ( type instanceof Class < ? > ) { return ( Class < ? > ) type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Type rawType = parameterizedType . getRawType ( ) ; return ( Class < ? > ) rawType ; } else if ( type instanceof GenericArrayType ) { Type componentType = ( ( GenericArrayType ) type ) . getGenericComponentType ( ) ; return Array . newInstance ( rawClassOf ( componentType ) , 0 ) . getClass ( ) ; } else if ( type instanceof TypeVariable ) { return Object . class ; } else { throw new IllegalArgumentException ( "Unsupported type " + type . getTypeName ( ) ) ; } }
Returns the raw class of the specified type .
11,311
public static Predicate < Class < ? > > classIs ( final Class < ? > reference ) { return candidate -> candidate != null && candidate . equals ( reference ) ; }
Checks if a candidate class is equal to the specified class .
11,312
public static Predicate < Class < ? > > classIsAssignableFrom ( Class < ? > ancestor ) { return candidate -> candidate != null && ancestor . isAssignableFrom ( candidate ) ; }
Check if a candidate class is assignable to the specified class .
11,313
public static Predicate < Class < ? > > classImplements ( Class < ? > anInterface ) { if ( ! anInterface . isInterface ( ) ) { throw new IllegalArgumentException ( "Class " + anInterface . getName ( ) + " is not an interface" ) ; } return candidate -> candidate != null && ! candidate . isInterface ( ) && anInterface . isAssignableFrom ( candidate ) ; }
Checks if a candidate class is an interface .
11,314
public static < T extends Executable > Predicate < T > executableModifierIs ( final int modifier ) { return candidate -> ( candidate . getModifiers ( ) & modifier ) != 0 ; }
Checks if a candidate class has the specified modifier .
11,315
public static Predicate < Class < ? > > atLeastOneConstructorIsPublic ( ) { return candidate -> candidate != null && Classes . from ( candidate ) . constructors ( ) . anyMatch ( executableModifierIs ( Modifier . PUBLIC ) ) ; }
Checks if a candidate class has at least one public constructor .
11,316
protected int getOffset ( long dt ) { int ret = 0 ; TimeZone tz = DateUtilities . getCurrentTimeZone ( ) ; if ( tz != null ) ret = tz . getOffset ( dt ) ; return ret ; }
Returns the current offset for the given date allowing for daylight savings .
11,317
public static boolean isDeprecated ( Doc doc ) { if ( doc . tags ( "deprecated" ) . length > 0 ) { return true ; } AnnotationDesc [ ] annotationDescList ; if ( doc instanceof PackageDoc ) annotationDescList = ( ( PackageDoc ) doc ) . annotations ( ) ; else annotationDescList = ( ( ProgramElementDoc ) doc ) . annotations ( ) ; for ( int i = 0 ; i < annotationDescList . length ; i ++ ) { if ( annotationDescList [ i ] . annotationType ( ) . qualifiedName ( ) . equals ( java . lang . Deprecated . class . getName ( ) ) ) { return true ; } } return false ; }
Return true if the given Doc is deprecated .
11,318
public static String propertyNameFromMethodName ( Configuration configuration , String name ) { String propertyName = null ; if ( name . startsWith ( "get" ) || name . startsWith ( "set" ) ) { propertyName = name . substring ( 3 ) ; } else if ( name . startsWith ( "is" ) ) { propertyName = name . substring ( 2 ) ; } if ( ( propertyName == null ) || propertyName . isEmpty ( ) ) { return "" ; } return propertyName . substring ( 0 , 1 ) . toLowerCase ( configuration . getLocale ( ) ) + propertyName . substring ( 1 ) ; }
A convenience method to get property name from the name of the getter or setter method .
11,319
public static boolean isJava5DeclarationElementType ( FieldDoc elt ) { return elt . name ( ) . contentEquals ( ElementType . ANNOTATION_TYPE . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . CONSTRUCTOR . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . FIELD . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . LOCAL_VARIABLE . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . METHOD . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . PACKAGE . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . PARAMETER . name ( ) ) || elt . name ( ) . contentEquals ( ElementType . TYPE . name ( ) ) ; }
Test whether the given FieldDoc is one of the declaration annotation ElementTypes defined in Java 5 . Instead of testing for one of the new enum constants added in Java 8 test for the old constants . This prevents bootstrapping problems .
11,320
void normalizeMethod ( JCMethodDecl md , List < JCStatement > initCode , List < TypeCompound > initTAs ) { if ( md . name == names . init && TreeInfo . isInitialConstructor ( md ) ) { List < JCStatement > stats = md . body . stats ; ListBuffer < JCStatement > newstats = new ListBuffer < JCStatement > ( ) ; if ( stats . nonEmpty ( ) ) { while ( TreeInfo . isSyntheticInit ( stats . head ) ) { newstats . append ( stats . head ) ; stats = stats . tail ; } newstats . append ( stats . head ) ; stats = stats . tail ; while ( stats . nonEmpty ( ) && TreeInfo . isSyntheticInit ( stats . head ) ) { newstats . append ( stats . head ) ; stats = stats . tail ; } newstats . appendList ( initCode ) ; while ( stats . nonEmpty ( ) ) { newstats . append ( stats . head ) ; stats = stats . tail ; } } md . body . stats = newstats . toList ( ) ; if ( md . body . endpos == Position . NOPOS ) md . body . endpos = TreeInfo . endPos ( md . body . stats . last ( ) ) ; md . sym . appendUniqueTypeAttributes ( initTAs ) ; } }
Insert instance initializer code into initial constructor .
11,321
void implementInterfaceMethods ( ClassSymbol c , ClassSymbol site ) { for ( List < Type > l = types . interfaces ( c . type ) ; l . nonEmpty ( ) ; l = l . tail ) { ClassSymbol i = ( ClassSymbol ) l . head . tsym ; for ( Scope . Entry e = i . members ( ) . elems ; e != null ; e = e . sibling ) { if ( e . sym . kind == MTH && ( e . sym . flags ( ) & STATIC ) == 0 ) { MethodSymbol absMeth = ( MethodSymbol ) e . sym ; MethodSymbol implMeth = absMeth . binaryImplementation ( site , types ) ; if ( implMeth == null ) addAbstractMethod ( site , absMeth ) ; else if ( ( implMeth . flags ( ) & IPROXY ) != 0 ) adjustAbstractMethod ( site , implMeth , absMeth ) ; } } implementInterfaceMethods ( i , site ) ; } }
Add abstract methods for all methods defined in one of the interfaces of a given class provided they are not already implemented in the class .
11,322
private void addAbstractMethod ( ClassSymbol c , MethodSymbol m ) { MethodSymbol absMeth = new MethodSymbol ( m . flags ( ) | IPROXY | SYNTHETIC , m . name , m . type , c ) ; c . members ( ) . enter ( absMeth ) ; }
Add an abstract methods to a class which implicitly implements a method defined in some interface implemented by the class . These methods are called Miranda methods . Enter the newly created method into its enclosing class scope . Note that it is not entered into the class tree as the emitter doesn t need to see it there to emit an abstract method .
11,323
void makeStringBuffer ( DiagnosticPosition pos ) { code . emitop2 ( new_ , makeRef ( pos , stringBufferType ) ) ; code . emitop0 ( dup ) ; callMethod ( pos , stringBufferType , names . init , List . < Type > nil ( ) , false ) ; }
Make a new string buffer .
11,324
void appendStrings ( JCTree tree ) { tree = TreeInfo . skipParens ( tree ) ; if ( tree . hasTag ( PLUS ) && tree . type . constValue ( ) == null ) { JCBinary op = ( JCBinary ) tree ; if ( op . operator . kind == MTH && ( ( OperatorSymbol ) op . operator ) . opcode == string_add ) { appendStrings ( op . lhs ) ; appendStrings ( op . rhs ) ; return ; } } genExpr ( tree , tree . type ) . load ( ) ; appendString ( tree ) ; }
Add all strings in tree to string buffer .
11,325
void bufferToString ( DiagnosticPosition pos ) { callMethod ( pos , stringBufferType , names . toString , List . < Type > nil ( ) , false ) ; }
Convert string buffer on tos to string .
11,326
public static < E > OptionalFunction < Selection < Element > , E > getValue ( ) { return OptionalFunction . of ( selection -> selection . result ( ) . getValue ( ) ) ; }
Returns a function that gets the value of a selected element .
11,327
public static Consumer < Selection < Element > > setValue ( Object newValue ) { return selection -> selection . result ( ) . setValue ( newValue ) ; }
Returns a function that sets the value of a selected element .
11,328
static public boolean validate ( String id ) { if ( id . equals ( "" ) ) { return false ; } else if ( id . equals ( "." ) || id . equals ( ".." ) ) { return false ; } Matcher matcher = IdUtil . pattern . matcher ( id ) ; return matcher . matches ( ) ; }
Verifies the correctness of an identifier .
11,329
private UiSelector buildSelector ( int selectorId , Object selectorValue ) { if ( selectorId == SELECTOR_CHILD || selectorId == SELECTOR_PARENT ) { throw new UnsupportedOperationException ( ) ; } else { this . mSelectorAttributes . put ( selectorId , selectorValue ) ; } return this ; }
Building a UiSelector always returns a new UiSelector and never modifies the existing UiSelector being used .
11,330
public void get ( String key , UserDataHandler handler ) { if ( cache . containsKey ( key ) ) { try { handler . data ( key , cache . get ( key ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return ; } user . sendGlobal ( "JWWF-storageGet" , "{\"key\":" + Json . escapeString ( key ) + "}" ) ; if ( waitingHandlers . containsKey ( key ) ) { waitingHandlers . get ( key ) . push ( handler ) ; } else { LinkedList < UserDataHandler > ll = new LinkedList < UserDataHandler > ( ) ; ll . push ( handler ) ; waitingHandlers . put ( key , ll ) ; } }
Gets userData string . if data exists in cache the callback is fired immediately if not async request is sent to user . If user don t have requested data empty string will arrive
11,331
public void set ( String key , String value ) { cache . put ( key , value ) ; user . sendGlobal ( "JWWF-storageSet" , "{\"key\":" + Json . escapeString ( key ) + ",\"value\":" + Json . escapeString ( value ) + "}" ) ; }
Sets userData for user data is set in cache and sent to user
11,332
public void setObjects ( Map < String , Object > objects ) { for ( Map . Entry < String , Object > entry : objects . entrySet ( ) ) { js . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } }
Provides objects to the JavaScript engine under various names .
11,333
protected ApplicationContext initializeContext ( ) { Function < Class < Object > , List < Object > > getBeans = this :: getBeans ; BeanFactory beanFactory = new BeanFactory ( getBeans ) ; InitContext context = new InitContext ( ) ; AutoConfigurer . configureInitializers ( ) . forEach ( initializer -> initializer . init ( context , beanFactory ) ) ; List < AbstractReaderWriter > readersWriters = AutoConfigurer . configureReadersWriters ( ) ; ExceptionHandlerInterceptor exceptionHandlerInterceptor = new ExceptionHandlerInterceptor ( ) ; COMMON_INTERCEPTORS . add ( exceptionHandlerInterceptor ) ; Map < Boolean , List < Reader > > readers = createTransformers ( concat ( beanFactory . getAll ( Reader . class ) , context . getReaders ( ) , readersWriters ) ) ; Map < Boolean , List < Writer > > writers = createTransformers ( concat ( beanFactory . getAll ( Writer . class ) , context . getWriters ( ) , readersWriters ) ) ; List < Interceptor > interceptors = sort ( concat ( beanFactory . getAll ( Interceptor . class ) , context . getInterceptors ( ) , COMMON_INTERCEPTORS ) ) ; List < ExceptionConfiguration > handlers = concat ( beanFactory . getAll ( ExceptionConfiguration . class ) , context . getExceptionConfigurations ( ) , COMMON_HANDLERS ) ; List < ControllerConfiguration > controllers = concat ( beanFactory . getAll ( ControllerConfiguration . class ) , context . getControllerConfigurations ( ) ) ; orderDuplicationCheck ( interceptors ) ; Map < Class < ? extends Exception > , InternalExceptionHandler > handlerMap = handlers . stream ( ) . peek ( ExceptionConfiguration :: initialize ) . flatMap ( config -> config . getExceptionHandlers ( ) . stream ( ) ) . peek ( handler -> { populateHandlerWriters ( writers , handler , nonNull ( handler . getResponseType ( ) ) ) ; logExceptionHandler ( handler ) ; } ) . collect ( toMap ( InternalExceptionHandler :: getExceptionClass , identity ( ) ) ) ; context . setExceptionHandlers ( handlerMap ) ; controllers . stream ( ) . peek ( ControllerConfiguration :: initialize ) . flatMap ( config -> config . getRoutes ( ) . stream ( ) ) . peek ( route -> { route . interceptor ( interceptors . toArray ( new Interceptor [ interceptors . size ( ) ] ) ) ; populateRouteReaders ( readers , route ) ; populateRouteWriters ( writers , route ) ; logRoute ( route ) ; } ) . forEach ( context :: addRoute ) ; ApplicationContextImpl applicationContext = new ApplicationContextImpl ( ) ; applicationContext . setRoutes ( context . getRoutes ( ) ) ; applicationContext . setExceptionHandlers ( context . getExceptionHandlers ( ) ) ; exceptionHandlerInterceptor . setApplicationContext ( applicationContext ) ; return applicationContext ; }
Method causes the initialization of the application context using the methods which returns a collection of beans such as
11,334
public synchronized T slow ( Factory < T > p , Object ... args ) throws Exception { T result = _value ; if ( isMissing ( result ) ) { _value = result = p . make ( args ) ; } return result ; }
For performance evaluation only - do not use .
11,335
public void clear ( ) { mPackedAxisBits = 0 ; x = 0 ; y = 0 ; pressure = 0 ; size = 0 ; touchMajor = 0 ; touchMinor = 0 ; toolMajor = 0 ; toolMinor = 0 ; orientation = 0 ; }
Clears the contents of this object . Resets all axes to zero .
11,336
public void copyFrom ( PointerCoords other ) { final long bits = other . mPackedAxisBits ; mPackedAxisBits = bits ; if ( bits != 0 ) { final float [ ] otherValues = other . mPackedAxisValues ; final int count = Long . bitCount ( bits ) ; float [ ] values = mPackedAxisValues ; if ( values == null || count > values . length ) { values = new float [ otherValues . length ] ; mPackedAxisValues = values ; } System . arraycopy ( otherValues , 0 , values , 0 , count ) ; } x = other . x ; y = other . y ; pressure = other . pressure ; size = other . size ; touchMajor = other . touchMajor ; touchMinor = other . touchMinor ; toolMajor = other . toolMajor ; toolMinor = other . toolMinor ; orientation = other . orientation ; }
Copies the contents of another pointer coords object .
11,337
public float getAxisValue ( int axis ) { switch ( axis ) { case AXIS_X : return x ; case AXIS_Y : return y ; case AXIS_PRESSURE : return pressure ; case AXIS_SIZE : return size ; case AXIS_TOUCH_MAJOR : return touchMajor ; case AXIS_TOUCH_MINOR : return touchMinor ; case AXIS_TOOL_MAJOR : return toolMajor ; case AXIS_TOOL_MINOR : return toolMinor ; case AXIS_ORIENTATION : return orientation ; default : { if ( axis < 0 || axis > 63 ) { throw new IllegalArgumentException ( "Axis out of range." ) ; } final long bits = mPackedAxisBits ; final long axisBit = 1L << axis ; if ( ( bits & axisBit ) == 0 ) { return 0 ; } final int index = Long . bitCount ( bits & ( axisBit - 1L ) ) ; return mPackedAxisValues [ index ] ; } } }
Gets the value associated with the specified axis .
11,338
public void setAxisValue ( int axis , float value ) { switch ( axis ) { case AXIS_X : x = value ; break ; case AXIS_Y : y = value ; break ; case AXIS_PRESSURE : pressure = value ; break ; case AXIS_SIZE : size = value ; break ; case AXIS_TOUCH_MAJOR : touchMajor = value ; break ; case AXIS_TOUCH_MINOR : touchMinor = value ; break ; case AXIS_TOOL_MAJOR : toolMajor = value ; break ; case AXIS_TOOL_MINOR : toolMinor = value ; break ; case AXIS_ORIENTATION : orientation = value ; break ; default : { if ( axis < 0 || axis > 63 ) { throw new IllegalArgumentException ( "Axis out of range." ) ; } final long bits = mPackedAxisBits ; final long axisBit = 1L << axis ; final int index = Long . bitCount ( bits & ( axisBit - 1L ) ) ; float [ ] values = mPackedAxisValues ; if ( ( bits & axisBit ) == 0 ) { if ( values == null ) { values = new float [ INITIAL_PACKED_AXIS_VALUES ] ; mPackedAxisValues = values ; } else { final int count = Long . bitCount ( bits ) ; if ( count < values . length ) { if ( index != count ) { System . arraycopy ( values , index , values , index + 1 , count - index ) ; } } else { float [ ] newValues = new float [ count * 2 ] ; System . arraycopy ( values , 0 , newValues , 0 , index ) ; System . arraycopy ( values , index , newValues , index + 1 , count - index ) ; values = newValues ; mPackedAxisValues = values ; } } mPackedAxisBits = bits | axisBit ; } values [ index ] = value ; } } }
Sets the value associated with the specified axis .
11,339
public static Set < String > set ( String ... ss ) { Set < String > set = new HashSet < String > ( ) ; set . addAll ( Arrays . asList ( ss ) ) ; return set ; }
Convenience method to create a set with strings .
11,340
public static ThreadFactory newThreadFactory ( final String format , final boolean daemon ) { final String nameFormat ; if ( ! format . contains ( "%d" ) ) { nameFormat = format + "-%d" ; } else { nameFormat = format ; } return new ThreadFactoryBuilder ( ) . setNameFormat ( nameFormat ) . setDaemon ( daemon ) . build ( ) ; }
Returns a new thread factory that uses the given pattern to set the thread name .
11,341
Tag [ ] tags ( String tagname ) { ListBuffer < Tag > found = new ListBuffer < Tag > ( ) ; String target = tagname ; if ( target . charAt ( 0 ) != '@' ) { target = "@" + target ; } for ( Tag tag : tagList ) { if ( tag . kind ( ) . equals ( target ) ) { found . append ( tag ) ; } } return found . toArray ( new Tag [ found . length ( ) ] ) ; }
Return tags of the specified kind in this comment .
11,342
private ParamTag [ ] paramTags ( boolean typeParams ) { ListBuffer < ParamTag > found = new ListBuffer < ParamTag > ( ) ; for ( Tag next : tagList ) { if ( next instanceof ParamTag ) { ParamTag p = ( ParamTag ) next ; if ( typeParams == p . isTypeParameter ( ) ) { found . append ( p ) ; } } } return found . toArray ( new ParamTag [ found . length ( ) ] ) ; }
Return param tags in this comment . If typeParams is true include only type param tags otherwise include only ordinary param tags .
11,343
SeeTag [ ] seeTags ( ) { ListBuffer < SeeTag > found = new ListBuffer < SeeTag > ( ) ; for ( Tag next : tagList ) { if ( next instanceof SeeTag ) { found . append ( ( SeeTag ) next ) ; } } return found . toArray ( new SeeTag [ found . length ( ) ] ) ; }
Return see also tags in this comment .
11,344
public C get ( String id ) { C container = this . containerMap . get ( id ) ; if ( container != null && ( container . getState ( ) ) . equals ( State . REMOVED ) ) { return null ; } return container ; }
Looks up a Container by its identifier .
11,345
public Collection < C > getAll ( Collection < String > ids ) { Set < C > list = new LinkedHashSet < C > ( ) ; for ( String id : ids ) { C container = get ( id ) ; if ( container != null ) { list . add ( container ) ; } } return list ; }
Looks up a Collection of Containers by their identifiers .
11,346
public static void main ( String argv [ ] ) throws Exception { String idlFile = null ; String pkgName = null ; String outDir = null ; String nsPkgName = null ; boolean allImmutable = false ; List < String > immutableSubstr = new ArrayList < String > ( ) ; for ( int i = 0 ; i < argv . length ; i ++ ) { if ( argv [ i ] . equals ( "-j" ) ) { idlFile = argv [ ++ i ] ; } else if ( argv [ i ] . equals ( "-p" ) ) { pkgName = argv [ ++ i ] ; } else if ( argv [ i ] . equals ( "-o" ) ) { outDir = argv [ ++ i ] ; } else if ( argv [ i ] . equals ( "-b" ) ) { nsPkgName = argv [ ++ i ] ; } else if ( argv [ i ] . equals ( "-s" ) ) { immutableSubstr . add ( argv [ ++ i ] ) ; } else if ( argv [ i ] . equals ( "-i" ) ) { allImmutable = true ; } } if ( isBlank ( idlFile ) || isBlank ( pkgName ) || isBlank ( outDir ) ) { out ( "Usage: java com.bitmechanic.barrister.Idl2Java -j [idl file] -p [Java package prefix] -b [Java package prefix for namespaced entities] -o [out dir] -i -s [immutable class substr]" ) ; System . exit ( 1 ) ; } if ( nsPkgName == null ) { nsPkgName = pkgName ; } new Idl2Java ( idlFile , pkgName , nsPkgName , outDir , allImmutable , immutableSubstr ) ; }
Runs the code generator on the command line .
11,347
public void init ( ) throws ServletException { _application = ( ( ManagedPlatform ) ServicePlatform . getService ( ManagedPlatform . INSTANCE ) . first ) . getName ( ) ; }
Initializes the servlet
11,348
public static ProfileSummaryBuilder getInstance ( Context context , Profile profile , ProfileSummaryWriter profileWriter ) { return new ProfileSummaryBuilder ( context , profile , profileWriter ) ; }
Construct a new ProfileSummaryBuilder .
11,349
public void buildProfileDoc ( XMLNode node , Content contentTree ) throws Exception { contentTree = profileWriter . getProfileHeader ( profile . name ) ; buildChildren ( node , contentTree ) ; profileWriter . addProfileFooter ( contentTree ) ; profileWriter . printDocument ( contentTree ) ; profileWriter . close ( ) ; Util . copyDocFiles ( configuration , DocPaths . profileSummary ( profile . name ) ) ; }
Build the profile documentation .
11,350
public void buildContent ( XMLNode node , Content contentTree ) { Content profileContentTree = profileWriter . getContentHeader ( ) ; buildChildren ( node , profileContentTree ) ; contentTree . addContent ( profileContentTree ) ; }
Build the content for the profile doc .
11,351
public void buildSummary ( XMLNode node , Content profileContentTree ) { Content summaryContentTree = profileWriter . getSummaryHeader ( ) ; buildChildren ( node , summaryContentTree ) ; profileContentTree . addContent ( profileWriter . getSummaryTree ( summaryContentTree ) ) ; }
Build the profile summary .
11,352
public void buildPackageSummary ( XMLNode node , Content summaryContentTree ) { PackageDoc [ ] packages = configuration . profilePackages . get ( profile . name ) ; for ( int i = 0 ; i < packages . length ; i ++ ) { this . pkg = packages [ i ] ; Content packageSummaryContentTree = profileWriter . getPackageSummaryHeader ( this . pkg ) ; buildChildren ( node , packageSummaryContentTree ) ; summaryContentTree . addContent ( profileWriter . getPackageSummaryTree ( packageSummaryContentTree ) ) ; } }
Build the profile package summary .
11,353
public void buildInterfaceSummary ( XMLNode node , Content packageSummaryContentTree ) { String interfaceTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Interface_Summary" ) , configuration . getText ( "doclet.interfaces" ) ) ; String [ ] interfaceTableHeader = new String [ ] { configuration . getText ( "doclet.Interface" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] interfaces = pkg . interfaces ( ) ; if ( interfaces . length > 0 ) { profileWriter . addClassesSummary ( interfaces , configuration . getText ( "doclet.Interface_Summary" ) , interfaceTableSummary , interfaceTableHeader , packageSummaryContentTree ) ; } }
Build the summary for the interfaces in the package .
11,354
public void buildClassSummary ( XMLNode node , Content packageSummaryContentTree ) { String classTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Class_Summary" ) , configuration . getText ( "doclet.classes" ) ) ; String [ ] classTableHeader = new String [ ] { configuration . getText ( "doclet.Class" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] classes = pkg . ordinaryClasses ( ) ; if ( classes . length > 0 ) { profileWriter . addClassesSummary ( classes , configuration . getText ( "doclet.Class_Summary" ) , classTableSummary , classTableHeader , packageSummaryContentTree ) ; } }
Build the summary for the classes in the package .
11,355
public void buildEnumSummary ( XMLNode node , Content packageSummaryContentTree ) { String enumTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Enum_Summary" ) , configuration . getText ( "doclet.enums" ) ) ; String [ ] enumTableHeader = new String [ ] { configuration . getText ( "doclet.Enum" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] enums = pkg . enums ( ) ; if ( enums . length > 0 ) { profileWriter . addClassesSummary ( enums , configuration . getText ( "doclet.Enum_Summary" ) , enumTableSummary , enumTableHeader , packageSummaryContentTree ) ; } }
Build the summary for the enums in the package .
11,356
public void buildExceptionSummary ( XMLNode node , Content packageSummaryContentTree ) { String exceptionTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Exception_Summary" ) , configuration . getText ( "doclet.exceptions" ) ) ; String [ ] exceptionTableHeader = new String [ ] { configuration . getText ( "doclet.Exception" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] exceptions = pkg . exceptions ( ) ; if ( exceptions . length > 0 ) { profileWriter . addClassesSummary ( exceptions , configuration . getText ( "doclet.Exception_Summary" ) , exceptionTableSummary , exceptionTableHeader , packageSummaryContentTree ) ; } }
Build the summary for the exceptions in the package .
11,357
public void buildErrorSummary ( XMLNode node , Content packageSummaryContentTree ) { String errorTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Error_Summary" ) , configuration . getText ( "doclet.errors" ) ) ; String [ ] errorTableHeader = new String [ ] { configuration . getText ( "doclet.Error" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] errors = pkg . errors ( ) ; if ( errors . length > 0 ) { profileWriter . addClassesSummary ( errors , configuration . getText ( "doclet.Error_Summary" ) , errorTableSummary , errorTableHeader , packageSummaryContentTree ) ; } }
Build the summary for the errors in the package .
11,358
public void buildAnnotationTypeSummary ( XMLNode node , Content packageSummaryContentTree ) { String annotationtypeTableSummary = configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Annotation_Types_Summary" ) , configuration . getText ( "doclet.annotationtypes" ) ) ; String [ ] annotationtypeTableHeader = new String [ ] { configuration . getText ( "doclet.AnnotationType" ) , configuration . getText ( "doclet.Description" ) } ; ClassDoc [ ] annotationTypes = pkg . annotationTypes ( ) ; if ( annotationTypes . length > 0 ) { profileWriter . addClassesSummary ( annotationTypes , configuration . getText ( "doclet.Annotation_Types_Summary" ) , annotationtypeTableSummary , annotationtypeTableHeader , packageSummaryContentTree ) ; } }
Build the summary for the annotation type in the package .
11,359
public static < T > T trueOrFalse ( final T trueCase , final T falseCase , final boolean ... flags ) { boolean interlink = true ; if ( flags != null && 0 < flags . length ) { interlink = false ; } for ( int i = 0 ; i < flags . length ; i ++ ) { if ( i == 0 ) { interlink = ! flags [ i ] ; continue ; } interlink &= ! flags [ i ] ; } if ( interlink ) { return falseCase ; } return trueCase ; }
Decides over the given flags if the true - case or the false - case will be return .
11,360
public void add ( Collection < AlertChannel > channels ) { for ( AlertChannel channel : channels ) this . channels . put ( channel . getId ( ) , channel ) ; }
Adds the channel list to the channels for the account .
11,361
void addAllClasses ( ListBuffer < ClassDocImpl > l , boolean filtered ) { try { if ( isSynthetic ( ) ) return ; if ( ! JavadocTool . isValidClassName ( tsym . name . toString ( ) ) ) return ; if ( filtered && ! env . shouldDocument ( tsym ) ) return ; if ( l . contains ( this ) ) return ; l . append ( this ) ; List < ClassDocImpl > more = List . nil ( ) ; for ( Scope . Entry e = tsym . members ( ) . elems ; e != null ; e = e . sibling ) { if ( e . sym != null && e . sym . kind == Kinds . TYP ) { ClassSymbol s = ( ClassSymbol ) e . sym ; ClassDocImpl c = env . getClassDoc ( s ) ; if ( c . isSynthetic ( ) ) continue ; if ( c != null ) more = more . prepend ( c ) ; } } for ( ; more . nonEmpty ( ) ; more = more . tail ) { more . head . addAllClasses ( l , filtered ) ; } } catch ( CompletionFailure e ) { } }
Adds all inner classes of this class and their inner classes recursively to the list l .
11,362
public static long randomLong ( final long min , final long max ) { return Math . round ( Math . random ( ) * ( max - min ) + min ) ; }
Returns a natural long value between given minimum value and max value .
11,363
public static Set < Class < ? > > getAllAnnotatedClasses ( final String packagePath , final Class < ? extends Annotation > annotationClass ) throws ClassNotFoundException , IOException , URISyntaxException { final List < File > directories = ClassExtensions . getDirectoriesFromResources ( packagePath , true ) ; final Set < Class < ? > > classes = new HashSet < > ( ) ; for ( final File directory : directories ) { classes . addAll ( scanForAnnotatedClasses ( directory , packagePath , annotationClass ) ) ; } return classes ; }
Gets all annotated classes that belongs from the given package path and the given annotation class .
11,364
public static Set < Class < ? > > getAllAnnotatedClassesFromSet ( final String packagePath , final Set < Class < ? extends Annotation > > annotationClasses ) throws ClassNotFoundException , IOException , URISyntaxException { final List < File > directories = ClassExtensions . getDirectoriesFromResources ( packagePath , true ) ; final Set < Class < ? > > classes = new HashSet < > ( ) ; for ( final File directory : directories ) { classes . addAll ( scanForAnnotatedClassesFromSet ( directory , packagePath , annotationClasses ) ) ; } return classes ; }
Gets all annotated classes that belongs from the given package path and the given list with annotation classes .
11,365
public static < T extends Annotation > T getAnnotation ( final Class < ? > componentClass , final Class < T > annotationClass ) { T annotation = componentClass . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return annotation ; } for ( final Class < ? > ifc : componentClass . getInterfaces ( ) ) { annotation = getAnnotation ( ifc , annotationClass ) ; if ( annotation != null ) { return annotation ; } } if ( ! Annotation . class . isAssignableFrom ( componentClass ) ) { for ( final Annotation ann : componentClass . getAnnotations ( ) ) { annotation = getAnnotation ( ann . annotationType ( ) , annotationClass ) ; if ( annotation != null ) { return annotation ; } } } final Class < ? > superClass = componentClass . getSuperclass ( ) ; if ( superClass == null || superClass . equals ( Object . class ) ) { return null ; } return getAnnotation ( superClass , annotationClass ) ; }
Search for the given annotationClass in the given componentClass and return it if search was successful .
11,366
public static Set < Class < ? > > scanForClasses ( final File directory , final String packagePath ) throws ClassNotFoundException { return AnnotationExtensions . scanForAnnotatedClasses ( directory , packagePath , null ) ; }
Scan recursive for classes in the given directory .
11,367
@ SuppressWarnings ( "unchecked" ) public static Object setAnnotationValue ( final Annotation annotation , final String key , final Object value ) throws NoSuchFieldException , SecurityException , IllegalArgumentException , IllegalAccessException { final Object invocationHandler = Proxy . getInvocationHandler ( annotation ) ; final Field field = invocationHandler . getClass ( ) . getDeclaredField ( "memberValues" ) ; field . setAccessible ( true ) ; final Map < String , Object > memberValues = ( Map < String , Object > ) field . get ( invocationHandler ) ; final Object oldValue = memberValues . get ( key ) ; if ( oldValue == null || oldValue . getClass ( ) != value . getClass ( ) ) { throw new IllegalArgumentException ( ) ; } memberValues . put ( key , value ) ; return oldValue ; }
Sets the annotation value for the given key of the given annotation to the given new value at runtime .
11,368
public Iterator < S > iterator ( ) { return new Iterator < S > ( ) { Iterator < Map . Entry < String , S > > knownProviders = providers . entrySet ( ) . iterator ( ) ; public boolean hasNext ( ) { if ( knownProviders . hasNext ( ) ) return true ; return lookupIterator . hasNext ( ) ; } public S next ( ) { if ( knownProviders . hasNext ( ) ) return knownProviders . next ( ) . getValue ( ) ; return lookupIterator . next ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Lazily loads the available providers of this loader s service .
11,369
public Function getFunction ( String name ) { for ( Function f : functions ) { if ( f . getName ( ) . equals ( name ) ) return f ; } return null ; }
Returns the Function with the given name or null if none matches .
11,370
public void setContract ( Contract c ) { super . setContract ( c ) ; for ( Function f : functions ) { f . setContract ( c ) ; } }
Sets the Contract this Interface is a part of . Propegates to its Functions
11,371
public static Collector < Triple , ? , Graph > toGraph ( ) { return of ( rdf :: createGraph , Graph :: add , ( left , right ) -> { right . iterate ( ) . forEach ( left :: add ) ; return left ; } , UNORDERED ) ; }
Collect a stream of Triples into a Graph
11,372
public static Collector < Quad , ? , Dataset > toDataset ( ) { return of ( rdf :: createDataset , Dataset :: add , ( left , right ) -> { right . iterate ( ) . forEach ( left :: add ) ; return left ; } , UNORDERED ) ; }
Collect a stream of Quads into a Dataset
11,373
public ContextFactory toCreate ( BiFunction < Constructor , Object [ ] , Object > function ) { return new ContextFactory ( this . context , function ) ; }
Changes the way the objects are created by using the given function .
11,374
public < E > Optional < E > create ( Class < E > type ) { List < Constructor < ? > > constructors = reflect ( ) . constructors ( ) . filter ( declared ( Modifier . PUBLIC ) ) . from ( type ) ; Optional created ; for ( Constructor < ? > constructor : constructors ) { created = tryCreate ( constructor ) ; if ( created . isPresent ( ) ) { return created ; } } return Optional . empty ( ) ; }
Creates a new instance of the given type by looping through its public constructors to find one which all parameters are resolved by the context .
11,375
private Optional tryCreate ( Constructor < ? > constructor ) { Object [ ] args = new Object [ constructor . getParameterCount ( ) ] ; Object arg ; Optional < Object > resolved ; int i = 0 ; for ( Parameter parameter : constructor . getParameters ( ) ) { resolved = context . resolve ( parameter ) ; if ( ! resolved . isPresent ( ) ) { return Optional . empty ( ) ; } arg = resolved . value ( ) ; args [ i ++ ] = arg ; } return Optional . of ( createFunction . apply ( constructor , args ) ) ; }
tries to create the object using the given constructor
11,376
public void reportPublicApi ( ClassSymbol sym ) { if ( sym . sourcefile != null ) { StringBuilder pathb = new StringBuilder ( ) ; StringTokenizer qn = new StringTokenizer ( sym . packge ( ) . toString ( ) , "." ) ; boolean first = true ; while ( qn . hasMoreTokens ( ) ) { String o = qn . nextToken ( ) ; pathb . append ( "/" ) ; pathb . append ( o ) ; first = false ; } pathb . append ( "/" ) ; String path = pathb . toString ( ) ; String p = sym . sourcefile . toUri ( ) . getPath ( ) ; int i = p . lastIndexOf ( "/" ) ; String pp = p . substring ( 0 , i + 1 ) ; if ( path . length ( ) > 0 && ! path . equals ( "/unnamed package/" ) && ! pp . endsWith ( path ) ) { compilerThread . logError ( "Error: The source file " + sym . sourcefile . getName ( ) + " is located in the wrong package directory, because it contains the class " + sym . getQualifiedName ( ) ) ; } } deps . visitPubapi ( sym ) ; }
Collect the public apis of classes supplied explicitly for compilation .
11,377
public void execute ( ) throws MojoExecutionException { getLog ( ) . debug ( "starting packaging" ) ; AbstractConfiguration [ ] configurations = ( AbstractConfiguration [ ] ) getPluginContext ( ) . get ( ConfiguratorMojo . GENERATED_CONFIGURATIONS_KEY ) ; try { for ( AbstractConfiguration configuration : configurations ) { if ( ! ( configuration instanceof NodeConfiguration ) ) { continue ; } String classifier = configuration . className . substring ( configuration . className . lastIndexOf ( '.' ) + 1 ) ; File jarFile = checkJarFile ( classifier ) ; JavaApplicationDescriptor descriptor = getDescriptor ( ) ; descriptor . setNodeConfiguration ( configuration . className ) ; descriptor . setJarFile ( jarFile ) ; File jadFile = getJadFile ( classifier ) ; getDescriptor ( ) . writeDescriptor ( jadFile ) ; getProjectHelper ( ) . attachArtifact ( getProject ( ) , "jad" , classifier , jadFile ) ; } } catch ( IOException ioe ) { throw new MojoExecutionException ( "could not create .jad file" , ioe ) ; } catch ( RuntimeException e ) { throw new MojoExecutionException ( "could not create .jad file" , e ) ; } getLog ( ) . debug ( "finished packaging" ) ; }
Generates the JAD .
11,378
public List < Map < String , Object > > resultSetToMap ( ResultSet rows ) { try { List < Map < String , Object > > beans = new ArrayList < Map < String , Object > > ( ) ; int columnCount = rows . getMetaData ( ) . getColumnCount ( ) ; while ( rows . next ( ) ) { LinkedHashMap < String , Object > bean = new LinkedHashMap < String , Object > ( ) ; beans . add ( bean ) ; for ( int i = 0 ; i < columnCount ; i ++ ) { Object object = rows . getObject ( i + 1 ) ; String columnLabel = rows . getMetaData ( ) . getColumnLabel ( i + 1 ) ; String columnName = rows . getMetaData ( ) . getColumnName ( i + 1 ) ; bean . put ( StringUtils . defaultIfEmpty ( columnLabel , columnName ) , object != null ? object . toString ( ) : "" ) ; } } return beans ; } catch ( Exception ex ) { errors . add ( ex . getMessage ( ) ) ; throw new RuntimeException ( ex ) ; } }
Returns a preparedStatement result into a List of Maps . Not the most efficient way of storing the values however the results should be limited at this stage .
11,379
private JCExpression makeMetafactoryIndyCall ( TranslationContext < ? > context , int refKind , Symbol refSym , List < JCExpression > indy_args ) { JCFunctionalExpression tree = context . tree ; MethodSymbol samSym = ( MethodSymbol ) types . findDescriptorSymbol ( tree . type . tsym ) ; List < Object > staticArgs = List . < Object > of ( typeToMethodType ( samSym . type ) , new Pool . MethodHandle ( refKind , refSym , types ) , typeToMethodType ( tree . getDescriptorType ( types ) ) ) ; ListBuffer < Type > indy_args_types = new ListBuffer < > ( ) ; for ( JCExpression arg : indy_args ) { indy_args_types . append ( arg . type ) ; } MethodType indyType = new MethodType ( indy_args_types . toList ( ) , tree . type , List . < Type > nil ( ) , syms . methodClass ) ; Name metafactoryName = context . needsAltMetafactory ( ) ? names . altMetafactory : names . metafactory ; if ( context . needsAltMetafactory ( ) ) { ListBuffer < Object > markers = new ListBuffer < > ( ) ; for ( Type t : tree . targets . tail ) { if ( t . tsym != syms . serializableType . tsym ) { markers . append ( t . tsym ) ; } } int flags = context . isSerializable ( ) ? FLAG_SERIALIZABLE : 0 ; boolean hasMarkers = markers . nonEmpty ( ) ; boolean hasBridges = context . bridges . nonEmpty ( ) ; if ( hasMarkers ) { flags |= FLAG_MARKERS ; } if ( hasBridges ) { flags |= FLAG_BRIDGES ; } staticArgs = staticArgs . append ( flags ) ; if ( hasMarkers ) { staticArgs = staticArgs . append ( markers . length ( ) ) ; staticArgs = staticArgs . appendList ( markers . toList ( ) ) ; } if ( hasBridges ) { staticArgs = staticArgs . append ( context . bridges . length ( ) - 1 ) ; for ( Symbol s : context . bridges ) { Type s_erasure = s . erasure ( types ) ; if ( ! types . isSameType ( s_erasure , samSym . erasure ( types ) ) ) { staticArgs = staticArgs . append ( s . erasure ( types ) ) ; } } } if ( context . isSerializable ( ) ) { int prevPos = make . pos ; try { make . at ( kInfo . clazz ) ; addDeserializationCase ( refKind , refSym , tree . type , samSym , tree , staticArgs , indyType ) ; } finally { make . at ( prevPos ) ; } } } return makeIndyCall ( tree , syms . lambdaMetafactory , metafactoryName , staticArgs , indyType , indy_args , samSym . name ) ; }
Generate an indy method call to the meta factory
11,380
private JCExpression makeIndyCall ( DiagnosticPosition pos , Type site , Name bsmName , List < Object > staticArgs , MethodType indyType , List < JCExpression > indyArgs , Name methName ) { int prevPos = make . pos ; try { make . at ( pos ) ; List < Type > bsm_staticArgs = List . of ( syms . methodHandleLookupType , syms . stringType , syms . methodTypeType ) . appendList ( bsmStaticArgToTypes ( staticArgs ) ) ; Symbol bsm = rs . resolveInternalMethod ( pos , attrEnv , site , bsmName , bsm_staticArgs , List . < Type > nil ( ) ) ; DynamicMethodSymbol dynSym = new DynamicMethodSymbol ( methName , syms . noSymbol , bsm . isStatic ( ) ? ClassFile . REF_invokeStatic : ClassFile . REF_invokeVirtual , ( MethodSymbol ) bsm , indyType , staticArgs . toArray ( ) ) ; JCFieldAccess qualifier = make . Select ( make . QualIdent ( site . tsym ) , bsmName ) ; qualifier . sym = dynSym ; qualifier . type = indyType . getReturnType ( ) ; JCMethodInvocation proxyCall = make . Apply ( List . < JCExpression > nil ( ) , qualifier , indyArgs ) ; proxyCall . type = indyType . getReturnType ( ) ; return proxyCall ; } finally { make . at ( prevPos ) ; } }
Generate an indy method call with given name type and static bootstrap arguments types
11,381
protected String lookupServerURL ( DataBinder binder ) { _logger . info ( "STANDARD lookupServerURL: servers=" + _servers + ", selector='" + _selector + '\'' ) ; if ( _servers != null ) { if ( _selector != null ) { return _servers . get ( binder . get ( _selector ) ) ; } else if ( _servers . size ( ) == 1 ) { return _servers . values ( ) . iterator ( ) . next ( ) ; } else { return null ; } } else { return null ; } }
Looks up server URL based on request parameters in the data binder .
11,382
public void clean ( ) { log . debug ( "[clean] Cleaning world" ) ; for ( Robot bot : robotsPosition . keySet ( ) ) { bot . die ( "World cleanup" ) ; if ( robotsPosition . containsKey ( bot ) ) { log . warn ( "[clean] Robot did not unregister itself. Removing it" ) ; remove ( bot ) ; } } }
Called to dispose of the world
11,383
public void move ( Robot robot ) { if ( ! robotsPosition . containsKey ( robot ) ) { throw new IllegalArgumentException ( "Robot doesn't exist" ) ; } if ( ! robot . getData ( ) . isMobile ( ) ) { throw new IllegalArgumentException ( "Robot can't move" ) ; } Point newPosition = getReferenceField ( robot , 1 ) ; if ( ! isOccupied ( newPosition ) ) { Point oldPosition = robotsPosition . get ( robot ) ; robotsPosition . put ( robot , newPosition ) ; eventDispatcher . fireEvent ( new RobotMovedEvent ( robot , oldPosition , newPosition ) ) ; } }
Changes the position of a robot to its current reference field
11,384
public Robot getNeighbour ( Robot robot ) { Point neighbourPos = getReferenceField ( robot , 1 ) ; return getRobotAt ( neighbourPos ) ; }
Gets the robot in the reference field
11,385
public ScanResult scan ( Robot robot , int dist ) { Point space = getReferenceField ( robot , dist ) ; Robot inPosition = getRobotAt ( space ) ; ScanResult ret = null ; if ( inPosition == null ) { ret = new ScanResult ( Found . EMPTY , dist ) ; } else { if ( robot . getData ( ) . getTeamId ( ) == inPosition . getData ( ) . getTeamId ( ) ) { ret = new ScanResult ( Found . FRIEND , dist ) ; } else { ret = new ScanResult ( Found . ENEMY , dist ) ; } } return ret ; }
Scans up to a number of fields in front of the robot stopping on the first field that contains a robot
11,386
public int getBotsCount ( int teamId , boolean invert ) { int total = 0 ; for ( Robot bot : robotsPosition . keySet ( ) ) { if ( bot . getData ( ) . getTeamId ( ) == teamId ) { if ( ! invert ) { total ++ ; } } else { if ( invert ) { total ++ ; } } } return total ; }
Get the total number of living robots from or not from a team
11,387
public CompilerThread grabCompilerThread ( ) throws InterruptedException { available . acquire ( ) ; if ( compilers . empty ( ) ) { return new CompilerThread ( this ) ; } return compilers . pop ( ) ; }
Acquire a compiler thread from the pool or block until a thread is available . If the pools is empty create a new thread but never more than is available .
11,388
public void add ( Collection < Server > servers ) { for ( Server server : servers ) this . servers . put ( server . getId ( ) , server ) ; }
Adds the server list to the servers for the account .
11,389
public Symbol resolveIdent ( String name ) { if ( name . equals ( "" ) ) return syms . errSymbol ; JavaFileObject prev = log . useSource ( null ) ; try { JCExpression tree = null ; for ( String s : name . split ( "\\." , - 1 ) ) { if ( ! SourceVersion . isIdentifier ( s ) ) return syms . errSymbol ; tree = ( tree == null ) ? make . Ident ( names . fromString ( s ) ) : make . Select ( tree , names . fromString ( s ) ) ; } JCCompilationUnit toplevel = make . TopLevel ( List . < JCTree . JCAnnotation > nil ( ) , null , List . < JCTree > nil ( ) ) ; toplevel . packge = syms . unnamedPackage ; return attr . attribIdent ( tree , toplevel ) ; } finally { log . useSource ( prev ) ; } }
Resolve an identifier .
11,390
JavaFileObject printSource ( Env < AttrContext > env , JCClassDecl cdef ) throws IOException { JavaFileObject outFile = fileManager . getJavaFileForOutput ( CLASS_OUTPUT , cdef . sym . flatname . toString ( ) , JavaFileObject . Kind . SOURCE , null ) ; if ( inputFiles . contains ( outFile ) ) { log . error ( cdef . pos ( ) , "source.cant.overwrite.input.file" , outFile ) ; return null ; } else { BufferedWriter out = new BufferedWriter ( outFile . openWriter ( ) ) ; try { new Pretty ( out , true ) . printUnit ( env . toplevel , cdef ) ; if ( verbose ) log . printVerbose ( "wrote.file" , outFile ) ; } finally { out . close ( ) ; } return outFile ; } }
Emit plain Java source for a class .
11,391
public List < JCCompilationUnit > enterTreesIfNeeded ( List < JCCompilationUnit > roots ) { if ( shouldStop ( CompileState . ATTR ) ) return List . nil ( ) ; return enterTrees ( roots ) ; }
Enter the symbols found in a list of parse trees if the compilation is expected to proceed beyond anno processing into attr . As a side - effect this puts elements on the todo list . Also stores a list of all top level classes in rootClasses .
11,392
public List < JCCompilationUnit > enterTrees ( List < JCCompilationUnit > roots ) { if ( ! taskListener . isEmpty ( ) ) { for ( JCCompilationUnit unit : roots ) { TaskEvent e = new TaskEvent ( TaskEvent . Kind . ENTER , unit ) ; taskListener . started ( e ) ; } } enter . main ( roots ) ; if ( ! taskListener . isEmpty ( ) ) { for ( JCCompilationUnit unit : roots ) { TaskEvent e = new TaskEvent ( TaskEvent . Kind . ENTER , unit ) ; taskListener . finished ( e ) ; } } if ( needRootClasses || sourceOutput || stubOutput ) { ListBuffer < JCClassDecl > cdefs = new ListBuffer < > ( ) ; for ( JCCompilationUnit unit : roots ) { for ( List < JCTree > defs = unit . defs ; defs . nonEmpty ( ) ; defs = defs . tail ) { if ( defs . head instanceof JCClassDecl ) cdefs . append ( ( JCClassDecl ) defs . head ) ; } } rootClasses = cdefs . toList ( ) ; } for ( JCCompilationUnit unit : roots ) { inputFiles . add ( unit . sourcefile ) ; } return roots ; }
Enter the symbols found in a list of parse trees . As a side - effect this puts elements on the todo list . Also stores a list of all top level classes in rootClasses .
11,393
protected void flow ( Env < AttrContext > env , Queue < Env < AttrContext > > results ) { if ( compileStates . isDone ( env , CompileState . FLOW ) ) { results . add ( env ) ; return ; } try { if ( shouldStop ( CompileState . FLOW ) ) return ; if ( relax ) { results . add ( env ) ; return ; } if ( verboseCompilePolicy ) printNote ( "[flow " + env . enclClass . sym + "]" ) ; JavaFileObject prev = log . useSource ( env . enclClass . sym . sourcefile != null ? env . enclClass . sym . sourcefile : env . toplevel . sourcefile ) ; try { make . at ( Position . FIRSTPOS ) ; TreeMaker localMake = make . forToplevel ( env . toplevel ) ; flow . analyzeTree ( env , localMake ) ; compileStates . put ( env , CompileState . FLOW ) ; if ( shouldStop ( CompileState . FLOW ) ) return ; results . add ( env ) ; } finally { log . useSource ( prev ) ; } } finally { if ( ! taskListener . isEmpty ( ) ) { TaskEvent e = new TaskEvent ( TaskEvent . Kind . ANALYZE , env . toplevel , env . enclClass . sym ) ; taskListener . finished ( e ) ; } } }
Perform dataflow checks on an attributed parse tree .
11,394
public Queue < Pair < Env < AttrContext > , JCClassDecl > > desugar ( Queue < Env < AttrContext > > envs ) { ListBuffer < Pair < Env < AttrContext > , JCClassDecl > > results = new ListBuffer < > ( ) ; for ( Env < AttrContext > env : envs ) desugar ( env , results ) ; return stopIfError ( CompileState . FLOW , results ) ; }
Prepare attributed parse trees in conjunction with their attribution contexts for source or code generation . If any errors occur an empty list will be returned .
11,395
private void setPackages ( DocEnv env , List < String > packages ) { ListBuffer < PackageDocImpl > packlist = new ListBuffer < PackageDocImpl > ( ) ; for ( String name : packages ) { PackageDocImpl pkg = env . lookupPackage ( name ) ; if ( pkg != null ) { pkg . isIncluded = true ; packlist . append ( pkg ) ; } else { env . warning ( null , "main.no_source_files_for_package" , name ) ; } } cmdLinePackages = packlist . toList ( ) ; }
Initialize packages information .
11,396
public ClassDoc [ ] specifiedClasses ( ) { ListBuffer < ClassDocImpl > classesToDocument = new ListBuffer < ClassDocImpl > ( ) ; for ( ClassDocImpl cd : cmdLineClasses ) { cd . addAllClasses ( classesToDocument , true ) ; } return ( ClassDoc [ ] ) classesToDocument . toArray ( new ClassDocImpl [ classesToDocument . length ( ) ] ) ; }
Classes and interfaces specified on the command line .
11,397
@ SuppressWarnings ( "unchecked" ) public Object unmarshal ( Object obj ) throws RpcException { if ( obj == null ) { return returnNullIfOptional ( ) ; } else if ( obj . getClass ( ) != String . class ) { String msg = "'" + obj + "' enum must be String, got: " + obj . getClass ( ) . getSimpleName ( ) ; throw RpcException . Error . INVALID_PARAMS . exc ( msg ) ; } else if ( e . getValues ( ) . contains ( ( String ) obj ) ) { try { Class clz = getTypeClass ( ) ; return java . lang . Enum . valueOf ( clz , ( String ) obj ) ; } catch ( Exception e ) { String msg = "Could not set enum value '" + obj + "' - " + e . getClass ( ) . getSimpleName ( ) + " - " + e . getMessage ( ) ; throw RpcException . Error . INTERNAL . exc ( msg ) ; } } else { String msg = "'" + obj + "' is not in enum: " + e . getValues ( ) ; throw RpcException . Error . INVALID_PARAMS . exc ( msg ) ; } }
Enforces that obj is a String contained in the Enum s values list
11,398
protected boolean loadReport ( ReportsConfig result , InputStream report , String reportName ) { ObjectMapper mapper = new ObjectMapper ( new YAMLFactory ( ) ) ; ReportConfig reportConfig = null ; try { reportConfig = mapper . readValue ( report , ReportConfig . class ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; errors . add ( "Error parsing " + reportName + " " + e . getMessage ( ) ) ; return false ; } reportConfig . setReportId ( reportName ) ; result . getReports ( ) . put ( reportName , reportConfig ) ; return true ; }
Loads a report this does the deserialization this method can be substituted with another called by child classes . Once it has deserialized it it put it into the map .
11,399
public ReportsConfig getReportsConfig ( Collection < String > restrictToNamed ) { resetErrors ( ) ; ReportsConfig result = new ReportsConfig ( ) ; InternalType [ ] reports = getReportList ( ) ; if ( reports == null ) { errors . add ( "No reports found." ) ; return result ; } for ( InternalType report : reports ) { String name = "Unknown" ; final String named = reportToName ( report ) ; if ( restrictToNamed != null && ! restrictToNamed . contains ( named ) ) continue ; try { name = loadReport ( result , report ) ; } catch ( Exception e ) { errors . add ( "Error in report " + named + ": " + e . getMessage ( ) ) ; e . printStackTrace ( ) ; continue ; } } return result ; }
Returns a list of reports in a ReportsConfig - uration object it only loads reports in restrictedToNamed this is useful as a secondary report - restriction mechanism . So you would pass in all reports the user can access .