idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,200 | static void parseData ( String [ ] args , BiConsumer < String , Boolean > data ) { CommandLine commandLine = parseCommandLine ( args ) ; Object value = commandLine . optionValue ( "d" ) ; if ( value != null ) { data . accept ( value . toString ( ) , commandLine . hasOption ( "x" ) ) ; } else { data . accept ( null , commandLine . hasOption ( "x" ) ) ; } } | Parse entries . |
21,201 | static CommandLine parseCommandLine ( String [ ] args ) { return CommandLine . build ( ) . addOption ( DATA_OPTION , "For passing the data" ) . addOption ( DEBUG_OPTIONS , "For outputting debug information" ) . parse ( args ) ; } | Parse command line entries . |
21,202 | public void writeTo ( OutputStream outputStream ) { try { ClassWriter classWriter = generateClassBytes ( ) ; writeClassToDisk ( outputStream , classWriter ) ; } catch ( Throwable e ) { throw new ClassGenerationException ( "Error generating annotation metadata: " + e . getMessage ( ) , e ) ; } } | Write the class to the output stream such a JavaFileObject created from a java annotation processor Filer object . |
21,203 | private static void pushAnnotationAttributes ( Type declaringType , ClassVisitor declaringClassWriter , GeneratorAdapter generatorAdapter , Map < ? extends CharSequence , Object > annotationData , Map < String , GeneratorAdapter > loadTypeMethods ) { int totalSize = annotationData . size ( ) * 2 ; pushNewArray ( generatorAdapter , Object . class , totalSize ) ; int i = 0 ; for ( Map . Entry < ? extends CharSequence , Object > entry : annotationData . entrySet ( ) ) { String memberName = entry . getKey ( ) . toString ( ) ; pushStoreStringInArray ( generatorAdapter , i ++ , totalSize , memberName ) ; Object value = entry . getValue ( ) ; pushStoreInArray ( generatorAdapter , i ++ , totalSize , ( ) -> pushValue ( declaringType , declaringClassWriter , generatorAdapter , value , loadTypeMethods ) ) ; } generatorAdapter . invokeStatic ( Type . getType ( AnnotationUtil . class ) , METHOD_MAP_OF ) ; } | Writes annotation attributes to the given generator . |
21,204 | protected com . github . benmanes . caffeine . cache . Cache buildCache ( CacheConfiguration cacheConfiguration ) { Caffeine < Object , Object > builder = Caffeine . newBuilder ( ) ; cacheConfiguration . getExpireAfterAccess ( ) . ifPresent ( duration -> builder . expireAfterAccess ( duration . toMillis ( ) , TimeUnit . MILLISECONDS ) ) ; cacheConfiguration . getExpireAfterWrite ( ) . ifPresent ( duration -> builder . expireAfterWrite ( duration . toMillis ( ) , TimeUnit . MILLISECONDS ) ) ; cacheConfiguration . getInitialCapacity ( ) . ifPresent ( builder :: initialCapacity ) ; cacheConfiguration . getMaximumSize ( ) . ifPresent ( builder :: maximumSize ) ; cacheConfiguration . getMaximumWeight ( ) . ifPresent ( ( long weight ) -> { builder . maximumWeight ( weight ) ; builder . weigher ( findWeigher ( ) ) ; } ) ; if ( cacheConfiguration . isRecordStats ( ) ) { builder . recordStats ( ) ; } if ( cacheConfiguration . isTestMode ( ) ) { builder . executor ( Runnable :: run ) ; } return builder . build ( ) ; } | Build a cache from the given configurations . |
21,205 | public static boolean isAtLeastMajorMinor ( String version , int majorVersion , int minorVersion ) { SemanticVersion semanticVersion = new SemanticVersion ( version ) ; return isAtLeastMajorMinorImpl ( semanticVersion , majorVersion , minorVersion ) ; } | Check whether the current version is at least the given major and minor version . |
21,206 | public static boolean isAtLeast ( String version , String requiredVersion ) { if ( version != null ) { SemanticVersion thisVersion = new SemanticVersion ( version ) ; SemanticVersion otherVersion = new SemanticVersion ( requiredVersion ) ; return thisVersion . compareTo ( otherVersion ) != - 1 ; } return false ; } | Check whether the version is at least the given version . |
21,207 | protected < T > TypeConverter findTypeConverter ( Class < ? > sourceType , Class < T > targetType , Class < ? extends Annotation > formattingAnnotation ) { TypeConverter typeConverter = null ; List < Class > sourceHierarchy = ClassUtils . resolveHierarchy ( sourceType ) ; List < Class > targetHierarchy = ClassUtils . resolveHierarchy ( targetType ) ; boolean hasFormatting = formattingAnnotation != null ; for ( Class sourceSuperType : sourceHierarchy ) { for ( Class targetSuperType : targetHierarchy ) { ConvertiblePair pair = new ConvertiblePair ( sourceSuperType , targetSuperType , formattingAnnotation ) ; typeConverter = typeConverters . get ( pair ) ; if ( typeConverter != null ) { converterCache . put ( pair , typeConverter ) ; return typeConverter ; } } } if ( hasFormatting ) { for ( Class sourceSuperType : sourceHierarchy ) { for ( Class targetSuperType : targetHierarchy ) { ConvertiblePair pair = new ConvertiblePair ( sourceSuperType , targetSuperType ) ; typeConverter = typeConverters . get ( pair ) ; if ( typeConverter != null ) { converterCache . put ( pair , typeConverter ) ; return typeConverter ; } } } } return typeConverter ; } | Find the type converter . |
21,208 | protected JsonNode readGcMetadataUrl ( URL url , int connectionTimeoutMs , int readTimeoutMs ) throws IOException { return readMetadataUrl ( url , connectionTimeoutMs , readTimeoutMs , objectMapper , Collections . emptyMap ( ) ) ; } | Get instance Metadata JSON . |
21,209 | Component addComponent ( Consumer < IOException > onError ) { Component component ; try { long readable = readableBytes ( data ) ; long offset = position . getAndUpdate ( p -> readable ) ; int length = new Long ( readable - offset ) . intValue ( ) ; component = new Component ( length , offset ) ; components . add ( component ) ; } catch ( IOException e ) { onError . accept ( e ) ; return null ; } if ( ! data . isInMemory ( ) ) { fileAccess . getAndUpdate ( channel -> { if ( channel == null ) { try { return new RandomAccessFile ( data . getFile ( ) , "r" ) ; } catch ( IOException e ) { onError . accept ( e ) ; } } return channel ; } ) ; } return component ; } | Adds a reference to a section of the http data . Should only be called after data has been added to the underlying http data . |
21,210 | void removeComponent ( int index ) { Component component = components . get ( index ) ; components . remove ( index ) ; updateComponentOffsets ( index ) ; position . getAndUpdate ( ( offset ) -> offset - component . length ) ; } | Removes a section from the http data and updates the indices of the remaining components . |
21,211 | void destroy ( ) { fileAccess . getAndUpdate ( channel -> { if ( channel != null ) { try { channel . close ( ) ; } catch ( IOException e ) { LOG . warn ( "Error closing file channel for disk file upload" , e ) ; } } return null ; } ) ; data . release ( ) ; } | Closes any file related access if the upload is on disk and releases the buffer for the file . |
21,212 | public static String convertDotToUnderscore ( String dottedProperty , boolean uppercase ) { if ( dottedProperty == null ) { return dottedProperty ; } Optional < String > converted = Optional . of ( dottedProperty ) . map ( value -> value . replace ( '.' , '_' ) ) . map ( value -> uppercase ? value . toUpperCase ( ) : value ) ; return converted . get ( ) ; } | Replace the dots in the property with underscore and transform to uppercase based on given flag . |
21,213 | public static String capitalize ( String str ) { char [ ] array = str . toCharArray ( ) ; if ( array . length > 0 ) { array [ 0 ] = Character . toUpperCase ( array [ 0 ] ) ; } return new String ( array ) ; } | Capitalizes the first character of the provided string . |
21,214 | static String buildMessage ( BeanResolutionContext resolutionContext , Argument argument , String message , boolean circular ) { StringBuilder builder = new StringBuilder ( "Failed to inject value for parameter [" ) ; String ls = System . getProperty ( "line.separator" ) ; BeanResolutionContext . Path path = resolutionContext . getPath ( ) ; builder . append ( argument . getName ( ) ) . append ( "] of class: " ) . append ( path . peek ( ) . getDeclaringType ( ) . getName ( ) ) . append ( ls ) . append ( ls ) ; if ( message != null ) { builder . append ( "Message: " ) . append ( message ) . append ( ls ) ; } appendPath ( circular , builder , ls , path ) ; return builder . toString ( ) ; } | Builds an appropriate error message for a constructor argument . |
21,215 | @ SuppressWarnings ( "unchecked" ) static void registerAnnotationType ( AnnotationClassValue < ? > annotationClassValue ) { final String name = annotationClassValue . getName ( ) ; if ( ! ANNOTATION_TYPES . containsKey ( name ) ) { annotationClassValue . getType ( ) . ifPresent ( ( Consumer < Class < ? > > ) aClass -> { if ( Annotation . class . isAssignableFrom ( aClass ) ) { ANNOTATION_TYPES . put ( name , ( Class < ? extends Annotation > ) aClass ) ; } } ) ; } } | Registers a annotation type . |
21,216 | protected ChannelFuture handleHandshake ( ChannelHandlerContext ctx , NettyHttpRequest req , WebSocketBean < ? > webSocketBean , MutableHttpResponse < ? > response ) { int maxFramePayloadLength = webSocketBean . messageMethod ( ) . flatMap ( m -> m . getValue ( OnMessage . class , "maxPayloadLength" , Integer . class ) ) . orElse ( 65536 ) ; WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory ( getWebSocketURL ( ctx , req ) , null , true , maxFramePayloadLength ) ; handshaker = wsFactory . newHandshaker ( req . getNativeRequest ( ) ) ; MutableHttpHeaders headers = response . getHeaders ( ) ; io . netty . handler . codec . http . HttpHeaders nettyHeaders ; if ( headers instanceof NettyHttpHeaders ) { nettyHeaders = ( ( NettyHttpHeaders ) headers ) . getNettyHeaders ( ) ; } else { nettyHeaders = new DefaultHttpHeaders ( ) ; for ( Map . Entry < String , List < String > > entry : headers ) { nettyHeaders . add ( entry . getKey ( ) , entry . getValue ( ) ) ; } } Channel channel = ctx . channel ( ) ; if ( handshaker == null ) { return WebSocketServerHandshakerFactory . sendUnsupportedVersionResponse ( channel ) ; } else { return handshaker . handshake ( channel , req . getNativeRequest ( ) , nettyHeaders , channel . newPromise ( ) ) ; } } | Do the handshaking for WebSocket request . |
21,217 | protected String getWebSocketURL ( ChannelHandlerContext ctx , HttpRequest req ) { boolean isSecure = ctx . pipeline ( ) . get ( SslHandler . class ) != null ; return ( isSecure ? SCHEME_SECURE_WEBSOCKET : SCHEME_WEBSOCKET ) + req . getHeaders ( ) . get ( HttpHeaderNames . HOST ) + req . getUri ( ) ; } | Obtains the web socket URL . |
21,218 | public static String getClassName ( Resource resource ) { try { return getClassName ( resource . getFile ( ) . getAbsolutePath ( ) ) ; } catch ( IOException e ) { return null ; } } | Gets the class name of the specified Micronaut resource . |
21,219 | public static String getClassName ( String path ) { for ( Pattern pattern : patterns ) { Matcher m = pattern . matcher ( path ) ; if ( m . find ( ) ) { return m . group ( 1 ) . replaceAll ( "[/\\\\]" , "." ) ; } } return null ; } | Returns the class name for a resource . |
21,220 | public static boolean isFileURL ( URL url ) { String protocol = url . getProtocol ( ) ; return ( URL_PROTOCOL_FILE . equals ( protocol ) || protocol . startsWith ( URL_PROTOCOL_VFS ) ) ; } | Determine whether the given URL points to a resource in the file system that is has protocol file or vfs . |
21,221 | public < T > Class < T > getPropertyAsClass ( String key , Class < T > targetType ) { Optional < String > property = propertyResolver . getProperty ( NameUtils . hyphenate ( key ) , String . class ) ; if ( property . isPresent ( ) ) { Optional < Class > aClass = ClassUtils . forName ( property . get ( ) , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; if ( aClass . isPresent ( ) ) { return aClass . get ( ) ; } } return null ; } | Return the property value converted to a class loaded by the current thread context class loader . |
21,222 | public synchronized BeanContext start ( ) { if ( ! isRunning ( ) ) { if ( initializing . compareAndSet ( false , true ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Starting BeanContext" ) ; } readAllBeanConfigurations ( ) ; readAllBeanDefinitionClasses ( ) ; if ( LOG . isDebugEnabled ( ) ) { String activeConfigurations = beanConfigurations . values ( ) . stream ( ) . filter ( config -> config . isEnabled ( this ) ) . map ( BeanConfiguration :: getName ) . collect ( Collectors . joining ( "," ) ) ; if ( StringUtils . isNotEmpty ( activeConfigurations ) ) { LOG . debug ( "Loaded active configurations: {}" , activeConfigurations ) ; } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "BeanContext Started." ) ; } publishEvent ( new StartupEvent ( this ) ) ; } processParallelBeans ( ) ; running . set ( true ) ; initializing . set ( false ) ; } return this ; } | The start method will read all bean definition classes found on the classpath and initialize any pre - required state . |
21,223 | protected < T > Stream < T > streamOfType ( BeanResolutionContext resolutionContext , Class < T > beanType , Qualifier < T > qualifier ) { return getBeansOfTypeInternal ( resolutionContext , beanType , qualifier ) . stream ( ) ; } | Obtains a stream of beans of the given type and qualifier . |
21,224 | protected void processParallelBeans ( ) { new Thread ( ( ) -> { final List < BeanDefinitionReference > parallelBeans = beanDefinitionsClasses . stream ( ) . filter ( bd -> bd . getAnnotationMetadata ( ) . hasDeclaredStereotype ( Parallel . class ) && bd . isEnabled ( this ) ) . collect ( Collectors . toList ( ) ) ; Collection < BeanDefinition > parallelDefinitions = new ArrayList < > ( ) ; parallelBeans . forEach ( beanDefinitionReference -> { try { if ( isRunning ( ) ) { synchronized ( singletonObjects ) { loadContextScopeBean ( beanDefinitionReference , parallelDefinitions :: add ) ; } } } catch ( Throwable e ) { LOG . error ( "Parallel Bean definition [" + beanDefinitionReference . getName ( ) + "] could not be loaded: " + e . getMessage ( ) , e ) ; Boolean shutdownOnError = beanDefinitionReference . getAnnotationMetadata ( ) . getValue ( Parallel . class , "shutdownOnError" , Boolean . class ) . orElse ( true ) ; if ( shutdownOnError ) { stop ( ) ; } } } ) ; filterProxiedTypes ( ( Collection ) parallelDefinitions , true , false ) ; filterReplacedBeans ( ( Collection ) parallelDefinitions ) ; parallelDefinitions . forEach ( beanDefinition -> ForkJoinPool . commonPool ( ) . execute ( ( ) -> { try { if ( isRunning ( ) ) { synchronized ( singletonObjects ) { loadContextScopeBean ( beanDefinition ) ; } } } catch ( Throwable e ) { LOG . error ( "Parallel Bean definition [" + beanDefinition . getName ( ) + "] could not be loaded: " + e . getMessage ( ) , e ) ; Boolean shutdownOnError = beanDefinition . getAnnotationMetadata ( ) . getValue ( Parallel . class , "shutdownOnError" , Boolean . class ) . orElse ( true ) ; if ( shutdownOnError ) { stop ( ) ; } } } ) ) ; parallelDefinitions . clear ( ) ; } ) . start ( ) ; } | Processes parallel bean definitions . |
21,225 | @ SuppressWarnings ( "unchecked" ) private < T > Optional < BeanDefinition < T > > findConcreteCandidate ( Class < T > beanType , Qualifier < T > qualifier , boolean throwNonUnique , boolean includeProvided ) { return ( Optional ) beanConcreteCandidateCache . computeIfAbsent ( new BeanKey ( beanType , qualifier ) , beanKey -> ( Optional ) findConcreteCandidateNoCache ( beanType , qualifier , throwNonUnique , includeProvided , true ) ) ; } | Find a concrete candidate for the given qualifier . |
21,226 | public Stream < Class > scan ( String annotation , String pkg ) { if ( pkg == null ) { return Stream . empty ( ) ; } List < Class > classes = doScan ( annotation , pkg ) ; return classes . stream ( ) ; } | Scan the given packages . |
21,227 | protected void closeWatchService ( ) { try { getWatchService ( ) . close ( ) ; } catch ( IOException e ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Error stopping file watch service: " + e . getMessage ( ) , e ) ; } } } | Closes the watch service . |
21,228 | protected UriRoute buildRoute ( HttpMethod httpMethod , String uri , Class < ? > type , String method , Class ... parameterTypes ) { Optional < ? extends MethodExecutionHandle < ? , Object > > executionHandle = executionHandleLocator . findExecutionHandle ( type , method , parameterTypes ) ; MethodExecutionHandle < ? , Object > executableHandle = executionHandle . orElseThrow ( ( ) -> new RoutingException ( "No such route: " + type . getName ( ) + "." + method ) ) ; return buildRoute ( httpMethod , uri , executableHandle ) ; } | Build a route . |
21,229 | public static < T > Stream < T > sort ( Stream < T > list ) { return list . sorted ( COMPARATOR ) ; } | Sort the given list . |
21,230 | public List < Segment > buildSegments ( String str ) { List < Segment > segments = new ArrayList < > ( ) ; String value = str ; int i = value . indexOf ( PREFIX ) ; while ( i > - 1 ) { if ( i > 0 ) { String rawSegment = value . substring ( 0 , i ) ; segments . add ( new RawSegment ( rawSegment ) ) ; } value = value . substring ( i + PREFIX . length ( ) ) ; int suffixIdx = value . indexOf ( SUFFIX ) ; if ( suffixIdx > - 1 ) { String expr = value . substring ( 0 , suffixIdx ) . trim ( ) ; segments . add ( new PlaceholderSegment ( expr ) ) ; if ( value . length ( ) > suffixIdx ) { value = value . substring ( suffixIdx + SUFFIX . length ( ) ) ; } } else { throw new ConfigurationException ( "Incomplete placeholder definitions detected: " + str ) ; } i = value . indexOf ( PREFIX ) ; } if ( value . length ( ) > 0 ) { segments . add ( new RawSegment ( value ) ) ; } return segments ; } | Split a placeholder value into logic segments . |
21,231 | protected boolean resolveReplacement ( StringBuilder builder , String str , String expr ) { if ( environment . containsProperty ( expr ) ) { builder . append ( environment . getProperty ( expr , String . class ) . orElseThrow ( ( ) -> new ConfigurationException ( "Could not resolve placeholder ${" + expr + "} in value: " + str ) ) ) ; return true ; } return false ; } | Resolves a replacement for the given expression . Returning true if the replacement was resolved . |
21,232 | protected < T > T resolveExpression ( String context , String expression , Class < T > type ) { if ( environment . containsProperty ( expression ) ) { return environment . getProperty ( expression , type ) . orElseThrow ( ( ) -> new ConfigurationException ( "Could not resolve expression: [" + expression + "] in placeholder ${" + context + "}" ) ) ; } if ( NameUtils . isEnvironmentName ( expression ) ) { String envVar = System . getenv ( expression ) ; if ( StringUtils . isNotEmpty ( envVar ) ) { return conversionService . convert ( envVar , type ) . orElseThrow ( ( ) -> new ConfigurationException ( "Could not resolve expression: [" + expression + "] in placeholder ${" + context + "}" ) ) ; } } return null ; } | Resolves a single expression . |
21,233 | protected void registerDefaultConverters ( ConversionService < ? > conversionService ) { conversionService . addConverter ( CharSequence . class , MediaType . class , ( object , targetType , context ) -> { if ( StringUtils . isEmpty ( object ) ) { return Optional . empty ( ) ; } else { final String str = object . toString ( ) ; try { return Optional . of ( new MediaType ( str ) ) ; } catch ( IllegalArgumentException e ) { context . reject ( e ) ; return Optional . empty ( ) ; } } } ) ; } | Registers a default converter . |
21,234 | @ Scheduled ( fixedDelay = "${micronaut.health.monitor.interval:1m}" , initialDelay = "${micronaut.health.monitor.initial-delay:1m}" ) void monitor ( ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Starting health monitor check" ) ; } List < Publisher < HealthResult > > healthResults = healthIndicators . stream ( ) . map ( HealthIndicator :: getResult ) . collect ( Collectors . toList ( ) ) ; Flowable < HealthResult > resultFlowable = Flowable . merge ( healthResults ) . filter ( healthResult -> { HealthStatus status = healthResult . getStatus ( ) ; return status . equals ( HealthStatus . DOWN ) || ! status . getOperational ( ) . orElse ( true ) ; } ) ; resultFlowable . firstElement ( ) . subscribe ( new MaybeObserver < HealthResult > ( ) { public void onSubscribe ( Disposable d ) { } public void onSuccess ( HealthResult healthResult ) { HealthStatus status = healthResult . getStatus ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Health monitor check failed with status {}" , status ) ; } currentHealthStatus . update ( status ) ; } public void onError ( Throwable e ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Health monitor check failed with exception: " + e . getMessage ( ) , e ) ; } currentHealthStatus . update ( HealthStatus . DOWN . describe ( "Error occurred running health check: " + e . getMessage ( ) ) ) ; } public void onComplete ( ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Health monitor check passed." ) ; } currentHealthStatus . update ( HealthStatus . UP ) ; } } ) ; } | Start the continuous health monitor . |
21,235 | public static < T > Set < T > setOf ( T ... objects ) { if ( objects == null || objects . length == 0 ) { return Collections . emptySet ( ) ; } return new HashSet < > ( Arrays . asList ( objects ) ) ; } | Creates a set of the given objects . |
21,236 | public CommandLineParser addOption ( String name , String description ) { int length = name . length ( ) ; if ( length > longestOptionNameLength ) { longestOptionNameLength = length ; } declaredOptions . put ( name , new Option ( name , description ) ) ; return this ; } | Adds a declared option . |
21,237 | CommandLine parse ( DefaultCommandLine cl , String [ ] args ) { parseInternal ( cl , args , true ) ; return cl ; } | Parse the command line entry . |
21,238 | public String getOptionsHelpMessage ( ) { String ls = System . getProperty ( "line.separator" ) ; usageMessage = "Available options:" ; StringBuilder sb = new StringBuilder ( usageMessage ) ; sb . append ( ls ) ; for ( Option option : declaredOptions . values ( ) ) { String name = option . getName ( ) ; int extraPadding = longestOptionNameLength - name . length ( ) ; sb . append ( " -" ) . append ( name ) ; for ( int i = 0 ; i < extraPadding ; i ++ ) { sb . append ( ' ' ) ; } sb . append ( DEFAULT_PADDING ) . append ( option . getDescription ( ) ) . append ( ls ) ; } return sb . toString ( ) ; } | Build the options message . |
21,239 | protected String processOption ( DefaultCommandLine cl , String arg ) { if ( arg . length ( ) < 2 ) { return null ; } if ( arg . charAt ( 1 ) == 'D' && arg . contains ( "=" ) ) { processSystemArg ( cl , arg ) ; return null ; } arg = ( arg . charAt ( 1 ) == '-' ? arg . substring ( 2 , arg . length ( ) ) : arg . substring ( 1 , arg . length ( ) ) ) . trim ( ) ; if ( arg . contains ( "=" ) ) { String [ ] split = arg . split ( "=" ) ; String name = split [ 0 ] . trim ( ) ; validateOptionName ( name ) ; String value = split [ 1 ] . trim ( ) ; if ( declaredOptions . containsKey ( name ) ) { cl . addDeclaredOption ( declaredOptions . get ( name ) , value ) ; } else { cl . addUndeclaredOption ( name , value ) ; } return null ; } validateOptionName ( arg ) ; if ( declaredOptions . containsKey ( arg ) ) { cl . addDeclaredOption ( declaredOptions . get ( arg ) ) ; } else { cl . addUndeclaredOption ( arg ) ; } return arg ; } | Process the passed in options . |
21,240 | protected void processSystemArg ( DefaultCommandLine cl , String arg ) { int i = arg . indexOf ( "=" ) ; String name = arg . substring ( 2 , i ) ; String value = arg . substring ( i + 1 , arg . length ( ) ) ; cl . addSystemProperty ( name , value ) ; } | Process System property arg . |
21,241 | @ SuppressWarnings ( "WeakerAccess" ) protected final void addAnnotation ( String annotation , Map < CharSequence , Object > values ) { if ( annotation != null ) { String repeatedName = getRepeatedName ( annotation ) ; Object v = values . get ( AnnotationMetadata . VALUE_MEMBER ) ; if ( v instanceof io . micronaut . core . annotation . AnnotationValue [ ] ) { io . micronaut . core . annotation . AnnotationValue [ ] avs = ( io . micronaut . core . annotation . AnnotationValue [ ] ) v ; for ( io . micronaut . core . annotation . AnnotationValue av : avs ) { addRepeatable ( annotation , av ) ; } } else if ( v instanceof Iterable && repeatedName != null ) { Iterable i = ( Iterable ) v ; for ( Object o : i ) { if ( o instanceof io . micronaut . core . annotation . AnnotationValue ) { addRepeatable ( annotation , ( ( io . micronaut . core . annotation . AnnotationValue ) o ) ) ; } } } else { Map < String , Map < CharSequence , Object > > allAnnotations = getAllAnnotations ( ) ; addAnnotation ( annotation , values , null , allAnnotations , false ) ; } } } | Adds an annotation and its member values if the annotation already exists the data will be merged with existing values replaced . |
21,242 | @ SuppressWarnings ( "unused" ) protected static void registerAnnotationDefaults ( String annotation , Map < String , Object > defaultValues ) { AnnotationMetadataSupport . registerDefaultValues ( annotation , defaultValues ) ; } | Registers annotation default values . Used by generated byte code . DO NOT REMOVE . |
21,243 | protected final void addRepeatable ( String annotationName , io . micronaut . core . annotation . AnnotationValue annotationValue ) { if ( StringUtils . isNotEmpty ( annotationName ) && annotationValue != null ) { Map < String , Map < CharSequence , Object > > allAnnotations = getAllAnnotations ( ) ; addRepeatableInternal ( annotationName , annotationValue , allAnnotations ) ; } } | Adds a repeatable annotation value . If a value already exists will be added |
21,244 | protected void addRepeatableStereotype ( List < String > parents , String stereotype , io . micronaut . core . annotation . AnnotationValue annotationValue ) { Map < String , Map < CharSequence , Object > > allStereotypes = getAllStereotypes ( ) ; List < String > annotationList = getAnnotationsByStereotypeInternal ( stereotype ) ; for ( String parentAnnotation : parents ) { if ( ! annotationList . contains ( parentAnnotation ) ) { annotationList . add ( parentAnnotation ) ; } } addRepeatableInternal ( stereotype , annotationValue , allStereotypes ) ; } | Adds a repeatable stereotype value . If a value already exists will be added |
21,245 | @ SuppressWarnings ( "WeakerAccess" ) protected final void addDeclaredStereotype ( List < String > parentAnnotations , String stereotype , Map < CharSequence , Object > values ) { if ( stereotype != null ) { String repeatedName = getRepeatedName ( stereotype ) ; if ( repeatedName != null ) { Object v = values . get ( AnnotationMetadata . VALUE_MEMBER ) ; if ( v instanceof io . micronaut . core . annotation . AnnotationValue [ ] ) { io . micronaut . core . annotation . AnnotationValue [ ] avs = ( io . micronaut . core . annotation . AnnotationValue [ ] ) v ; for ( io . micronaut . core . annotation . AnnotationValue av : avs ) { addDeclaredRepeatableStereotype ( parentAnnotations , stereotype , av ) ; } } else if ( v instanceof Iterable ) { Iterable i = ( Iterable ) v ; for ( Object o : i ) { if ( o instanceof io . micronaut . core . annotation . AnnotationValue ) { addDeclaredRepeatableStereotype ( parentAnnotations , stereotype , ( io . micronaut . core . annotation . AnnotationValue ) o ) ; } } } } else { Map < String , Map < CharSequence , Object > > declaredStereotypes = getDeclaredStereotypesInternal ( ) ; Map < String , Map < CharSequence , Object > > allStereotypes = getAllStereotypes ( ) ; List < String > annotationList = getAnnotationsByStereotypeInternal ( stereotype ) ; for ( String parentAnnotation : parentAnnotations ) { if ( ! annotationList . contains ( parentAnnotation ) ) { annotationList . add ( parentAnnotation ) ; } } addAnnotation ( stereotype , values , declaredStereotypes , allStereotypes , true ) ; } } } | Adds a stereotype and its member values if the annotation already exists the data will be merged with existing values replaced . |
21,246 | @ SuppressWarnings ( "unused" ) void dump ( ) { System . out . println ( "declaredAnnotations = " + declaredAnnotations ) ; System . out . println ( "declaredStereotypes = " + declaredStereotypes ) ; System . out . println ( "allAnnotations = " + allAnnotations ) ; System . out . println ( "allStereotypes = " + allStereotypes ) ; System . out . println ( "annotationsByStereotype = " + annotationsByStereotype ) ; } | Dump the values . |
21,247 | public static void contributeDefaults ( AnnotationMetadata target , AnnotationMetadata source ) { if ( target instanceof DefaultAnnotationMetadata && source instanceof DefaultAnnotationMetadata ) { final Map < String , Map < CharSequence , Object > > existingDefaults = ( ( DefaultAnnotationMetadata ) target ) . annotationDefaultValues ; if ( existingDefaults != null ) { final Map < String , Map < CharSequence , Object > > additionalDefaults = ( ( DefaultAnnotationMetadata ) source ) . annotationDefaultValues ; if ( additionalDefaults != null ) { existingDefaults . putAll ( additionalDefaults ) ; } } } } | Contributes defaults to the given target . |
21,248 | protected Cache < String , InMemorySession > newSessionCache ( SessionConfiguration configuration ) { Caffeine < String , InMemorySession > builder = Caffeine . newBuilder ( ) . removalListener ( newRemovalListener ( ) ) . expireAfter ( newExpiry ( ) ) ; configuration . getMaxActiveSessions ( ) . ifPresent ( builder :: maximumSize ) ; return builder . build ( ) ; } | Creates a new session cache . |
21,249 | @ SuppressWarnings ( "MagicNumber" ) public static int calculateHashCode ( Map < ? extends CharSequence , Object > values ) { int hashCode = 0 ; for ( Map . Entry < ? extends CharSequence , Object > member : values . entrySet ( ) ) { Object value = member . getValue ( ) ; int nameHashCode = member . getKey ( ) . hashCode ( ) ; int valueHashCode = ! value . getClass ( ) . isArray ( ) ? value . hashCode ( ) : value . getClass ( ) == boolean [ ] . class ? Arrays . hashCode ( ( boolean [ ] ) value ) : value . getClass ( ) == byte [ ] . class ? Arrays . hashCode ( ( byte [ ] ) value ) : value . getClass ( ) == char [ ] . class ? Arrays . hashCode ( ( char [ ] ) value ) : value . getClass ( ) == double [ ] . class ? Arrays . hashCode ( ( double [ ] ) value ) : value . getClass ( ) == float [ ] . class ? Arrays . hashCode ( ( float [ ] ) value ) : value . getClass ( ) == int [ ] . class ? Arrays . hashCode ( ( int [ ] ) value ) : value . getClass ( ) == long [ ] . class ? Arrays . hashCode ( ( long [ ] ) value ) : value . getClass ( ) == short [ ] . class ? Arrays . hashCode ( ( short [ ] ) value ) : Arrays . hashCode ( ( Object [ ] ) value ) ; hashCode += 127 * nameHashCode ^ valueHashCode ; } return hashCode ; } | Calculates the hash code of annotation values . |
21,250 | public static boolean areEqual ( Object o1 , Object o2 ) { return ! o1 . getClass ( ) . isArray ( ) ? o1 . equals ( o2 ) : o1 . getClass ( ) == boolean [ ] . class ? Arrays . equals ( ( boolean [ ] ) o1 , ( boolean [ ] ) o2 ) : o1 . getClass ( ) == byte [ ] . class ? Arrays . equals ( ( byte [ ] ) o1 , ( byte [ ] ) o2 ) : o1 . getClass ( ) == char [ ] . class ? Arrays . equals ( ( char [ ] ) o1 , ( char [ ] ) o2 ) : o1 . getClass ( ) == double [ ] . class ? Arrays . equals ( ( double [ ] ) o1 , ( double [ ] ) o2 ) : o1 . getClass ( ) == float [ ] . class ? Arrays . equals ( ( float [ ] ) o1 , ( float [ ] ) o2 ) : o1 . getClass ( ) == int [ ] . class ? Arrays . equals ( ( int [ ] ) o1 , ( int [ ] ) o2 ) : o1 . getClass ( ) == long [ ] . class ? Arrays . equals ( ( long [ ] ) o1 , ( long [ ] ) o2 ) : o1 . getClass ( ) == short [ ] . class ? Arrays . equals ( ( short [ ] ) o1 , ( short [ ] ) o2 ) : Arrays . equals ( ( Object [ ] ) o1 , ( Object [ ] ) o2 ) ; } | Computes whether 2 annotation values are equal . |
21,251 | private int readAnnotationValues ( int v , final char [ ] buf , final boolean named , final AnnotationVisitor av ) { int i = readUnsignedShort ( v ) ; v += 2 ; if ( named ) { for ( ; i > 0 ; -- i ) { v = readAnnotationValue ( v + 2 , buf , readUTF8 ( v , buf ) , av ) ; } } else { for ( ; i > 0 ; -- i ) { v = readAnnotationValue ( v , buf , null , av ) ; } } if ( av != null ) { av . visitEnd ( ) ; } return v ; } | Reads the values of an annotation and makes the given visitor visit them . |
21,252 | protected Label readLabel ( int offset , Label [ ] labels ) { if ( offset >= labels . length ) { return new Label ( ) ; } if ( labels [ offset ] == null ) { labels [ offset ] = new Label ( ) ; } return labels [ offset ] ; } | Returns the label corresponding to the given offset . The default implementation of this method creates a label for the given offset if it has not been already created . |
21,253 | private int getAttributes ( ) { int u = header + 8 + readUnsignedShort ( header + 6 ) * 2 ; for ( int i = readUnsignedShort ( u ) ; i > 0 ; -- i ) { for ( int j = readUnsignedShort ( u + 8 ) ; j > 0 ; -- j ) { u += 6 + readInt ( u + 12 ) ; } u += 8 ; } u += 2 ; for ( int i = readUnsignedShort ( u ) ; i > 0 ; -- i ) { for ( int j = readUnsignedShort ( u + 8 ) ; j > 0 ; -- j ) { u += 6 + readInt ( u + 12 ) ; } u += 8 ; } return u + 2 ; } | Returns the start index of the attribute_info structure of this class . |
21,254 | public void writeTenant ( MutableHttpRequest < ? > request , Serializable tenant ) { if ( tenant instanceof CharSequence ) { request . header ( getHeaderName ( ) , ( CharSequence ) tenant ) ; } } | Writes the token to the request . |
21,255 | public static Set < String > calcPropertySourceNames ( String prefix , Set < String > activeNames , String separator ) { Set < String > propertySourceNames ; if ( prefix . contains ( separator ) ) { String [ ] tokens = prefix . split ( separator ) ; if ( tokens . length == 1 ) { propertySourceNames = Collections . singleton ( tokens [ 0 ] ) ; } else { String name = tokens [ 0 ] ; Set < String > newSet = new HashSet < > ( tokens . length - 1 ) ; for ( int j = 1 ; j < tokens . length ; j ++ ) { String envName = tokens [ j ] ; if ( ! activeNames . contains ( envName ) ) { return Collections . emptySet ( ) ; } newSet . add ( name + '[' + envName + ']' ) ; } propertySourceNames = newSet ; } } else { propertySourceNames = Collections . singleton ( prefix ) ; } return propertySourceNames ; } | Calculates property source names . This is used across several clients to make naming consistent . |
21,256 | public void writeTenant ( MutableHttpRequest < ? > request , Serializable tenant ) { if ( tenant instanceof String ) { Cookie cookie = Cookie . of ( cookieTenantWriterConfiguration . getCookiename ( ) , ( String ) tenant ) ; cookie . configure ( cookieTenantWriterConfiguration , request . isSecure ( ) ) ; if ( cookieTenantWriterConfiguration . getCookieMaxAge ( ) . isPresent ( ) ) { cookie . maxAge ( cookieTenantWriterConfiguration . getCookieMaxAge ( ) . get ( ) ) ; } else { cookie . maxAge ( Integer . MAX_VALUE ) ; } request . cookie ( cookie ) ; } } | Writes the Tenant Id in a cookie of the request . |
21,257 | public List < ? extends TypeMirror > interfaceGenericTypesFor ( TypeElement element , String interfaceName ) { for ( TypeMirror tm : element . getInterfaces ( ) ) { DeclaredType declaredType = ( DeclaredType ) tm ; Element declaredElement = declaredType . asElement ( ) ; if ( declaredElement instanceof TypeElement ) { TypeElement te = ( TypeElement ) declaredElement ; if ( interfaceName . equals ( te . getQualifiedName ( ) . toString ( ) ) ) { return declaredType . getTypeArguments ( ) ; } } } return Collections . emptyList ( ) ; } | Finds the generic types for the given interface for the given class element . |
21,258 | protected Object resolveTypeReference ( TypeMirror mirror , Map < String , Object > boundTypes ) { TypeKind kind = mirror . getKind ( ) ; switch ( kind ) { case TYPEVAR : TypeVariable tv = ( TypeVariable ) mirror ; String name = tv . toString ( ) ; if ( boundTypes . containsKey ( name ) ) { return boundTypes . get ( name ) ; } else { return modelUtils . resolveTypeReference ( mirror ) ; } case WILDCARD : WildcardType wcType = ( WildcardType ) mirror ; TypeMirror extendsBound = wcType . getExtendsBound ( ) ; TypeMirror superBound = wcType . getSuperBound ( ) ; if ( extendsBound == null && superBound == null ) { return Object . class . getName ( ) ; } else if ( extendsBound != null ) { return resolveTypeReference ( typeUtils . erasure ( extendsBound ) , boundTypes ) ; } else if ( superBound != null ) { return resolveTypeReference ( superBound , boundTypes ) ; } else { return resolveTypeReference ( typeUtils . getWildcardType ( extendsBound , superBound ) , boundTypes ) ; } case ARRAY : ArrayType arrayType = ( ArrayType ) mirror ; Object reference = resolveTypeReference ( arrayType . getComponentType ( ) , boundTypes ) ; if ( reference instanceof Class ) { Class componentType = ( Class ) reference ; return Array . newInstance ( componentType , 0 ) . getClass ( ) ; } else if ( reference instanceof String ) { return reference + "[]" ; } else { return modelUtils . resolveTypeReference ( mirror ) ; } case BOOLEAN : case BYTE : case CHAR : case DOUBLE : case FLOAT : case INT : case LONG : case SHORT : Optional < Class > type = ClassUtils . getPrimitiveType ( mirror . toString ( ) ) ; if ( type . isPresent ( ) ) { return type . get ( ) ; } else { throw new IllegalStateException ( "Unknown primitive type: " + mirror . toString ( ) ) ; } default : return modelUtils . resolveTypeReference ( mirror ) ; } } | Resolve a type reference to use for the given type mirror taking into account generic type variables . |
21,259 | protected DeclaredType resolveTypeVariable ( Element element , TypeVariable typeVariable ) { Element enclosing = element . getEnclosingElement ( ) ; while ( enclosing instanceof Parameterizable ) { Parameterizable parameterizable = ( Parameterizable ) enclosing ; String name = typeVariable . toString ( ) ; for ( TypeParameterElement typeParameter : parameterizable . getTypeParameters ( ) ) { if ( name . equals ( typeParameter . toString ( ) ) ) { List < ? extends TypeMirror > bounds = typeParameter . getBounds ( ) ; if ( bounds . size ( ) == 1 ) { TypeMirror typeMirror = bounds . get ( 0 ) ; if ( typeMirror . getKind ( ) == TypeKind . DECLARED ) { return ( DeclaredType ) typeMirror ; } } } } enclosing = enclosing . getEnclosingElement ( ) ; } return null ; } | Resolve the first type argument to a parameterized type . |
21,260 | protected Map < String , Object > resolveBoundTypes ( DeclaredType type ) { Map < String , Object > boundTypes = new LinkedHashMap < > ( 2 ) ; TypeElement element = ( TypeElement ) type . asElement ( ) ; List < ? extends TypeParameterElement > typeParameters = element . getTypeParameters ( ) ; List < ? extends TypeMirror > typeArguments = type . getTypeArguments ( ) ; if ( typeArguments . size ( ) == typeParameters . size ( ) ) { Iterator < ? extends TypeMirror > i = typeArguments . iterator ( ) ; for ( TypeParameterElement typeParameter : typeParameters ) { boundTypes . put ( typeParameter . toString ( ) , resolveTypeReference ( i . next ( ) , boundTypes ) ) ; } } return boundTypes ; } | Resolve bound types for the given declared type . |
21,261 | public RouteMatch < ? > fulfillArgumentRequirements ( RouteMatch < ? > route , HttpRequest < ? > request , boolean satisfyOptionals ) { Collection < Argument > requiredArguments = route . getRequiredArguments ( ) ; Map < String , Object > argumentValues ; if ( requiredArguments . isEmpty ( ) ) { argumentValues = Collections . emptyMap ( ) ; } else { argumentValues = new LinkedHashMap < > ( ) ; for ( Argument argument : requiredArguments ) { getValueForArgument ( argument , request , satisfyOptionals ) . ifPresent ( ( value ) -> argumentValues . put ( argument . getName ( ) , value ) ) ; } } route = route . fulfill ( argumentValues ) ; return route ; } | Attempt to satisfy the arguments of the given route with the data from the given request . |
21,262 | protected String buildMessage ( ConstraintViolation violation ) { Path propertyPath = violation . getPropertyPath ( ) ; StringBuilder message = new StringBuilder ( ) ; Iterator < Path . Node > i = propertyPath . iterator ( ) ; while ( i . hasNext ( ) ) { Path . Node node = i . next ( ) ; if ( node . getKind ( ) == ElementKind . METHOD || node . getKind ( ) == ElementKind . CONSTRUCTOR ) { continue ; } message . append ( node . getName ( ) ) ; if ( i . hasNext ( ) ) { message . append ( '.' ) ; } } message . append ( ": " ) . append ( violation . getMessage ( ) ) ; return message . toString ( ) ; } | Builds a message based on the provided violation . |
21,263 | public static void logError ( Span span , Throwable e ) { HashMap < String , Object > fields = new HashMap < > ( ) ; fields . put ( Fields . ERROR_OBJECT , e ) ; String message = e . getMessage ( ) ; if ( message != null ) { fields . put ( Fields . MESSAGE , message ) ; } span . log ( fields ) ; } | Logs an error to the span . |
21,264 | public Map < String , Object > getAllProperties ( ) { Map < String , Object > map = new HashMap < > ( ) ; Arrays . stream ( catalog ) . filter ( Objects :: nonNull ) . map ( Map :: entrySet ) . flatMap ( Collection :: stream ) . forEach ( ( Map . Entry < String , Object > entry ) -> { String k = entry . getKey ( ) ; Object value = resolvePlaceHoldersIfNecessary ( entry . getValue ( ) ) ; Map finalMap = map ; int index = k . indexOf ( '.' ) ; if ( index != - 1 ) { String [ ] keys = k . split ( "\\." ) ; for ( int i = 0 ; i < keys . length - 1 ; i ++ ) { if ( ! finalMap . containsKey ( keys [ i ] ) ) { finalMap . put ( keys [ i ] , new HashMap < > ( ) ) ; } Object next = finalMap . get ( keys [ i ] ) ; if ( next instanceof Map ) { finalMap = ( ( Map ) next ) ; } } finalMap . put ( keys [ keys . length - 1 ] , value ) ; } else { finalMap . put ( k , value ) ; } } ) ; return map ; } | Returns a combined Map of all properties in the catalog . |
21,265 | protected Map < String , Object > resolveSubMap ( String name , Map < String , Object > entries , ArgumentConversionContext < ? > conversionContext , StringConvention keyConvention , MapFormat . MapTransformation transformation ) { final Argument < ? > valueType = conversionContext . getTypeVariable ( "V" ) . orElse ( Argument . OBJECT_ARGUMENT ) ; Map < String , Object > subMap = new LinkedHashMap < > ( entries . size ( ) ) ; String prefix = name + '.' ; for ( Map . Entry < String , Object > entry : entries . entrySet ( ) ) { final String key = entry . getKey ( ) ; if ( key . startsWith ( prefix ) ) { String subMapKey = key . substring ( prefix . length ( ) ) ; Object value = resolvePlaceHoldersIfNecessary ( entry . getValue ( ) ) ; if ( transformation == MapFormat . MapTransformation . FLAT ) { subMapKey = keyConvention . format ( subMapKey ) ; value = conversionService . convert ( value , valueType ) . orElse ( null ) ; subMap . put ( subMapKey , value ) ; } else { processSubmapKey ( subMap , subMapKey , value , keyConvention ) ; } } } return subMap ; } | Resolves a submap for the given name and parameters . |
21,266 | protected void handleResponse ( HttpRequest < ? > request , MutableHttpResponse < ? > response ) { HttpHeaders headers = request . getHeaders ( ) ; Optional < String > originHeader = headers . getOrigin ( ) ; originHeader . ifPresent ( requestOrigin -> { Optional < CorsOriginConfiguration > optionalConfig = getConfiguration ( requestOrigin ) ; if ( optionalConfig . isPresent ( ) ) { CorsOriginConfiguration config = optionalConfig . get ( ) ; if ( CorsUtil . isPreflightRequest ( request ) ) { Optional < HttpMethod > result = headers . getFirst ( ACCESS_CONTROL_REQUEST_METHOD , HttpMethod . class ) ; setAllowMethods ( result . get ( ) , response ) ; Argument < List > type = Argument . of ( List . class , String . class ) ; Optional < List > allowedHeaders = headers . get ( ACCESS_CONTROL_REQUEST_HEADERS , type ) ; allowedHeaders . ifPresent ( val -> setAllowHeaders ( val , response ) ) ; setMaxAge ( config . getMaxAge ( ) , response ) ; } setOrigin ( requestOrigin , response ) ; setVary ( response ) ; setExposeHeaders ( config . getExposedHeaders ( ) , response ) ; setAllowCredentials ( config , response ) ; } } ) ; } | Handles a CORS response . |
21,267 | public static < T > Supplier < T > memoized ( Supplier < T > actual ) { return new Supplier < T > ( ) { Supplier < T > delegate = this :: initialize ; boolean initialized ; public T get ( ) { return delegate . get ( ) ; } private synchronized T initialize ( ) { if ( ! initialized ) { T value = actual . get ( ) ; delegate = ( ) -> value ; initialized = true ; } return delegate . get ( ) ; } } ; } | Caches the result of supplier in a thread safe manner . |
21,268 | public static < T > Supplier < T > memoizedNonEmpty ( Supplier < T > actual ) { return new Supplier < T > ( ) { Supplier < T > delegate = this :: initialize ; boolean initialized ; public T get ( ) { return delegate . get ( ) ; } private synchronized T initialize ( ) { if ( ! initialized ) { T value = actual . get ( ) ; if ( value == null ) { return null ; } if ( value instanceof Optional ) { if ( ! ( ( Optional ) value ) . isPresent ( ) ) { return value ; } } delegate = ( ) -> value ; initialized = true ; } return delegate . get ( ) ; } } ; } | Caches the result of supplier in a thread safe manner . The result is only cached if it is non null or non empty if an optional . |
21,269 | public Maybe < Boolean > invalidateCaches ( ) { return Flowable . fromIterable ( cacheManager . getCacheNames ( ) ) . map ( cacheManager :: getCache ) . flatMap ( c -> Publishers . fromCompletableFuture ( ( ) -> c . async ( ) . invalidateAll ( ) ) ) . reduce ( ( aBoolean , aBoolean2 ) -> aBoolean && aBoolean2 ) ; } | Invalidates all the caches . |
21,270 | protected Object interceptCompletableFuture ( MethodInvocationContext < Object , Object > context , ReturnType < ? > returnTypeObject , Class returnType ) { CacheOperation cacheOperation = new CacheOperation ( context , returnType ) ; AnnotationValue < Cacheable > cacheable = cacheOperation . cacheable ; CompletableFuture < Object > returnFuture ; if ( cacheable != null ) { AsyncCache < ? > asyncCache = cacheManager . getCache ( cacheOperation . cacheableCacheName ) . async ( ) ; CacheKeyGenerator keyGenerator = resolveKeyGenerator ( cacheOperation . defaultKeyGenerator , cacheable ) ; Object [ ] params = resolveParams ( context , cacheable . get ( MEMBER_PARAMETERS , String [ ] . class , StringUtils . EMPTY_STRING_ARRAY ) ) ; Object key = keyGenerator . generateKey ( context , params ) ; CompletableFuture < Object > thisFuture = new CompletableFuture < > ( ) ; Argument < ? > firstTypeVariable = returnTypeObject . getFirstTypeVariable ( ) . orElse ( Argument . of ( Object . class ) ) ; asyncCache . get ( key , firstTypeVariable ) . whenComplete ( ( BiConsumer < Optional < ? > , Throwable > ) ( o , throwable ) -> { if ( throwable == null && o . isPresent ( ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Value found in cache [" + asyncCache . getName ( ) + "] for invocation: " + context ) ; } thisFuture . complete ( o . get ( ) ) ; } else { try { if ( throwable != null ) { if ( errorHandler . handleLoadError ( asyncCache , key , asRuntimeException ( throwable ) ) ) { thisFuture . completeExceptionally ( throwable ) ; return ; } } CompletableFuture < ? > completableFuture = ( CompletableFuture ) context . proceed ( ) ; if ( completableFuture == null ) { thisFuture . complete ( null ) ; } else { completableFuture . whenComplete ( ( BiConsumer < Object , Throwable > ) ( o1 , t2 ) -> { if ( t2 != null ) { thisFuture . completeExceptionally ( t2 ) ; } else { asyncCache . put ( key , o1 ) . whenComplete ( ( aBoolean , throwable1 ) -> { if ( throwable1 == null ) { thisFuture . complete ( o1 ) ; } else { thisFuture . completeExceptionally ( throwable1 ) ; } } ) ; } } ) ; } } catch ( RuntimeException e ) { thisFuture . completeExceptionally ( e ) ; } } } ) ; returnFuture = thisFuture ; } else { returnFuture = ( CompletableFuture < Object > ) context . proceed ( ) ; } if ( cacheOperation . hasWriteOperations ( ) ) { returnFuture = processFuturePutOperations ( context , cacheOperation , returnFuture ) ; } return returnFuture ; } | Intercept the aync method invocation . |
21,271 | public static < T , A , D > Collector < T , ? , D > maxAll ( Comparator < ? super T > comparator , Collector < ? super T , A , D > downstream ) { Supplier < A > downstreamSupplier = downstream . supplier ( ) ; BiConsumer < A , ? super T > downstreamAccumulator = downstream . accumulator ( ) ; BinaryOperator < A > downstreamCombiner = downstream . combiner ( ) ; class Container { A acc ; T obj ; boolean hasAny ; Container ( A acc ) { this . acc = acc ; } } Supplier < Container > supplier = ( ) -> new Container ( downstreamSupplier . get ( ) ) ; BiConsumer < Container , T > accumulator = ( acc , t ) -> { if ( ! acc . hasAny ) { downstreamAccumulator . accept ( acc . acc , t ) ; acc . obj = t ; acc . hasAny = true ; } else { int cmp = comparator . compare ( t , acc . obj ) ; if ( cmp > 0 ) { acc . acc = downstreamSupplier . get ( ) ; acc . obj = t ; } if ( cmp >= 0 ) { downstreamAccumulator . accept ( acc . acc , t ) ; } } } ; BinaryOperator < Container > combiner = ( acc1 , acc2 ) -> { if ( ! acc2 . hasAny ) { return acc1 ; } if ( ! acc1 . hasAny ) { return acc2 ; } int cmp = comparator . compare ( acc1 . obj , acc2 . obj ) ; if ( cmp > 0 ) { return acc1 ; } if ( cmp < 0 ) { return acc2 ; } acc1 . acc = downstreamCombiner . apply ( acc1 . acc , acc2 . acc ) ; return acc1 ; } ; Function < Container , D > finisher = acc -> downstream . finisher ( ) . apply ( acc . acc ) ; return Collector . of ( supplier , accumulator , combiner , finisher ) ; } | A collector that returns all results that are the maximum based on the provided comparator . |
21,272 | @ SuppressWarnings ( "WeakerAccess" ) protected Object resolveModel ( Object responseBody ) { if ( responseBody instanceof ModelAndView ) { return ( ( ModelAndView ) responseBody ) . getModel ( ) . orElse ( null ) ; } return responseBody ; } | Resolves the model for the given response body . Subclasses can override to customize . |
21,273 | @ SuppressWarnings ( "WeakerAccess" ) protected Optional < String > resolveView ( AnnotationMetadata route , Object responseBody ) { Optional optionalViewName = route . getValue ( View . class ) ; if ( optionalViewName . isPresent ( ) ) { return Optional . of ( ( String ) optionalViewName . get ( ) ) ; } else if ( responseBody instanceof ModelAndView ) { return ( ( ModelAndView ) responseBody ) . getView ( ) ; } return Optional . empty ( ) ; } | Resolves the view for the given method and response body . Subclasses can override to customize . |
21,274 | public static Optional < Class > arrayTypeForPrimitive ( String primitiveType ) { if ( primitiveType != null ) { return Optional . ofNullable ( PRIMITIVE_ARRAY_MAP . get ( primitiveType ) ) ; } return Optional . empty ( ) ; } | Returns the array type for the given primitive type name . |
21,275 | public static List < Class > resolveHierarchy ( Class < ? > type ) { Class < ? > superclass = type . getSuperclass ( ) ; List < Class > hierarchy = new ArrayList < > ( ) ; if ( superclass != null ) { populateHierarchyInterfaces ( type , hierarchy ) ; while ( superclass != Object . class ) { populateHierarchyInterfaces ( superclass , hierarchy ) ; superclass = superclass . getSuperclass ( ) ; } } else if ( type . isInterface ( ) ) { populateHierarchyInterfaces ( type , hierarchy ) ; } if ( type . isArray ( ) ) { if ( ! type . getComponentType ( ) . isPrimitive ( ) ) { hierarchy . add ( Object [ ] . class ) ; } } else { hierarchy . add ( Object . class ) ; } return hierarchy ; } | Builds a class hierarchy that includes all super classes and interfaces that the given class implements or extends from . |
21,276 | protected final void warning ( Element e , String msg , Object ... args ) { if ( messager == null ) { illegalState ( ) ; } messager . printMessage ( Diagnostic . Kind . WARNING , String . format ( msg , args ) , e ) ; } | Produce a compile warning for the given element and message . |
21,277 | private String readEc2MetadataUrl ( URL url , int connectionTimeoutMs , int readTimeoutMs ) throws IOException { if ( url . getProtocol ( ) . equalsIgnoreCase ( "file" ) ) { url = rewriteUrl ( url ) ; URLConnection urlConnection = url . openConnection ( ) ; urlConnection . connect ( ) ; try ( BufferedReader in = new BufferedReader ( new InputStreamReader ( urlConnection . getInputStream ( ) ) ) ) { return IOUtils . readText ( in ) ; } } else { URLConnection urlConnection = url . openConnection ( ) ; HttpURLConnection uc = ( HttpURLConnection ) urlConnection ; uc . setConnectTimeout ( connectionTimeoutMs ) ; uc . setReadTimeout ( readTimeoutMs ) ; uc . setRequestMethod ( "GET" ) ; uc . setDoOutput ( true ) ; int responseCode = uc . getResponseCode ( ) ; try ( BufferedReader in = new BufferedReader ( new InputStreamReader ( uc . getInputStream ( ) ) ) ) { return IOUtils . readText ( in ) ; } } } | Read EC2 metadata from the given URL . |
21,278 | public static boolean isValidServiceId ( String name ) { return name != null && name . length ( ) > 0 && SERVICE_ID_REGEX . matcher ( name ) . matches ( ) && Character . isLetter ( name . charAt ( 0 ) ) ; } | Checks whether the given name is a valid service identifier . |
21,279 | public static String getSetterName ( String propertyName ) { final String suffix = getSuffixForGetterOrSetter ( propertyName ) ; return PROPERTY_SET_PREFIX + suffix ; } | Retrieves the name of a setter for the specified property name . |
21,280 | public static String getGetterName ( String propertyName ) { final String suffix = getSuffixForGetterOrSetter ( propertyName ) ; return PROPERTY_GET_PREFIX + suffix ; } | Calculate the name for a getter method to retrieve the specified property . |
21,281 | public static String getClassName ( String logicalName , String trailingName ) { if ( isBlank ( logicalName ) ) { throw new IllegalArgumentException ( "Argument [logicalName] cannot be null or blank" ) ; } String className = logicalName . substring ( 0 , 1 ) . toUpperCase ( Locale . ENGLISH ) + logicalName . substring ( 1 ) ; if ( trailingName != null ) { className = className + trailingName ; } return className ; } | Returns the class name for the given logical name and trailing name . For example person and Controller would evaluate to PersonController . |
21,282 | public static String getClassNameRepresentation ( String name ) { if ( name == null || name . length ( ) == 0 ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; String [ ] tokens = name . split ( "[^\\w\\d]" ) ; for ( String token1 : tokens ) { String token = token1 . trim ( ) ; int length = token . length ( ) ; if ( length > 0 ) { buf . append ( token . substring ( 0 , 1 ) . toUpperCase ( Locale . ENGLISH ) ) ; if ( length > 1 ) { buf . append ( token . substring ( 1 ) ) ; } } } return buf . toString ( ) ; } | Returns the class name representation of the given name . |
21,283 | private static String getClassNameForLowerCaseHyphenSeparatedName ( String name ) { if ( isBlank ( name ) ) { return name ; } if ( name . indexOf ( '-' ) == - 1 ) { return name . substring ( 0 , 1 ) . toUpperCase ( ) + name . substring ( 1 ) ; } StringBuilder buf = new StringBuilder ( ) ; String [ ] tokens = name . split ( "-" ) ; for ( String token : tokens ) { if ( token == null || token . length ( ) == 0 ) { continue ; } buf . append ( token . substring ( 0 , 1 ) . toUpperCase ( ) ) . append ( token . substring ( 1 ) ) ; } return buf . toString ( ) ; } | Converts foo - bar into FooBar . Empty and null strings are returned as - is . |
21,284 | public static String getLogicalName ( Class < ? > clazz , String trailingName ) { return getLogicalName ( clazz . getName ( ) , trailingName ) ; } | Retrieves the logical class name of a Micronaut artifact given the Micronaut class and a specified trailing name . |
21,285 | public static String getLogicalName ( String name , String trailingName ) { if ( isBlank ( trailingName ) ) { return name ; } String shortName = getShortName ( name ) ; if ( shortName . indexOf ( trailingName ) == - 1 ) { return name ; } return shortName . substring ( 0 , shortName . length ( ) - trailingName . length ( ) ) ; } | Retrieves the logical name of the class without the trailing name . |
21,286 | public static String getPropertyNameRepresentation ( String name ) { int pos = name . lastIndexOf ( '.' ) ; if ( pos != - 1 ) { name = name . substring ( pos + 1 ) ; } if ( name . isEmpty ( ) ) { return name ; } if ( name . length ( ) > 1 && Character . isUpperCase ( name . charAt ( 0 ) ) && Character . isUpperCase ( name . charAt ( 1 ) ) ) { return name ; } String propertyName = name . substring ( 0 , 1 ) . toLowerCase ( Locale . ENGLISH ) + name . substring ( 1 ) ; if ( propertyName . indexOf ( ' ' ) > - 1 ) { propertyName = propertyName . replaceAll ( "\\s" , "" ) ; } return propertyName ; } | Returns the property name representation of the given name . |
21,287 | public static String getShortName ( String className ) { int i = className . lastIndexOf ( "." ) ; if ( i > - 1 ) { className = className . substring ( i + 1 , className . length ( ) ) ; } return className ; } | Returns the class name without the package prefix . |
21,288 | public static String getScriptName ( Class < ? > clazz ) { return clazz == null ? null : getScriptName ( clazz . getName ( ) ) ; } | Retrieves the script name representation of the supplied class . For example MyFunkyGrailsScript would be my - funky - grails - script . |
21,289 | public static String getScriptName ( String name ) { if ( name == null ) { return null ; } if ( name . endsWith ( ".groovy" ) ) { name = name . substring ( 0 , name . length ( ) - 7 ) ; } return getNaturalName ( name ) . replaceAll ( "\\s" , "-" ) . toLowerCase ( ) ; } | Retrieves the script name representation of the given class name . For example MyFunkyGrailsScript would be my - funky - grails - script . |
21,290 | public static boolean isValidJavaPackage ( String packageName ) { if ( isBlank ( packageName ) ) { return false ; } final String [ ] parts = packageName . split ( "\\." ) ; for ( String part : parts ) { if ( ! isValidJavaIdentifier ( part ) ) { return false ; } } return true ; } | Test whether the give package name is a valid Java package . |
21,291 | public static boolean isValidJavaIdentifier ( String name ) { if ( isBlank ( name ) ) { return false ; } final char [ ] chars = name . toCharArray ( ) ; if ( ! Character . isJavaIdentifierStart ( chars [ 0 ] ) ) { return false ; } for ( char c : chars ) { if ( ! Character . isJavaIdentifierPart ( c ) ) { return false ; } } return true ; } | Test whether the given name is a valid Java identifier . |
21,292 | public static String getPropertyNameConvention ( Object object , String suffix ) { if ( object != null ) { Class < ? > type = object . getClass ( ) ; if ( type . isArray ( ) ) { return getPropertyName ( type . getComponentType ( ) ) + suffix + "Array" ; } if ( object instanceof Collection ) { Collection coll = ( Collection ) object ; if ( coll . isEmpty ( ) ) { return "emptyCollection" ; } Object first = coll . iterator ( ) . next ( ) ; if ( coll instanceof List ) { return getPropertyName ( first . getClass ( ) ) + suffix + "List" ; } if ( coll instanceof Set ) { return getPropertyName ( first . getClass ( ) ) + suffix + "Set" ; } return getPropertyName ( first . getClass ( ) ) + suffix + "Collection" ; } if ( object instanceof Map ) { Map map = ( Map ) object ; if ( map . isEmpty ( ) ) { return "emptyMap" ; } Object entry = map . values ( ) . iterator ( ) . next ( ) ; if ( entry != null ) { return getPropertyName ( entry . getClass ( ) ) + suffix + "Map" ; } } else { return getPropertyName ( object . getClass ( ) ) + suffix ; } } return null ; } | Returns an appropriate property name for the given object . If the object is a collection will append List Set Collection or Map to the property name . |
21,293 | public static String readText ( BufferedReader reader ) throws IOException { StringBuilder answer = new StringBuilder ( ) ; if ( reader == null ) { return answer . toString ( ) ; } char [ ] charBuffer = new char [ BUFFER_MAX ] ; int nbCharRead ; try { while ( ( nbCharRead = reader . read ( charBuffer ) ) != - 1 ) { answer . append ( charBuffer , 0 , nbCharRead ) ; } Reader temp = reader ; reader = null ; temp . close ( ) ; } finally { try { if ( reader != null ) { reader . close ( ) ; } } catch ( IOException e ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( "Failed to close reader: " + e . getMessage ( ) , e ) ; } } } return answer . toString ( ) ; } | Read the content of the BufferedReader and return it as a String in a blocking manner . The BufferedReader is closed afterwards . |
21,294 | public < T extends Throwable > Micronaut mapError ( Class < T > exception , Function < T , Integer > mapper ) { this . exitHandlers . put ( exception , ( Function < Throwable , Integer > ) mapper ) ; return this ; } | Maps an exception to the given error code . |
21,295 | protected void handleStartupException ( Environment environment , Throwable exception ) { Function < Throwable , Integer > exitCodeMapper = exitHandlers . computeIfAbsent ( exception . getClass ( ) , exceptionType -> ( throwable -> 1 ) ) ; Integer code = exitCodeMapper . apply ( exception ) ; if ( code > 0 ) { if ( ! environment . getActiveNames ( ) . contains ( Environment . TEST ) ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Error starting Micronaut server: " + exception . getMessage ( ) , exception ) ; } System . exit ( code ) ; } } throw new ApplicationStartupException ( "Error starting Micronaut server: " + exception . getMessage ( ) , exception ) ; } | Default handling of startup exceptions . |
21,296 | @ Requires ( classes = JaegerTracer . Builder . class ) Configuration jaegerConfiguration ( ) { return this . configuration . getConfiguration ( ) ; } | The Jaeger configuration bean . |
21,297 | @ Requires ( classes = JaegerTracer . Builder . class ) JaegerTracer . Builder jaegerTracerBuilder ( Configuration configuration ) { JaegerTracer . Builder tracerBuilder = resolveBuilder ( configuration ) ; if ( this . configuration . isExpandExceptionLogs ( ) ) { tracerBuilder . withExpandExceptionLogs ( ) ; } if ( this . configuration . isZipkinSharedRpcSpan ( ) ) { tracerBuilder . withZipkinSharedRpcSpan ( ) ; } if ( reporter != null ) { tracerBuilder . withReporter ( reporter ) ; } if ( sampler != null ) { tracerBuilder . withSampler ( sampler ) ; } return tracerBuilder ; } | The Jaeger Tracer builder bean . |
21,298 | public void release ( ) { Object body = getBody ( ) . orElse ( null ) ; releaseIfNecessary ( body ) ; for ( ByteBufHolder byteBuf : receivedContent ) { releaseIfNecessary ( byteBuf ) ; } for ( ByteBufHolder byteBuf : receivedData . values ( ) ) { releaseIfNecessary ( byteBuf ) ; } if ( this . body != null && this . body instanceof ReferenceCounted ) { ReferenceCounted referenceCounted = ( ReferenceCounted ) this . body ; releaseIfNecessary ( referenceCounted ) ; } for ( Map . Entry < String , Object > attribute : attributes ) { Object value = attribute . getValue ( ) ; releaseIfNecessary ( value ) ; } } | Release and cleanup resources . |
21,299 | public void setBody ( T body ) { this . body = ( ) -> Optional . ofNullable ( body ) ; this . convertedBodies . clear ( ) ; } | Sets the body . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.