idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
37,700
protected Device resolveWithPlatform ( DeviceType deviceType , DevicePlatform devicePlatform ) { return LiteDevice . from ( deviceType , devicePlatform ) ; }
Wrapper method for allow subclassing platform based resolution
37,701
protected void init ( ) { getMobileUserAgentPrefixes ( ) . addAll ( Arrays . asList ( KNOWN_MOBILE_USER_AGENT_PREFIXES ) ) ; getMobileUserAgentKeywords ( ) . addAll ( Arrays . asList ( KNOWN_MOBILE_USER_AGENT_KEYWORDS ) ) ; getTabletUserAgentKeywords ( ) . addAll ( Arrays . asList ( KNOWN_TABLET_USER_AGENT_KEYWORDS ) ) ; }
Initialize this device resolver implementation . Registers the known set of device signature strings . Subclasses may override to register additional strings .
37,702
public static SitePreference getCurrentSitePreference ( RequestAttributes attributes ) { return ( SitePreference ) attributes . getAttribute ( CURRENT_SITE_PREFERENCE_ATTRIBUTE , RequestAttributes . SCOPE_REQUEST ) ; }
Get the current site preference for the user from the request attributes map .
37,703
protected String optionalPort ( HttpServletRequest request ) { if ( "http" . equals ( request . getScheme ( ) ) && request . getServerPort ( ) != 80 || "https" . equals ( request . getScheme ( ) ) && request . getServerPort ( ) != 443 ) { return ":" + request . getServerPort ( ) ; } else { return null ; } }
Returns the HTTP port specified on the given request if it s a non - standard port . The port is considered non - standard if it s not port 80 for insecure request and not port 443 of secure requests .
37,704
protected Map < String , Set < String > > filterQueryParamsByKey ( QueryParamsParserContext context , String queryKey ) { Map < String , Set < String > > filteredQueryParams = new HashMap < > ( ) ; for ( String paramName : context . getParameterNames ( ) ) { if ( paramName . startsWith ( queryKey ) ) { filteredQueryParams . put ( paramName , parseDelimitedParameters ( context . getParameterValue ( paramName ) ) ) ; } } return filteredQueryParams ; }
Filters provided query params to one starting with provided string key . This override also splits param values if they are contained in a comma - delimited list .
37,705
public static String getProperty ( Object bean , String field ) { Object property = PropertyUtils . getProperty ( bean , field ) ; if ( property == null ) { return "null" ; } return property . toString ( ) ; }
Get bean s property value and maps to String
37,706
public FilterSpec addExpression ( FilterSpec expr ) { if ( expressions == null ) { expressions = new ArrayList < > ( ) ; } expressions . add ( ( FilterSpec ) expr ) ; return this ; }
Adds the given expression to the expression list and returns itself .
37,707
private static void addMergeInclusions ( JpaQueryExecutor < ? > executor , QuerySpec querySpec ) { ArrayDeque < String > attributePath = new ArrayDeque < > ( ) ; Class < ? > resourceClass = querySpec . getResourceClass ( ) ; addMergeInclusions ( attributePath , executor , resourceClass ) ; }
related attribute that are merged into a resource should be loaded by graph control to avoid lazy - loading or potential lack of session in serialization .
37,708
public QueryParams buildQueryParams ( QueryParamsParserContext context ) { try { return queryParamsParser . parse ( context ) ; } catch ( KatharsisException e ) { throw e ; } catch ( RuntimeException e ) { throw new ParametersDeserializationException ( e . getMessage ( ) , e ) ; } }
Parses the query parameters of the current request using this builder s QueryParamsParser and the given context .
37,709
public void filter ( ContainerRequestContext requestContext , ContainerResponseContext responseContext ) throws IOException { Object response = responseContext . getEntity ( ) ; if ( response == null ) { return ; } if ( isResourceResponse ( response ) ) { KatharsisBoot boot = feature . getBoot ( ) ; ResourceRegistry resourceRegistry = boot . getResourceRegistry ( ) ; DocumentMapper documentMapper = boot . getDocumentMapper ( ) ; ServiceUrlProvider serviceUrlProvider = resourceRegistry . getServiceUrlProvider ( ) ; try { UriInfo uriInfo = requestContext . getUriInfo ( ) ; if ( serviceUrlProvider instanceof UriInfoServiceUrlProvider ) { ( ( UriInfoServiceUrlProvider ) serviceUrlProvider ) . onRequestStarted ( uriInfo ) ; } JsonApiResponse jsonApiResponse = new JsonApiResponse ( ) ; jsonApiResponse . setEntity ( response ) ; responseContext . setEntity ( documentMapper . toDocument ( jsonApiResponse , null ) ) ; responseContext . getHeaders ( ) . put ( "Content-Type" , Arrays . asList ( ( Object ) JsonApiMediaType . APPLICATION_JSON_API ) ) ; } finally { if ( serviceUrlProvider instanceof UriInfoServiceUrlProvider ) { ( ( UriInfoServiceUrlProvider ) serviceUrlProvider ) . onRequestFinished ( ) ; } } } }
Creates JSON API responses for custom JAX - RS actions returning Katharsis resources .
37,710
private boolean isResourceResponse ( Object response ) { boolean singleResource = response . getClass ( ) . getAnnotation ( JsonApiResource . class ) != null ; boolean resourceList = ResourceListBase . class . isAssignableFrom ( response . getClass ( ) ) ; return singleResource || resourceList ; }
Determines whether the given response entity is either a Katharsis resource or a list of Katharsis resources .
37,711
public SimpleModule build ( ResourceRegistry resourceRegistry , boolean isClient ) { SimpleModule simpleModule = new SimpleModule ( JSON_API_MODULE_NAME , new Version ( 1 , 0 , 0 , null , null , null ) ) ; simpleModule . addSerializer ( new ErrorDataSerializer ( ) ) ; simpleModule . addDeserializer ( ErrorData . class , new ErrorDataDeserializer ( ) ) ; return simpleModule ; }
Creates Katharsis Jackson module with all required serializers
37,712
@ SuppressWarnings ( "unchecked" ) private Set < Resource > lookupRelationshipField ( Collection < Resource > sourceResources , ResourceField relationshipField , QueryAdapter queryAdapter , RepositoryMethodParameterProvider parameterProvider , Map < ResourceIdentifier , Resource > resourceMap , Map < ResourceIdentifier , Object > entityMap ) { if ( sourceResources . isEmpty ( ) ) { return Collections . emptySet ( ) ; } ResourceInformation resourceInformation = relationshipField . getParentResourceInformation ( ) ; RegistryEntry registyEntry = resourceRegistry . getEntry ( resourceInformation . getResourceType ( ) ) ; List < Serializable > resourceIds = getIds ( sourceResources , resourceInformation ) ; boolean isMany = Iterable . class . isAssignableFrom ( relationshipField . getType ( ) ) ; Class < ? > relationshipFieldClass = relationshipField . getElementType ( ) ; Set < Resource > loadedTargets = new HashSet < > ( ) ; @ SuppressWarnings ( "rawtypes" ) RelationshipRepositoryAdapter relationshipRepository = registyEntry . getRelationshipRepositoryForClass ( relationshipFieldClass , parameterProvider ) ; if ( relationshipRepository != null ) { Map < Object , JsonApiResponse > responseMap ; if ( isMany ) { responseMap = relationshipRepository . findBulkManyTargets ( resourceIds , relationshipField , queryAdapter ) ; } else { responseMap = relationshipRepository . findBulkOneTargets ( resourceIds , relationshipField , queryAdapter ) ; } for ( Resource sourceResource : sourceResources ) { Serializable sourceId = resourceInformation . parseIdString ( sourceResource . getId ( ) ) ; JsonApiResponse targetResponse = responseMap . get ( sourceId ) ; if ( targetResponse != null && targetResponse . getEntity ( ) != null ) { Object targetEntity = targetResponse . getEntity ( ) ; List < Resource > targets = setupRelation ( sourceResource , relationshipField , targetEntity , queryAdapter , resourceMap , entityMap ) ; loadedTargets . addAll ( targets ) ; } else { Nullable < Object > emptyData = Nullable . of ( Iterable . class . isAssignableFrom ( relationshipField . getType ( ) ) ? ( Object ) Collections . emptyList ( ) : null ) ; Relationship relationship = sourceResource . getRelationships ( ) . get ( relationshipField . getJsonName ( ) ) ; relationship . setData ( emptyData ) ; } } } return loadedTargets ; }
Loads all related resources for the given resources and relationship field . It updates the relationship data of the source resources accordingly and returns the loaded resources for potential inclusion in the result document .
37,713
public Object [ ] buildParameters ( Object [ ] firstParameters , Method method , QueryAdapter queryAdapter , Class < ? extends Annotation > annotationType ) { int parametersLength = method . getParameterTypes ( ) . length ; if ( firstParameters . length > 0 && parametersLength < 1 ) { throw new RepositoryMethodException ( String . format ( "Method with %s annotation should have at least one parameter." , annotationType ) ) ; } int parametersToResolve = parametersLength - firstParameters . length ; Object [ ] additionalParameters = new Object [ parametersToResolve ] ; for ( int i = firstParameters . length ; i < parametersLength ; i ++ ) { Class < ? > parameterType = method . getParameterTypes ( ) [ i ] ; if ( isQueryType ( parameterType ) ) { additionalParameters [ i - firstParameters . length ] = toQueryObject ( queryAdapter , parameterType ) ; } else { additionalParameters [ i - firstParameters . length ] = parameterProvider . provide ( method , i ) ; } } return concatenate ( firstParameters , additionalParameters ) ; }
Build a list of parameters that can be provided to a method .
37,714
public < M extends MetaInformation > M as ( Class < M > metaClass ) { try { return mapper . readerFor ( metaClass ) . readValue ( data ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }
Converts this generic meta information to the provided type .
37,715
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public Serializable parseIdString ( String id ) { Class idType = getIdField ( ) . getType ( ) ; return parser . parse ( id , idType ) ; }
Converts the given id string into its object representation .
37,716
public Response dispatchRequest ( JsonPath jsonPath , String method , Map < String , Set < String > > parameters , RepositoryMethodParameterProvider parameterProvider , Document requestBody ) { try { BaseController controller = controllerRegistry . getController ( jsonPath , method ) ; ResourceInformation resourceInformation = getRequestedResource ( jsonPath ) ; QueryAdapter queryAdapter = queryAdapterBuilder . build ( resourceInformation , parameters ) ; DefaultFilterRequestContext context = new DefaultFilterRequestContext ( jsonPath , queryAdapter , parameterProvider , requestBody , method ) ; DefaultFilterChain chain = new DefaultFilterChain ( controller ) ; return chain . doFilter ( context ) ; } catch ( Exception e ) { Optional < JsonApiExceptionMapper > exceptionMapper = exceptionMapperRegistry . findMapperFor ( e . getClass ( ) ) ; if ( exceptionMapper . isPresent ( ) ) { return exceptionMapper . get ( ) . toErrorResponse ( e ) . toResponse ( ) ; } else { logger . error ( "failed to process request" , e ) ; throw e ; } } }
Dispatch the request from a client
37,717
public static String buildPath ( JsonPath jsonPath ) { List < String > urlParts = new LinkedList < > ( ) ; JsonPath currentJsonPath = jsonPath ; String pathPart ; do { if ( currentJsonPath instanceof RelationshipsPath ) { pathPart = RELATIONSHIP_MARK + SEPARATOR + currentJsonPath . getElementName ( ) ; } else if ( currentJsonPath instanceof FieldPath ) { pathPart = currentJsonPath . getElementName ( ) ; } else { pathPart = currentJsonPath . getElementName ( ) ; if ( currentJsonPath . getIds ( ) != null ) { pathPart += SEPARATOR + mergeIds ( currentJsonPath . getIds ( ) ) ; } } urlParts . add ( pathPart ) ; currentJsonPath = currentJsonPath . getParentResource ( ) ; } while ( currentJsonPath != null ) ; Collections . reverse ( urlParts ) ; return SEPARATOR + StringUtils . join ( SEPARATOR , urlParts ) + SEPARATOR ; }
Creates a path using the provided JsonPath structure .
37,718
public RegistryEntry addEntry ( Class < ? > resource , RegistryEntry registryEntry ) { resources . put ( resource , registryEntry ) ; registryEntry . initialize ( moduleRegistry ) ; logger . debug ( "Added resource {} to ResourceRegistry" , resource . getName ( ) ) ; return registryEntry ; }
Adds a new resource definition to a registry .
37,719
public BraveModule braveModule ( ) { String serviceName = "exampleApp" ; Endpoint localEndpoint = Endpoint . builder ( ) . serviceName ( serviceName ) . build ( ) ; InheritableServerClientAndLocalSpanState spanState = new InheritableServerClientAndLocalSpanState ( localEndpoint ) ; Brave . Builder builder = new Brave . Builder ( spanState ) ; builder = builder . reporter ( new LoggingReporter ( ) ) ; Brave brave = builder . build ( ) ; return BraveModule . newServerModule ( brave ) ; }
Basic monitoring setup with Brave
37,720
public JpaModule jpaModule ( ) { JpaModule module = JpaModule . newServerModule ( em , transactionRunner ) ; module . addRepository ( JpaRepositoryConfig . builder ( ScheduleEntity . class ) . build ( ) ) ; module . addRepository ( JpaRepositoryConfig . builder ( ScheduleEntity . class , ScheduleDto . class , new ScheduleMapper ( ) ) . build ( ) ) ; JpaCriteriaQueryFactory queryFactory = ( JpaCriteriaQueryFactory ) module . getQueryFactory ( ) ; queryFactory . registerComputedAttribute ( ScheduleEntity . class , "upperName" , String . class , new JpaCriteriaExpressionFactory < From < ? , ScheduleEntity > > ( ) { @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public Expression < String > getExpression ( From < ? , ScheduleEntity > entity , CriteriaQuery < ? > query ) { CriteriaBuilder builder = em . getCriteriaBuilder ( ) ; return builder . upper ( ( Expression ) entity . get ( "name" ) ) ; } } ) ; return module ; }
Expose JPA entities as repositories .
37,721
public String getMethodName ( Method method ) { String name ; if ( ClassUtils . isBooleanGetter ( method ) ) { name = extractMethodName ( method , 2 ) ; } else { name = extractMethodName ( method , 3 ) ; } return name ; }
Extract Java bean name from getter s name
37,722
public static Method findMethodWith ( Class < ? > searchClass , Class < ? extends Annotation > annotationClass ) { Method foundMethod = null ; methodFinder : while ( searchClass != null && searchClass != Object . class ) { for ( Method method : searchClass . getDeclaredMethods ( ) ) { if ( method . isAnnotationPresent ( annotationClass ) ) { foundMethod = method ; break methodFinder ; } } searchClass = searchClass . getSuperclass ( ) ; } return foundMethod ; }
Return a first occurrence of a method annotated with specified annotation
37,723
public static < T > T newInstance ( Class < T > clazz ) { try { return clazz . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new ResourceException ( String . format ( "couldn't create a new instance of %s" , clazz ) ) ; } }
Create a new instance of a resource using a default constructor
37,724
public static JpaModule newServerModule ( EntityManagerFactory emFactory , EntityManager em , TransactionRunner transactionRunner ) { return new JpaModule ( emFactory , em , transactionRunner ) ; }
Creates a new JpaModule for a Katharsis server . All entities managed by the provided EntityManagerFactory are registered to the module and exposed as JSON API resources if not later configured otherwise .
37,725
public < T > void addRepository ( JpaRepositoryConfig < T > config ) { checkNotInitialized ( ) ; Class < ? > resourceClass = config . getResourceClass ( ) ; if ( repositoryConfigurationMap . containsKey ( resourceClass ) ) { throw new IllegalArgumentException ( resourceClass . getName ( ) + " is already registered" ) ; } repositoryConfigurationMap . put ( resourceClass , config ) ; }
Adds the repository to this module .
37,726
private void setupRelationshipRepositories ( Class < ? > resourceClass , boolean mapped ) { MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup ; Class < ? extends MetaDataObject > metaClass = mapped ? MetaJsonObject . class : MetaJpaDataObject . class ; MetaDataObject meta = metaLookup . getMeta ( resourceClass , metaClass ) ; for ( MetaAttribute attr : meta . getAttributes ( ) ) { if ( ! attr . isAssociation ( ) ) { continue ; } MetaType attrType = attr . getType ( ) . getElementType ( ) ; if ( attrType instanceof MetaEntity ) { Class < ? > attrImplClass = attrType . getImplementationClass ( ) ; JpaRepositoryConfig < ? > attrConfig = getRepositoryConfig ( attrImplClass ) ; if ( attrConfig != null ) { RelationshipRepositoryV2 < ? , ? , ? , ? > relationshipRepository = filterRelationshipCreation ( attrImplClass , repositoryFactory . createRelationshipRepository ( this , resourceClass , attrConfig ) ) ; context . addRepository ( relationshipRepository ) ; } } else if ( attrType instanceof MetaResource ) { Class < ? > attrImplClass = attrType . getImplementationClass ( ) ; JpaRepositoryConfig < ? > attrConfig = getRepositoryConfig ( attrImplClass ) ; if ( attrConfig == null || attrConfig . getMapper ( ) == null ) { throw new IllegalStateException ( "no mapped entity for " + attrType . getName ( ) + " reference by " + attr . getId ( ) + " registered" ) ; } JpaRepositoryConfig < ? > targetConfig = getRepositoryConfig ( attrImplClass ) ; Class < ? > targetResourceClass = targetConfig . getResourceClass ( ) ; RelationshipRepositoryV2 < ? , ? , ? , ? > relationshipRepository = filterRelationshipCreation ( targetResourceClass , repositoryFactory . createRelationshipRepository ( this , resourceClass , attrConfig ) ) ; context . addRepository ( relationshipRepository ) ; } else { throw new IllegalStateException ( "unable to process relation: " + attr . getId ( ) + ", neither a entity nor a mapped entity is referenced" ) ; } } }
Sets up relationship repositories for the given resource class . In case of a mapper the resource class might not correspond to the entity class .
37,727
public void addRelations ( Task task , Iterable < ObjectId > projectIds , String fieldName ) { List < Project > newProjectList = new LinkedList < > ( ) ; Iterable < Project > projectsToAdd = projectRepository . findAll ( projectIds , null ) ; for ( Project project : projectsToAdd ) { newProjectList . add ( project ) ; } try { if ( PropertyUtils . getProperty ( task , fieldName ) != null ) { Iterable < Project > projects = ( Iterable < Project > ) PropertyUtils . getProperty ( task , fieldName ) ; for ( Project project : projects ) { newProjectList . add ( project ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } try { PropertyUtils . setProperty ( task , fieldName , newProjectList ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } taskRepository . save ( task ) ; }
A simple implementation of the addRelations method which presents the general concept of the method . It SHOULD NOT be used in production because of possible race condition - production ready code should perform an atomic operation .
37,728
public void removeRelations ( Task task , Iterable < ObjectId > projectIds , String fieldName ) { try { if ( PropertyUtils . getProperty ( task , fieldName ) != null ) { Iterable < Project > projects = ( Iterable < Project > ) PropertyUtils . getProperty ( task , fieldName ) ; Iterator < Project > iterator = projects . iterator ( ) ; while ( iterator . hasNext ( ) ) { for ( ObjectId projectIdToRemove : projectIds ) { if ( iterator . next ( ) . getId ( ) . equals ( projectIdToRemove ) ) { iterator . remove ( ) ; break ; } } } List < Project > newProjectList = new ArrayList < > ( ) ; for ( Project project : projects ) { newProjectList . add ( project ) ; } PropertyUtils . setProperty ( task , fieldName , newProjectList ) ; taskRepository . save ( task ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
A simple implementation of the removeRelations method which presents the general concept of the method . It SHOULD NOT be used in production because of possible race condition - production ready code should perform an atomic operation .
37,729
public static ByAttribute attribute ( final String name , final String value ) { if ( name == null ) throw new IllegalArgumentException ( "Cannot find elements when the attribute name is null" ) ; return new ByAttribute ( name , value ) ; }
Finds elements by an named attribute matching a given value irrespective of element name . Currently implemented via XPath .
37,730
public static ByComposite composite ( By . ByTagName b0 , By . ByClassName b1 ) { return new ByComposite ( b0 , b1 ) ; }
Finds elements a composite of other By strategies
37,731
public FluentSelect deselectByIndex ( final int index ) { executeAndWrapReThrowIfNeeded ( new DeselectByIndex ( index ) , Context . singular ( context , "deselectByIndex" , null , index ) , true ) ; return new FluentSelect ( super . delegate , currentElement . getFound ( ) , this . context , monitor , booleanInsteadOfNotFoundException ) ; }
Deselect the option at the given index . This is done by examining the index attribute of an element and not merely by counting .
37,732
public static MethodIdentifier of ( final String containingClass , final String methodName , final String signature , final boolean staticMethod ) { final String returnType = JavaUtils . getReturnType ( signature ) ; final List < String > parameters = JavaUtils . getParameters ( signature ) ; return new MethodIdentifier ( containingClass , methodName , parameters , returnType , staticMethod ) ; }
Creates an identifier of the given parameters .
37,733
public static MethodIdentifier ofNonStatic ( final String containingClass , final String methodName , final String returnType , final String ... parameterTypes ) { return of ( containingClass , methodName , returnType , false , parameterTypes ) ; }
Creates an identifier of a non - static method .
37,734
public static MethodIdentifier ofStatic ( final String containingClass , final String methodName , final String returnType , final String ... parameterTypes ) { return of ( containingClass , methodName , returnType , true , parameterTypes ) ; }
Creates an identifier of a static method .
37,735
public static boolean isAssignableTo ( final String leftType , final String rightType ) { if ( leftType . equals ( rightType ) ) return true ; final boolean firstTypeArray = leftType . charAt ( 0 ) == '[' ; if ( firstTypeArray ^ rightType . charAt ( 0 ) == '[' ) { return false ; } final Class < ? > leftClass = loadClassFromType ( leftType ) ; final Class < ? > rightClass = loadClassFromType ( rightType ) ; if ( leftClass == null || rightClass == null ) return false ; final boolean bothTypesParameterized = hasTypeParameters ( leftType ) && hasTypeParameters ( rightType ) ; return rightClass . isAssignableFrom ( leftClass ) && ( firstTypeArray || ! bothTypesParameterized || getTypeParameters ( leftType ) . equals ( getTypeParameters ( rightType ) ) ) ; }
Checks if the left type is assignable to the right type i . e . the right type is of the same or a sub - type .
37,736
public static List < String > getTypeParameters ( final String type ) { if ( type . charAt ( 0 ) != 'L' ) return emptyList ( ) ; int lastStart = type . indexOf ( '<' ) + 1 ; final List < String > parameters = new ArrayList < > ( ) ; if ( lastStart > 0 ) { int depth = 0 ; for ( int i = lastStart ; i < type . length ( ) - 2 ; i ++ ) { final char c = type . charAt ( i ) ; if ( c == '<' ) depth ++ ; else if ( c == '>' ) depth -- ; else if ( c == ';' && depth == 0 ) { parameters . add ( type . substring ( lastStart , i + 1 ) ) ; lastStart = i + 1 ; } } } return parameters ; }
Returns the type parameters of the given type . Will be an empty list if the type is not parametrized .
37,737
public static List < String > getParameters ( final String methodDesc ) { if ( methodDesc == null ) return emptyList ( ) ; final char [ ] buffer = methodDesc . toCharArray ( ) ; final List < String > args = new ArrayList < > ( ) ; int offset = methodDesc . indexOf ( '(' ) + 1 ; while ( buffer [ offset ] != ')' ) { final String type = getNextType ( buffer , offset ) ; args . add ( type ) ; offset += type . length ( ) ; } final ListIterator < String > iterator = args . listIterator ( ) ; while ( iterator . hasNext ( ) ) { final String arg = iterator . next ( ) ; if ( arg . charAt ( 0 ) == 'T' ) iterator . set ( OBJECT ) ; } return args ; }
Returns the parameter types of the given method signature . Parametrized types are supported .
37,738
public static void debug ( final Throwable throwable ) { final StringWriter errors = new StringWriter ( ) ; throwable . printStackTrace ( new PrintWriter ( errors ) ) ; debugLogger . accept ( errors . toString ( ) ) ; }
Logs the stacktrace of the throwable to the debug logger .
37,739
public void analyze ( ) { final Resources resources = new ProjectAnalyzer ( analysis . classPaths ) . analyze ( analysis . projectClassPaths , analysis . projectSourcePaths , analysis . ignoredResources ) ; if ( resources . isEmpty ( ) ) { LogProvider . info ( "Empty JAX-RS analysis result, omitting output" ) ; return ; } final Project project = new Project ( analysis . projectName , analysis . projectVersion , resources ) ; final byte [ ] output = analysis . backend . render ( project ) ; if ( analysis . outputLocation != null ) { outputToFile ( output , analysis . outputLocation ) ; } else { outputToConsole ( output ) ; } }
Analyzes the JAX - RS project at the class path and produces the output as configured .
37,740
public static TypeRepresentation ofEnum ( final TypeIdentifier identifier , final String ... enumValues ) { return new EnumTypeRepresentation ( identifier , new HashSet < > ( Arrays . asList ( enumValues ) ) ) ; }
Creates a type representation of an enum type plus the available enumeration values .
37,741
public static < V , W > Pair < V , W > of ( final V left , final W right ) { return new Pair < > ( left , right ) ; }
Creates a new pair with left and right value .
37,742
public void addProjectMethod ( final ProjectMethod method ) { readWriteLock . writeLock ( ) . lock ( ) ; try { availableMethods . add ( method ) ; } finally { readWriteLock . writeLock ( ) . unlock ( ) ; } }
Adds a project method to the pool .
37,743
public Method get ( final MethodIdentifier identifier ) { readWriteLock . readLock ( ) . lock ( ) ; try { final Optional < ? extends IdentifiableMethod > method = availableMethods . stream ( ) . filter ( m -> m . matches ( identifier ) ) . findAny ( ) ; if ( method . isPresent ( ) ) return method . get ( ) ; } finally { readWriteLock . readLock ( ) . unlock ( ) ; } return DEFAULT_METHOD . apply ( identifier ) ; }
Returns a method identified by an method identifier .
37,744
static Set < Integer > findLoadIndexes ( final List < Instruction > instructions , final Predicate < LoadInstruction > isLoadIgnored ) { return instructions . stream ( ) . filter ( i -> i . getType ( ) == Instruction . InstructionType . LOAD ) . map ( i -> ( LoadInstruction ) i ) . filter ( i -> ! isLoadIgnored . test ( i ) ) . map ( LoadInstruction :: getNumber ) . collect ( TreeSet :: new , Set :: add , Set :: addAll ) ; }
Searches for all LOAD indexes which occur in the given instructions . The LOAD instruction is checked against the given predicate if it should be ignored .
37,745
static Set < Integer > findReturnsAndThrows ( final List < Instruction > instructions ) { return find ( instruction -> instruction . getType ( ) == Instruction . InstructionType . RETURN || instruction . getType ( ) == Instruction . InstructionType . THROW , instructions ) ; }
Searches for return instructions in the given instructions .
37,746
private static Set < Integer > find ( final Predicate < Instruction > predicate , final List < Instruction > instructions ) { final Set < Integer > positions = new HashSet < > ( ) ; for ( int i = 0 ; i < instructions . size ( ) ; i ++ ) { final Instruction instruction = instructions . get ( i ) ; if ( predicate . test ( instruction ) ) { positions . add ( i ) ; } } return positions ; }
Searches for certain instruction positions be testing against the predicate .
37,747
public Element simulate ( final List < Instruction > instructions ) { lock . lock ( ) ; try { returnElement = null ; return simulateInternal ( instructions ) ; } finally { lock . unlock ( ) ; } }
Simulates the instructions and collects information about the resource method .
37,748
private void simulate ( final Instruction instruction ) { switch ( instruction . getType ( ) ) { case PUSH : final PushInstruction pushInstruction = ( PushInstruction ) instruction ; runtimeStack . push ( new Element ( pushInstruction . getValueType ( ) , pushInstruction . getValue ( ) ) ) ; break ; case METHOD_HANDLE : simulateMethodHandle ( ( InvokeDynamicInstruction ) instruction ) ; break ; case INVOKE : simulateInvoke ( ( InvokeInstruction ) instruction ) ; break ; case GET_FIELD : runtimeStack . pop ( ) ; runtimeStack . push ( new Element ( ( ( GetFieldInstruction ) instruction ) . getPropertyType ( ) ) ) ; break ; case GET_STATIC : final GetStaticInstruction getStaticInstruction = ( GetStaticInstruction ) instruction ; final Object value = getStaticInstruction . getValue ( ) ; if ( value != null ) runtimeStack . push ( new Element ( getStaticInstruction . getPropertyType ( ) , value ) ) ; else runtimeStack . push ( new Element ( getStaticInstruction . getPropertyType ( ) ) ) ; break ; case LOAD : final LoadInstruction loadInstruction = ( LoadInstruction ) instruction ; runtimeStack . push ( localVariables . getOrDefault ( loadInstruction . getNumber ( ) , new Element ( loadInstruction . getVariableType ( ) ) ) ) ; runtimeStack . peek ( ) . getTypes ( ) . add ( loadInstruction . getVariableType ( ) ) ; variableInvalidation . add ( loadInstruction . getValidUntil ( ) , loadInstruction . getNumber ( ) ) ; break ; case STORE : simulateStore ( ( StoreInstruction ) instruction ) ; break ; case SIZE_CHANGE : simulateSizeChange ( ( SizeChangingInstruction ) instruction ) ; break ; case NEW : final NewInstruction newInstruction = ( NewInstruction ) instruction ; runtimeStack . push ( new Element ( toType ( newInstruction . getClassName ( ) ) ) ) ; break ; case DUP : runtimeStack . push ( runtimeStack . peek ( ) ) ; break ; case OTHER : break ; case RETURN : mergeReturnElement ( runtimeStack . pop ( ) ) ; case THROW : mergePossibleResponse ( ) ; runtimeStack . clear ( ) ; break ; default : throw new IllegalArgumentException ( "Instruction without type!" ) ; } if ( instruction . getLabel ( ) != active && variableInvalidation . containsKey ( active ) ) { variableInvalidation . get ( active ) . forEach ( localVariables :: remove ) ; } active = instruction . getLabel ( ) ; }
Simulates the instruction .
37,749
private void simulateMethodHandle ( final InvokeDynamicInstruction instruction ) { final List < Element > arguments = IntStream . range ( 0 , instruction . getDynamicIdentifier ( ) . getParameters ( ) . size ( ) ) . mapToObj ( t -> runtimeStack . pop ( ) ) . collect ( Collectors . toList ( ) ) ; Collections . reverse ( arguments ) ; if ( ! instruction . getDynamicIdentifier ( ) . isStaticMethod ( ) ) arguments . remove ( 0 ) ; runtimeStack . push ( new MethodHandle ( instruction . getDynamicIdentifier ( ) . getReturnType ( ) , instruction . getIdentifier ( ) , arguments ) ) ; }
Simulates the invoke dynamic call . Pushes a method handle on the stack .
37,750
private void simulateInvoke ( final InvokeInstruction instruction ) { final List < Element > arguments = new LinkedList < > ( ) ; MethodIdentifier identifier = instruction . getIdentifier ( ) ; IntStream . range ( 0 , identifier . getParameters ( ) . size ( ) ) . forEach ( i -> arguments . add ( runtimeStack . pop ( ) ) ) ; Collections . reverse ( arguments ) ; Element object = null ; Method method ; if ( ! identifier . isStaticMethod ( ) ) { object = runtimeStack . pop ( ) ; if ( object instanceof MethodHandle ) { method = ( Method ) object ; } else { method = methodPool . get ( identifier ) ; } } else { method = methodPool . get ( identifier ) ; } final Element returnedElement = method . invoke ( object , arguments ) ; if ( returnedElement != null ) runtimeStack . push ( returnedElement ) ; else if ( ! identifier . getReturnType ( ) . equals ( Types . PRIMITIVE_VOID ) ) runtimeStack . push ( new Element ( identifier . getReturnType ( ) ) ) ; }
Simulates the invoke instruction .
37,751
private void simulateStore ( final StoreInstruction instruction ) { final int index = instruction . getNumber ( ) ; final Element elementToStore = runtimeStack . pop ( ) ; if ( elementToStore instanceof MethodHandle ) mergeMethodHandleStore ( index , ( MethodHandle ) elementToStore ) ; else mergeElementStore ( index , instruction . getVariableType ( ) , elementToStore ) ; }
Simulates the store instruction .
37,752
private void mergeElementStore ( final int index , final String type , final Element element ) { final String elementType = type . equals ( Types . OBJECT ) ? determineLeastSpecificType ( element . getTypes ( ) . toArray ( new String [ element . getTypes ( ) . size ( ) ] ) ) : type ; final Element created = new Element ( elementType ) ; created . merge ( element ) ; localVariables . merge ( index , created , Element :: merge ) ; }
Merges a stored element to the local variables .
37,753
private void mergeMethodHandleStore ( final int index , final MethodHandle methodHandle ) { localVariables . merge ( index , new MethodHandle ( methodHandle ) , Element :: merge ) ; }
Merges a stored method handle to the local variables .
37,754
private void mergePossibleResponse ( ) { if ( ! runtimeStack . isEmpty ( ) && runtimeStack . peek ( ) . getTypes ( ) . contains ( Types . RESPONSE ) ) { mergeReturnElement ( runtimeStack . peek ( ) ) ; } }
Checks if the current stack element is eligible for being merged with the returned element .
37,755
private void simulateSizeChange ( final SizeChangingInstruction instruction ) { IntStream . range ( 0 , instruction . getNumberOfPops ( ) ) . forEach ( i -> runtimeStack . pop ( ) ) ; IntStream . range ( 0 , instruction . getNumberOfPushes ( ) ) . forEach ( i -> runtimeStack . push ( new Element ( ) ) ) ; }
Simulates the size change instruction .
37,756
public Resources interpret ( final Set < ClassResult > classResults ) { resources = new Resources ( ) ; resources . setBasePath ( PathNormalizer . getApplicationPath ( classResults ) ) ; javaTypeAnalyzer = new JavaTypeAnalyzer ( resources . getTypeRepresentations ( ) ) ; dynamicTypeAnalyzer = new DynamicTypeAnalyzer ( resources . getTypeRepresentations ( ) ) ; stringParameterResolver = new StringParameterResolver ( resources . getTypeRepresentations ( ) , javaTypeAnalyzer ) ; classResults . stream ( ) . filter ( c -> c . getResourcePath ( ) != null ) . forEach ( this :: interpretClassResult ) ; resources . consolidateMultiplePaths ( ) ; return resources ; }
Interprets the class results .
37,757
private void interpretClassResult ( final ClassResult classResult ) { classResult . getMethods ( ) . forEach ( m -> interpretMethodResult ( m , classResult ) ) ; }
Interprets the class result .
37,758
private void interpretMethodResult ( final MethodResult methodResult , final ClassResult classResult ) { if ( methodResult . getSubResource ( ) != null ) { interpretClassResult ( methodResult . getSubResource ( ) ) ; return ; } final String path = PathNormalizer . getPath ( methodResult ) ; final ResourceMethod resourceMethod = interpretResourceMethod ( methodResult , classResult ) ; resources . addMethod ( path , resourceMethod ) ; }
Interprets the method result .
37,759
private ResourceMethod interpretResourceMethod ( final MethodResult methodResult , final ClassResult classResult ) { final MethodComment methodDoc = methodResult . getMethodDoc ( ) ; final String description = methodDoc != null ? methodDoc . getComment ( ) : null ; final ResourceMethod resourceMethod = new ResourceMethod ( methodResult . getHttpMethod ( ) , description ) ; updateMethodParameters ( resourceMethod . getMethodParameters ( ) , classResult . getClassFields ( ) ) ; updateMethodParameters ( resourceMethod . getMethodParameters ( ) , methodResult . getMethodParameters ( ) ) ; addParameterDescriptions ( resourceMethod . getMethodParameters ( ) , methodDoc ) ; stringParameterResolver . replaceParametersTypes ( resourceMethod . getMethodParameters ( ) ) ; if ( methodResult . getRequestBodyType ( ) != null ) { resourceMethod . setRequestBody ( javaTypeAnalyzer . analyze ( methodResult . getRequestBodyType ( ) ) ) ; resourceMethod . setRequestBodyDescription ( findRequestBodyDescription ( methodDoc ) ) ; } addDefaultResponses ( methodResult ) ; methodResult . getResponses ( ) . forEach ( r -> interpretResponse ( r , resourceMethod ) ) ; addResponseComments ( methodResult , resourceMethod ) ; addMediaTypes ( methodResult , classResult , resourceMethod ) ; if ( methodResult . isDeprecated ( ) || classResult . isDeprecated ( ) || hasDeprecationTag ( methodDoc ) ) resourceMethod . setDeprecated ( true ) ; return resourceMethod ; }
Interprets the result of a resource method .
37,760
private void addMediaTypes ( final MethodResult methodResult , final ClassResult classResult , final ResourceMethod resourceMethod ) { resourceMethod . getRequestMediaTypes ( ) . addAll ( methodResult . getRequestMediaTypes ( ) ) ; if ( resourceMethod . getRequestMediaTypes ( ) . isEmpty ( ) ) { resourceMethod . getRequestMediaTypes ( ) . addAll ( classResult . getRequestMediaTypes ( ) ) ; } if ( resourceMethod . getResponseMediaTypes ( ) . isEmpty ( ) ) resourceMethod . getResponseMediaTypes ( ) . addAll ( methodResult . getResponseMediaTypes ( ) ) ; if ( resourceMethod . getResponseMediaTypes ( ) . isEmpty ( ) ) { resourceMethod . getResponseMediaTypes ( ) . addAll ( classResult . getResponseMediaTypes ( ) ) ; } }
Adds the request and response media type information to the resource method .
37,761
void buildPackagePrefix ( final String className ) { final int lastPackageSeparator = className . lastIndexOf ( '/' ) ; final String packageName = className . substring ( 0 , lastPackageSeparator == - 1 ? className . length ( ) : lastPackageSeparator ) ; final String [ ] splitPackage = packageName . split ( "/" ) ; if ( splitPackage . length >= PROJECT_PACKAGE_HIERARCHIES ) { projectPackagePrefix = IntStream . range ( 0 , PROJECT_PACKAGE_HIERARCHIES ) . mapToObj ( i -> splitPackage [ i ] ) . collect ( Collectors . joining ( "/" ) ) ; } else { projectPackagePrefix = packageName ; } }
Builds the project package prefix for the class of given method . The current project which is analyzed is identified by the first two package nodes .
37,762
Set < ProjectMethod > findProjectMethods ( final List < Instruction > instructions ) { final Set < ProjectMethod > projectMethods = new HashSet < > ( ) ; addProjectMethods ( instructions , projectMethods ) ; return projectMethods ; }
Searches for own project method invoke instructions in the given list .
37,763
private boolean isProjectMethod ( final InvokeInstruction instruction ) { final MethodIdentifier identifier = instruction . getIdentifier ( ) ; return identifier . getContainingClass ( ) . startsWith ( projectPackagePrefix ) ; }
Checks if the given instruction invokes a method defined in the analyzed project .
37,764
private static boolean isStackCleared ( final Instruction instruction ) { return instruction . getType ( ) == Instruction . InstructionType . RETURN || instruction . getType ( ) == Instruction . InstructionType . THROW ; }
Checks if the stack will be cleared on invoking the given instruction .
37,765
private int findBacktrackPosition ( final int position ) { int currentPosition = position ; while ( stackSizes . get ( currentPosition ) . getRight ( ) > 0 ) { currentPosition ++ ; } return currentPosition ; }
Returns the next position where the stack will be empty .
37,766
private boolean equalsSimpleTypeNames ( MethodIdentifier identifier , MethodResult methodResult ) { MethodIdentifier originalIdentifier = methodResult . getOriginalMethodSignature ( ) ; return originalIdentifier . getMethodName ( ) . equals ( identifier . getMethodName ( ) ) && matchesTypeBestEffort ( originalIdentifier . getReturnType ( ) , identifier . getReturnType ( ) ) && parameterMatch ( originalIdentifier . getParameters ( ) , identifier . getParameters ( ) ) ; }
This is a best - effort approach combining only the simple types .
37,767
static String normalizeCollection ( final String type ) { if ( isAssignableTo ( type , Types . COLLECTION ) ) { if ( ! getTypeParameters ( type ) . isEmpty ( ) ) { return getTypeParameters ( type ) . get ( 0 ) ; } return Types . OBJECT ; } return type ; }
Normalizes the contained collection type .
37,768
public List < Instruction > reduceInstructions ( final List < Instruction > instructions ) { lock . lock ( ) ; try { this . instructions = instructions ; stackSizeSimulator . buildStackSizes ( instructions ) ; return reduceInstructionsInternal ( instructions ) ; } finally { lock . unlock ( ) ; } }
Returns all instructions which are somewhat relevant for the returned object of the method . The instructions are visited backwards - starting from the return statement . Load and Store operations are handled as well .
37,769
private List < Instruction > reduceInstructionsInternal ( final List < Instruction > instructions ) { final List < Instruction > visitedInstructions = new LinkedList < > ( ) ; final Set < Integer > visitedInstructionPositions = new HashSet < > ( ) ; final Set < Integer > handledLoadIndexes = new HashSet < > ( ) ; final Set < Integer > backtrackPositions = new LinkedHashSet < > ( findSortedBacktrackPositions ( ) ) ; while ( ! visitedInstructionPositions . containsAll ( backtrackPositions ) ) { final int backtrackPosition = backtrackPositions . stream ( ) . filter ( pos -> ! visitedInstructionPositions . contains ( pos ) ) . findFirst ( ) . orElseThrow ( IllegalStateException :: new ) ; final List < Integer > lastVisitedPositions = stackSizeSimulator . simulateStatementBackwards ( backtrackPosition ) ; final List < Instruction > lastVisitedInstructions = lastVisitedPositions . stream ( ) . map ( instructions :: get ) . collect ( Collectors . toList ( ) ) ; visitedInstructionPositions . addAll ( lastVisitedPositions ) ; visitedInstructions . addAll ( lastVisitedInstructions ) ; final Set < Integer > unhandledLoadIndexes = findUnhandledLoadIndexes ( handledLoadIndexes , lastVisitedInstructions ) ; final SortedSet < Integer > loadStoreBacktrackPositions = findLoadStoreBacktrackPositions ( unhandledLoadIndexes ) ; handledLoadIndexes . addAll ( unhandledLoadIndexes ) ; loadStoreBacktrackPositions . stream ( ) . forEach ( backtrackPositions :: add ) ; } Collections . reverse ( visitedInstructions ) ; return visitedInstructions ; }
Returns all reduced instructions .
37,770
private static boolean isLoadIgnored ( final LoadInstruction instruction ) { return Stream . of ( VARIABLE_NAMES_TO_IGNORE ) . anyMatch ( instruction . getName ( ) :: equals ) ; }
Checks if the given LOAD instruction should be ignored for backtracking .
37,771
public Resources analyze ( Set < Path > projectClassPaths , Set < Path > projectSourcePaths , Set < String > ignoredResources ) { lock . lock ( ) ; try { projectClassPaths . forEach ( this :: addProjectPath ) ; final JobRegistry jobRegistry = JobRegistry . getInstance ( ) ; final Set < ClassResult > classResults = new HashSet < > ( ) ; classes . stream ( ) . filter ( this :: isJAXRSRootResource ) . filter ( r -> ! ignoredResources . contains ( r ) ) . forEach ( c -> jobRegistry . analyzeResourceClass ( c , new ClassResult ( ) ) ) ; Pair < String , ClassResult > classResultPair ; while ( ( classResultPair = jobRegistry . nextUnhandledClass ( ) ) != null ) { final ClassResult classResult = classResultPair . getRight ( ) ; classResults . add ( classResult ) ; analyzeClass ( classResultPair . getLeft ( ) , classResult ) ; bytecodeAnalyzer . analyzeBytecode ( classResult ) ; } javaDocAnalyzer . analyze ( projectSourcePaths , classResults ) ; return resultInterpreter . interpret ( classResults ) ; } finally { lock . unlock ( ) ; } }
Analyzes all classes in the given project path .
37,772
private void addToClassPool ( final Path location ) { if ( ! location . toFile ( ) . exists ( ) ) throw new IllegalArgumentException ( "The location '" + location + "' does not exist!" ) ; try { ContextClassReader . addClassPath ( location . toUri ( ) . toURL ( ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "The location '" + location + "' could not be loaded to the class path!" , e ) ; } }
Adds the location to the class pool .
37,773
private void addProjectPath ( final Path path ) { addToClassPool ( path ) ; if ( path . toFile ( ) . isFile ( ) && path . toString ( ) . endsWith ( ".jar" ) ) { addJarClasses ( path ) ; } else if ( path . toFile ( ) . isDirectory ( ) ) { addDirectoryClasses ( path , Paths . get ( "" ) ) ; } else { throw new IllegalArgumentException ( "The project path '" + path + "' must be a jar file or a directory" ) ; } }
Adds the project paths and loads all classes .
37,774
private void addJarClasses ( final Path location ) { try ( final JarFile jarFile = new JarFile ( location . toFile ( ) ) ) { final Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { final JarEntry entry = entries . nextElement ( ) ; final String entryName = entry . getName ( ) ; if ( entryName . endsWith ( ".class" ) ) classes . add ( toQualifiedClassName ( entryName ) ) ; } } catch ( IOException e ) { throw new IllegalArgumentException ( "Could not read jar-file '" + location + "', reason: " + e . getMessage ( ) ) ; } }
Adds all classes in the given jar - file location to the set of known classes .
37,775
private void addDirectoryClasses ( final Path location , final Path subPath ) { for ( final File file : location . toFile ( ) . listFiles ( ) ) { if ( file . isDirectory ( ) ) addDirectoryClasses ( location . resolve ( file . getName ( ) ) , subPath . resolve ( file . getName ( ) ) ) ; else if ( file . isFile ( ) && file . getName ( ) . endsWith ( ".class" ) ) { final String classFileName = subPath . resolve ( file . getName ( ) ) . toString ( ) ; classes . add ( toQualifiedClassName ( classFileName ) ) ; } } }
Adds all classes in the given directory location to the set of known classes .
37,776
private static String toQualifiedClassName ( final String fileName ) { final String replacedSeparators = fileName . replace ( File . separatorChar , '.' ) ; return replacedSeparators . substring ( 0 , replacedSeparators . length ( ) - ".class" . length ( ) ) ; }
Converts the given file name of a class - file to the fully - qualified class name .
37,777
static String getApplicationPath ( final Set < ClassResult > classResults ) { return classResults . stream ( ) . map ( ClassResult :: getApplicationPath ) . filter ( Objects :: nonNull ) . map ( PathNormalizer :: normalize ) . findAny ( ) . orElse ( "" ) ; }
Returns the normalized application path found in any of the given class results .
37,778
private static List < String > determinePaths ( final MethodResult methodResult ) { final List < String > paths = new LinkedList < > ( ) ; MethodResult currentMethod = methodResult ; while ( true ) { addNonBlank ( currentMethod . getPath ( ) , paths ) ; final ClassResult parentClass = currentMethod . getParentResource ( ) ; if ( parentClass == null ) break ; currentMethod = parentClass . getParentSubResourceLocator ( ) ; if ( currentMethod == null ) { addNonBlank ( parentClass . getResourcePath ( ) , paths ) ; break ; } } Collections . reverse ( paths ) ; return paths ; }
Determines all single paths of the method result recursively . All parent class and method results are analyzed as well .
37,779
private static void addNonBlank ( final String string , final List < String > strings ) { if ( ! StringUtils . isBlank ( string ) && ! "/" . equals ( string ) ) strings . add ( string ) ; }
Adds the string to the list if it is not blank .
37,780
private static String normalize ( final String path ) { final StringBuilder builder = new StringBuilder ( path ) ; int index = 0 ; int colonIndex = - 1 ; char current = 0 ; char last ; while ( ( index > - 1 ) && ( index < builder . length ( ) ) ) { last = current ; current = builder . charAt ( index ) ; switch ( current ) { case '}' : if ( last == '\\' ) break ; if ( colonIndex != - 1 ) { builder . delete ( colonIndex , index ) ; index = colonIndex ; colonIndex = - 1 ; } break ; case ':' : if ( colonIndex == - 1 ) { colonIndex = index ; } break ; } if ( ( index == 0 || index == builder . length ( ) - 1 ) && current == '/' ) { builder . deleteCharAt ( index ) ; if ( index == builder . length ( ) ) { index -- ; } } else { index ++ ; } } return builder . toString ( ) ; }
Normalizes the given path i . e . trims leading or trailing forward - slashes and removes path parameter matchers .
37,781
public Element simulate ( final List < Element > arguments , final List < Instruction > instructions , final MethodIdentifier identifier ) { if ( EXECUTED_PATH_METHODS . contains ( identifier ) ) return new Element ( ) ; lock . lock ( ) ; EXECUTED_PATH_METHODS . add ( identifier ) ; try { injectArguments ( arguments , identifier ) ; return simulateInternal ( instructions ) ; } finally { EXECUTED_PATH_METHODS . remove ( identifier ) ; lock . unlock ( ) ; } }
Simulates the instructions of the method which will be called with the given arguments .
37,782
private void injectArguments ( final List < Element > arguments , final MethodIdentifier identifier ) { final boolean staticMethod = identifier . isStaticMethod ( ) ; final int startIndex = staticMethod ? 0 : 1 ; final int endIndex = staticMethod ? arguments . size ( ) - 1 : arguments . size ( ) ; IntStream . rangeClosed ( startIndex , endIndex ) . forEach ( i -> localVariables . put ( i , arguments . get ( staticMethod ? i : i - 1 ) ) ) ; }
Injects the arguments of the method invocation to the local variables .
37,783
private static SwaggerType toSwaggerType ( final String type ) { if ( INTEGER_TYPES . contains ( type ) ) return SwaggerType . INTEGER ; if ( DOUBLE_TYPES . contains ( type ) ) return SwaggerType . NUMBER ; if ( BOOLEAN . equals ( type ) || PRIMITIVE_BOOLEAN . equals ( type ) ) return SwaggerType . BOOLEAN ; if ( STRING . equals ( type ) ) return SwaggerType . STRING ; return SwaggerType . OBJECT ; }
Converts the given Java type to the Swagger JSON type .
37,784
public Element merge ( final Element element ) { types . addAll ( element . types ) ; possibleValues . addAll ( element . possibleValues ) ; return this ; }
Merges the other element into this element .
37,785
public void addMethod ( final String resource , final ResourceMethod method ) { resources . putIfAbsent ( resource , new HashSet < > ( ) ) ; resources . get ( resource ) . add ( method ) ; }
Adds the method to the resource s methods .
37,786
public Set < ResourceMethod > getMethods ( final String resource ) { return Collections . unmodifiableSet ( resources . get ( resource ) ) ; }
Returns the resource methods for a given resource .
37,787
public void consolidateMultiplePaths ( ) { Map < String , Set < ResourceMethod > > oldResources = resources ; resources = new HashMap < > ( ) ; oldResources . keySet ( ) . forEach ( s -> consolidateMultipleMethodsForSamePath ( s , oldResources . get ( s ) ) ) ; }
Consolidates the information contained in multiple responses for the same path . Internally creates new resources .
37,788
public Changelog getChangelog ( final boolean useIntegrationIfConfigured ) throws GitChangelogRepositoryException { try ( GitRepo gitRepo = new GitRepo ( new File ( this . settings . getFromRepo ( ) ) ) ) { return getChangelog ( gitRepo , useIntegrationIfConfigured ) ; } catch ( final IOException e ) { throw new GitChangelogRepositoryException ( "" , e ) ; } }
Get the changelog as data object .
37,789
public void toFile ( final File file ) throws GitChangelogRepositoryException , IOException { createParentDirs ( file ) ; write ( render ( ) . getBytes ( "UTF-8" ) , file ) ; }
Write changelog to file .
37,790
public void toMediaWiki ( final String username , final String password , final String url , final String title ) throws GitChangelogRepositoryException , GitChangelogIntegrationException { new MediaWikiClient ( url , title , render ( ) ) . withUser ( username , password ) . createMediaWikiPage ( ) ; }
Create MediaWiki page with changelog .
37,791
public Slot insertSlotAt ( final int position , final Slot slot ) { if ( position < 0 || size < position ) { throw new IndexOutOfBoundsException ( "New slot position should be inside the slots list. Or on the tail (position = size)" ) ; } final Slot toInsert = new Slot ( slot ) ; Slot currentSlot = getSlot ( position ) ; Slot leftNeighbour ; Slot rightNeighbour = null ; if ( currentSlot == null ) { leftNeighbour = lastSlot ; } else { leftNeighbour = currentSlot . getPrevSlot ( ) ; rightNeighbour = currentSlot ; } toInsert . setNextSlot ( rightNeighbour ) ; toInsert . setPrevSlot ( leftNeighbour ) ; if ( rightNeighbour != null ) { rightNeighbour . setPrevSlot ( toInsert ) ; } if ( leftNeighbour != null ) { leftNeighbour . setNextSlot ( toInsert ) ; } if ( position == 0 ) { firstSlot = toInsert ; } else if ( position == size ) { lastSlot = toInsert ; } size ++ ; return toInsert ; }
Inserts a slot on a specified position
37,792
public String uri ( String name ) { try { return String . format ( "otpauth://totp/%s?secret=%s" , URLEncoder . encode ( name , "UTF-8" ) , secret ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( e . getMessage ( ) , e ) ; } }
Prover - To be used only on the client side Retrieves the encoded URI to generated the QRCode required by Google Authenticator
37,793
public boolean verify ( String otp ) { long code = Long . parseLong ( otp ) ; long currentInterval = clock . getCurrentInterval ( ) ; int pastResponse = Math . max ( DELAY_WINDOW , 0 ) ; for ( int i = pastResponse ; i >= 0 ; -- i ) { int candidate = generate ( this . secret , currentInterval - i ) ; if ( candidate == code ) { return true ; } } return false ; }
Verifier - To be used only on the server side
37,794
private void reattach ( HeapElement el ) { if ( el . shift ( ) ) { queue . add ( el ) ; } else if ( el . inclusion ) { if ( -- nInclusionsRemaining == 0 ) { queue . clear ( ) ; } } }
If the given element s iterator has more data then push back onto the heap .
37,795
boolean shift ( ) { if ( ! it . hasNext ( ) ) { return false ; } head = it . next ( ) ; comparable = DateValueComparison . comparable ( head ) ; return true ; }
Discards the current element and move to the next .
37,796
int [ ] toIntArray ( ) { int [ ] out = new int [ size ( ) ] ; int a = 0 , b = out . length ; for ( int i = - 1 ; ( i = ints . nextSetBit ( i + 1 ) ) >= 0 ; ) { int n = decode ( i ) ; if ( n < 0 ) { out [ a ++ ] = n ; } else { out [ -- b ] = n ; } } reverse ( out , 0 , a ) ; reverse ( out , a , out . length ) ; return out ; }
Converts this set to a new integer array that is sorted in ascending order .
37,797
private static void reverse ( int [ ] array , int start , int end ) { for ( int i = start , j = end ; i < -- j ; ++ i ) { int t = array [ i ] ; array [ i ] = array [ j ] ; array [ j ] = t ; } }
Reverses an array .
37,798
public void addTimezonedDate ( String tzid , ICalProperty property , ICalDate date ) { timezonedDates . put ( tzid , new TimezonedDate ( date , property ) ) ; }
Keeps track of a date - time property value that uses a timezone so it can be parsed later . Timezones cannot be handled until the entire iCalendar object has been parsed .
37,799
public void setValue ( Date value , boolean hasTime ) { setValue ( ( value == null ) ? null : new ICalDate ( value , hasTime ) ) ; }
Sets the date - time value .