idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,000 | public UnusedStubbings getUnusedStubbings ( Iterable < Object > mocks ) { Set < Stubbing > stubbings = AllInvocationsFinder . findStubbings ( mocks ) ; List < Stubbing > unused = filter ( stubbings , new Filter < Stubbing > ( ) { public boolean isOut ( Stubbing s ) { return ! UnusedStubbingReporting . shouldBeReported ( s ) ; } } ) ; return new UnusedStubbings ( unused ) ; } | Gets all unused stubbings for given set of mock objects in order . Stubbings explicitily marked as LENIENT are not included . |
21,001 | public StubbedInvocationMatcher addAnswer ( Answer answer , boolean isConsecutive , Strictness stubbingStrictness ) { Invocation invocation = invocationForStubbing . getInvocation ( ) ; mockingProgress ( ) . stubbingCompleted ( ) ; if ( answer instanceof ValidableAnswer ) { ( ( ValidableAnswer ) answer ) . validateFor ( invocation ) ; } synchronized ( stubbed ) { if ( isConsecutive ) { stubbed . getFirst ( ) . addAnswer ( answer ) ; } else { Strictness effectiveStrictness = stubbingStrictness != null ? stubbingStrictness : this . mockStrictness ; stubbed . addFirst ( new StubbedInvocationMatcher ( answer , invocationForStubbing , effectiveStrictness ) ) ; } return stubbed . getFirst ( ) ; } } | Adds new stubbed answer and returns the invocation matcher the answer was added to . |
21,002 | public void setAnswersForStubbing ( List < Answer < ? > > answers , Strictness strictness ) { doAnswerStyleStubbing . setAnswers ( answers , strictness ) ; } | Sets the answers declared with doAnswer style . |
21,003 | public Collection < Stubbing > getStubbingsAscending ( ) { List < Stubbing > result = new LinkedList < Stubbing > ( stubbed ) ; Collections . reverse ( result ) ; return result ; } | Stubbings in ascending order most recent last |
21,004 | public static List < Field > sortSuperTypesLast ( Collection < ? extends Field > unsortedFields ) { List < Field > fields = new ArrayList < Field > ( unsortedFields ) ; Collections . sort ( fields , compareFieldsByName ) ; int i = 0 ; while ( i < fields . size ( ) - 1 ) { Field f = fields . get ( i ) ; Class < ? > ft = f . getType ( ) ; int newPos = i ; for ( int j = i + 1 ; j < fields . size ( ) ; j ++ ) { Class < ? > t = fields . get ( j ) . getType ( ) ; if ( ft != t && ft . isAssignableFrom ( t ) ) { newPos = j ; } } if ( newPos == i ) { i ++ ; } else { fields . remove ( i ) ; fields . add ( newPos , f ) ; } } return fields ; } | Return a new collection with the fields sorted first by name then with any fields moved after their supertypes . |
21,005 | public static < T > Iterable < T > toIterable ( Enumeration < T > in ) { List < T > out = new LinkedList < T > ( ) ; while ( in . hasMoreElements ( ) ) { out . add ( in . nextElement ( ) ) ; } return out ; } | Converts enumeration into iterable |
21,006 | public static String join ( String start , String linePrefix , Collection < ? > lines ) { if ( lines . isEmpty ( ) ) { return "" ; } StringBuilder out = new StringBuilder ( start ) ; for ( Object line : lines ) { out . append ( linePrefix ) . append ( line ) . append ( "\n" ) ; } return out . substring ( 0 , out . length ( ) - 1 ) ; } | Joins Strings with EOL character |
21,007 | @ SuppressWarnings ( "unchecked" ) < T > T loadPlugin ( final Class < T > pluginType ) { return ( T ) loadPlugin ( pluginType , null ) ; } | Scans the classpath for given pluginType . If not found default class is used . |
21,008 | private static Type findGenericInterface ( Class < ? > sourceClass , Class < ? > targetBaseInterface ) { for ( int i = 0 ; i < sourceClass . getInterfaces ( ) . length ; i ++ ) { Class < ? > inter = sourceClass . getInterfaces ( ) [ i ] ; if ( inter == targetBaseInterface ) { return sourceClass . getGenericInterfaces ( ) [ 0 ] ; } else { Type deeper = findGenericInterface ( inter , targetBaseInterface ) ; if ( deeper != null ) { return deeper ; } } } return null ; } | Finds generic interface implementation based on the source class and the target interface . Returns null if not found . Recurses the interface hierarchy . |
21,009 | private static Class < ? > extractGeneric ( Type type ) { if ( type instanceof ParameterizedType ) { Type [ ] genericTypes = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; if ( genericTypes . length > 0 && genericTypes [ 0 ] instanceof Class ) { return ( Class < ? > ) genericTypes [ 0 ] ; } } return Object . class ; } | Attempts to extract generic parameter type of given type . If there is no generic parameter it returns Object . class |
21,010 | public static InstanceFields allDeclaredFieldsOf ( Object instance ) { List < InstanceField > instanceFields = new ArrayList < InstanceField > ( ) ; for ( Class < ? > clazz = instance . getClass ( ) ; clazz != Object . class ; clazz = clazz . getSuperclass ( ) ) { instanceFields . addAll ( instanceFieldsIn ( instance , clazz . getDeclaredFields ( ) ) ) ; } return new InstanceFields ( instance , instanceFields ) ; } | Instance fields declared in the class and superclasses of the given instance . |
21,011 | public static InstanceFields declaredFieldsOf ( Object instance ) { List < InstanceField > instanceFields = new ArrayList < InstanceField > ( ) ; instanceFields . addAll ( instanceFieldsIn ( instance , instance . getClass ( ) . getDeclaredFields ( ) ) ) ; return new InstanceFields ( instance , instanceFields ) ; } | Instance fields declared in the class of the given instance . |
21,012 | @ SuppressWarnings ( { "unchecked" , "vararg" } ) public static Filter < InstanceField > annotatedBy ( final Class < ? extends Annotation > ... annotations ) { return new Filter < InstanceField > ( ) { public boolean isOut ( InstanceField instanceField ) { Checks . checkNotNull ( annotations , "Provide at least one annotation class" ) ; for ( Class < ? extends Annotation > annotation : annotations ) { if ( instanceField . isAnnotatedBy ( annotation ) ) { return false ; } } return true ; } } ; } | Accept fields annotated by the given annotations . |
21,013 | private static Class < ? > findTypeFromGeneric ( final InvocationOnMock invocation , final TypeVariable returnType ) { final MockCreationSettings mockSettings = MockUtil . getMockHandler ( invocation . getMock ( ) ) . getMockSettings ( ) ; final GenericMetadataSupport returnTypeSupport = GenericMetadataSupport . inferFrom ( mockSettings . getTypeToMock ( ) ) . resolveGenericReturnType ( invocation . getMethod ( ) ) ; final Class < ? > rawType = returnTypeSupport . rawType ( ) ; if ( rawType == Object . class ) { return findTypeFromGenericInArguments ( invocation , returnType ) ; } return rawType ; } | Retrieve the expected type when it came from a primitive . If the type cannot be retrieve return null . |
21,014 | private static Class < ? > findTypeFromGenericInArguments ( final InvocationOnMock invocation , final TypeVariable returnType ) { final Type [ ] parameterTypes = invocation . getMethod ( ) . getGenericParameterTypes ( ) ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { Type argType = parameterTypes [ i ] ; if ( returnType . equals ( argType ) ) { Object argument = invocation . getArgument ( i ) ; if ( argument == null ) { return null ; } return argument . getClass ( ) ; } if ( argType instanceof GenericArrayType ) { argType = ( ( GenericArrayType ) argType ) . getGenericComponentType ( ) ; if ( returnType . equals ( argType ) ) { return invocation . getArgument ( i ) . getClass ( ) ; } } } return null ; } | Find a return type using generic arguments provided by the calling method . |
21,015 | public static OngoingMockInjection onFields ( Set < Field > fields , Object ofInstance ) { return new OngoingMockInjection ( fields , ofInstance ) ; } | Create a new configuration setup for fields |
21,016 | void withSpanInScope ( HttpRequest < ? > request , Span span ) { request . setAttribute ( TraceRequestAttributes . CURRENT_SPAN , span ) ; Tracer . SpanInScope spanInScope = httpTracing . tracing ( ) . tracer ( ) . withSpanInScope ( span ) ; request . setAttribute ( TraceRequestAttributes . CURRENT_SCOPE , spanInScope ) ; } | Configures the request with the given Span . |
21,017 | void afterTerminate ( HttpRequest < ? > request ) { Optional < Tracer . SpanInScope > scope = request . removeAttribute ( TraceRequestAttributes . CURRENT_SCOPE , Tracer . SpanInScope . class ) ; scope . ifPresent ( Tracer . SpanInScope :: close ) ; } | Closes the scope after terminating the request . |
21,018 | Optional < Span > configuredSpan ( HttpRequest < ? > request , HttpResponse < ? > response ) { Optional < Object > routeTemplate = request . getAttribute ( HttpAttributes . URI_TEMPLATE ) ; routeTemplate . ifPresent ( o -> response . setAttribute ( HttpAttributes . URI_TEMPLATE , o ) ) ; response . setAttribute ( HttpAttributes . METHOD_NAME , request . getMethod ( ) . name ( ) ) ; return request . getAttribute ( TraceRequestAttributes . CURRENT_SPAN , Span . class ) ; } | Obtain the value of current span attribute on the HTTP method . |
21,019 | protected static void pushTypeArguments ( GeneratorAdapter generatorAdapter , Map < String , Object > types ) { if ( types == null || types . isEmpty ( ) ) { generatorAdapter . visitInsn ( ACONST_NULL ) ; return ; } int len = types . size ( ) ; pushNewArray ( generatorAdapter , Argument . class , len ) ; int i = 0 ; for ( Map . Entry < String , Object > entry : types . entrySet ( ) ) { generatorAdapter . push ( i ) ; String typeParameterName = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( value instanceof Map ) { buildArgumentWithGenerics ( generatorAdapter , typeParameterName , ( Map ) value ) ; } else { buildArgument ( generatorAdapter , typeParameterName , value ) ; } generatorAdapter . visitInsn ( AASTORE ) ; if ( i != ( len - 1 ) ) { generatorAdapter . visitInsn ( DUP ) ; } i ++ ; } } | Pushes type arguments onto the stack . |
21,020 | protected static void buildArgument ( GeneratorAdapter generatorAdapter , String argumentName , Object objectType ) { generatorAdapter . push ( getTypeReference ( objectType ) ) ; generatorAdapter . push ( argumentName ) ; invokeInterfaceStaticMethod ( generatorAdapter , Argument . class , METHOD_CREATE_ARGUMENT_SIMPLE ) ; } | Builds an argument instance . |
21,021 | protected Map < String , Object > toParameterTypes ( ParameterElement ... parameters ) { final LinkedHashMap < String , Object > map = new LinkedHashMap < > ( parameters . length ) ; for ( ParameterElement ce : parameters ) { final ClassElement type = ce . getType ( ) ; if ( type == null ) { continue ; } final Type typeReference = getTypeForElement ( type ) ; map . put ( ce . getName ( ) , typeReference ) ; } return map ; } | Converts a parameters to type arguments . |
21,022 | protected static Type getTypeReferenceForName ( String className , String ... genericTypes ) { String referenceString = getTypeDescriptor ( className , genericTypes ) ; return Type . getType ( referenceString ) ; } | Returns the Type reference corresponding to the given class . |
21,023 | protected static Type getTypeReference ( Object type ) { if ( type instanceof Type ) { return ( Type ) type ; } else if ( type instanceof Class ) { return Type . getType ( ( Class ) type ) ; } else if ( type instanceof String ) { String className = type . toString ( ) ; String internalName = getInternalName ( className ) ; if ( className . endsWith ( "[]" ) ) { internalName = "[L" + internalName + ";" ; } return Type . getObjectType ( internalName ) ; } else { throw new IllegalArgumentException ( "Type reference [" + type + "] should be a Class or a String representing the class name" ) ; } } | Return the type reference for a class . |
21,024 | protected void writeClassToDisk ( File targetDir , ClassWriter classWriter , String className ) throws IOException { if ( targetDir != null ) { String fileName = className . replace ( '.' , '/' ) + ".class" ; File targetFile = new File ( targetDir , fileName ) ; targetFile . getParentFile ( ) . mkdirs ( ) ; try ( OutputStream outputStream = Files . newOutputStream ( targetFile . toPath ( ) ) ) { writeClassToDisk ( outputStream , classWriter ) ; } } } | Writes the class file to disk in the given directory . |
21,025 | protected void generateServiceDescriptor ( String className , GeneratedFile generatedFile ) throws IOException { CharSequence contents = generatedFile . getTextContent ( ) ; if ( contents != null ) { String [ ] entries = contents . toString ( ) . split ( "\\n" ) ; if ( ! Arrays . asList ( entries ) . contains ( className ) ) { try ( BufferedWriter w = new BufferedWriter ( generatedFile . openWriter ( ) ) ) { w . newLine ( ) ; w . write ( className ) ; } } } else { try ( BufferedWriter w = new BufferedWriter ( generatedFile . openWriter ( ) ) ) { w . write ( className ) ; } } } | Generates a service discovery for the given class name and file . |
21,026 | protected void pushNewInstance ( GeneratorAdapter generatorAdapter , Type typeToInstantiate ) { generatorAdapter . newInstance ( typeToInstantiate ) ; generatorAdapter . dup ( ) ; generatorAdapter . invokeConstructor ( typeToInstantiate , METHOD_DEFAULT_CONSTRUCTOR ) ; } | Push the instantiation of the given type . |
21,027 | public void accept ( ClassWriterOutputVisitor visitor ) throws IOException { proxyBeanDefinitionWriter . accept ( visitor ) ; try ( OutputStream out = visitor . visitClass ( proxyFullName ) ) { out . write ( classWriter . toByteArray ( ) ) ; for ( ExecutableMethodWriter method : proxiedMethods ) { method . accept ( visitor ) ; } } } | Write the class to output via a visitor that manages output destination . |
21,028 | public AnnotationMetadata buildDeclared ( T element ) { final AnnotationMetadata existing = MUTATED_ANNOTATION_METADATA . get ( element ) ; if ( existing != null ) { return existing ; } else { DefaultAnnotationMetadata annotationMetadata = new DefaultAnnotationMetadata ( ) ; try { AnnotationMetadata metadata = buildInternal ( null , element , annotationMetadata , true , true ) ; if ( metadata . isEmpty ( ) ) { return AnnotationMetadata . EMPTY_METADATA ; } return metadata ; } catch ( RuntimeException e ) { if ( "org.eclipse.jdt.internal.compiler.problem.AbortCompilation" . equals ( e . getClass ( ) . getName ( ) ) ) { return AnnotationMetadata . EMPTY_METADATA ; } else { throw e ; } } } } | Build only metadata for declared annotations . |
21,029 | protected void validateAnnotationValue ( T originatingElement , String annotationName , T member , String memberName , Object resolvedValue ) { final AnnotatedElementValidator elementValidator = getElementValidator ( ) ; if ( elementValidator != null && ! erroneousElements . contains ( member ) ) { final boolean shouldValidate = ! ( annotationName . equals ( AliasFor . class . getName ( ) ) ) && ( ! ( resolvedValue instanceof String ) || ! resolvedValue . toString ( ) . contains ( "${" ) ) ; if ( shouldValidate ) { final Set < String > errors = elementValidator . validatedAnnotatedElement ( new AnnotatedElement ( ) { AnnotationMetadata metadata = buildDeclared ( member ) ; public String getName ( ) { return memberName ; } public AnnotationMetadata getAnnotationMetadata ( ) { return metadata ; } } , resolvedValue ) ; if ( CollectionUtils . isNotEmpty ( errors ) ) { erroneousElements . add ( member ) ; for ( String error : errors ) { error = "@" + NameUtils . getSimpleName ( annotationName ) + "." + memberName + ": " + error ; addError ( originatingElement , error ) ; } } } } } | Validates an annotation value . |
21,030 | public static void addMutatedMetadata ( Object element , AnnotationMetadata metadata ) { if ( element != null && metadata != null ) { MUTATED_ANNOTATION_METADATA . put ( element , metadata ) ; } } | Used to store metadata mutations at compilation time . Not for public consumption . |
21,031 | public < A2 extends Annotation > AnnotationMetadata annotate ( AnnotationMetadata annotationMetadata , AnnotationValue < A2 > annotationValue ) { if ( annotationMetadata instanceof DefaultAnnotationMetadata ) { final Optional < T > annotationMirror = getAnnotationMirror ( annotationValue . getAnnotationName ( ) ) ; final DefaultAnnotationMetadata defaultMetadata = ( DefaultAnnotationMetadata ) annotationMetadata ; defaultMetadata . addDeclaredAnnotation ( annotationValue . getAnnotationName ( ) , annotationValue . getValues ( ) ) ; annotationMirror . ifPresent ( annotationType -> processAnnotationStereotypes ( defaultMetadata , true , annotationType , annotationValue . getAnnotationName ( ) ) ) ; } return annotationMetadata ; } | Annotate an existing annotation metadata object . |
21,032 | public static Session create ( SessionStore sessionStore , HttpRequest < ? > request ) { Session session = sessionStore . newSession ( ) ; request . getAttributes ( ) . put ( HttpSessionFilter . SESSION_ATTRIBUTE , session ) ; return session ; } | Creates a session and stores it in the request attributes . |
21,033 | public static Optional < Session > find ( HttpRequest < ? > request ) { return request . getAttributes ( ) . get ( HttpSessionFilter . SESSION_ATTRIBUTE , Session . class ) ; } | Finds a session . |
21,034 | public static Session findOrCreate ( HttpRequest < ? > request , SessionStore sessionStore ) { return find ( request ) . orElseGet ( ( ) -> create ( sessionStore , request ) ) ; } | Finds a session or creates a new one and stores it in the request attributes . |
21,035 | public String getBeanDefinitionQualifiedClassName ( ) { String newClassName = beanDefinitionName ; if ( newClassName . endsWith ( "[]" ) ) { newClassName = newClassName . substring ( 0 , newClassName . length ( ) - 2 ) ; } return newClassName + REF_SUFFIX ; } | Obtains the class name of the bean definition to be written . Java Annotation Processors need this information to create a JavaFileObject using a Filer . |
21,036 | public static Optional < EmbeddedJdbcDatabase > get ( ClassLoader classLoader ) { return databases . stream ( ) . filter ( JdbcDatabase :: isEmbedded ) . map ( EmbeddedJdbcDatabase . class :: cast ) . filter ( embeddedDatabase -> ClassUtils . isPresent ( embeddedDatabase . getDriverClassName ( ) , classLoader ) ) . findFirst ( ) ; } | Searches the provided classloader for an embedded database driver . |
21,037 | public static boolean isEmbedded ( String driverClassName ) { return databases . stream ( ) . filter ( JdbcDatabase :: isEmbedded ) . anyMatch ( db -> db . driverClassName . equals ( driverClassName ) ) ; } | Searches embedded databases where the driver matches the argument . |
21,038 | @ Requires ( classes = { MDC . class , CurrentTraceContext . class } ) CurrentTraceContext currentTraceContext ( ) { return ThreadLocalCurrentTraceContext . newBuilder ( ) . addScopeDecorator ( new Slf4jScopeDecorator ( ) ) . build ( ) ; } | Current Slf4j trace context . |
21,039 | static < T > Subscriber < T > wrap ( Subscriber < T > downstream , List < RunnableInstrumenter > instrumentations ) { if ( downstream instanceof FlowableSubscriber ) { return new RxInstrumentedFlowableSubscriber < > ( downstream , instrumentations ) ; } return new RxInstrumentedSubscriber < > ( downstream , instrumentations ) ; } | Wrap a subscriber . |
21,040 | static Completable wrap ( CompletableSource source , Collection < ReactiveInstrumenter > instrumentations ) { if ( source instanceof Callable ) { return new RxInstrumentedCallableCompletable < > ( source , instrumentations ) ; } return new RxInstrumentedCompletable ( source , instrumentations ) ; } | Wrap a completable source . |
21,041 | static < T > Maybe < T > wrap ( MaybeSource < T > source , Collection < ReactiveInstrumenter > instrumentations ) { if ( source instanceof Callable ) { return new RxInstrumentedCallableMaybe < > ( source , instrumentations ) ; } return new RxInstrumentedMaybe < > ( source , instrumentations ) ; } | Wrap a maybe . |
21,042 | static < T > Single < T > wrap ( SingleSource < T > source , Collection < ReactiveInstrumenter > instrumentations ) { if ( source instanceof Callable ) { return new RxInstrumentedCallableSingle < > ( source , instrumentations ) ; } return new RxInstrumentedSingle < > ( source , instrumentations ) ; } | Wrap a single . |
21,043 | static < T > Observable < T > wrap ( ObservableSource < T > source , Collection < ReactiveInstrumenter > instrumentations ) { if ( source instanceof Callable ) { return new RxInstrumentedCallableObservable < > ( source , instrumentations ) ; } return new RxInstrumentedObservable < > ( source , instrumentations ) ; } | Wrap a observable . |
21,044 | static < T > ConnectableObservable < T > wrap ( ConnectableObservable < T > source , Collection < ReactiveInstrumenter > instrumentations ) { return new RxInstrumentedConnectableObservable < > ( source , instrumentations ) ; } | Wrap a connectable observable . |
21,045 | static < T > ParallelFlowable < T > wrap ( ParallelFlowable < T > source , Collection < ReactiveInstrumenter > instrumentations ) { return new RxInstrumentedParallelFlowable < > ( source , instrumentations ) ; } | Wrap a parallel flowable . |
21,046 | private CircuitState openCircuit ( Throwable cause ) { if ( cause == null ) { throw new IllegalArgumentException ( "Exception cause cannot be null" ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Opening Circuit Breaker [{}] due to error: {}" , method , cause . getMessage ( ) ) ; } this . childState = ( MutableRetryState ) retryStateBuilder . build ( ) ; this . lastError = cause ; this . time = System . currentTimeMillis ( ) ; try { return state . getAndSet ( CircuitState . OPEN ) ; } finally { if ( eventPublisher != null ) { try { eventPublisher . publishEvent ( new CircuitOpenEvent ( method , childState , cause ) ) ; } catch ( Exception e ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Error publishing CircuitOpen event: " + e . getMessage ( ) , e ) ; } } } } } | Opens the circuit . |
21,047 | public static int findAvailableTcpPort ( int minPortRange , int maxPortRange ) { ArgumentUtils . check ( ( ) -> minPortRange > MIN_PORT_RANGE ) . orElseFail ( "Port minimum value must be greater than " + MIN_PORT_RANGE ) ; ArgumentUtils . check ( ( ) -> maxPortRange >= minPortRange ) . orElseFail ( "Max port range must be greater than minimum port range" ) ; ArgumentUtils . check ( ( ) -> maxPortRange <= MAX_PORT_RANGE ) . orElseFail ( "Port maximum value must be less than " + MAX_PORT_RANGE ) ; int currentPort = nextPort ( minPortRange , maxPortRange ) ; while ( ! isTcpPortAvailable ( currentPort ) ) { currentPort = nextPort ( minPortRange , maxPortRange ) ; } return currentPort ; } | Finds an available TCP port . |
21,048 | public static boolean isTcpPortAvailable ( int currentPort ) { try { Socket socket = SocketFactory . getDefault ( ) . createSocket ( InetAddress . getLocalHost ( ) , currentPort ) ; socket . close ( ) ; return false ; } catch ( Throwable e ) { return true ; } } | Check whether the given TCP port is available . |
21,049 | protected String resolveFunctionName ( Environment env ) { return env . getProperty ( LocalFunctionRegistry . FUNCTION_NAME , String . class , ( String ) null ) ; } | Resolves the function name to execution for the environment . |
21,050 | protected Environment startEnvironment ( ApplicationContext applicationContext ) { if ( ! applicationContext . isRunning ( ) ) { if ( this instanceof PropertySource ) { applicationContext . getEnvironment ( ) . addPropertySource ( ( PropertySource ) this ) ; } return applicationContext . start ( ) . getEnvironment ( ) ; } else { return applicationContext . getEnvironment ( ) ; } } | Start the environment specified . |
21,051 | public void execute ( InputStream input , OutputStream output ) throws IOException { execute ( input , output , null ) ; } | Execute the function for the given input and output . |
21,052 | protected void execute ( InputStream input , OutputStream output , C context ) throws IOException { final ApplicationContext applicationContext = buildApplicationContext ( context ) ; if ( context == null ) { context = ( C ) applicationContext ; } final Environment env = startEnvironment ( applicationContext ) ; final String functionName = resolveFunctionName ( env ) ; if ( functionName == null ) { throw new InvocationException ( "No Function name configured. Set 'micronaut.function.name' in your Function configuration" ) ; } LocalFunctionRegistry localFunctionRegistry = applicationContext . getBean ( LocalFunctionRegistry . class ) ; ExecutableMethod < Object , Object > method = resolveFunction ( localFunctionRegistry , functionName ) ; Class < ? > returnJavaType = method . getReturnType ( ) . getType ( ) ; if ( ClassLoadingReporter . isReportingEnabled ( ) ) { ClassLoadingReporter . reportBeanPresent ( returnJavaType ) ; } Argument [ ] requiredArguments = method . getArguments ( ) ; int argCount = requiredArguments . length ; Object result ; Qualifier < Object > qualifier = Qualifiers . byName ( functionName ) ; Class < Object > functionType = method . getDeclaringType ( ) ; BeanDefinition < Object > beanDefinition = applicationContext . getBeanDefinition ( functionType , qualifier ) ; Object bean = applicationContext . getBean ( functionType , qualifier ) ; List < Argument < ? > > typeArguments = beanDefinition . getTypeArguments ( ) ; try { switch ( argCount ) { case 0 : result = method . invoke ( bean ) ; break ; case 1 : Argument arg = requiredArguments [ 0 ] ; if ( ! typeArguments . isEmpty ( ) ) { arg = Argument . of ( typeArguments . get ( 0 ) . getType ( ) , arg . getName ( ) ) ; } Object value = decodeInputArgument ( env , localFunctionRegistry , arg , input ) ; result = method . invoke ( bean , value ) ; break ; case 2 : Argument firstArgument = requiredArguments [ 0 ] ; Argument secondArgument = requiredArguments [ 1 ] ; if ( ! typeArguments . isEmpty ( ) ) { firstArgument = Argument . of ( typeArguments . get ( 0 ) . getType ( ) , firstArgument . getName ( ) ) ; } Object first = decodeInputArgument ( env , localFunctionRegistry , firstArgument , input ) ; Object second = decodeContext ( env , secondArgument , context ) ; result = method . invoke ( bean , first , second ) ; break ; default : throw new InvocationException ( "Function [" + functionName + "] cannot be made executable." ) ; } if ( result != null ) { encode ( env , localFunctionRegistry , returnJavaType , result , output ) ; } } finally { closeApplicationContext ( ) ; } } | Execute the function with given context object . |
21,053 | static void encode ( Environment environment , LocalFunctionRegistry registry , Class returnType , Object result , OutputStream output ) throws IOException { if ( ClassUtils . isJavaLangType ( returnType ) ) { if ( result instanceof Byte ) { output . write ( ( Byte ) result ) ; } else if ( result instanceof Boolean ) { output . write ( ( ( Boolean ) result ) ? 1 : 0 ) ; } else if ( result instanceof byte [ ] ) { output . write ( ( byte [ ] ) result ) ; } else { byte [ ] bytes = environment . convert ( result . toString ( ) , byte [ ] . class ) . orElseThrow ( ( ) -> new InvocationException ( "Unable to convert result [" + result + "] for output stream" ) ) ; output . write ( bytes ) ; } } } | Encode and write to output stream . |
21,054 | @ Requires ( beans = AWSLambdaConfiguration . class ) AWSLambdaAsync awsLambdaAsyncClient ( ) { AWSLambdaAsyncClientBuilder builder = configuration . getBuilder ( ) ; return builder . build ( ) ; } | The client returned from a builder . |
21,055 | @ EachBean ( ExecutorConfiguration . class ) @ Bean ( preDestroy = "shutdown" ) public ExecutorService executorService ( ExecutorConfiguration executorConfiguration ) { ExecutorType executorType = executorConfiguration . getType ( ) ; switch ( executorType ) { case FIXED : return executorConfiguration . getThreadFactoryClass ( ) . flatMap ( InstantiationUtils :: tryInstantiate ) . map ( factory -> Executors . newFixedThreadPool ( executorConfiguration . getNumberOfThreads ( ) , factory ) ) . orElse ( Executors . newFixedThreadPool ( executorConfiguration . getNumberOfThreads ( ) , threadFactory ) ) ; case CACHED : return executorConfiguration . getThreadFactoryClass ( ) . flatMap ( InstantiationUtils :: tryInstantiate ) . map ( Executors :: newCachedThreadPool ) . orElse ( Executors . newCachedThreadPool ( threadFactory ) ) ; case SCHEDULED : return executorConfiguration . getThreadFactoryClass ( ) . flatMap ( InstantiationUtils :: tryInstantiate ) . map ( factory -> Executors . newScheduledThreadPool ( executorConfiguration . getCorePoolSize ( ) , factory ) ) . orElse ( Executors . newScheduledThreadPool ( executorConfiguration . getCorePoolSize ( ) , threadFactory ) ) ; case WORK_STEALING : return Executors . newWorkStealingPool ( executorConfiguration . getParallelism ( ) ) ; default : throw new IllegalStateException ( "Could not create Executor service for enum value: " + executorType ) ; } } | Create the ExecutorService with the given configuration . |
21,056 | public String getDriverClassName ( ) { final String driverClassName = basicJdbcConfiguration . getConfiguredDriverClassName ( ) ; if ( calculatedDriverClassName == null || StringUtils . hasText ( driverClassName ) ) { if ( StringUtils . hasText ( driverClassName ) ) { if ( ! driverClassIsPresent ( driverClassName ) ) { throw new ConfigurationException ( String . format ( "Error configuring data source '%s'. The driver class '%s' was not found on the classpath" , basicJdbcConfiguration . getName ( ) , driverClassName ) ) ; } calculatedDriverClassName = driverClassName ; } else { final String url = basicJdbcConfiguration . getUrl ( ) ; if ( StringUtils . hasText ( url ) ) { JdbcDatabaseManager . findDatabase ( url ) . ifPresent ( db -> calculatedDriverClassName = db . getDriverClassName ( ) ) ; } if ( ! StringUtils . hasText ( calculatedDriverClassName ) && embeddedDatabaseConnection . isPresent ( ) ) { calculatedDriverClassName = this . embeddedDatabaseConnection . get ( ) . getDriverClassName ( ) ; } if ( ! StringUtils . hasText ( calculatedDriverClassName ) ) { throw new ConfigurationException ( String . format ( "Error configuring data source '%s'. No driver class name specified" , basicJdbcConfiguration . getName ( ) ) ) ; } } } return calculatedDriverClassName ; } | Determines the driver class name based on the configured value . If not configured determine the driver class name based on the URL . If the URL is not configured look for an embedded database driver on the classpath . |
21,057 | public String getUrl ( ) { final String url = basicJdbcConfiguration . getConfiguredUrl ( ) ; if ( calculatedUrl == null || StringUtils . hasText ( url ) ) { calculatedUrl = url ; if ( ! StringUtils . hasText ( calculatedUrl ) && embeddedDatabaseConnection . isPresent ( ) ) { calculatedUrl = embeddedDatabaseConnection . get ( ) . getUrl ( basicJdbcConfiguration . getName ( ) ) ; } if ( ! StringUtils . hasText ( calculatedUrl ) ) { throw new ConfigurationException ( String . format ( "Error configuring data source '%s'. No URL specified" , basicJdbcConfiguration . getName ( ) ) ) ; } } return calculatedUrl ; } | Determines the URL based on the configured value . If the URL is not configured search for an embedded database driver on the classpath and retrieve a default URL for it . |
21,058 | public String getUsername ( ) { final String username = basicJdbcConfiguration . getConfiguredUsername ( ) ; if ( calculatedUsername == null || StringUtils . hasText ( username ) ) { calculatedUsername = username ; if ( ! StringUtils . hasText ( calculatedUsername ) && JdbcDatabaseManager . isEmbedded ( basicJdbcConfiguration . getDriverClassName ( ) ) ) { calculatedUsername = "sa" ; } } return calculatedUsername ; } | Determines the username based on the configured value . If the username is not configured and an embedded database driver is on the classpath return sa . |
21,059 | public String getPassword ( ) { final String password = basicJdbcConfiguration . getConfiguredPassword ( ) ; if ( calculatedPassword == null || StringUtils . hasText ( password ) ) { calculatedPassword = password ; if ( ! StringUtils . hasText ( calculatedPassword ) && JdbcDatabaseManager . isEmbedded ( basicJdbcConfiguration . getDriverClassName ( ) ) ) { calculatedPassword = "" ; } } return calculatedPassword ; } | Determines the password based on the configured value . If the password is not configured and an embedded database driver is on the classpath return an empty string . |
21,060 | public String getValidationQuery ( ) { final String validationQuery = basicJdbcConfiguration . getConfiguredValidationQuery ( ) ; if ( calculatedValidationQuery == null || StringUtils . hasText ( validationQuery ) ) { calculatedValidationQuery = validationQuery ; if ( ! StringUtils . hasText ( calculatedValidationQuery ) ) { JdbcDatabaseManager . findDatabase ( getUrl ( ) ) . ifPresent ( db -> calculatedValidationQuery = db . getValidationQuery ( ) ) ; } } return calculatedValidationQuery ; } | Determines the validation query based on the configured value . If the validation query is not configured search pre - defined databases for a match based on the URL . If a match is found return the defined validation query for that database . |
21,061 | public static Optional < Class > resolveGenericTypeArgument ( Field field ) { Type genericType = field != null ? field . getGenericType ( ) : null ; if ( genericType instanceof ParameterizedType ) { Type [ ] typeArguments = ( ( ParameterizedType ) genericType ) . getActualTypeArguments ( ) ; if ( typeArguments . length > 0 ) { Type typeArg = typeArguments [ 0 ] ; return resolveParameterizedTypeArgument ( typeArg ) ; } } return Optional . empty ( ) ; } | Resolves a single generic type argument for the given field . |
21,062 | public static Class [ ] resolveInterfaceTypeArguments ( Class < ? > type , Class < ? > interfaceType ) { Optional < Type > resolvedType = getAllGenericInterfaces ( type ) . stream ( ) . filter ( t -> { if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; return pt . getRawType ( ) == interfaceType ; } return false ; } ) . findFirst ( ) ; return resolvedType . map ( GenericTypeUtils :: resolveTypeArguments ) . orElse ( ReflectionUtils . EMPTY_CLASS_ARRAY ) ; } | Resolve all of the type arguments for the given interface from the given type . Also searches superclasses . |
21,063 | public static Class [ ] resolveSuperTypeGenericArguments ( Class < ? > type , Class < ? > superTypeToResolve ) { Type supertype = type . getGenericSuperclass ( ) ; Class < ? > superclass = type . getSuperclass ( ) ; while ( superclass != null && superclass != Object . class ) { if ( supertype instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) supertype ; if ( pt . getRawType ( ) == superTypeToResolve ) { return resolveTypeArguments ( supertype ) ; } } supertype = superclass . getGenericSuperclass ( ) ; superclass = superclass . getSuperclass ( ) ; } return ReflectionUtils . EMPTY_CLASS_ARRAY ; } | Resolve all of the type arguments for the given super type from the given type . |
21,064 | public static Optional < Class > resolveSuperGenericTypeArgument ( Class type ) { try { Type genericSuperclass = type . getGenericSuperclass ( ) ; if ( genericSuperclass instanceof ParameterizedType ) { return resolveSingleTypeArgument ( genericSuperclass ) ; } return Optional . empty ( ) ; } catch ( NoClassDefFoundError e ) { return Optional . empty ( ) ; } } | Resolves a single generic type argument from the super class of the given type . |
21,065 | public static Class [ ] resolveTypeArguments ( Type genericType ) { Class [ ] typeArguments = ReflectionUtils . EMPTY_CLASS_ARRAY ; if ( genericType instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) genericType ; typeArguments = resolveParameterizedType ( pt ) ; } return typeArguments ; } | Resolves the type arguments for a generic type . |
21,066 | public static Optional < Class > resolveInterfaceTypeArgument ( Class type , Class interfaceType ) { Type [ ] genericInterfaces = type . getGenericInterfaces ( ) ; for ( Type genericInterface : genericInterfaces ) { if ( genericInterface instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) genericInterface ; if ( pt . getRawType ( ) == interfaceType ) { return resolveSingleTypeArgument ( genericInterface ) ; } } } Class superClass = type . getSuperclass ( ) ; if ( superClass != null && superClass != Object . class ) { return resolveInterfaceTypeArgument ( superClass , interfaceType ) ; } return Optional . empty ( ) ; } | Resolves a single type argument from the given interface of the given class . Also searches superclasses . |
21,067 | private static Optional < Class > resolveSingleTypeArgument ( Type genericType ) { if ( genericType instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) genericType ; Type [ ] actualTypeArguments = pt . getActualTypeArguments ( ) ; if ( actualTypeArguments . length == 1 ) { Type actualTypeArgument = actualTypeArguments [ 0 ] ; return resolveParameterizedTypeArgument ( actualTypeArgument ) ; } } return Optional . empty ( ) ; } | Resolve a single type from the given generic type . |
21,068 | protected void performRegistration ( String discoveryService , RegistrationConfiguration registration , ServiceInstance instance , Publisher < HttpStatus > registrationObservable ) { registrationObservable . subscribe ( new Subscriber < HttpStatus > ( ) { public void onSubscribe ( Subscription s ) { s . request ( 1 ) ; } public void onNext ( HttpStatus httpStatus ) { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Registered service [{}] with {}" , instance . getId ( ) , discoveryService ) ; } } public void onError ( Throwable t ) { if ( LOG . isErrorEnabled ( ) ) { String message = getErrorMessage ( discoveryService , t ) ; LOG . error ( message , t ) ; } if ( registration . isFailFast ( ) && instance instanceof EmbeddedServerInstance ) { ( ( EmbeddedServerInstance ) instance ) . getEmbeddedServer ( ) . stop ( ) ; } } public void onComplete ( ) { } } ) ; } | Register a new service instance in the discovery service . |
21,069 | protected void performDeregistration ( String discoveryService , RegistrationConfiguration registration , Publisher < HttpStatus > deregisterPublisher , String applicationName ) { if ( registration . isFailFast ( ) ) { try { Flowable . fromPublisher ( deregisterPublisher ) . blockingFirst ( ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "De-registered service [{}] with {}" , applicationName , discoveryService ) ; } } catch ( Throwable t ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Error occurred de-registering service [" + applicationName + "] with " + discoveryService + ": " + t . getMessage ( ) , t ) ; } } } else { deregisterPublisher . subscribe ( new Subscriber < HttpStatus > ( ) { public void onSubscribe ( Subscription subscription ) { subscription . request ( 1 ) ; } public void onNext ( HttpStatus httpStatus ) { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "De-registered service [{}] with {}" , applicationName , discoveryService ) ; } } public void onError ( Throwable t ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Error occurred de-registering service [" + applicationName + "] with " + discoveryService + ": " + t . getMessage ( ) , t ) ; } } public void onComplete ( ) { } } ) ; } } | De - register a service from the discovery client . |
21,070 | protected ClassElement mirrorToClassElement ( TypeMirror returnType , JavaVisitorContext visitorContext ) { if ( returnType instanceof NoType ) { return new JavaVoidElement ( ) ; } else if ( returnType instanceof DeclaredType ) { DeclaredType dt = ( DeclaredType ) returnType ; Element e = dt . asElement ( ) ; List < ? extends TypeMirror > typeArguments = dt . getTypeArguments ( ) ; if ( e instanceof TypeElement ) { TypeElement typeElement = ( TypeElement ) e ; if ( JavaModelUtils . resolveKind ( typeElement , ElementKind . ENUM ) . isPresent ( ) ) { return new JavaEnumElement ( typeElement , visitorContext . getAnnotationUtils ( ) . getAnnotationMetadata ( typeElement ) , visitorContext , typeArguments ) ; } else { return new JavaClassElement ( typeElement , visitorContext . getAnnotationUtils ( ) . getAnnotationMetadata ( typeElement ) , visitorContext , typeArguments ) ; } } } else if ( returnType instanceof TypeVariable ) { TypeVariable tv = ( TypeVariable ) returnType ; TypeMirror upperBound = tv . getUpperBound ( ) ; ClassElement classElement = mirrorToClassElement ( upperBound , visitorContext ) ; if ( classElement != null ) { return classElement ; } else { return mirrorToClassElement ( tv . getLowerBound ( ) , visitorContext ) ; } } else if ( returnType instanceof ArrayType ) { ArrayType at = ( ArrayType ) returnType ; TypeMirror componentType = at . getComponentType ( ) ; ClassElement arrayType = mirrorToClassElement ( componentType , visitorContext ) ; if ( arrayType != null ) { if ( arrayType instanceof JavaPrimitiveElement ) { JavaPrimitiveElement jpe = ( JavaPrimitiveElement ) arrayType ; return jpe . toArray ( ) ; } else { return new JavaClassElement ( ( TypeElement ) arrayType . getNativeType ( ) , arrayType , visitorContext ) { public boolean isArray ( ) { return true ; } } ; } } } else if ( returnType instanceof PrimitiveType ) { PrimitiveType pt = ( PrimitiveType ) returnType ; return JavaPrimitiveElement . valueOf ( pt . getKind ( ) . name ( ) ) ; } return null ; } | Obtain the ClassElement for the given mirror . |
21,071 | public ZonedDateTime nextTimeAfter ( ZonedDateTime afterTime , long durationInMillis ) { return nextTimeAfter ( afterTime , afterTime . plus ( Duration . ofMillis ( durationInMillis ) ) ) ; } | This will search for the next time within the next durationInMillis millisecond . Be aware that the duration is specified in millis but in fact the limit is checked on a day - to - day basis . |
21,072 | public ZonedDateTime nextTimeAfter ( ZonedDateTime afterTime , ZonedDateTime dateTimeBarrier ) { ZonedDateTime nextTime = ZonedDateTime . from ( afterTime ) . withNano ( 0 ) . plusSeconds ( 1 ) . withNano ( 0 ) ; while ( true ) { while ( true ) { while ( true ) { while ( true ) { while ( true ) { while ( true ) { if ( secondField . matches ( nextTime . getSecond ( ) ) ) { break ; } nextTime = nextTime . plusSeconds ( 1 ) . withNano ( 0 ) ; } if ( minuteField . matches ( nextTime . getMinute ( ) ) ) { break ; } nextTime = nextTime . plusMinutes ( 1 ) . withSecond ( 0 ) . withNano ( 0 ) ; } if ( hourField . matches ( nextTime . getHour ( ) ) ) { break ; } nextTime = nextTime . plusHours ( 1 ) . withMinute ( 0 ) . withSecond ( 0 ) . withNano ( 0 ) ; } if ( dayOfMonthField . matches ( nextTime . toLocalDate ( ) ) ) { break ; } nextTime = nextTime . plusDays ( 1 ) . withHour ( 0 ) . withMinute ( 0 ) . withSecond ( 0 ) . withNano ( 0 ) ; checkIfDateTimeBarrierIsReached ( nextTime , dateTimeBarrier ) ; } if ( monthField . matches ( nextTime . getMonth ( ) . getValue ( ) ) ) { break ; } nextTime = nextTime . plusMonths ( 1 ) . withDayOfMonth ( 1 ) . withHour ( 0 ) . withMinute ( 0 ) . withSecond ( 0 ) . withNano ( 0 ) ; checkIfDateTimeBarrierIsReached ( nextTime , dateTimeBarrier ) ; } if ( dayOfWeekField . matches ( nextTime . toLocalDate ( ) ) ) { break ; } nextTime = nextTime . plusDays ( 1 ) . withHour ( 0 ) . withMinute ( 0 ) . withSecond ( 0 ) . withNano ( 0 ) ; checkIfDateTimeBarrierIsReached ( nextTime , dateTimeBarrier ) ; } return nextTime ; } | This will search for the next time within the given dateTimeBarrier . |
21,073 | @ Scheduled ( fixedDelay = "${micronaut.heartbeat.interval:15s}" , initialDelay = "${micronaut.heartbeat.initial-delay:5s}" ) public void pulsate ( ) { ServiceInstance instance = eventReference . get ( ) ; if ( instance != null ) { eventPublisher . publishEvent ( new HeartbeatEvent ( instance , currentHealthStatus . current ( ) ) ) ; } } | Publish the heartbeat event with current health status . |
21,074 | static Set < String > getCNamesFromTxtRecord ( String discoveryDnsName ) throws NamingException { Attributes attrs = DIR_CONTEXT . getAttributes ( discoveryDnsName , new String [ ] { TXT_RECORD_TYPE } ) ; Attribute attr = attrs . get ( TXT_RECORD_TYPE ) ; String txtRecord = null ; if ( attr != null ) { txtRecord = attr . get ( ) . toString ( ) ; if ( txtRecord . startsWith ( "\"" ) && txtRecord . endsWith ( "\"" ) ) { txtRecord = txtRecord . substring ( 1 , txtRecord . length ( ) - 1 ) ; } } Set < String > cnamesSet = new TreeSet < > ( ) ; if ( txtRecord == null || txtRecord . trim ( ) . isEmpty ( ) ) { return cnamesSet ; } String [ ] cnames = txtRecord . split ( " " ) ; Collections . addAll ( cnamesSet , cnames ) ; return cnamesSet ; } | Looks up the DNS name provided in the JNDI context . |
21,075 | private static DirContext getDirContext ( ) { Hashtable < String , String > env = new Hashtable < > ( ) ; env . put ( JAVA_NAMING_FACTORY_INITIAL , DNS_NAMING_FACTORY ) ; env . put ( JAVA_NAMING_PROVIDER_URL , DNS_PROVIDER_URL ) ; try { return new InitialDirContext ( env ) ; } catch ( Throwable e ) { throw new RuntimeException ( "Cannot get dir context for some reason" , e ) ; } } | Load up the DNS JNDI context provider . |
21,076 | static void writeAttribute ( Writer out , String name , String value ) throws IOException { out . write ( '"' ) ; out . write ( name ) ; out . write ( "\":" ) ; out . write ( quote ( value ) ) ; } | Write a quoted attribute with a value to a writer . |
21,077 | public String expand ( Map < String , Object > parameters ) { StringBuilder builder = new StringBuilder ( ) ; boolean previousHasContent = false ; boolean anyPreviousHasOperator = false ; for ( PathSegment segment : segments ) { String result = segment . expand ( parameters , previousHasContent , anyPreviousHasOperator ) ; if ( result == null ) { break ; } if ( segment instanceof UriTemplateParser . VariablePathSegment ) { if ( result . contains ( String . valueOf ( ( ( UriTemplateParser . VariablePathSegment ) segment ) . getOperator ( ) ) ) ) { anyPreviousHasOperator = true ; } } previousHasContent = result . length ( ) > 0 ; builder . append ( result ) ; } return builder . toString ( ) ; } | Expand the string with the given parameters . |
21,078 | protected UriTemplate nest ( CharSequence uriTemplate , Object ... parserArguments ) { if ( uriTemplate == null ) { return this ; } int len = uriTemplate . length ( ) ; if ( len == 0 ) { return this ; } List < PathSegment > newSegments = buildNestedSegments ( uriTemplate , len , parserArguments ) ; return newUriTemplate ( uriTemplate , newSegments ) ; } | Nests another URI template with this template . |
21,079 | protected String normalizeNested ( String uri , CharSequence nested ) { if ( StringUtils . isEmpty ( nested ) ) { return uri ; } String nestedStr = nested . toString ( ) ; char firstNested = nestedStr . charAt ( 0 ) ; int len = nestedStr . length ( ) ; if ( len == 1 && firstNested == SLASH_OPERATOR ) { return uri ; } switch ( firstNested ) { case VAR_START : if ( len > 1 ) { switch ( nested . charAt ( 1 ) ) { case SLASH_OPERATOR : case HASH_OPERATOR : case QUERY_OPERATOR : case AND_OPERATOR : if ( uri . endsWith ( SLASH_STRING ) ) { return uri . substring ( 0 , uri . length ( ) - 1 ) + nestedStr ; } else { return uri + nestedStr ; } default : if ( ! uri . endsWith ( SLASH_STRING ) ) { return uri + SLASH_STRING + nestedStr ; } else { return uri + nestedStr ; } } } else { return uri ; } case SLASH_OPERATOR : if ( uri . endsWith ( SLASH_STRING ) ) { return uri + nestedStr . substring ( 1 ) ; } else { return uri + nestedStr ; } default : if ( uri . endsWith ( SLASH_STRING ) ) { return uri + nestedStr ; } else { return uri + SLASH_STRING + nestedStr ; } } } | Normalize a nested URI . |
21,080 | protected Map < MessageKey , Optional < String > > buildMessageCache ( ) { return new ConcurrentLinkedHashMap . Builder < MessageKey , Optional < String > > ( ) . maximumWeightedCapacity ( 100 ) . build ( ) ; } | Build the cache used to store resolved messages . |
21,081 | public void process ( ) { Collection < BeanDefinition < ? > > filterDefinitions = beanContext . getBeanDefinitions ( Qualifiers . byStereotype ( Filter . class ) ) ; for ( BeanDefinition < ? > beanDefinition : filterDefinitions ) { if ( HttpClientFilter . class . isAssignableFrom ( beanDefinition . getBeanType ( ) ) ) { continue ; } String [ ] patterns = beanDefinition . getValue ( Filter . class , String [ ] . class ) . orElse ( null ) ; if ( ArrayUtils . isNotEmpty ( patterns ) ) { HttpMethod [ ] methods = beanDefinition . getValue ( Filter . class , "methods" , HttpMethod [ ] . class ) . orElse ( null ) ; String first = patterns [ 0 ] ; FilterRoute filterRoute = addFilter ( first , ( ) -> beanContext . getBean ( ( Class < HttpFilter > ) beanDefinition . getBeanType ( ) ) ) ; if ( patterns . length > 1 ) { for ( int i = 1 ; i < patterns . length ; i ++ ) { String pattern = patterns [ i ] ; filterRoute . pattern ( pattern ) ; } } if ( ArrayUtils . isNotEmpty ( methods ) ) { filterRoute . methods ( methods ) ; } } } } | Executed after the bean creation . |
21,082 | protected void setResponseTags ( HttpRequest < ? > request , HttpResponse < ? > response , Span span ) { HttpStatus status = response . getStatus ( ) ; int code = status . getCode ( ) ; if ( code > HTTP_SUCCESS_CODE_UPPER_LIMIT ) { span . setTag ( TAG_HTTP_STATUS_CODE , code ) ; span . setTag ( TAG_ERROR , status . getReason ( ) ) ; } request . getAttribute ( HttpAttributes . ERROR , Throwable . class ) . ifPresent ( error -> setErrorTags ( span , error ) ) ; } | Sets the response tags . |
21,083 | protected void setErrorTags ( Span span , Throwable error ) { if ( error != null ) { String message = error . getMessage ( ) ; if ( message == null ) { message = error . getClass ( ) . getSimpleName ( ) ; } span . setTag ( TAG_ERROR , message ) ; } } | Sets the error tags to use on the span . |
21,084 | protected String resolveSpanName ( HttpRequest < ? > request ) { Optional < String > route = request . getAttribute ( HttpAttributes . URI_TEMPLATE , String . class ) ; return route . map ( s -> request . getMethod ( ) + " " + s ) . orElse ( request . getMethod ( ) + " " + request . getPath ( ) ) ; } | Resolve the span name to use for the request . |
21,085 | protected Tracer . SpanBuilder newSpan ( HttpRequest < ? > request , SpanContext spanContext ) { String spanName = resolveSpanName ( request ) ; Tracer . SpanBuilder spanBuilder = tracer . buildSpan ( spanName ) . asChildOf ( spanContext ) ; spanBuilder . withTag ( TAG_METHOD , request . getMethod ( ) . name ( ) ) ; String path = request . getPath ( ) ; spanBuilder . withTag ( TAG_PATH , path ) ; return spanBuilder ; } | Creates a new span for the given request and span context . |
21,086 | public String toPathString ( ) { return toString ( pathSegment -> { final Optional < String > var = pathSegment . getVariable ( ) ; if ( var . isPresent ( ) ) { final Optional < UriMatchVariable > umv = variables . stream ( ) . filter ( v -> v . getName ( ) . equals ( var . get ( ) ) ) . findFirst ( ) ; if ( umv . isPresent ( ) ) { final UriMatchVariable uriMatchVariable = umv . get ( ) ; if ( uriMatchVariable . isQuery ( ) ) { return false ; } } } return true ; } ) ; } | Returns the path string excluding any query variables . |
21,087 | public Optional < UriMatchInfo > match ( String uri ) { if ( uri == null ) { throw new IllegalArgumentException ( "Argument 'uri' cannot be null" ) ; } if ( uri . length ( ) > 1 && uri . charAt ( uri . length ( ) - 1 ) == '/' ) { uri = uri . substring ( 0 , uri . length ( ) - 1 ) ; } int len = uri . length ( ) ; if ( isRoot && ( len == 0 || ( len == 1 && uri . charAt ( 0 ) == '/' ) ) ) { return Optional . of ( new DefaultUriMatchInfo ( uri , Collections . emptyMap ( ) , variables ) ) ; } int parameterIndex = uri . indexOf ( '?' ) ; if ( parameterIndex > - 1 ) { uri = uri . substring ( 0 , parameterIndex ) ; } Matcher matcher = matchPattern . matcher ( uri ) ; if ( matcher . matches ( ) ) { if ( variables . isEmpty ( ) ) { return Optional . of ( new DefaultUriMatchInfo ( uri , Collections . emptyMap ( ) , variables ) ) ; } else { Map < String , Object > variableMap = new LinkedHashMap < > ( ) ; int count = matcher . groupCount ( ) ; for ( int j = 0 ; j < variables . size ( ) ; j ++ ) { int index = ( j * 2 ) + 2 ; if ( index > count ) { break ; } UriMatchVariable variable = variables . get ( j ) ; String value = matcher . group ( index ) ; variableMap . put ( variable . getName ( ) , value ) ; } return Optional . of ( new DefaultUriMatchInfo ( uri , variableMap , variables ) ) ; } } return Optional . empty ( ) ; } | Match the given URI string . |
21,088 | public final void setNoRollbackFor ( Class < ? extends Throwable > ... exceptions ) { if ( ArrayUtils . isNotEmpty ( exceptions ) ) { noRollbackFor . addAll ( Arrays . asList ( exceptions ) ) ; } } | Configures the exceptions to not rollback for . |
21,089 | public final void setRollbackFor ( Class < ? extends Throwable > ... exceptions ) { if ( ArrayUtils . isNotEmpty ( exceptions ) ) { if ( rollbackFor == null ) { rollbackFor = new HashSet < > ( ) ; } rollbackFor . addAll ( Arrays . asList ( exceptions ) ) ; } } | Configures the exceptions to rollback for . |
21,090 | public Builder metadata ( Map < String , String > metadata ) { if ( metadata != null ) { this . metadata = ConvertibleValues . of ( metadata ) ; } return this ; } | Builder for metadata in map format . |
21,091 | private void unlink ( E e ) { final E prev = e . getPrevious ( ) ; final E next = e . getNext ( ) ; if ( prev == null ) { first = next ; } else { prev . setNext ( next ) ; e . setPrevious ( null ) ; } if ( next == null ) { last = prev ; } else { next . setPrevious ( prev ) ; e . setNext ( null ) ; } } | Unlinks the non - null element . |
21,092 | boolean contains ( Linked < ? > e ) { return ( e . getPrevious ( ) != null ) || ( e . getNext ( ) != null ) || ( e == first ) ; } | check whether the linked is contained within this linked deque . |
21,093 | public Optional < ? extends MethodExecutionHandle < ? , Object > > findFallbackMethod ( MethodInvocationContext < Object , Object > context ) { Class < ? > declaringType = context . getDeclaringType ( ) ; Optional < ? extends MethodExecutionHandle < ? , Object > > result = beanContext . findExecutionHandle ( declaringType , Qualifiers . byStereotype ( Fallback . class ) , context . getMethodName ( ) , context . getArgumentTypes ( ) ) ; if ( ! result . isPresent ( ) ) { Set < Class > allInterfaces = ReflectionUtils . getAllInterfaces ( declaringType ) ; for ( Class i : allInterfaces ) { result = beanContext . findExecutionHandle ( i , Qualifiers . byStereotype ( Fallback . class ) , context . getMethodName ( ) , context . getArgumentTypes ( ) ) ; if ( result . isPresent ( ) ) { return result ; } } } return result ; } | Finds a fallback method for the given context . |
21,094 | protected Object resolveFallback ( MethodInvocationContext < Object , Object > context , RuntimeException exception ) { if ( exception instanceof NoAvailableServiceException ) { NoAvailableServiceException nase = ( NoAvailableServiceException ) exception ; if ( LOG . isErrorEnabled ( ) ) { LOG . debug ( nase . getMessage ( ) , nase ) ; LOG . error ( "Type [{}] attempting to resolve fallback for unavailable service [{}]" , context . getTarget ( ) . getClass ( ) . getName ( ) , nase . getServiceID ( ) ) ; } } else { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Type [" + context . getTarget ( ) . getClass ( ) . getName ( ) + "] executed with error: " + exception . getMessage ( ) , exception ) ; } } Optional < ? extends MethodExecutionHandle < ? , Object > > fallback = findFallbackMethod ( context ) ; if ( fallback . isPresent ( ) ) { MethodExecutionHandle < ? , Object > fallbackMethod = fallback . get ( ) ; try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Type [{}] resolved fallback: {}" , context . getTarget ( ) . getClass ( ) . getName ( ) , fallbackMethod ) ; } return fallbackMethod . invoke ( context . getParameterValues ( ) ) ; } catch ( Exception e ) { throw new FallbackException ( "Error invoking fallback for type [" + context . getTarget ( ) . getClass ( ) . getName ( ) + "]: " + e . getMessage ( ) , e ) ; } } else { throw exception ; } } | Resolves a fallback for the given execution context and exception . |
21,095 | public static boolean areTypesCompatible ( Class [ ] typeArguments , List < Class > classToCompare ) { if ( classToCompare . size ( ) == 0 ) { return true ; } else { if ( classToCompare . size ( ) != typeArguments . length ) { return false ; } else { for ( int i = 0 ; i < classToCompare . size ( ) ; i ++ ) { Class left = classToCompare . get ( i ) ; Class right = typeArguments [ i ] ; if ( right == Object . class ) { continue ; } if ( left != right && ! left . isAssignableFrom ( right ) ) { return false ; } } } } return true ; } | Are the given types compatible . |
21,096 | public io . micronaut . inject . ast . Element visit ( Element element , AnnotationMetadata annotationMetadata ) { if ( element instanceof VariableElement ) { final JavaFieldElement e = new JavaFieldElement ( ( VariableElement ) element , annotationMetadata , visitorContext ) ; visitor . visitField ( e , visitorContext ) ; return e ; } else if ( element instanceof ExecutableElement ) { ExecutableElement executableElement = ( ExecutableElement ) element ; if ( executableElement . getSimpleName ( ) . toString ( ) . equals ( "<init>" ) ) { final JavaConstructorElement e = new JavaConstructorElement ( executableElement , annotationMetadata , visitorContext ) ; visitor . visitConstructor ( e , visitorContext ) ; return e ; } else { final JavaMethodElement e = new JavaMethodElement ( executableElement , annotationMetadata , visitorContext ) ; visitor . visitMethod ( e , visitorContext ) ; return e ; } } else if ( element instanceof TypeElement ) { TypeElement typeElement = ( TypeElement ) element ; boolean isEnum = JavaModelUtils . resolveKind ( typeElement , ElementKind . ENUM ) . isPresent ( ) ; if ( isEnum ) { final JavaEnumElement e = new JavaEnumElement ( typeElement , annotationMetadata , visitorContext , Collections . emptyList ( ) ) ; visitor . visitClass ( e , visitorContext ) ; return e ; } else { final JavaClassElement e = new JavaClassElement ( typeElement , annotationMetadata , visitorContext ) ; visitor . visitClass ( e , visitorContext ) ; return e ; } } return null ; } | Invoke the underlying visitor for the given element . |
21,097 | @ Requires ( classes = HibernateValidator . class ) ValidatorFactory validatorFactory ( Optional < Environment > environment ) { Configuration validatorConfiguration = Validation . byDefaultProvider ( ) . configure ( ) ; messageInterpolator . ifPresent ( validatorConfiguration :: messageInterpolator ) ; traversableResolver . ifPresent ( validatorConfiguration :: traversableResolver ) ; constraintValidatorFactory . ifPresent ( validatorConfiguration :: constraintValidatorFactory ) ; parameterNameProvider . ifPresent ( validatorConfiguration :: parameterNameProvider ) ; if ( ignoreXmlConfiguration ) { validatorConfiguration . ignoreXmlConfiguration ( ) ; } environment . ifPresent ( env -> { Optional < Properties > config = env . getProperty ( "hibernate.validator" , Properties . class ) ; config . ifPresent ( properties -> { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { Object value = entry . getValue ( ) ; if ( value != null ) { validatorConfiguration . addProperty ( "hibernate.validator." + entry . getKey ( ) , value . toString ( ) ) ; } } } ) ; } ) ; return validatorConfiguration . buildValidatorFactory ( ) ; } | Produces a Validator factory class . |
21,098 | protected void startEnvironment ( ) { Environment defaultEnvironment = getEnvironment ( ) ; defaultEnvironment . start ( ) ; registerSingleton ( Environment . class , defaultEnvironment ) ; registerSingleton ( new AnnotationProcessorListener ( ) ) ; } | Start the environment . |
21,099 | protected final void readExisting ( SslConfiguration defaultSslConfiguration , KeyConfiguration defaultKeyConfiguration , KeyStoreConfiguration defaultKeyStoreConfiguration , TrustStoreConfiguration defaultTrustStoreConfiguration ) { if ( defaultKeyConfiguration != null ) { this . key = defaultKeyConfiguration ; } if ( defaultKeyStoreConfiguration != null ) { this . keyStore = defaultKeyStoreConfiguration ; } if ( defaultKeyConfiguration != null ) { this . trustStore = defaultTrustStoreConfiguration ; } if ( defaultSslConfiguration != null ) { this . port = defaultSslConfiguration . getPort ( ) ; this . enabled = defaultSslConfiguration . isEnabled ( ) ; this . buildSelfSigned = defaultSslConfiguration . buildSelfSigned ( ) ; defaultSslConfiguration . getProtocols ( ) . ifPresent ( strings -> this . protocols = strings ) ; defaultSslConfiguration . getProtocol ( ) . ifPresent ( protocol -> this . protocol = protocol ) ; defaultSslConfiguration . getCiphers ( ) . ifPresent ( ciphers -> this . ciphers = ciphers ) ; defaultSslConfiguration . getClientAuthentication ( ) . ifPresent ( ca -> this . clientAuthentication = ca ) ; } } | Reads an existing config . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.