idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,400 | public Map < String , Collection < String > > queries ( ) { Map < String , Collection < String > > queryMap = new LinkedHashMap < > ( ) ; this . queries . forEach ( ( key , queryTemplate ) -> { List < String > values = new ArrayList < > ( queryTemplate . getValues ( ) ) ; queryMap . put ( key , Collections . unmodifiableList ( values ) ) ; } ) ; return Collections . unmodifiableMap ( queryMap ) ; } | Return an immutable Map of all Query Parameters and their values . |
21,401 | public RequestTemplate header ( String name , Iterable < String > values ) { if ( name == null || name . isEmpty ( ) ) { throw new IllegalArgumentException ( "name is required." ) ; } if ( values == null ) { values = Collections . emptyList ( ) ; } return appendHeader ( name , values ) ; } | Specify a Header with the specified values . Values can be literals or template expressions . |
21,402 | private RequestTemplate appendHeader ( String name , Iterable < String > values ) { if ( ! values . iterator ( ) . hasNext ( ) ) { this . headers . remove ( name ) ; return this ; } this . headers . compute ( name , ( headerName , headerTemplate ) -> { if ( headerTemplate == null ) { return HeaderTemplate . create ( headerName , values ) ; } else { return HeaderTemplate . append ( headerTemplate , values ) ; } } ) ; return this ; } | Create a Header Template . |
21,403 | public RequestTemplate headers ( Map < String , Collection < String > > headers ) { if ( headers != null && ! headers . isEmpty ( ) ) { headers . forEach ( this :: header ) ; } else { this . headers . clear ( ) ; } return this ; } | Headers for this Request . |
21,404 | public Map < String , Collection < String > > headers ( ) { Map < String , Collection < String > > headerMap = new TreeMap < > ( String . CASE_INSENSITIVE_ORDER ) ; this . headers . forEach ( ( key , headerTemplate ) -> { List < String > values = new ArrayList < > ( headerTemplate . getValues ( ) ) ; if ( ! values . isEmpty ( ) ) { headerMap . put ( key , Collections . unmodifiableList ( values ) ) ; } } ) ; return Collections . unmodifiableMap ( headerMap ) ; } | Returns an immutable copy of the Headers for this request . |
21,405 | public RequestTemplate body ( byte [ ] bodyData , Charset charset ) { this . body ( Request . Body . encoded ( bodyData , charset ) ) ; return this ; } | Sets the Body and Charset for this request . |
21,406 | public RequestTemplate body ( String bodyText ) { byte [ ] bodyData = bodyText != null ? bodyText . getBytes ( UTF_8 ) : null ; return body ( bodyData , UTF_8 ) ; } | Set the Body for this request . Charset is assumed to be UTF_8 . Data must be encoded . |
21,407 | public RequestTemplate body ( Request . Body body ) { this . body = body ; header ( CONTENT_LENGTH ) ; if ( body . length ( ) > 0 ) { header ( CONTENT_LENGTH , String . valueOf ( body . length ( ) ) ) ; } return this ; } | Set the Body for this request . |
21,408 | public RequestTemplate bodyTemplate ( String bodyTemplate ) { this . body ( Request . Body . bodyTemplate ( bodyTemplate , Util . UTF_8 ) ) ; return this ; } | Specify the Body Template to use . Can contain literals and expressions . |
21,409 | public Collection < String > getRequestVariables ( ) { final Collection < String > variables = new LinkedHashSet < > ( this . uriTemplate . getVariables ( ) ) ; this . queries . values ( ) . forEach ( queryTemplate -> variables . addAll ( queryTemplate . getVariables ( ) ) ) ; this . headers . values ( ) . forEach ( headerTemplate -> variables . addAll ( headerTemplate . getVariables ( ) ) ) ; return variables ; } | Retrieve all uri header and query template variables . |
21,410 | public String queryLine ( ) { StringBuilder queryString = new StringBuilder ( ) ; if ( ! this . queries . isEmpty ( ) ) { Iterator < QueryTemplate > iterator = this . queries . values ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { QueryTemplate queryTemplate = iterator . next ( ) ; String query = queryTemplate . toString ( ) ; if ( query != null && ! query . isEmpty ( ) ) { queryString . append ( query ) ; if ( iterator . hasNext ( ) ) { queryString . append ( "&" ) ; } } } } String result = queryString . toString ( ) ; if ( result . endsWith ( "&" ) ) { result = result . substring ( 0 , result . length ( ) - 1 ) ; } if ( ! result . isEmpty ( ) ) { result = "?" + result ; } return result ; } | The Query String for the template . Expressions are not resolved . |
21,411 | public static QueryTemplate append ( QueryTemplate queryTemplate , Iterable < String > values , CollectionFormat collectionFormat ) { List < String > queryValues = new ArrayList < > ( queryTemplate . getValues ( ) ) ; queryValues . addAll ( StreamSupport . stream ( values . spliterator ( ) , false ) . filter ( Util :: isNotBlank ) . collect ( Collectors . toList ( ) ) ) ; return create ( queryTemplate . getName ( ) , queryValues , queryTemplate . getCharset ( ) , collectionFormat ) ; } | Append a value to the Query Template . |
21,412 | public String expand ( Map < String , ? > variables ) { String name = this . name . expand ( variables ) ; return this . queryString ( name , super . expand ( variables ) ) ; } | Expand this template . Unresolved variables are removed . If all values remain unresolved the result is an empty string . |
21,413 | private void preloadContextCache ( List < Class < ? > > classes ) throws JAXBException { if ( classes != null && ! classes . isEmpty ( ) ) { for ( Class < ? > clazz : classes ) { getContext ( clazz ) ; } } } | Will preload factory s cache with JAXBContext for provided classes |
21,414 | public static < T > Collection < T > valuesOrEmpty ( Map < String , Collection < T > > map , String key ) { return map . containsKey ( key ) && map . get ( key ) != null ? map . get ( key ) : Collections . < T > emptyList ( ) ; } | Returns an unmodifiable collection which may be empty but is never null . |
21,415 | public static Object emptyValueOf ( Type type ) { return EMPTIES . getOrDefault ( Types . getRawType ( type ) , ( ) -> null ) . get ( ) ; } | This returns well known empty values for well - known java types . This returns null for types not in the following list . |
21,416 | public Response buildAndQuery_fake ( ) { return Feign . builder ( ) . client ( fakeClient ) . target ( FeignTestInterface . class , "http://localhost" ) . query ( ) ; } | How fast is creating a feign instance for each http request without considering network? |
21,417 | public Response buildAndQuery_fake_cachedContract ( ) { return Feign . builder ( ) . contract ( cachedContact ) . client ( fakeClient ) . target ( FeignTestInterface . class , "http://localhost" ) . query ( ) ; } | How fast is creating a feign instance for each http request without considering network and without re - parsing the annotated http api? |
21,418 | public okhttp3 . Response query_baseCaseUsingOkHttp ( ) throws IOException { okhttp3 . Response result = client . newCall ( queryRequest ) . execute ( ) ; result . body ( ) . close ( ) ; return result ; } | How fast can we execute get commands synchronously? |
21,419 | static Map < Method , Method > toFallbackMethod ( Map < Method , MethodHandler > dispatch ) { Map < Method , Method > result = new LinkedHashMap < Method , Method > ( ) ; for ( Method method : dispatch . keySet ( ) ) { method . setAccessible ( true ) ; result . put ( method , method ) ; } return result ; } | If the method param of InvocationHandler . invoke is not accessible i . e in a package - private interface the fallback call in hystrix command will fail cause of access restrictions . But methods in dispatch are copied methods . So setting access to dispatch method doesn t take effect to the method in InvocationHandler . invoke . Use map to store a copy of method to invoke the fallback to bypass this and reducing the count of reflection calls . |
21,420 | static Map < Method , Setter > toSetters ( SetterFactory setterFactory , Target < ? > target , Set < Method > methods ) { Map < Method , Setter > result = new LinkedHashMap < Method , Setter > ( ) ; for ( Method method : methods ) { method . setAccessible ( true ) ; result . put ( method , setterFactory . create ( target , method ) ) ; } return result ; } | Process all methods in the target so that appropriate setters are created . |
21,421 | public void shutdownClusterMonitors ( ) { for ( String clusterName : clustersProvider . getClusterNames ( ) ) { ClusterMonitor < AggDataFromCluster > clusterMonitor = ( ClusterMonitor < AggDataFromCluster > ) AggregateClusterMonitor . findOrRegisterAggregateMonitor ( clusterName ) ; clusterMonitor . stopMonitor ( ) ; clusterMonitor . getDispatcher ( ) . stopDispatcher ( ) ; } } | shutdown all configured cluster monitors . |
21,422 | public < C extends IClient < ? , ? > > C getClient ( String name , Class < C > clientClass ) { return getInstance ( name , clientClass ) ; } | Get the rest client associated with the name . |
21,423 | protected void destroyEurekaServerContext ( ) throws Exception { EurekaMonitors . shutdown ( ) ; if ( this . awsBinder != null ) { this . awsBinder . shutdown ( ) ; } if ( this . serverContext != null ) { this . serverContext . shutdown ( ) ; } } | Server context shutdown hook . Override for custom logic |
21,424 | public Collection < Instance > getInstanceList ( ) throws Exception { List < Instance > instances = new ArrayList < > ( ) ; List < String > appNames = getApplications ( ) ; if ( appNames == null || appNames . size ( ) == 0 ) { log . info ( "No apps configured, returning an empty instance list" ) ; return instances ; } log . info ( "Fetching instance list for apps: " + appNames ) ; for ( String appName : appNames ) { try { instances . addAll ( getInstancesForApp ( appName ) ) ; } catch ( Exception ex ) { log . error ( "Failed to fetch instances for app: " + appName + ", retrying once more" , ex ) ; try { instances . addAll ( getInstancesForApp ( appName ) ) ; } catch ( Exception retryException ) { log . error ( "Failed again to fetch instances for app: " + appName + ", giving up" , ex ) ; } } } return instances ; } | Method that queries DiscoveryClient for a list of configured application names . |
21,425 | protected List < Instance > getInstancesForApp ( String serviceId ) throws Exception { List < Instance > instances = new ArrayList < > ( ) ; log . info ( "Fetching instances for app: " + serviceId ) ; List < ServiceInstance > serviceInstances = discoveryClient . getInstances ( serviceId ) ; if ( serviceInstances == null || serviceInstances . isEmpty ( ) ) { log . warn ( "DiscoveryClient returned null or empty for service: " + serviceId ) ; return instances ; } try { log . info ( "Received instance list for service: " + serviceId + ", size=" + serviceInstances . size ( ) ) ; for ( ServiceInstance serviceInstance : serviceInstances ) { Instance instance = marshall ( serviceInstance ) ; if ( instance != null ) { instances . add ( instance ) ; } } } catch ( Exception e ) { log . warn ( "Failed to retrieve instances from DiscoveryClient" , e ) ; } return instances ; } | helper that fetches the Instances for each application from DiscoveryClient . |
21,426 | Instance marshall ( ServiceInstance serviceInstance ) { String hostname = serviceInstance . getHost ( ) ; String managementPort = serviceInstance . getMetadata ( ) . get ( "management.port" ) ; String port = managementPort == null ? String . valueOf ( serviceInstance . getPort ( ) ) : managementPort ; String cluster = getClusterName ( serviceInstance ) ; Boolean status = Boolean . TRUE ; if ( hostname != null && cluster != null && status != null ) { Instance instance = getInstance ( hostname , port , cluster , status ) ; Map < String , String > metadata = serviceInstance . getMetadata ( ) ; boolean securePortEnabled = serviceInstance . isSecure ( ) ; addMetadata ( instance , hostname , port , securePortEnabled , port , metadata ) ; return instance ; } else { return null ; } } | Private helper that marshals the information from each instance into something that Turbine can understand . Override this method for your own implementation . |
21,427 | protected String getClusterName ( Object object ) { StandardEvaluationContext context = new StandardEvaluationContext ( object ) ; Object value = this . clusterNameExpression . getValue ( context ) ; if ( value != null ) { return value . toString ( ) ; } return null ; } | Helper that fetches the cluster name . Cluster is a Turbine concept and not a commons concept . By default we choose the amazon serviceId as the cluster . A custom implementation can be plugged in by overriding this method . |
21,428 | public static String extractApproximateZone ( String host ) { String [ ] split = StringUtils . split ( host , "." ) ; return split == null ? host : split [ 1 ] ; } | Approximates Eureka zones from a host name . This method approximates the zone to be everything after the first . in the host name . |
21,429 | public ServerWebExchangeLimiterBuilder partitionByHeader ( String name ) { return partitionResolver ( exchange -> exchange . getRequest ( ) . getHeaders ( ) . getFirst ( name ) ) ; } | Partition the limit by header . |
21,430 | public ServerWebExchangeLimiterBuilder partitionByParameter ( String name ) { return partitionResolver ( exchange -> exchange . getRequest ( ) . getQueryParams ( ) . getFirst ( name ) ) ; } | Partition the limit by request parameter . |
21,431 | public FilterRegistrationBean jerseyFilterRegistration ( javax . ws . rs . core . Application eurekaJerseyApp ) { FilterRegistrationBean bean = new FilterRegistrationBean ( ) ; bean . setFilter ( new ServletContainer ( eurekaJerseyApp ) ) ; bean . setOrder ( Ordered . LOWEST_PRECEDENCE ) ; bean . setUrlPatterns ( Collections . singletonList ( EurekaConstants . DEFAULT_PREFIX + "/*" ) ) ; return bean ; } | Register the Jersey filter . |
21,432 | public String apply ( String serviceId ) { Matcher matcher = this . servicePattern . matcher ( serviceId ) ; String route = matcher . replaceFirst ( this . routePattern ) ; route = cleanRoute ( route ) ; return ( StringUtils . hasText ( route ) ? route : serviceId ) ; } | Use servicePattern to extract groups and routePattern to construct the route . |
21,433 | protected List < Instance > getInstancesForApp ( String serviceId ) throws Exception { List < Instance > instances = new ArrayList < > ( ) ; log . info ( "Fetching instances for app: " + serviceId ) ; Application app = eurekaClient . getApplication ( serviceId ) ; if ( app == null ) { log . warn ( "Eureka returned null for app: " + serviceId ) ; return instances ; } try { List < InstanceInfo > instancesForApp = app . getInstances ( ) ; if ( instancesForApp != null ) { log . info ( "Received instance list for app: " + serviceId + ", size=" + instancesForApp . size ( ) ) ; for ( InstanceInfo iInfo : instancesForApp ) { Instance instance = marshall ( iInfo ) ; if ( instance != null ) { instances . add ( instance ) ; } } } } catch ( Exception e ) { log . warn ( "Failed to retrieve instances from Eureka" , e ) ; } return instances ; } | Private helper that fetches the Instances for each application . |
21,434 | Instance marshall ( InstanceInfo instanceInfo ) { String hostname = instanceInfo . getHostName ( ) ; final String managementPort = instanceInfo . getMetadata ( ) . get ( "management.port" ) ; String port = managementPort == null ? String . valueOf ( instanceInfo . getPort ( ) ) : managementPort ; String cluster = getClusterName ( instanceInfo ) ; Boolean status = parseInstanceStatus ( instanceInfo . getStatus ( ) ) ; if ( hostname != null && cluster != null && status != null ) { Instance instance = getInstance ( hostname , port , cluster , status ) ; Map < String , String > metadata = instanceInfo . getMetadata ( ) ; boolean securePortEnabled = instanceInfo . isPortEnabled ( InstanceInfo . PortType . SECURE ) ; String securePort = String . valueOf ( instanceInfo . getSecurePort ( ) ) ; addMetadata ( instance , hostname , port , securePortEnabled , securePort , metadata ) ; String asgName = instanceInfo . getASGName ( ) ; if ( asgName != null ) { instance . getAttributes ( ) . put ( ASG_KEY , asgName ) ; } DataCenterInfo dcInfo = instanceInfo . getDataCenterInfo ( ) ; if ( dcInfo != null && dcInfo . getName ( ) . equals ( DataCenterInfo . Name . Amazon ) ) { AmazonInfo amznInfo = ( AmazonInfo ) dcInfo ; instance . getAttributes ( ) . putAll ( amznInfo . getMetadata ( ) ) ; } return instance ; } else { return null ; } } | Private helper that marshals the information from each instance into something that Turbine can understand . Override this method for your own implementation for parsing Eureka info . |
21,435 | protected Boolean parseInstanceStatus ( InstanceStatus status ) { if ( status == null ) { return null ; } return status == InstanceStatus . UP ; } | Helper that returns whether the instance is Up of Down . |
21,436 | protected long getContentLength ( HttpServletRequest request ) { if ( useServlet31 ) { return request . getContentLengthLong ( ) ; } String contentLengthHeader = request . getHeader ( HttpHeaders . CONTENT_LENGTH ) ; if ( contentLengthHeader != null ) { try { return Long . parseLong ( contentLengthHeader ) ; } catch ( NumberFormatException e ) { } } return request . getContentLength ( ) ; } | Get the header value as a long in order to more correctly proxy very large requests |
21,437 | private FormatPreferences tryEasy ( FormatPreferences preferences , boolean force ) { int count = 0 ; for ( Map . Entry < String , String > e : preferences . rawMap . entrySet ( ) ) { if ( ! "scan" . equalsIgnoreCase ( e . getValue ( ) ) ) count ++ ; } if ( force || count >= FormatPreferences . KEYS . size ( ) ) return preferences ; return null ; } | Checks validity of preferences and returns with a non - null value if ALL format keys are available thus negating the need for a scan . |
21,438 | public static Object calculateGuess ( JCExpression expr ) { if ( expr instanceof JCLiteral ) { JCLiteral lit = ( JCLiteral ) expr ; if ( lit . getKind ( ) == com . sun . source . tree . Tree . Kind . BOOLEAN_LITERAL ) { return ( ( Number ) lit . value ) . intValue ( ) == 0 ? false : true ; } return lit . value ; } if ( expr instanceof JCIdent || expr instanceof JCFieldAccess ) { String x = expr . toString ( ) ; if ( x . endsWith ( ".class" ) ) return new ClassLiteral ( x . substring ( 0 , x . length ( ) - 6 ) ) ; int idx = x . lastIndexOf ( '.' ) ; if ( idx > - 1 ) x = x . substring ( idx + 1 ) ; return new FieldSelect ( x ) ; } return null ; } | Turns an expression into a guessed intended literal . Only works for literals as you can imagine . |
21,439 | public static String canonical ( File p ) { try { return p . getCanonicalPath ( ) ; } catch ( IOException e ) { String x = p . getAbsolutePath ( ) ; return x == null ? p . getPath ( ) : x ; } } | Returns a full path to the provided file . Returns the canonical path unless that is not available in which case it returns the absolute path . |
21,440 | public L up ( ) { L result = parent ; while ( result != null && ! result . isStructurallySignificant ) result = result . parent ; return result ; } | Returns the structurally significant node that encloses this one . |
21,441 | @ SuppressWarnings ( { "unchecked" } ) public L add ( N newChild , Kind newChildKind ) { getAst ( ) . setChanged ( ) ; L n = getAst ( ) . buildTree ( newChild , newChildKind ) ; if ( n == null ) return null ; n . parent = ( L ) this ; children = children . append ( n ) ; return n ; } | Adds the stated node as a direct child of this node . |
21,442 | public void rebuild ( ) { Map < N , L > oldNodes = new IdentityHashMap < N , L > ( ) ; gatherAndRemoveChildren ( oldNodes ) ; L newNode = getAst ( ) . buildTree ( get ( ) , kind ) ; getAst ( ) . setChanged ( ) ; getAst ( ) . replaceNewWithExistingOld ( oldNodes , newNode ) ; } | Reparses the AST node represented by this node . Any existing nodes that occupy a different space in the AST are rehomed any nodes that no longer exist are removed and new nodes are created . |
21,443 | public static boolean annotationTypeMatches ( Class < ? extends Annotation > type , JavacNode node ) { if ( node . getKind ( ) != Kind . ANNOTATION ) return false ; return typeMatches ( type , node , ( ( JCAnnotation ) node . get ( ) ) . annotationType ) ; } | Checks if the Annotation AST Node provided is likely to be an instance of the provided annotation type . |
21,444 | public static MemberExistsResult fieldExists ( String fieldName , JavacNode node ) { node = upToTypeNode ( node ) ; if ( node != null && node . get ( ) instanceof JCClassDecl ) { for ( JCTree def : ( ( JCClassDecl ) node . get ( ) ) . defs ) { if ( def instanceof JCVariableDecl ) { if ( ( ( JCVariableDecl ) def ) . name . contentEquals ( fieldName ) ) { return getGeneratedBy ( def ) == null ? MemberExistsResult . EXISTS_BY_USER : MemberExistsResult . EXISTS_BY_LOMBOK ; } } } } return MemberExistsResult . NOT_EXISTS ; } | Checks if there is a field with the provided name . |
21,445 | static JCExpression getFieldType ( JavacNode field , FieldAccess fieldAccess ) { if ( field . getKind ( ) == Kind . METHOD ) return ( ( JCMethodDecl ) field . get ( ) ) . restype ; boolean lookForGetter = lookForGetter ( field , fieldAccess ) ; GetterMethod getter = lookForGetter ? findGetter ( field ) : null ; if ( getter == null ) { return ( ( JCVariableDecl ) field . get ( ) ) . vartype ; } return getter . type ; } | Returns the type of the field unless a getter exists for this field in which case the return type of the getter is returned . |
21,446 | public static JavacNode injectField ( JavacNode typeNode , JCVariableDecl field ) { return injectField ( typeNode , field , false ) ; } | Adds the given new field declaration to the provided type AST Node . |
21,447 | public static void injectMethod ( JavacNode typeNode , JCMethodDecl method , List < Type > paramTypes , Type returnType ) { JCClassDecl type = ( JCClassDecl ) typeNode . get ( ) ; if ( method . getName ( ) . contentEquals ( "<init>" ) ) { int idx = 0 ; for ( JCTree def : type . defs ) { if ( def instanceof JCMethodDecl ) { if ( ( ( ( JCMethodDecl ) def ) . mods . flags & Flags . GENERATEDCONSTR ) != 0 ) { JavacNode tossMe = typeNode . getNodeFor ( def ) ; if ( tossMe != null ) tossMe . up ( ) . removeChild ( tossMe ) ; type . defs = addAllButOne ( type . defs , idx ) ; ClassSymbolMembersField . remove ( type . sym , ( ( JCMethodDecl ) def ) . sym ) ; break ; } } idx ++ ; } } addSuppressWarningsAll ( method . mods , typeNode , method . pos , getGeneratedBy ( method ) , typeNode . getContext ( ) ) ; addGenerated ( method . mods , typeNode , method . pos , getGeneratedBy ( method ) , typeNode . getContext ( ) ) ; type . defs = type . defs . append ( method ) ; fixMethodMirror ( typeNode . getContext ( ) , typeNode . getElement ( ) , method . getModifiers ( ) . flags , method . getName ( ) , paramTypes , returnType ) ; typeNode . add ( method , Kind . METHOD ) ; } | Adds the given new method declaration to the provided type AST Node . Can also inject constructors . |
21,448 | public static List < Integer > createListOfNonExistentFields ( List < String > list , JavacNode type , boolean excludeStandard , boolean excludeTransient ) { boolean [ ] matched = new boolean [ list . size ( ) ] ; for ( JavacNode child : type . down ( ) ) { if ( list . isEmpty ( ) ) break ; if ( child . getKind ( ) != Kind . FIELD ) continue ; JCVariableDecl field = ( JCVariableDecl ) child . get ( ) ; if ( excludeStandard ) { if ( ( field . mods . flags & Flags . STATIC ) != 0 ) continue ; if ( field . name . toString ( ) . startsWith ( "$" ) ) continue ; } if ( excludeTransient && ( field . mods . flags & Flags . TRANSIENT ) != 0 ) continue ; int idx = list . indexOf ( child . getName ( ) ) ; if ( idx > - 1 ) matched [ idx ] = true ; } ListBuffer < Integer > problematic = new ListBuffer < Integer > ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( ! matched [ i ] ) problematic . append ( i ) ; } return problematic . toList ( ) ; } | Given a list of field names and a node referring to a type finds each name in the list that does not match a field within the type . |
21,449 | public boolean usesField ( String className , String fieldName ) { int classIndex = findClass ( className ) ; if ( classIndex == NOT_FOUND ) return false ; int fieldNameIndex = findUtf8 ( fieldName ) ; if ( fieldNameIndex == NOT_FOUND ) return false ; for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( types [ i ] == FIELD && readValue ( offsets [ i ] ) == classIndex ) { int nameAndTypeIndex = readValue ( offsets [ i ] + 2 ) ; if ( readValue ( offsets [ nameAndTypeIndex ] ) == fieldNameIndex ) return true ; } } return false ; } | Checks if the constant pool contains a reference to a given field either for writing or reading . |
21,450 | public boolean usesMethod ( String className , String methodName , String descriptor ) { int classIndex = findClass ( className ) ; if ( classIndex == NOT_FOUND ) return false ; int nameAndTypeIndex = findNameAndType ( methodName , descriptor ) ; if ( nameAndTypeIndex == NOT_FOUND ) return false ; for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( isMethod ( i ) && readValue ( offsets [ i ] ) == classIndex && readValue ( offsets [ i ] + 2 ) == nameAndTypeIndex ) return true ; } return false ; } | Checks if the constant pool contains a reference to a given method . |
21,451 | public boolean containsStringConstant ( String value ) { int index = findUtf8 ( value ) ; if ( index == NOT_FOUND ) return false ; for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( types [ i ] == STRING && readValue ( offsets [ i ] ) == index ) return true ; } return false ; } | Checks if the constant pool contains the provided string constant which implies the constant is used somewhere in the code . |
21,452 | public boolean containsLong ( long value ) { for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( types [ i ] == LONG && readLong ( i ) == value ) return true ; } return false ; } | Checks if the constant pool contains the provided long constant which implies the constant is used somewhere in the code . |
21,453 | public boolean containsDouble ( double value ) { boolean isNan = Double . isNaN ( value ) ; for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( types [ i ] == DOUBLE ) { double d = readDouble ( i ) ; if ( d == value || ( isNan && Double . isNaN ( d ) ) ) return true ; } } return false ; } | Checks if the constant pool contains the provided double constant which implies the constant is used somewhere in the code . |
21,454 | public boolean containsInteger ( int value ) { for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( types [ i ] == INTEGER && readInteger ( i ) == value ) return true ; } return false ; } | Checks if the constant pool contains the provided int constant which implies the constant is used somewhere in the code . |
21,455 | public boolean containsFloat ( float value ) { boolean isNan = Float . isNaN ( value ) ; for ( int i = 1 ; i < maxPoolSize ; i ++ ) { if ( types [ i ] == FLOAT ) { float f = readFloat ( i ) ; if ( f == value || ( isNan && Float . isNaN ( f ) ) ) return true ; } } return false ; } | Checks if the constant pool contains the provided float constant which implies the constant is used somewhere in the code . |
21,456 | public List < String > getInterfaces ( ) { int size = readValue ( endOfPool + 6 ) ; if ( size == 0 ) return Collections . emptyList ( ) ; List < String > result = new ArrayList < String > ( ) ; for ( int i = 0 ; i < size ; i ++ ) { result . add ( getClassName ( readValue ( endOfPool + 8 + ( i * 2 ) ) ) ) ; } return result ; } | Returns the name of all implemented interfaces . |
21,457 | public Expression longToIntForHashCode ( Expression ref1 , Expression ref2 , ASTNode source ) { int pS = source . sourceStart , pE = source . sourceEnd ; IntLiteral int32 = makeIntLiteral ( "32" . toCharArray ( ) , source ) ; BinaryExpression higherBits = new BinaryExpression ( ref1 , int32 , OperatorIds . UNSIGNED_RIGHT_SHIFT ) ; setGeneratedBy ( higherBits , source ) ; BinaryExpression xorParts = new BinaryExpression ( ref2 , higherBits , OperatorIds . XOR ) ; setGeneratedBy ( xorParts , source ) ; TypeReference intRef = TypeReference . baseTypeReference ( TypeIds . T_int , 0 ) ; intRef . sourceStart = pS ; intRef . sourceEnd = pE ; setGeneratedBy ( intRef , source ) ; CastExpression expr = makeCastExpression ( xorParts , intRef , source ) ; expr . sourceStart = pS ; expr . sourceEnd = pE ; return expr ; } | Give 2 clones! |
21,458 | @ SuppressWarnings ( "unused" ) private String listAnnotationProcessorsBeforeOurs ( ) { try { Object discoveredProcessors = javacProcessingEnvironment_discoveredProcs . get ( this . javacProcessingEnv ) ; ArrayList < ? > states = ( ArrayList < ? > ) discoveredProcessors_procStateList . get ( discoveredProcessors ) ; if ( states == null || states . isEmpty ( ) ) return null ; if ( states . size ( ) == 1 ) return processorState_processor . get ( states . get ( 0 ) ) . getClass ( ) . getName ( ) ; int idx = 0 ; StringBuilder out = new StringBuilder ( ) ; for ( Object processState : states ) { idx ++ ; String name = processorState_processor . get ( processState ) . getClass ( ) . getName ( ) ; if ( out . length ( ) > 0 ) out . append ( ", " ) ; out . append ( "[" ) . append ( idx ) . append ( "] " ) . append ( name ) ; } return out . toString ( ) ; } catch ( Exception e ) { return null ; } } | Hence for now no warnings . |
21,459 | public JavacProcessingEnvironment getJavacProcessingEnvironment ( Object procEnv ) { if ( procEnv instanceof JavacProcessingEnvironment ) return ( JavacProcessingEnvironment ) procEnv ; for ( Class < ? > procEnvClass = procEnv . getClass ( ) ; procEnvClass != null ; procEnvClass = procEnvClass . getSuperclass ( ) ) { try { return getJavacProcessingEnvironment ( tryGetDelegateField ( procEnvClass , procEnv ) ) ; } catch ( final Exception e ) { } } processingEnv . getMessager ( ) . printMessage ( Kind . WARNING , "Can't get the delegate of the gradle IncrementalProcessingEnvironment. Lombok won't work." ) ; return null ; } | This class casts the given processing environment to a JavacProcessingEnvironment . In case of gradle incremental compilation the delegate ProcessingEnvironment of the gradle wrapper is returned . |
21,460 | public static List < String > getDrivesOnWindows ( ) throws Throwable { loadWindowsDriveInfoLib ( ) ; List < String > drives = new ArrayList < String > ( ) ; WindowsDriveInfo info = new WindowsDriveInfo ( ) ; for ( String drive : info . getLogicalDrives ( ) ) { if ( info . isFixedDisk ( drive ) ) drives . add ( drive ) ; } return drives ; } | Returns all drive letters on windows that represent fixed disks . |
21,461 | public static void transform ( Parser parser , CompilationUnitDeclaration ast ) { if ( disableLombok ) return ; if ( Symbols . hasSymbol ( "lombok.disable" ) ) return ; if ( Boolean . TRUE . equals ( LombokConfiguration . read ( ConfigurationKeys . LOMBOK_DISABLE , EclipseAST . getAbsoluteFileLocation ( ast ) ) ) ) return ; try { DebugSnapshotStore . INSTANCE . snapshot ( ast , "transform entry" ) ; long histoToken = lombokTracker == null ? 0L : lombokTracker . start ( ) ; EclipseAST existing = getAST ( ast , false ) ; new TransformEclipseAST ( existing ) . go ( ) ; if ( lombokTracker != null ) lombokTracker . end ( histoToken ) ; DebugSnapshotStore . INSTANCE . snapshot ( ast , "transform exit" ) ; } catch ( Throwable t ) { DebugSnapshotStore . INSTANCE . snapshot ( ast , "transform error: %s" , t . getClass ( ) . getSimpleName ( ) ) ; try { String message = "Lombok can't parse this source: " + t . toString ( ) ; EclipseAST . addProblemToCompilationResult ( ast . getFileName ( ) , ast . compilationResult , false , message , 0 , 0 ) ; t . printStackTrace ( ) ; } catch ( Throwable t2 ) { try { error ( ast , "Can't create an error in the problems dialog while adding: " + t . toString ( ) , t2 ) ; } catch ( Throwable t3 ) { disableLombok = true ; } } } } | This method is called immediately after Eclipse finishes building a CompilationUnitDeclaration which is the top - level AST node when Eclipse parses a source file . The signature is magic - you should not change it! |
21,462 | public void go ( ) { long nextPriority = Long . MIN_VALUE ; for ( Long d : handlers . getPriorities ( ) ) { if ( nextPriority > d ) continue ; AnnotationVisitor visitor = new AnnotationVisitor ( d ) ; ast . traverse ( visitor ) ; nextPriority = visitor . getNextPriority ( ) ; nextPriority = Math . min ( nextPriority , handlers . callASTVisitors ( ast , d , ast . isCompleteParse ( ) ) ) ; } } | First handles all lombok annotations except PrintAST then calls all non - annotation based handlers . then handles any PrintASTs . |
21,463 | public static boolean isPrimitive ( TypeReference ref ) { if ( ref . dimensions ( ) > 0 ) return false ; return PRIMITIVE_TYPE_NAME_PATTERN . matcher ( toQualifiedName ( ref . getTypeName ( ) ) ) . matches ( ) ; } | Checks if the given type reference represents a primitive type . |
21,464 | public static Object calculateValue ( Expression e ) { if ( e instanceof Literal ) { ( ( Literal ) e ) . computeConstant ( ) ; switch ( e . constant . typeID ( ) ) { case TypeIds . T_int : return e . constant . intValue ( ) ; case TypeIds . T_byte : return e . constant . byteValue ( ) ; case TypeIds . T_short : return e . constant . shortValue ( ) ; case TypeIds . T_char : return e . constant . charValue ( ) ; case TypeIds . T_float : return e . constant . floatValue ( ) ; case TypeIds . T_double : return e . constant . doubleValue ( ) ; case TypeIds . T_boolean : return e . constant . booleanValue ( ) ; case TypeIds . T_long : return e . constant . longValue ( ) ; case TypeIds . T_JavaLangString : return e . constant . stringValue ( ) ; default : return null ; } } else if ( e instanceof ClassLiteralAccess ) { return new ClassLiteral ( Eclipse . toQualifiedName ( ( ( ClassLiteralAccess ) e ) . type . getTypeName ( ) ) ) ; } else if ( e instanceof SingleNameReference ) { return new FieldSelect ( new String ( ( ( SingleNameReference ) e ) . token ) ) ; } else if ( e instanceof QualifiedNameReference ) { String qName = Eclipse . toQualifiedName ( ( ( QualifiedNameReference ) e ) . tokens ) ; int idx = qName . lastIndexOf ( '.' ) ; return new FieldSelect ( idx == - 1 ? qName : qName . substring ( idx + 1 ) ) ; } else if ( e instanceof UnaryExpression ) { if ( "-" . equals ( ( ( UnaryExpression ) e ) . operatorToString ( ) ) ) { Object inner = calculateValue ( ( ( UnaryExpression ) e ) . expression ) ; if ( inner instanceof Integer ) return - ( ( Integer ) inner ) . intValue ( ) ; if ( inner instanceof Byte ) return - ( ( Byte ) inner ) . byteValue ( ) ; if ( inner instanceof Short ) return - ( ( Short ) inner ) . shortValue ( ) ; if ( inner instanceof Long ) return - ( ( Long ) inner ) . longValue ( ) ; if ( inner instanceof Float ) return - ( ( Float ) inner ) . floatValue ( ) ; if ( inner instanceof Double ) return - ( ( Double ) inner ) . doubleValue ( ) ; return null ; } } return null ; } | Returns the actual value of the given Literal or Literal - like node . |
21,465 | public static HandlerLibrary load ( Messager messager , Trees trees ) { HandlerLibrary library = new HandlerLibrary ( messager ) ; try { loadAnnotationHandlers ( library , trees ) ; loadVisitorHandlers ( library , trees ) ; } catch ( IOException e ) { System . err . println ( "Lombok isn't running due to misconfigured SPI files: " + e ) ; } library . calculatePriorities ( ) ; return library ; } | Creates a new HandlerLibrary that will report any problems or errors to the provided messager then uses SPI discovery to load all annotation and visitor based handlers so that future calls to the handle methods will defer to these handlers . |
21,466 | public void javacWarning ( String message , Throwable t ) { messager . printMessage ( Diagnostic . Kind . WARNING , message + ( t == null ? "" : ( ": " + t ) ) ) ; } | Generates a warning in the Messager that was used to initialize this HandlerLibrary . |
21,467 | public void javacError ( String message , Throwable t ) { messager . printMessage ( Diagnostic . Kind . ERROR , message + ( t == null ? "" : ( ": " + t ) ) ) ; if ( t != null ) t . printStackTrace ( ) ; } | Generates an error in the Messager that was used to initialize this HandlerLibrary . |
21,468 | static < J > MethodId < J > MethodId ( String name , Class < J > returnType , Class < ? > ... types ) { return new MethodId < J > ( TreeMaker . class , name , returnType , types ) ; } | Creates a new method ID based on the name of the method to invoke the return type of that method and the types of the parameters . |
21,469 | public void show ( ) { appWindow . setVisible ( true ) ; if ( OsUtils . getOS ( ) == OS . MAC_OS_X ) { try { AppleNativeLook . go ( ) ; } catch ( Throwable ignore ) { } } } | Makes the installer window visible . |
21,470 | public List < CommentInfo > integrate ( List < CommentInfo > comments , JCCompilationUnit unit ) { List < CommentInfo > out = new ArrayList < CommentInfo > ( ) ; CommentInfo lastExcisedComment = null ; JCTree lastNode = null ; for ( CommentInfo cmt : comments ) { if ( ! cmt . isJavadoc ( ) ) { out . add ( cmt ) ; continue ; } JCTree node = findJavadocableNodeOnOrAfter ( unit , cmt . endPos ) ; if ( node == null ) { out . add ( cmt ) ; continue ; } if ( node == lastNode ) { out . add ( lastExcisedComment ) ; } if ( ! attach ( unit , node , cmt ) ) { out . add ( cmt ) ; } else { lastNode = node ; lastExcisedComment = cmt ; } } return out ; } | Returns the same comment list as when this integrator was created minus all doc comments that have been successfully integrated into the compilation unit . |
21,471 | private List < File > getUninstallDirs ( ) { List < File > result = new ArrayList < File > ( ) ; File x = new File ( name ) ; if ( ! x . isDirectory ( ) ) x = x . getParentFile ( ) ; if ( x . isDirectory ( ) ) result . add ( x ) ; result . add ( eclipseIniPath . getParentFile ( ) ) ; return result ; } | Returns directories that may contain lombok . jar files that need to be deleted . |
21,472 | @ SuppressWarnings ( "unchecked" ) public static Map < String , ConfigurationKey < ? > > registeredKeys ( ) { synchronized ( registeredKeys ) { if ( copy == null ) copy = Collections . unmodifiableMap ( ( Map < String , ConfigurationKey < ? > > ) registeredKeys . clone ( ) ) ; return copy ; } } | Returns a copy of the currently registered keys . |
21,473 | public void addType ( String fullyQualifiedTypeName ) { String dotBased = fullyQualifiedTypeName . replace ( "$" , "." ) ; if ( locked ) throw new IllegalStateException ( "locked" ) ; int idx = fullyQualifiedTypeName . lastIndexOf ( '.' ) ; if ( idx == - 1 ) throw new IllegalArgumentException ( "Only fully qualified types are allowed (and stuff in the default package is not palatable to us either!)" ) ; String unqualified = fullyQualifiedTypeName . substring ( idx + 1 ) ; if ( unqualifiedToQualifiedMap == null ) throw new IllegalStateException ( "SingleType library" ) ; unqualifiedToQualifiedMap . put ( unqualified . replace ( "$" , "." ) , dotBased ) ; unqualifiedToQualifiedMap . put ( unqualified , dotBased ) ; unqualifiedToQualifiedMap . put ( fullyQualifiedTypeName , dotBased ) ; unqualifiedToQualifiedMap . put ( dotBased , dotBased ) ; for ( Map . Entry < String , String > e : LombokInternalAliasing . ALIASES . entrySet ( ) ) { if ( fullyQualifiedTypeName . equals ( e . getValue ( ) ) ) unqualifiedToQualifiedMap . put ( e . getKey ( ) , dotBased ) ; } int idx2 = fullyQualifiedTypeName . indexOf ( '$' , idx + 1 ) ; while ( idx2 != - 1 ) { String unq = fullyQualifiedTypeName . substring ( idx2 + 1 ) ; unqualifiedToQualifiedMap . put ( unq . replace ( "$" , "." ) , dotBased ) ; unqualifiedToQualifiedMap . put ( unq , dotBased ) ; idx2 = fullyQualifiedTypeName . indexOf ( '$' , idx2 + 1 ) ; } } | Add a type to the library . |
21,474 | public void init ( ProcessingEnvironment procEnv ) { super . init ( procEnv ) ; String className = procEnv . getClass ( ) . getName ( ) ; if ( className . startsWith ( "org.eclipse.jdt." ) ) { errorToShow = "This version of disableCheckedExceptions is not compatible with eclipse. javac only; sorry." ; procEnv . getMessager ( ) . printMessage ( Kind . WARNING , errorToShow ) ; } else if ( ! procEnv . getClass ( ) . getName ( ) . equals ( "com.sun.tools.javac.processing.JavacProcessingEnvironment" ) ) { procEnv . getMessager ( ) . printMessage ( Kind . WARNING , "You aren't using a compiler based around javac v1.6, so disableCheckedExceptions will not work.\n" + "Your processor class is: " + className ) ; } else { new LiveInjector ( ) . inject ( ClassRootFinder . findClassRootOfClass ( DisableCheckedExceptionsAgent . class ) ) ; } } | Inject an agent if we re on a sun - esque JVM . |
21,475 | public boolean process ( Set < ? extends TypeElement > annotations , RoundEnvironment roundEnv ) { if ( errorToShow != null ) { if ( errorToShow != null ) { Set < ? extends Element > rootElements = roundEnv . getRootElements ( ) ; if ( ! rootElements . isEmpty ( ) ) { processingEnv . getMessager ( ) . printMessage ( Kind . WARNING , errorToShow , rootElements . iterator ( ) . next ( ) ) ; errorToShow = null ; } } } return false ; } | Does nothing - we just wanted the init method so we can inject an agent . |
21,476 | public static boolean checkName ( String nameSpec , String identifier , LombokNode < ? , ? , ? > errorNode ) { if ( identifier . isEmpty ( ) ) { errorNode . addError ( nameSpec + " cannot be the empty string." ) ; return false ; } if ( ! JavaIdentifiers . isValidJavaIdentifier ( identifier ) ) { errorNode . addError ( nameSpec + " must be a valid java identifier." ) ; return false ; } return true ; } | Checks if the given name is a valid identifier . |
21,477 | public static String toGetterName ( AST < ? , ? , ? > ast , AnnotationValues < Accessors > accessors , CharSequence fieldName , boolean isBoolean ) { return toAccessorName ( ast , accessors , fieldName , isBoolean , "is" , "get" , true ) ; } | Generates a getter name from a given field name . |
21,478 | public static String toWitherName ( AST < ? , ? , ? > ast , AnnotationValues < Accessors > accessors , CharSequence fieldName , boolean isBoolean ) { return toAccessorName ( ast , accessors , fieldName , isBoolean , "with" , "with" , false ) ; } | Generates a wither name from a given field name . |
21,479 | public static List < String > toAllGetterNames ( AST < ? , ? , ? > ast , AnnotationValues < Accessors > accessors , CharSequence fieldName , boolean isBoolean ) { return toAllAccessorNames ( ast , accessors , fieldName , isBoolean , "is" , "get" , true ) ; } | Returns all names of methods that would represent the getter for a field with the provided name . |
21,480 | public static List < String > toAllWitherNames ( AST < ? , ? , ? > ast , AnnotationValues < Accessors > accessors , CharSequence fieldName , boolean isBoolean ) { return toAllAccessorNames ( ast , accessors , fieldName , isBoolean , "with" , "with" , false ) ; } | Returns all names of methods that would represent the wither for a field with the provided name . |
21,481 | public static < C > Iterable < C > findServices ( Class < C > target ) throws IOException { return findServices ( target , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } | Returns an iterator of instances that at least according to the spi discovery file are implementations of the stated class . |
21,482 | public static < C > Iterable < C > findServices ( final Class < C > target , ClassLoader loader ) throws IOException { if ( loader == null ) loader = ClassLoader . getSystemClassLoader ( ) ; Enumeration < URL > resources = loader . getResources ( "META-INF/services/" + target . getName ( ) ) ; final Set < String > entries = new LinkedHashSet < String > ( ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; readServicesFromUrl ( entries , url ) ; } final Iterator < String > names = entries . iterator ( ) ; final ClassLoader fLoader = loader ; return new Iterable < C > ( ) { public Iterator < C > iterator ( ) { return new Iterator < C > ( ) { public boolean hasNext ( ) { return names . hasNext ( ) ; } public C next ( ) { try { return target . cast ( Class . forName ( names . next ( ) , true , fLoader ) . newInstance ( ) ) ; } catch ( Exception e ) { if ( e instanceof RuntimeException ) throw ( RuntimeException ) e ; throw new RuntimeException ( e ) ; } } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } } ; } | Returns an iterator of class objects that at least according to the spi discovery file are implementations of the stated class . |
21,483 | protected Collection < L > buildWithField ( Class < L > nodeType , N statement , FieldAccess fa ) { List < L > list = new ArrayList < L > ( ) ; buildWithField0 ( nodeType , statement , fa , list ) ; return list ; } | buildTree implementation that uses reflection to find all child nodes by way of inspecting the fields . |
21,484 | protected boolean replaceStatementInNode ( N statement , N oldN , N newN ) { for ( FieldAccess fa : fieldsOf ( statement . getClass ( ) ) ) { if ( replaceStatementInField ( fa , statement , oldN , newN ) ) return true ; } return false ; } | Uses reflection to find the given direct child on the given statement and replace it with a new child . |
21,485 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected void setElementInASTCollection ( Field field , Object fieldRef , List < Collection < ? > > chain , Collection < ? > collection , int idx , N newN ) throws IllegalAccessException { if ( collection instanceof List < ? > ) { ( ( List ) collection ) . set ( idx , newN ) ; } } | Override if your AST collection does not support the set method . Javac s for example does not . |
21,486 | public void findIdes ( List < IdeLocation > locations , List < CorruptedIdeLocationException > problems ) { switch ( OsUtils . getOS ( ) ) { case WINDOWS : new WindowsFinder ( ) . findEclipse ( locations , problems ) ; break ; case MAC_OS_X : new MacFinder ( ) . findEclipse ( locations , problems ) ; break ; default : case UNIX : new UnixFinder ( ) . findEclipse ( locations , problems ) ; break ; } } | Calls the OS - dependent find Eclipse routine . If the local OS doesn t have a routine written for it null is returned . |
21,487 | private List < String > getSourceDirsOnWindowsWithDriveLetters ( ) { List < String > driveLetters = asList ( "C" ) ; try { driveLetters = OsUtils . getDrivesOnWindows ( ) ; } catch ( Throwable ignore ) { ignore . printStackTrace ( ) ; } List < String > sourceDirs = new ArrayList < String > ( ) ; for ( String letter : driveLetters ) { for ( String possibleSource : descriptor . getSourceDirsOnWindows ( ) ) { if ( ! isDriveSpecificOnWindows ( possibleSource ) ) { sourceDirs . add ( letter + ":" + possibleSource ) ; } } } for ( String possibleSource : descriptor . getSourceDirsOnWindows ( ) ) { if ( isDriveSpecificOnWindows ( possibleSource ) ) sourceDirs . add ( possibleSource ) ; } return sourceDirs ; } | Returns a list of paths of Eclipse installations . |
21,488 | public JCTree visitLabeledStatement ( LabeledStatementTree node , Void p ) { return node . getStatement ( ) . accept ( this , p ) ; } | This and visitVariable is rather hacky but we re working around evident bugs or at least inconsistencies in javac . |
21,489 | public void addError ( String message , int sourceStart , int sourceEnd ) { ast . addProblem ( ast . new ParseProblem ( false , message , sourceStart , sourceEnd ) ) ; } | Generate a compiler error that shows the wavy underline from - to the stated character positions . |
21,490 | public void addWarning ( String message , int sourceStart , int sourceEnd ) { ast . addProblem ( ast . new ParseProblem ( true , message , sourceStart , sourceEnd ) ) ; } | Generate a compiler warning that shows the wavy underline from - to the stated character positions . |
21,491 | public static void main ( String [ ] args ) { if ( args . length > 0 ) { System . out . printf ( "%s\n" , getFullVersion ( ) ) ; } else { System . out . println ( VERSION ) ; } } | Prints the version followed by a newline and exits . |
21,492 | public JCExpression longToIntForHashCode ( JavacTreeMaker maker , JCExpression ref1 , JCExpression ref2 ) { JCExpression shift = maker . Binary ( CTC_UNSIGNED_SHIFT_RIGHT , ref1 , maker . Literal ( 32 ) ) ; JCExpression xorBits = maker . Binary ( CTC_BITXOR , shift , ref2 ) ; return maker . TypeCast ( maker . TypeIdent ( CTC_INT ) , maker . Parens ( xorBits ) ) ; } | The 2 references must be clones of each other . |
21,493 | public < T > T get ( int index ) { if ( size ( ) <= index ) { return null ; } return ( T ) args . get ( index ) ; } | index out of bounds - safe method for getting elements |
21,494 | private long readLong ( ByteBuf chars , int length ) { long result = 0 ; for ( int i = chars . readerIndex ( ) ; i < chars . readerIndex ( ) + length ; i ++ ) { int digit = ( ( int ) chars . getByte ( i ) & 0xF ) ; for ( int j = 0 ; j < chars . readerIndex ( ) + length - 1 - i ; j ++ ) { digit *= 10 ; } result += digit ; } chars . readerIndex ( chars . readerIndex ( ) + length ) ; return result ; } | fastest way to parse chars to int |
21,495 | public SocketIOClient getClient ( UUID uuid ) { return namespacesHub . get ( Namespace . DEFAULT_NAME ) . getClient ( uuid ) ; } | Get client by uuid from default namespace |
21,496 | public Future < Void > startAsync ( ) { log . info ( "Session store / pubsub factory used: {}" , configCopy . getStoreFactory ( ) ) ; initGroups ( ) ; pipelineFactory . start ( configCopy , namespacesHub ) ; Class < ? extends ServerChannel > channelClass = NioServerSocketChannel . class ; if ( configCopy . isUseLinuxNativeEpoll ( ) ) { channelClass = EpollServerSocketChannel . class ; } ServerBootstrap b = new ServerBootstrap ( ) ; b . group ( bossGroup , workerGroup ) . channel ( channelClass ) . childHandler ( pipelineFactory ) ; applyConnectionOptions ( b ) ; InetSocketAddress addr = new InetSocketAddress ( configCopy . getPort ( ) ) ; if ( configCopy . getHostname ( ) != null ) { addr = new InetSocketAddress ( configCopy . getHostname ( ) , configCopy . getPort ( ) ) ; } return b . bind ( addr ) . addListener ( new FutureListener < Void > ( ) { public void operationComplete ( Future < Void > future ) throws Exception { if ( future . isSuccess ( ) ) { log . info ( "SocketIO server started at port: {}" , configCopy . getPort ( ) ) ; } else { log . error ( "SocketIO server start failed at port: {}!" , configCopy . getPort ( ) ) ; } } } ) ; } | Start server asynchronously |
21,497 | protected void addSslHandler ( ChannelPipeline pipeline ) { if ( sslContext != null ) { SSLEngine engine = sslContext . createSSLEngine ( ) ; engine . setUseClientMode ( false ) ; pipeline . addLast ( SSL_HANDLER , new SslHandler ( engine ) ) ; } } | Adds the ssl handler |
21,498 | protected void addSocketioHandlers ( ChannelPipeline pipeline ) { pipeline . addLast ( HTTP_REQUEST_DECODER , new HttpRequestDecoder ( ) ) ; pipeline . addLast ( HTTP_AGGREGATOR , new HttpObjectAggregator ( configuration . getMaxHttpContentLength ( ) ) { protected Object newContinueResponse ( HttpMessage start , int maxContentLength , ChannelPipeline pipeline ) { return null ; } } ) ; pipeline . addLast ( HTTP_ENCODER , new HttpResponseEncoder ( ) ) ; if ( configuration . isHttpCompression ( ) ) { pipeline . addLast ( HTTP_COMPRESSION , new HttpContentCompressor ( ) ) ; } pipeline . addLast ( PACKET_HANDLER , packetHandler ) ; pipeline . addLast ( AUTHORIZE_HANDLER , authorizeHandler ) ; pipeline . addLast ( XHR_POLLING_TRANSPORT , xhrPollingTransport ) ; if ( configuration . isWebsocketCompression ( ) ) { pipeline . addLast ( WEB_SOCKET_TRANSPORT_COMPRESSION , new WebSocketServerCompressionHandler ( ) ) ; } pipeline . addLast ( WEB_SOCKET_TRANSPORT , webSocketTransport ) ; pipeline . addLast ( SOCKETIO_ENCODER , encoderHandler ) ; pipeline . addLast ( WRONG_URL_HANDLER , wrongUrlHandler ) ; } | Adds the socketio channel handlers |
21,499 | public void setTransports ( Transport ... transports ) { if ( transports . length == 0 ) { throw new IllegalArgumentException ( "Transports list can't be empty" ) ; } this . transports = Arrays . asList ( transports ) ; } | Transports supported by server |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.