idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
21,600
public static String generateRid ( ) { byte [ ] encode = Base64 . getEncoder ( ) . encode ( DigestUtils . sha256 ( UUID . randomUUID ( ) . toString ( ) ) ) ; try { String rid = new String ( encode , StandardCharsets . UTF_8 . name ( ) ) ; rid = StringUtils . replaceChars ( rid , "+/=" , "" ) ; return StringUtils . right ( rid , RID_LENGTH ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } }
Generates request id based on UID and SHA - 256 .
130
12
21,601
@ Override public void onBeforeExecutionEvent ( BeforeExecutionEvent event ) { LepManager manager = event . getSource ( ) ; ScopedContext threadContext = manager . getContext ( ContextScopes . THREAD ) ; if ( threadContext == null ) { throw new IllegalStateException ( "LEP manager thread context doesn't initialized" ) ; } TenantContext tenantContext = getRequiredValue ( threadContext , THREAD_CONTEXT_KEY_TENANT_CONTEXT , TenantContext . class ) ; XmAuthenticationContext authContext = getRequiredValue ( threadContext , THREAD_CONTEXT_KEY_AUTH_CONTEXT , XmAuthenticationContext . class ) ; ScopedContext executionContext = manager . getContext ( ContextScopes . EXECUTION ) ; // add contexts executionContext . setValue ( BINDING_KEY_TENANT_CONTEXT , tenantContext ) ; executionContext . setValue ( BINDING_KEY_AUTH_CONTEXT , authContext ) ; bindExecutionContext ( executionContext ) ; }
Init execution context for script variables bindings .
226
8
21,602
@ SuppressWarnings ( "squid:S00112" ) //suppress throwable warning public Object onMethodInvoke ( Class < ? > targetType , Object target , Method method , Object [ ] args ) throws Throwable { LepService typeLepService = targetType . getAnnotation ( LepService . class ) ; Objects . requireNonNull ( typeLepService , "No " + LepService . class . getSimpleName ( ) + " annotation for type " + targetType . getCanonicalName ( ) ) ; LogicExtensionPoint methodLep = AnnotationUtils . getAnnotation ( method , LogicExtensionPoint . class ) ; // TODO methodLep can be null (if used interface method without @LogicExtensionPoint) !!! // create/get key resolver instance LepKeyResolver keyResolver = getKeyResolver ( methodLep ) ; // create base LEP key instance LepKey baseLepKey = getBaseLepKey ( typeLepService , methodLep , method ) ; // create LEP method descriptor LepMethod lepMethod = buildLepMethod ( targetType , target , method , args ) ; // call LepManager to process LEP try { return getLepManager ( ) . processLep ( baseLepKey , XmLepConstants . UNUSED_RESOURCE_VERSION , keyResolver , lepMethod ) ; } catch ( LepInvocationCauseException e ) { log . debug ( "Error process target" , e ) ; throw e . getCause ( ) ; } catch ( Exception e ) { throw e ; } }
Processes a LEP method invocation on a proxy instance and returns the result . This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with .
346
40
21,603
@ Retryable ( maxAttemptsExpression = "${application.retry.max-attempts}" , backoff = @ Backoff ( delayExpression = "${application.retry.delay}" , multiplierExpression = "${application.retry.multiplier}" ) ) public void consumeEvent ( ConsumerRecord < String , String > message ) { MdcUtils . putRid ( ) ; try { log . info ( "Consume event from topic [{}]" , message . topic ( ) ) ; try { ConfigEvent event = mapper . readValue ( message . value ( ) , ConfigEvent . class ) ; log . info ( "Process event from topic [{}], event_id ='{}'" , message . topic ( ) , event . getEventId ( ) ) ; configService . updateConfigurations ( event . getCommit ( ) , event . getPaths ( ) ) ; } catch ( IOException e ) { log . error ( "Config topic message has incorrect format: '{}'" , message . value ( ) , e ) ; } } finally { MdcUtils . removeRid ( ) ; } }
Consume tenant command event message .
247
7
21,604
static Object executeScript ( UrlLepResourceKey scriptResourceKey , ProceedingLep proceedingLep , // can be null LepMethod method , LepManagerService managerService , Supplier < GroovyScriptRunner > resourceExecutorSupplier , LepMethodResult methodResult , // can be null Object ... overrodeArgValues ) throws LepInvocationCauseException { GroovyScriptRunner runner = resourceExecutorSupplier . get ( ) ; String scriptName = runner . getResourceKeyMapper ( ) . map ( scriptResourceKey ) ; Binding binding = buildBinding ( scriptResourceKey , managerService , method , proceedingLep , methodResult , overrodeArgValues ) ; return runner . runScript ( scriptResourceKey , method , managerService , scriptName , binding ) ; }
Executes any script .
165
5
21,605
private static Binding buildBinding ( UrlLepResourceKey scriptResourceKey , LepManagerService managerService , LepMethod method , ProceedingLep proceedingLep , LepMethodResult lepMethodResult , Object ... overrodeArgValues ) { boolean isOverrodeArgs = overrodeArgValues != null && overrodeArgValues . length > 0 ; if ( isOverrodeArgs ) { int actual = overrodeArgValues . length ; int expected = method . getMethodSignature ( ) . getParameterTypes ( ) . length ; if ( actual != expected ) { throw new IllegalArgumentException ( "When calling LEP resource: " + scriptResourceKey + ", overrode method argument values " + "count doesn't corresponds method signature (expected: " + expected + ", actual: " + actual + ")" ) ; } } Map < String , Object > lepContext = new LinkedHashMap <> ( ) ; Binding binding = new Binding ( ) ; // add execution context values ScopedContext executionContext = managerService . getContext ( ContextScopes . EXECUTION ) ; if ( executionContext != null ) { executionContext . getValues ( ) . forEach ( lepContext :: put ) ; } // add method arg values final String [ ] parameterNames = method . getMethodSignature ( ) . getParameterNames ( ) ; final Object [ ] methodArgValues = isOverrodeArgs ? overrodeArgValues : method . getMethodArgValues ( ) ; Map < String , Object > inVars = new LinkedHashMap <> ( parameterNames . length ) ; for ( int i = 0 ; i < parameterNames . length ; i ++ ) { String paramName = parameterNames [ i ] ; Object paramValue = methodArgValues [ i ] ; inVars . put ( paramName , paramValue ) ; } lepContext . put ( XmLepScriptConstants . BINDING_KEY_IN_ARGS , inVars ) ; // add proceedingLep support lepContext . put ( XmLepScriptConstants . BINDING_KEY_LEP , proceedingLep ) ; // add returned value if ( lepMethodResult != null ) { lepContext . put ( XmLepScriptConstants . BINDING_KEY_RETURNED_VALUE , lepMethodResult . getReturnedValue ( ) ) ; } // add method result lepContext . put ( XmLepScriptConstants . BINDING_KEY_METHOD_RESULT , lepMethodResult ) ; binding . setVariable ( XmLepScriptConstants . BINDING_VAR_LEP_SCRIPT_CONTEXT , lepContext ) ; return binding ; }
Build scripts bindings .
580
4
21,606
@ Override protected Map < String , Object > decode ( String token ) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties . getSignatureVerification ( ) . getTtl ( ) ; if ( ttl > 0 && System . currentTimeMillis ( ) - lastKeyFetchTimestamp > ttl ) { throw new InvalidTokenException ( "public key expired" ) ; } return super . decode ( token ) ; } catch ( InvalidTokenException ex ) { if ( tryCreateSignatureVerifier ( ) ) { return super . decode ( token ) ; } throw ex ; } }
Try to decode the token with the current public key . If it fails contact the OAuth2 server to get a new public key then try again . We might not have fetched it in the first place or it might have changed .
139
47
21,607
private boolean tryCreateSignatureVerifier ( ) { long t = System . currentTimeMillis ( ) ; if ( t - lastKeyFetchTimestamp < oAuth2Properties . getSignatureVerification ( ) . getPublicKeyRefreshRateLimit ( ) ) { return false ; } try { SignatureVerifier verifier = signatureVerifierClient . getSignatureVerifier ( ) ; if ( verifier != null ) { setVerifier ( verifier ) ; lastKeyFetchTimestamp = t ; log . debug ( "Public key retrieved from OAuth2 server to create SignatureVerifier" ) ; return true ; } } catch ( Throwable ex ) { log . error ( "could not get public key from OAuth2 server to create SignatureVerifier" , ex ) ; } return false ; }
Fetch a new public key from the AuthorizationServer .
172
11
21,608
public static void install ( Application app , IWicketJquerySelectorsSettings settings ) { final IWicketJquerySelectorsSettings existingSettings = settings ( app ) ; if ( existingSettings == null ) { if ( settings == null ) { settings = new WicketJquerySelectorsSettings ( ) ; } app . setMetaData ( JQUERY_SELECTORS_SETTINGS_METADATA_KEY , settings ) ; LOG . info ( "initialize wicket jquery selectors with given settings: {}" , settings ) ; } }
installs the library settings to given app .
116
9
21,609
public String privilegesToYml ( Collection < Privilege > privileges ) { try { Map < String , Set < Privilege > > map = new TreeMap <> ( ) ; privileges . forEach ( privilege -> { map . putIfAbsent ( privilege . getMsName ( ) , new TreeSet <> ( ) ) ; map . get ( privilege . getMsName ( ) ) . add ( privilege ) ; } ) ; return mapper . writeValueAsString ( map ) ; } catch ( Exception e ) { log . error ( "Failed to create privileges YML file from collection, error: {}" , e . getMessage ( ) , e ) ; } return null ; }
Convert privileges collection to yml string .
145
9
21,610
public String privilegesMapToYml ( Map < String , Collection < Privilege > > privileges ) { try { return mapper . writeValueAsString ( privileges ) ; } catch ( Exception e ) { log . error ( "Failed to create privileges YML file from map, error: {}" , e . getMessage ( ) , e ) ; } return null ; }
Convert privileges map to yml string .
78
9
21,611
public Map < String , Set < Privilege > > ymlToPrivileges ( String yml ) { try { Map < String , Set < Privilege > > map = mapper . readValue ( yml , new TypeReference < TreeMap < String , TreeSet < Privilege > > > ( ) { } ) ; map . forEach ( ( msName , privileges ) -> privileges . forEach ( privilege -> privilege . setMsName ( msName ) ) ) ; return Collections . unmodifiableMap ( map ) ; } catch ( Exception e ) { log . error ( "Failed to create privileges collection from YML file, error: {}" , e . getMessage ( ) , e ) ; } return Collections . emptyMap ( ) ; }
Convert privileges yml string to map .
159
9
21,612
public static < T > T fromJson ( final String json , final JavaType type ) { try { return createObjectMapper ( ) . readValue ( json , type ) ; } catch ( Exception e ) { throw new ParseException ( e ) ; } }
Convert a string to a Java value
56
8
21,613
public static JsonNode toJson ( final Object data ) { if ( data == null ) { return newObject ( ) ; } try { return createObjectMapper ( ) . valueToTree ( data ) ; } catch ( Exception e ) { throw new ParseException ( e ) ; } }
Convert an object to JsonNode .
63
9
21,614
public static String stringify ( final JsonNode json ) { try { return json != null ? createObjectMapper ( ) . writeValueAsString ( json ) : "{}" ; } catch ( JsonProcessingException jpx ) { throw new RuntimeException ( "A problem occurred while stringifying a JsonNode: " + jpx . getMessage ( ) , jpx ) ; } }
Convert a JsonNode to its string representation . If given value is null an empty json object will returned .
83
23
21,615
public static boolean isValid ( final String json ) { if ( Strings . isEmpty ( json ) ) { return false ; } try { return parse ( json ) != null ; } catch ( ParseException e ) { return false ; } }
verifies a valid json string
51
6
21,616
public static JsonNode parse ( final String jsonString ) { if ( Strings . isEmpty ( jsonString ) ) { return newObject ( ) ; } try { return createObjectMapper ( ) . readValue ( jsonString , JsonNode . class ) ; } catch ( Throwable e ) { throw new ParseException ( String . format ( "can't parse string [%s]" , jsonString ) , e ) ; } }
Parse a String representing a json and return it as a JsonNode .
93
16
21,617
public static void validateScriptsCombination ( Set < XmLepResourceSubType > scriptTypes , LepMethod lepMethod , UrlLepResourceKey compositeResourceKey ) { byte mask = getCombinationMask ( scriptTypes , lepMethod , compositeResourceKey ) ; StringBuilder errors = new StringBuilder ( ) ; if ( isZero ( mask , ZERO_PATTERN_NO_TENANT_AND_DEFAULT_AND_JAVA_CODE ) ) { errors . append ( String . format ( "Has no one script of '%s', '%s' or native (java) implementation." , XmLepResourceSubType . TENANT , XmLepResourceSubType . DEFAULT ) ) ; } if ( isSetByPattern ( mask , IS_SET_PATTERN_AROUND_AND_BEFORE ) ) { if ( errors . length ( ) > 0 ) { errors . append ( " " ) ; } errors . append ( String . format ( "Has '%s' script with '%s'." , XmLepResourceSubType . BEFORE , XmLepResourceSubType . AROUND ) ) ; } if ( isSetByPattern ( mask , IS_SET_PATTERN_AROUND_AND_AFTER ) ) { if ( errors . length ( ) > 0 ) { errors . append ( " " ) ; } errors . append ( String . format ( "Has '%s' script with '%s'." , XmLepResourceSubType . AROUND , XmLepResourceSubType . AFTER ) ) ; } if ( isSetByPattern ( mask , IS_SET_PATTERN_AROUND_AND_TENANT ) ) { if ( errors . length ( ) > 0 ) { errors . append ( " " ) ; } errors . append ( String . format ( "Unallowed combination '%s' and '%s' scripts." , XmLepResourceSubType . AROUND , XmLepResourceSubType . TENANT ) ) ; } if ( errors . length ( ) > 0 ) { throw new IllegalArgumentException ( String . format ( "Resource key %s has script combination errors. %s" , compositeResourceKey , errors . toString ( ) ) ) ; } }
Validate script combination .
485
5
21,618
private static byte getCombinationMask ( Set < XmLepResourceSubType > scriptTypes , LepMethod lepMethod , UrlLepResourceKey compositeResourceKey ) { byte combinationMask = 0 ; for ( XmLepResourceSubType scriptType : scriptTypes ) { switch ( scriptType ) { case BEFORE : combinationMask |= BEFORE_MASK ; break ; case AROUND : combinationMask |= AROUND_MASK ; break ; case TENANT : combinationMask |= TENANT_MASK ; break ; case DEFAULT : combinationMask |= DEFAULT_MASK ; break ; case AFTER : combinationMask |= AFTER_MASK ; break ; default : throw new IllegalArgumentException ( "Unsupported script type: " + scriptType + " for resource key: " + compositeResourceKey + ", all script types: " + scriptTypes ) ; } } if ( lepMethod . getTarget ( ) != null ) { combinationMask |= JAVA_CODE_MASK ; } return combinationMask ; }
Builds script combination mask .
220
6
21,619
public String createEventJson ( HttpServletRequest request , HttpServletResponse response , String tenant , String userLogin , String userKey ) { try { String requestBody = getRequestContent ( request ) ; String responseBody = getResponseContent ( response ) ; Instant startDate = Instant . ofEpochMilli ( System . currentTimeMillis ( ) - MdcUtils . getExecTimeMs ( ) ) ; Map < String , Object > data = new LinkedHashMap <> ( ) ; data . put ( "rid" , MdcUtils . getRid ( ) ) ; data . put ( "login" , userLogin ) ; data . put ( "userKey" , userKey ) ; data . put ( "tenant" , tenant ) ; data . put ( "msName" , appName ) ; data . put ( "operationName" , getResourceName ( request . getRequestURI ( ) ) + " " + getOperation ( request . getMethod ( ) ) ) ; data . put ( "operationUrl" , request . getRequestURI ( ) ) ; data . put ( "operationQueryString" , request . getQueryString ( ) ) ; data . put ( "startDate" , startDate . toString ( ) ) ; data . put ( "httpMethod" , request . getMethod ( ) ) ; data . put ( "requestBody" , maskContent ( requestBody , request . getRequestURI ( ) , true , request . getMethod ( ) ) ) ; data . put ( "requestLength" , requestBody . length ( ) ) ; data . put ( "responseBody" , maskContent ( responseBody , request . getRequestURI ( ) , false , request . getMethod ( ) ) ) ; data . put ( "responseLength" , responseBody . length ( ) ) ; data . put ( "requestHeaders" , getRequestHeaders ( request ) ) ; data . put ( "responseHeaders" , getResponseHeaders ( response ) ) ; data . put ( "httpStatusCode" , response . getStatus ( ) ) ; data . put ( "channelType" , "HTTP" ) ; data . put ( "entityId" , getEntityField ( responseBody , "id" ) ) ; data . put ( "entityKey" , getEntityField ( responseBody , "key" ) ) ; data . put ( "entityTypeKey" , getEntityField ( responseBody , "typeKey" ) ) ; data . put ( "execTime" , MdcUtils . getExecTimeMs ( ) ) ; return mapper . writeValueAsString ( data ) ; } catch ( Exception e ) { log . warn ( "Error creating timeline event" , e ) ; } return null ; }
Create event json string .
588
5
21,620
@ Async public void send ( String topic , String content ) { try { if ( ! StringUtils . isBlank ( content ) ) { log . debug ( "Sending kafka event with data {} to topic {}" , content , topic ) ; template . send ( topic , content ) ; } } catch ( Exception e ) { log . error ( "Error send timeline event" , e ) ; throw e ; } }
Send event to kafka .
91
7
21,621
public static String join ( final Iterable < ? > elements , final char separator ) { return Joiner . on ( separator ) . skipNulls ( ) . join ( elements ) ; }
joins all given elements with a special separator
41
10
21,622
protected void registerTenantInterceptorWithIgnorePathPattern ( InterceptorRegistry registry , HandlerInterceptor interceptor ) { InterceptorRegistration tenantInterceptorRegistration = registry . addInterceptor ( interceptor ) ; tenantInterceptorRegistration . addPathPatterns ( "/**" ) ; List < String > tenantIgnorePathPatterns = getTenantIgnorePathPatterns ( ) ; Objects . requireNonNull ( tenantIgnorePathPatterns , "tenantIgnorePathPatterns can't be null" ) ; for ( String pattern : tenantIgnorePathPatterns ) { tenantInterceptorRegistration . excludePathPatterns ( pattern ) ; } LOGGER . info ( "Added handler interceptor '{}' to all urls, exclude {}" , interceptor . getClass ( ) . getSimpleName ( ) , tenantIgnorePathPatterns ) ; }
Registered interceptor to all request except passed urls .
182
11
21,623
public static Optional < LoggingAspectConfig > getConfigAnnotation ( JoinPoint joinPoint ) { Optional < Method > method = getCallingMethod ( joinPoint ) ; Optional < LoggingAspectConfig > result = method . map ( m -> AnnotationUtils . findAnnotation ( m , LoggingAspectConfig . class ) ) ; if ( ! result . isPresent ( ) ) { Optional < Class > clazz = getDeclaringClass ( joinPoint ) ; result = clazz . map ( aClass -> AnnotationUtils . getAnnotation ( aClass , LoggingAspectConfig . class ) ) ; } return result ; }
Find annotation related to method intercepted by joinPoint .
136
10
21,624
public String rolesToYml ( Collection < Role > roles ) { try { Map < String , Role > map = new TreeMap <> ( ) ; roles . forEach ( role -> map . put ( role . getKey ( ) , role ) ) ; return mapper . writeValueAsString ( map ) ; } catch ( Exception e ) { log . error ( "Failed to create roles YML file from collection, error: {}" , e . getMessage ( ) , e ) ; } return null ; }
Convert roles collection to yml string .
109
9
21,625
public Map < String , Role > ymlToRoles ( String yml ) { try { Map < String , Role > map = mapper . readValue ( yml , new TypeReference < TreeMap < String , Role > > ( ) { } ) ; map . forEach ( ( roleKey , role ) -> role . setKey ( roleKey ) ) ; return map ; } catch ( Exception e ) { log . error ( "Failed to create roles collection from YML file, error: {}" , e . getMessage ( ) , e ) ; } return Collections . emptyMap ( ) ; }
Convert roles yml string to map .
128
9
21,626
public boolean hasPermission ( Authentication authentication , Object privilege ) { return checkRole ( authentication , privilege , true ) || checkPermission ( authentication , null , privilege , false , true ) ; }
Check permission for role and privilege key only .
40
9
21,627
public boolean hasPermission ( Authentication authentication , Object resource , Object privilege ) { boolean logPermission = isLogPermission ( resource ) ; return checkRole ( authentication , privilege , logPermission ) || checkPermission ( authentication , resource , privilege , true , logPermission ) ; }
Check permission for role privilege key and resource condition .
60
10
21,628
@ SuppressWarnings ( "unchecked" ) public boolean hasPermission ( Authentication authentication , Serializable resource , String resourceType , Object privilege ) { boolean logPermission = isLogPermission ( resource ) ; if ( checkRole ( authentication , privilege , logPermission ) ) { return true ; } if ( resource != null ) { Object resourceId = ( ( Map < String , Object > ) resource ) . get ( "id" ) ; if ( resourceId != null ) { ( ( Map < String , Object > ) resource ) . put ( resourceType , resourceFactory . getResource ( resourceId , resourceType ) ) ; } } return checkPermission ( authentication , resource , privilege , true , logPermission ) ; }
Check permission for role privilege key new resource and old resource .
155
12
21,629
public String createCondition ( Authentication authentication , Object privilegeKey , SpelTranslator translator ) { if ( ! hasPermission ( authentication , privilegeKey ) ) { throw new AccessDeniedException ( "Access is denied" ) ; } String roleKey = getRoleKey ( authentication ) ; Permission permission = getPermission ( roleKey , privilegeKey ) ; Subject subject = getSubject ( roleKey ) ; if ( ! RoleConstant . SUPER_ADMIN . equals ( roleKey ) && permission != null && permission . getResourceCondition ( ) != null ) { return translator . translate ( permission . getResourceCondition ( ) . getExpressionString ( ) , subject ) ; } return null ; }
Create condition with replaced subject variables .
145
7
21,630
protected Module addSerializer ( SimpleModule module ) { module . addSerializer ( ConfigModel . class , Holder . CONFIG_MODEL_SERIALIZER ) ; module . addSerializer ( Config . class , Holder . CONFIG_SERIALIZER ) ; module . addSerializer ( Json . RawValue . class , Holder . RAW_VALUE_SERIALIZER ) ; return module ; }
adds custom serializers to given module
85
8
21,631
protected ObjectMapper configure ( ObjectMapper mapper ) { mapper . configure ( JsonParser . Feature . ALLOW_SINGLE_QUOTES , true ) ; mapper . configure ( JsonParser . Feature . ALLOW_UNQUOTED_FIELD_NAMES , true ) ; return mapper ; }
configures given object mapper instance .
70
8
21,632
public String permissionsToYml ( Collection < Permission > permissions ) { try { Map < String , Map < String , Set < Permission > > > map = new TreeMap <> ( ) ; permissions . forEach ( permission -> { map . putIfAbsent ( permission . getMsName ( ) , new TreeMap <> ( ) ) ; map . get ( permission . getMsName ( ) ) . putIfAbsent ( permission . getRoleKey ( ) , new TreeSet <> ( ) ) ; map . get ( permission . getMsName ( ) ) . get ( permission . getRoleKey ( ) ) . add ( permission ) ; } ) ; return mapper . writeValueAsString ( map ) ; } catch ( Exception e ) { log . error ( "Failed to create permissions YML file from collection, error: {}" , e . getMessage ( ) , e ) ; } return null ; }
Convert permissions collection to yml string .
196
9
21,633
public Map < String , Permission > ymlToPermissions ( String yml , String msName ) { Map < String , Permission > result = new TreeMap <> ( ) ; try { Map < String , Map < String , Set < Permission > > > map = mapper . readValue ( yml , new TypeReference < TreeMap < String , TreeMap < String , TreeSet < Permission > > > > ( ) { } ) ; map . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isBlank ( msName ) || StringUtils . startsWithIgnoreCase ( entry . getKey ( ) , msName ) ) . filter ( entry -> entry . getValue ( ) != null ) . forEach ( entry -> entry . getValue ( ) . forEach ( ( roleKey , permissions ) -> permissions . forEach ( permission -> { permission . setMsName ( entry . getKey ( ) ) ; permission . setRoleKey ( roleKey ) ; result . put ( roleKey + ":" + permission . getPrivilegeKey ( ) , permission ) ; } ) ) ) ; } catch ( Exception e ) { log . error ( "Failed to create permissions collection from YML file, error: {}" , e . getMessage ( ) , e ) ; } return Collections . unmodifiableMap ( result ) ; }
Convert permissions yml string to map with role and privilege keys . Return map fo specific service or all .
292
22
21,634
public < T > List < T > findAll ( Class < T > entityClass , String privilegeKey ) { return findAll ( null , entityClass , privilegeKey ) . getContent ( ) ; }
Find all permitted entities .
42
5
21,635
public < T > Page < T > findAll ( Pageable pageable , Class < T > entityClass , String privilegeKey ) { String selectSql = format ( SELECT_ALL_SQL , entityClass . getSimpleName ( ) ) ; String countSql = format ( COUNT_ALL_SQL , entityClass . getSimpleName ( ) ) ; String permittedCondition = createPermissionCondition ( privilegeKey ) ; if ( StringUtils . isNotBlank ( permittedCondition ) ) { selectSql += WHERE_SQL + permittedCondition ; countSql += WHERE_SQL + permittedCondition ; } log . debug ( "Executing SQL '{}'" , selectSql ) ; return execute ( createCountQuery ( countSql ) , pageable , createSelectQuery ( selectSql , pageable , entityClass ) ) ; }
Find all pageable permitted entities .
177
7
21,636
public < T > Page < T > findByCondition ( String whereCondition , Map < String , Object > conditionParams , Collection < String > embed , Pageable pageable , Class < T > entityClass , String privilegeKey ) { String selectSql = format ( SELECT_ALL_SQL , entityClass . getSimpleName ( ) ) ; String countSql = format ( COUNT_ALL_SQL , entityClass . getSimpleName ( ) ) ; selectSql += WHERE_SQL + whereCondition ; countSql += WHERE_SQL + whereCondition ; String permittedCondition = createPermissionCondition ( privilegeKey ) ; if ( StringUtils . isNotBlank ( permittedCondition ) ) { selectSql += AND_SQL + "(" + permittedCondition + ")" ; countSql += AND_SQL + "(" + permittedCondition + ")" ; } TypedQuery < T > selectQuery = createSelectQuery ( selectSql , pageable , entityClass ) ; if ( ! CollectionUtils . isEmpty ( embed ) ) { selectQuery . setHint ( QueryHints . HINT_LOADGRAPH , createEnitityGraph ( embed , entityClass ) ) ; } TypedQuery < Long > countQuery = createCountQuery ( countSql ) ; conditionParams . forEach ( ( paramName , paramValue ) -> { selectQuery . setParameter ( paramName , paramValue ) ; countQuery . setParameter ( paramName , paramValue ) ; } ) ; log . debug ( "Executing SQL '{}' with params '{}'" , selectQuery , conditionParams ) ; return execute ( countQuery , pageable , selectQuery ) ; }
Find permitted entities by parameters with embed graph .
356
9
21,637
public CombinableConfig combine ( Config ... fallbackConfigs ) { CombinableConfig newConfig = this ; for ( Config fallback : fallbackConfigs ) { newConfig = new ConfigWithFallback ( newConfig , fallback ) ; } return newConfig ; }
combines this configuration with given ones . Given configuration doesn t override existing one .
58
16
21,638
@ PostConstruct public void init ( ) { log . debug ( "Registering JVM gauges" ) ; metricRegistry . register ( PROP_METRIC_REG_JVM_MEMORY , new MemoryUsageGaugeSet ( ) ) ; metricRegistry . register ( PROP_METRIC_REG_JVM_GARBAGE , new GarbageCollectorMetricSet ( ) ) ; metricRegistry . register ( PROP_METRIC_REG_JVM_THREADS , new ThreadStatesGaugeSet ( ) ) ; metricRegistry . register ( PROP_METRIC_REG_JVM_FILES , new FileDescriptorRatioGauge ( ) ) ; metricRegistry . register ( PROP_METRIC_REG_JVM_BUFFERS , new BufferPoolMetricSet ( getPlatformMBeanServer ( ) ) ) ; metricRegistry . register ( PROP_METRIC_REG_JVM_ATTRIBUTE_SET , new JvmAttributeGaugeSet ( ) ) ; metricRegistry . register ( PROP_METRIC_REG_OS , new OperatingSystemGaugeSet ( getOperatingSystemMXBean ( ) ) ) ; if ( jhipsterProperties . getMetrics ( ) . getJmx ( ) . isEnabled ( ) ) { log . debug ( "Initializing Metrics JMX reporting" ) ; JmxReporter jmxReporter = JmxReporter . forRegistry ( metricRegistry ) . build ( ) ; jmxReporter . start ( ) ; } if ( jhipsterProperties . getMetrics ( ) . getLogs ( ) . isEnabled ( ) ) { log . info ( "Initializing Metrics Log reporting" ) ; Marker metricsMarker = MarkerFactory . getMarker ( "metrics" ) ; final Slf4jReporter reporter = Slf4jReporter . forRegistry ( metricRegistry ) . outputTo ( LoggerFactory . getLogger ( "metrics" ) ) . markWith ( metricsMarker ) . convertRatesTo ( TimeUnit . SECONDS ) . convertDurationsTo ( TimeUnit . MILLISECONDS ) . build ( ) ; reporter . start ( jhipsterProperties . getMetrics ( ) . getLogs ( ) . getReportFrequency ( ) , TimeUnit . SECONDS ) ; } }
Init commons metrics
524
3
21,639
@ Override public SignatureVerifier getSignatureVerifier ( ) throws Exception { try { HttpEntity < Void > request = new HttpEntity <> ( new HttpHeaders ( ) ) ; String content = restTemplate . exchange ( getPublicKeyEndpoint ( ) , HttpMethod . GET , request , String . class ) . getBody ( ) ; if ( StringUtils . isEmpty ( content ) ) { log . info ( "Public key not fetched" ) ; return null ; } InputStream fin = new ByteArrayInputStream ( content . getBytes ( ) ) ; CertificateFactory f = CertificateFactory . getInstance ( "X.509" ) ; X509Certificate certificate = ( X509Certificate ) f . generateCertificate ( fin ) ; PublicKey pk = certificate . getPublicKey ( ) ; return new RsaVerifier ( String . format ( PUBLIC_KEY , new String ( Base64 . getEncoder ( ) . encode ( pk . getEncoded ( ) ) ) ) ) ; } catch ( IllegalStateException ex ) { log . warn ( "could not contact Config to get public key" ) ; return null ; } }
Fetches the public key from the MS Config .
248
11
21,640
private String getPublicKeyEndpoint ( ) { String tokenEndpointUrl = oauth2Properties . getSignatureVerification ( ) . getPublicKeyEndpointUri ( ) ; if ( tokenEndpointUrl == null ) { throw new InvalidClientException ( "no token endpoint configured in application properties" ) ; } return tokenEndpointUrl ; }
Returns the configured endpoint URI to retrieve the public key .
75
11
21,641
public String logicalCollectionTableName ( String tableName , String ownerEntityTable , String associatedEntityTable , String propertyName ) { if ( tableName == null ) { // use of a stringbuilder to workaround a JDK bug return new StringBuilder ( ownerEntityTable ) . append ( "_" ) . append ( associatedEntityTable == null ? unqualify ( propertyName ) : associatedEntityTable ) . toString ( ) ; } else { return tableName ; } }
Returns either the table name if explicit or if there is an associated table the concatenation of owner entity table and associated table otherwise the concatenation of owner entity table and the unqualified property name
97
40
21,642
protected final void addMessage ( String msgKey , Object ... args ) { getFlash ( ) . addMessageNow ( getTextInternal ( msgKey , args ) ) ; }
Add action message .
36
4
21,643
protected final void addError ( String msgKey , Object ... args ) { getFlash ( ) . addErrorNow ( getTextInternal ( msgKey , args ) ) ; }
Add action error .
36
4
21,644
protected final void addFlashError ( String msgKey , Object ... args ) { getFlash ( ) . addError ( getTextInternal ( msgKey , args ) ) ; }
Add error to next action .
36
6
21,645
protected final void addFlashMessage ( String msgKey , Object ... args ) { getFlash ( ) . addMessage ( getTextInternal ( msgKey , args ) ) ; }
Add message to next action .
36
6
21,646
private void addGetterAndSetter ( JDefinedClass traversingVisitor , JFieldVar field ) { String propName = Character . toUpperCase ( field . name ( ) . charAt ( 0 ) ) + field . name ( ) . substring ( 1 ) ; traversingVisitor . method ( JMod . PUBLIC , field . type ( ) , "get" + propName ) . body ( ) . _return ( field ) ; JMethod setVisitor = traversingVisitor . method ( JMod . PUBLIC , void . class , "set" + propName ) ; JVar visParam = setVisitor . param ( field . type ( ) , "aVisitor" ) ; setVisitor . body ( ) . assign ( field , visParam ) ; }
Convenience method to add a getter and setter method for the given field .
167
18
21,647
private String buildServletPath ( ) { String uri = servletPath ; if ( uri == null && null != requestURI ) { uri = requestURI ; if ( ! contextPath . equals ( "/" ) ) uri = uri . substring ( contextPath . length ( ) ) ; } return ( null == uri ) ? "" : uri ; }
Returns servetPath without contextPath
80
7
21,648
public String buildRequestUrl ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( buildServletPath ( ) ) ; if ( null != pathInfo ) { sb . append ( pathInfo ) ; } if ( null != queryString ) { sb . append ( ' ' ) . append ( queryString ) ; } return sb . toString ( ) ; }
Returns request Url contain pathinfo and queryString but without contextPath .
84
15
21,649
public String buildUrl ( ) { StringBuilder sb = new StringBuilder ( ) ; boolean includePort = true ; if ( null != scheme ) { sb . append ( scheme ) . append ( "://" ) ; includePort = ( port != ( scheme . equals ( "http" ) ? 80 : 443 ) ) ; } if ( null != serverName ) { sb . append ( serverName ) ; if ( includePort && port > 0 ) { sb . append ( ' ' ) . append ( port ) ; } } if ( ! Objects . equals ( contextPath , "/" ) ) { sb . append ( contextPath ) ; } sb . append ( buildRequestUrl ( ) ) ; return sb . toString ( ) ; }
Returns full url
159
3
21,650
public Map . Entry < K , V > getEntry ( Object key ) { EntryImpl < K , V > entry = _entries [ keyHash ( key ) & _mask ] ; while ( entry != null ) { if ( key . equals ( entry . _key ) ) { return entry ; } entry = entry . _next ; } return null ; }
Returns the entry with the specified key .
75
8
21,651
private void addEntry ( K key , V value ) { EntryImpl < K , V > entry = _poolFirst ; if ( entry != null ) { _poolFirst = entry . _after ; entry . _after = null ; } else { // Pool empty. entry = new EntryImpl < K , V > ( ) ; } // Setup entry paramters. entry . _key = key ; entry . _value = value ; int index = keyHash ( key ) & _mask ; entry . _index = index ; // Connects to bucket. EntryImpl < K , V > next = _entries [ index ] ; entry . _next = next ; if ( next != null ) { next . _previous = entry ; } _entries [ index ] = entry ; // Connects to collection. if ( _mapLast != null ) { entry . _before = _mapLast ; _mapLast . _after = entry ; } else { _mapFirst = entry ; } _mapLast = entry ; // Updates size. _size ++ ; sizeChanged ( ) ; }
Adds a new entry for the specified key and value .
225
11
21,652
private void removeEntry ( EntryImpl < K , V > entry ) { // Removes from bucket. EntryImpl < K , V > previous = entry . _previous ; EntryImpl < K , V > next = entry . _next ; if ( previous != null ) { previous . _next = next ; entry . _previous = null ; } else { // First in bucket. _entries [ entry . _index ] = next ; } if ( next != null ) { next . _previous = previous ; entry . _next = null ; } // Else do nothing, no last pointer. // Removes from collection. EntryImpl < K , V > before = entry . _before ; EntryImpl < K , V > after = entry . _after ; if ( before != null ) { before . _after = after ; entry . _before = null ; } else { // First in collection. _mapFirst = after ; } if ( after != null ) { after . _before = before ; } else { // Last in collection. _mapLast = before ; } // Clears value and key. entry . _key = null ; entry . _value = null ; // Recycles. entry . _after = _poolFirst ; _poolFirst = entry ; // Updates size. _size -- ; sizeChanged ( ) ; }
Removes the specified entry from the map .
279
9
21,653
@ SuppressWarnings ( "unchecked" ) private void readObject ( ObjectInputStream stream ) throws IOException , ClassNotFoundException { int capacity = stream . readInt ( ) ; initialize ( capacity ) ; int size = stream . readInt ( ) ; for ( int i = 0 ; i < size ; i ++ ) { addEntry ( ( K ) stream . readObject ( ) , ( V ) stream . readObject ( ) ) ; } }
Requires special handling during de - serialization process .
97
10
21,654
private void writeObject ( ObjectOutputStream stream ) throws IOException { stream . writeInt ( _capacity ) ; stream . writeInt ( _size ) ; int count = 0 ; EntryImpl < K , V > entry = _mapFirst ; while ( entry != null ) { stream . writeObject ( entry . _key ) ; stream . writeObject ( entry . _value ) ; count ++ ; entry = entry . _after ; } if ( count != _size ) { throw new IOException ( "FastMap Corrupted" ) ; } }
Requires special handling during serialization process .
113
8
21,655
static Set < JClass > discoverDirectClasses ( Outline outline , Set < ClassOutline > classes ) throws IllegalAccessException { Set < String > directClassNames = new LinkedHashSet <> ( ) ; for ( ClassOutline classOutline : classes ) { // for each field, if it's a bean, then visit it List < FieldOutline > fields = findAllDeclaredAndInheritedFields ( classOutline ) ; for ( FieldOutline fieldOutline : fields ) { JType rawType = fieldOutline . getRawType ( ) ; CPropertyInfo propertyInfo = fieldOutline . getPropertyInfo ( ) ; boolean isCollection = propertyInfo . isCollection ( ) ; if ( isCollection ) { JClass collClazz = ( JClass ) rawType ; JClass collType = collClazz . getTypeParameters ( ) . get ( 0 ) ; addIfDirectClass ( directClassNames , collType ) ; } else { addIfDirectClass ( directClassNames , rawType ) ; } parseXmlAnnotations ( outline , fieldOutline , directClassNames ) ; } } Set < JClass > direct = directClassNames . stream ( ) . map ( cn -> outline . getCodeModel ( ) . directClass ( cn ) ) . collect ( Collectors . toCollection ( LinkedHashSet :: new ) ) ; return direct ; }
Finds all external class references
296
6
21,656
private static void parseXmlAnnotations ( Outline outline , FieldOutline field , Set < String > directClasses ) throws IllegalAccessException { if ( field instanceof UntypedListField ) { JFieldVar jfv = ( JFieldVar ) FieldHack . listField . get ( field ) ; for ( JAnnotationUse jau : jfv . annotations ( ) ) { JClass jc = jau . getAnnotationClass ( ) ; if ( jc . fullName ( ) . equals ( XmlElements . class . getName ( ) ) ) { JAnnotationArrayMember value = ( JAnnotationArrayMember ) jau . getAnnotationMembers ( ) . get ( "value" ) ; for ( JAnnotationUse anno : value . annotations ( ) ) { handleXmlElement ( outline , directClasses , anno . getAnnotationMembers ( ) . get ( "type" ) ) ; } } } } }
Parse the annotations on the field to see if there is an XmlElements annotation on it . If so we ll check this annotation to see if it refers to any classes that are external from our code schema compile . If we find any then we ll add them to our visitor .
206
58
21,657
private static void handleXmlElement ( Outline outline , Set < String > directClasses , JAnnotationValue type ) { StringWriter sw = new StringWriter ( ) ; JFormatter jf = new JFormatter ( new PrintWriter ( sw ) ) ; type . generate ( jf ) ; String s = sw . toString ( ) ; s = s . substring ( 0 , s . length ( ) - ".class" . length ( ) ) ; if ( ! s . startsWith ( "java" ) && outline . getCodeModel ( ) . _getClass ( s ) == null && ! foundWithinOutline ( s , outline ) ) { directClasses . add ( s ) ; } }
Handles the extraction of the schema type from the XmlElement annotation . This was surprisingly difficult . Apparently the model doesn t provide access to the annotation we re referring to so I need to print it and read the string back . Even the formatter itself is final!
151
54
21,658
static JMethod getter ( FieldOutline fieldOutline ) { final JDefinedClass theClass = fieldOutline . parent ( ) . implClass ; final String publicName = fieldOutline . getPropertyInfo ( ) . getName ( true ) ; final JMethod getgetter = theClass . getMethod ( "get" + publicName , NONE ) ; if ( getgetter != null ) { return getgetter ; } else { final JMethod isgetter = theClass . getMethod ( "is" + publicName , NONE ) ; if ( isgetter != null ) { return isgetter ; } else { return null ; } } }
Borrowed this code from jaxb - commons project
142
12
21,659
static boolean isJAXBElement ( JType type ) { //noinspection RedundantIfStatement if ( type . fullName ( ) . startsWith ( JAXBElement . class . getName ( ) ) ) { return true ; } return false ; }
Returns true if the type is a JAXBElement . In the case of JAXBElements we want to traverse its underlying value as opposed to the JAXBElement .
56
36
21,660
static List < JClass > allConcreteClasses ( Set < ClassOutline > classes ) { return allConcreteClasses ( classes , Collections . emptySet ( ) ) ; }
Returns all of the concrete classes in the system
39
9
21,661
static List < JClass > allConcreteClasses ( Set < ClassOutline > classes , Set < JClass > directClasses ) { List < JClass > results = new ArrayList <> ( ) ; classes . stream ( ) . filter ( classOutline -> ! classOutline . target . isAbstract ( ) ) . forEach ( classOutline -> { JClass implClass = classOutline . implClass ; results . add ( implClass ) ; } ) ; results . addAll ( directClasses ) ; return results ; }
Returns all of the concrete classes plus the direct classes passed in
115
12
21,662
private Set < ClassOutline > sortClasses ( Outline outline ) { Set < ClassOutline > sorted = new TreeSet <> ( ( aOne , aTwo ) -> { String one = aOne . implClass . fullName ( ) ; String two = aTwo . implClass . fullName ( ) ; return one . compareTo ( two ) ; } ) ; sorted . addAll ( outline . getClasses ( ) ) ; return sorted ; }
The classes are sorted for test purposes only . This gives us a predictable order for our assertions on the generated code .
97
23
21,663
private < T extends Annotation > T findAnnotation ( Class < ? > cls , Class < T > annotationClass , String name ) { Class < ? > curr = cls ; T ann = null ; while ( ann == null && curr != null && ! curr . equals ( Object . class ) ) { ann = findAnnotationLocal ( curr , annotationClass , name ) ; curr = curr . getSuperclass ( ) ; } return ann ; }
find annotation on specified member
101
5
21,664
public Short getShort ( Map < String , Object > data , String name ) { return get ( data , name , Short . class ) ; }
Get Short .
30
3
21,665
protected Method findGetter ( Object data , String property ) throws IntrospectionException { Class < ? > clazz = getClass ( data ) ; String key = clazz . getName ( ) + ":" + property ; Method method = methods . get ( key ) ; if ( method == null ) { Method newMethod = null ; PropertyDescriptor [ ] props = Introspector . getBeanInfo ( clazz ) . getPropertyDescriptors ( ) ; for ( PropertyDescriptor prop : props ) { if ( prop . getName ( ) . equalsIgnoreCase ( property ) ) { newMethod = prop . getReadMethod ( ) ; } } method = methods . putIfAbsent ( key , newMethod ) ; if ( method == null ) { // put succeeded, use new value method = newMethod ; } } return method ; }
Cache the method if possible using the classname and property name to allow for similar named methods .
180
19
21,666
public final int getReadIndex ( String property ) { MethodInfo method = propertyReadMethods . get ( property ) ; return ( null == method ) ? - 1 : method . index ; }
Return property read index return - 1 when not found .
39
11
21,667
public final Class < ? > getPropertyType ( String property ) { MethodInfo info = propertyWriteMethods . get ( property ) ; if ( null == info ) return null ; else return info . parameterTypes [ 0 ] ; }
Return property type return null when not found .
47
9
21,668
public final int getWriteIndex ( String property ) { MethodInfo method = propertyWriteMethods . get ( property ) ; return ( null == method ) ? - 1 : method . index ; }
Return property write index return - 1 if not found .
39
11
21,669
public final int getIndex ( String name , Object ... args ) { Integer defaultIndex = methodIndexs . get ( name ) ; if ( null != defaultIndex ) return defaultIndex . intValue ( ) ; else { final List < MethodInfo > exists = methods . get ( name ) ; if ( null != exists ) { for ( MethodInfo info : exists ) if ( info . matches ( args ) ) return info . index ; } return - 1 ; } }
Return method index return - 1 if not found .
96
10
21,670
public final List < MethodInfo > getMethods ( String name ) { List < MethodInfo > namedMethod = methods . get ( name ) ; if ( null == namedMethod ) return Collections . emptyList ( ) ; else return namedMethod ; }
Return public metheds according to given name
50
9
21,671
public final List < MethodInfo > getMethods ( ) { List < MethodInfo > methodInfos = CollectUtils . newArrayList ( ) ; for ( Map . Entry < String , List < MethodInfo > > entry : methods . entrySet ( ) ) { for ( MethodInfo info : entry . getValue ( ) ) methodInfos . ( info ) ; } Collections . sort ( methodInfos ) ; return methodInfos ; }
Return all public methods .
92
5
21,672
public static < T > List < T > getAll ( Collection < Option < T > > values ) { List < T > results = CollectUtils . newArrayList ( values . size ( ) ) ; for ( Option < T > op : values ) { if ( op . isDefined ( ) ) results . add ( op . get ( ) ) ; } return results ; }
Return all value from Option Collection
80
6
21,673
public static List < Method > getBeanSetters ( Class < ? > clazz ) { List < Method > methods = CollectUtils . newArrayList ( ) ; for ( Method m : clazz . getMethods ( ) ) { if ( m . getName ( ) . startsWith ( "set" ) && m . getName ( ) . length ( ) > 3 ) { if ( Modifier . isPublic ( m . getModifiers ( ) ) && ! Modifier . isStatic ( m . getModifiers ( ) ) && m . getParameterTypes ( ) . length == 1 ) { methods . add ( m ) ; } } } return methods ; }
Return list of setters
141
5
21,674
protected List < ResultConfig > buildResultConfigs ( Class < ? > clazz , PackageConfig . Builder pcb ) { List < ResultConfig > configs = CollectUtils . newArrayList ( ) ; // load annotation results Result [ ] results = new Result [ 0 ] ; Results rs = clazz . getAnnotation ( Results . class ) ; if ( null == rs ) { org . beangle . struts2 . annotation . Action an = clazz . getAnnotation ( org . beangle . struts2 . annotation . Action . class ) ; if ( null != an ) results = an . results ( ) ; } else { results = rs . value ( ) ; } Set < String > annotationResults = CollectUtils . newHashSet ( ) ; if ( null != results ) { for ( Result result : results ) { String resultType = result . type ( ) ; if ( Strings . isEmpty ( resultType ) ) resultType = "dispatcher" ; ResultTypeConfig rtc = pcb . getResultType ( resultType ) ; ResultConfig . Builder rcb = new ResultConfig . Builder ( result . name ( ) , rtc . getClassName ( ) ) ; if ( null != rtc . getDefaultResultParam ( ) ) rcb . addParam ( rtc . getDefaultResultParam ( ) , result . location ( ) ) ; configs . add ( rcb . build ( ) ) ; annotationResults . add ( result . name ( ) ) ; } } // load ftl convension results if ( ! preloadftl || null == profileService ) return configs ; String extention = profileService . getProfile ( clazz . getName ( ) ) . getViewExtension ( ) ; if ( ! extention . equals ( "ftl" ) ) return configs ; ResultTypeConfig rtc = pcb . getResultType ( "freemarker" ) ; for ( Method m : clazz . getMethods ( ) ) { String methodName = m . getName ( ) ; if ( ! annotationResults . contains ( methodName ) && shouldGenerateResult ( m ) ) { String path = templateFinder . find ( clazz , methodName , methodName , extention ) ; if ( null != path ) { configs . add ( new ResultConfig . Builder ( m . getName ( ) , rtc . getClassName ( ) ) . addParam ( rtc . getDefaultResultParam ( ) , path ) . build ( ) ) ; } } } return configs ; }
generator default results by method name
538
7
21,675
public Stopwatch start ( ) { Assert . isTrue ( ! isRunning ) ; isRunning = true ; startTick = ticker . read ( ) ; return this ; }
Starts the stopwatch .
38
6
21,676
protected void populateValue ( Object entity , EntityType type , String attr , Object value ) { // 当有深层次属性 if ( Strings . contains ( attr , ' ' ) ) { if ( null != foreignerKeys ) { boolean isForeigner = isForeigner ( attr ) ; // 如果是个外键,先根据parentPath生成新的外键实体。 // 因此导入的是外键,只能有一个属性导入. if ( isForeigner ) { String parentPath = Strings . substringBeforeLast ( attr , "." ) ; ObjectAndType propertyType = populator . initProperty ( entity , type , parentPath ) ; Object property = propertyType . getObj ( ) ; if ( property instanceof Entity < ? > ) { if ( ( ( Entity < ? > ) property ) . isPersisted ( ) ) { populator . populateValue ( entity , type , parentPath , null ) ; populator . initProperty ( entity , type , parentPath ) ; } } } } } if ( ! populator . populateValue ( entity , type , attr , value ) ) { transferResult . addFailure ( descriptions . get ( attr ) + " data format error." , value ) ; } }
Populate single attribute
321
4
21,677
@ SuppressWarnings ( "rawtypes" ) protected ModelFactory getModelFactory ( Class clazz ) { if ( altMapWrapper && Map . class . isAssignableFrom ( clazz ) ) { return FriendlyMapModel . FACTORY ; } return super . getModelFactory ( clazz ) ; }
of FM .
68
3
21,678
protected final Pair < ? , ? > entry ( Object key , Object value ) { return Pair . of ( key , value ) ; }
Return new map entry
28
4
21,679
protected final Definition bean ( Class < ? > clazz ) { Definition def = new Definition ( clazz . getName ( ) , clazz , Scope . SINGLETON . toString ( ) ) ; def . beanName = clazz . getName ( ) + "#" + Math . abs ( System . identityHashCode ( def ) ) ; return def ; }
Generate a inner bean definition
77
6
21,680
protected Option < TextBundle > loadJavaBundle ( String bundleName , Locale locale ) { Properties properties = new Properties ( ) ; String resource = toJavaResourceName ( bundleName , locale ) ; try { InputStream is = ClassLoaders . getResourceAsStream ( resource , getClass ( ) ) ; if ( null == is ) return Option . none ( ) ; properties . load ( is ) ; is . close ( ) ; } catch ( IOException e ) { return Option . none ( ) ; } finally { } return Option . < TextBundle > from ( new DefaultTextBundle ( locale , resource , properties ) ) ; }
Load java properties bundle with iso - 8859 - 1
136
11
21,681
protected final String toJavaResourceName ( String bundleName , Locale locale ) { String fullName = bundleName ; final String localeName = toLocaleStr ( locale ) ; final String suffix = "properties" ; if ( ! "" . equals ( localeName ) ) fullName = fullName + "_" + localeName ; StringBuilder sb = new StringBuilder ( fullName . length ( ) + 1 + suffix . length ( ) ) ; sb . append ( fullName . replace ( ' ' , ' ' ) ) . append ( ' ' ) . append ( suffix ) ; return sb . toString ( ) ; }
java properties bundle name
132
4
21,682
private String getComponentName ( ) { Class < ? > c = getClass ( ) ; String name = c . getName ( ) ; int dot = name . lastIndexOf ( ' ' ) ; return name . substring ( dot + 1 ) . toLowerCase ( ) ; }
Gets the name of this component .
60
8
21,683
protected Stack < Component > getComponentStack ( ) { @ SuppressWarnings ( "unchecked" ) Stack < Component > componentStack = ( Stack < Component > ) stack . getContext ( ) . get ( COMPONENT_STACK ) ; if ( componentStack == null ) { componentStack = new Stack < Component > ( ) ; stack . getContext ( ) . put ( COMPONENT_STACK , componentStack ) ; } return componentStack ; }
Gets the component stack of this component .
98
9
21,684
@ SuppressWarnings ( "unchecked" ) protected < T extends Component > T findAncestor ( Class < T > clazz ) { Stack < ? extends Component > componentStack = getComponentStack ( ) ; for ( int i = componentStack . size ( ) - 2 ; i >= 0 ; i -- ) { Component component = componentStack . get ( i ) ; if ( clazz . equals ( component . getClass ( ) ) ) return ( T ) component ; } return null ; }
Finds the nearest ancestor of this component stack .
106
10
21,685
public static List < String > readLines ( File file , Charset charset ) throws IOException { InputStream in = null ; try { in = new FileInputStream ( file ) ; if ( null == charset ) { return IOs . readLines ( new InputStreamReader ( in ) ) ; } else { InputStreamReader reader = new InputStreamReader ( in , charset . name ( ) ) ; return IOs . readLines ( reader ) ; } } finally { IOs . close ( in ) ; } }
Reads the contents of a file line by line to a List of Strings . The file is always closed .
114
23
21,686
public String getParamstring ( ) { StringWriter sw = new StringWriter ( ) ; Enumeration < ? > em = req . getParameterNames ( ) ; while ( em . hasMoreElements ( ) ) { String attr = ( String ) em . nextElement ( ) ; if ( attr . equals ( "method" ) ) continue ; String value = req . getParameter ( attr ) ; if ( attr . equals ( "x-requested-with" ) ) continue ; sw . write ( attr ) ; sw . write ( ' ' ) ; sw . write ( StringUtil . javaScriptStringEnc ( value ) ) ; if ( em . hasMoreElements ( ) ) sw . write ( ' ' ) ; } return sw . toString ( ) ; }
query string and form control
167
5
21,687
protected void error ( String message , Element source , Throwable cause ) { logger . error ( message ) ; }
Report an error with the given message for the given source element .
23
13
21,688
protected void checkNameUniqueness ( String beanName , List < String > aliases , Element beanElement ) { String foundName = null ; if ( StringUtils . hasText ( beanName ) && this . usedNames . contains ( beanName ) ) foundName = beanName ; if ( foundName == null ) foundName = ( String ) CollectionUtils . findFirstMatch ( this . usedNames , aliases ) ; if ( foundName != null ) error ( "Bean name '" + foundName + "' is already used in this file" , beanElement ) ; this . usedNames . add ( beanName ) ; this . usedNames . addAll ( aliases ) ; }
Validate that the specified bean name and aliases have not been used already .
142
15
21,689
protected AbstractBeanDefinition createBeanDefinition ( String className , String parentName ) throws ClassNotFoundException { return BeanDefinitionReaderUtils . createBeanDefinition ( parentName , className , null ) ; }
Create a bean definition for the given class name and parent name .
46
13
21,690
public void parseConstructorArgElements ( Element beanEle , BeanDefinition bd ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , CONSTRUCTOR_ARG_ELEMENT ) ) parseConstructorArgElement ( ( Element ) node , bd ) ; } }
Parse constructor - arg sub - elements of the given bean element .
109
14
21,691
public void parsePropertyElements ( Element beanEle , BeanDefinition bd ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , PROPERTY_ELEMENT ) ) parsePropertyElement ( ( Element ) node , bd ) ; } }
Parse property sub - elements of the given bean element .
102
12
21,692
public void parseQualifierElements ( Element beanEle , AbstractBeanDefinition bd ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , QUALIFIER_ELEMENT ) ) parseQualifierElement ( ( Element ) node , bd ) ; } }
Parse qualifier sub - elements of the given bean element .
107
12
21,693
public void parseLookupOverrideSubElements ( Element beanEle , MethodOverrides overrides ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , LOOKUP_METHOD_ELEMENT ) ) { Element ele = ( Element ) node ; String methodName = ele . getAttribute ( NAME_ATTRIBUTE ) ; String beanRef = ele . getAttribute ( BEAN_ELEMENT ) ; LookupOverride override = new LookupOverride ( methodName , beanRef ) ; override . setSource ( extractSource ( ele ) ) ; overrides . addOverride ( override ) ; } } }
Parse lookup - override sub - elements of the given bean element .
177
14
21,694
public void parseReplacedMethodSubElements ( Element beanEle , MethodOverrides overrides ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , REPLACED_METHOD_ELEMENT ) ) { Element replacedMethodEle = ( Element ) node ; String name = replacedMethodEle . getAttribute ( NAME_ATTRIBUTE ) ; String callback = replacedMethodEle . getAttribute ( REPLACER_ATTRIBUTE ) ; ReplaceOverride replaceOverride = new ReplaceOverride ( name , callback ) ; // Look for arg-type match elements. List < Element > argTypeEles = DomUtils . getChildElementsByTagName ( replacedMethodEle , ARG_TYPE_ELEMENT ) ; for ( Element argTypeEle : argTypeEles ) { replaceOverride . addTypeIdentifier ( argTypeEle . getAttribute ( ARG_TYPE_MATCH_ATTRIBUTE ) ) ; } replaceOverride . setSource ( extractSource ( replacedMethodEle ) ) ; overrides . addOverride ( replaceOverride ) ; } } }
Parse replaced - method sub - elements of the given bean element .
273
14
21,695
public void parseConstructorArgElement ( Element ele , BeanDefinition bd ) { String indexAttr = ele . getAttribute ( INDEX_ATTRIBUTE ) ; String typeAttr = ele . getAttribute ( TYPE_ATTRIBUTE ) ; String nameAttr = ele . getAttribute ( NAME_ATTRIBUTE ) ; if ( StringUtils . hasLength ( indexAttr ) ) { try { int index = Integer . parseInt ( indexAttr ) ; if ( index < 0 ) { error ( "'index' cannot be lower than 0" , ele ) ; } else { try { this . parseState . push ( new ConstructorArgumentEntry ( index ) ) ; Object value = parsePropertyValue ( ele , bd , null ) ; ConstructorArgumentValues . ValueHolder valueHolder = new ConstructorArgumentValues . ValueHolder ( value ) ; if ( StringUtils . hasLength ( typeAttr ) ) valueHolder . setType ( typeAttr ) ; if ( StringUtils . hasLength ( nameAttr ) ) valueHolder . setName ( nameAttr ) ; valueHolder . setSource ( extractSource ( ele ) ) ; if ( bd . getConstructorArgumentValues ( ) . hasIndexedArgumentValue ( index ) ) { error ( "Ambiguous constructor-arg entries for index " + index , ele ) ; } else { bd . getConstructorArgumentValues ( ) . addIndexedArgumentValue ( index , valueHolder ) ; } } finally { this . parseState . pop ( ) ; } } } catch ( NumberFormatException ex ) { error ( "Attribute 'index' of tag 'constructor-arg' must be an integer" , ele ) ; } } else { try { this . parseState . push ( new ConstructorArgumentEntry ( ) ) ; Object value = parsePropertyValue ( ele , bd , null ) ; ConstructorArgumentValues . ValueHolder valueHolder = new ConstructorArgumentValues . ValueHolder ( value ) ; if ( StringUtils . hasLength ( typeAttr ) ) valueHolder . setType ( typeAttr ) ; if ( StringUtils . hasLength ( nameAttr ) ) valueHolder . setName ( nameAttr ) ; valueHolder . setSource ( extractSource ( ele ) ) ; bd . getConstructorArgumentValues ( ) . addGenericArgumentValue ( valueHolder ) ; } finally { this . parseState . pop ( ) ; } } }
Parse a constructor - arg element .
544
8
21,696
public void parsePropertyElement ( Element ele , BeanDefinition bd ) { String propertyName = ele . getAttribute ( NAME_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( propertyName ) ) { error ( "Tag 'property' must have a 'name' attribute" , ele ) ; return ; } this . parseState . push ( new PropertyEntry ( propertyName ) ) ; try { if ( bd . getPropertyValues ( ) . contains ( propertyName ) ) { error ( "Multiple 'property' definitions for property '" + propertyName + "'" , ele ) ; return ; } Object val = parsePropertyValue ( ele , bd , propertyName ) ; PropertyValue pv = new PropertyValue ( propertyName , val ) ; parseMetaElements ( ele , pv ) ; pv . setSource ( extractSource ( ele ) ) ; bd . getPropertyValues ( ) . addPropertyValue ( pv ) ; } finally { this . parseState . pop ( ) ; } }
Parse a property element .
216
6
21,697
public void parseQualifierElement ( Element ele , AbstractBeanDefinition bd ) { String typeName = ele . getAttribute ( TYPE_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( typeName ) ) { error ( "Tag 'qualifier' must have a 'type' attribute" , ele ) ; return ; } this . parseState . push ( new QualifierEntry ( typeName ) ) ; try { AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier ( typeName ) ; qualifier . setSource ( extractSource ( ele ) ) ; String value = ele . getAttribute ( VALUE_ATTRIBUTE ) ; if ( StringUtils . hasLength ( value ) ) { qualifier . setAttribute ( AutowireCandidateQualifier . VALUE_KEY , value ) ; } NodeList nl = ele . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , QUALIFIER_ATTRIBUTE_ELEMENT ) ) { Element attributeEle = ( Element ) node ; String attributeName = attributeEle . getAttribute ( KEY_ATTRIBUTE ) ; String attributeValue = attributeEle . getAttribute ( VALUE_ATTRIBUTE ) ; if ( StringUtils . hasLength ( attributeName ) && StringUtils . hasLength ( attributeValue ) ) { BeanMetadataAttribute attribute = new BeanMetadataAttribute ( attributeName , attributeValue ) ; attribute . setSource ( extractSource ( attributeEle ) ) ; qualifier . addMetadataAttribute ( attribute ) ; } else { error ( "Qualifier 'attribute' tag must have a 'name' and 'value'" , attributeEle ) ; return ; } } } bd . addQualifier ( qualifier ) ; } finally { this . parseState . pop ( ) ; } }
Parse a qualifier element .
423
6
21,698
public Object parsePropertyValue ( Element ele , BeanDefinition bd , String propertyName ) { String elementName = ( propertyName != null ) ? "<property> element for property '" + propertyName + "'" : "<constructor-arg> element" ; // Should only have one child element: ref, value, list, etc. NodeList nl = ele . getChildNodes ( ) ; Element subElement = null ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && ! nodeNameEquals ( node , DESCRIPTION_ELEMENT ) && ! nodeNameEquals ( node , META_ELEMENT ) ) { // Child element is what we're looking for. if ( subElement != null ) error ( elementName + " must not contain more than one sub-element" , ele ) ; else subElement = ( Element ) node ; } } boolean hasRefAttribute = ele . hasAttribute ( REF_ATTRIBUTE ) ; boolean hasValueAttribute = ele . hasAttribute ( VALUE_ATTRIBUTE ) ; if ( ( hasRefAttribute && hasValueAttribute ) || ( ( hasRefAttribute || hasValueAttribute ) && subElement != null ) ) { error ( elementName + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element" , ele ) ; } if ( hasRefAttribute ) { String refName = ele . getAttribute ( REF_ATTRIBUTE ) ; if ( ! StringUtils . hasText ( refName ) ) error ( elementName + " contains empty 'ref' attribute" , ele ) ; RuntimeBeanReference ref = new RuntimeBeanReference ( refName ) ; ref . setSource ( extractSource ( ele ) ) ; return ref ; } else if ( hasValueAttribute ) { TypedStringValue valueHolder = new TypedStringValue ( ele . getAttribute ( VALUE_ATTRIBUTE ) ) ; valueHolder . setSource ( extractSource ( ele ) ) ; return valueHolder ; } else if ( subElement != null ) { return parsePropertySubElement ( subElement , bd ) ; } else { // Neither child element nor "ref" or "value" attribute found. error ( elementName + " must specify a ref or value" , ele ) ; return null ; } }
Get the value of a property element . May be a list etc . Also used for constructor arguments propertyName being null in this case .
516
27
21,699
public Object parsePropertySubElement ( Element ele , BeanDefinition bd , String defaultValueType ) { if ( ! isDefaultNamespace ( getNamespaceURI ( ele ) ) ) { error ( "Cannot support nested element ." , ele ) ; return null ; } else if ( nodeNameEquals ( ele , BEAN_ELEMENT ) ) { BeanDefinitionHolder nestedBd = parseBeanDefinitionElement ( ele , bd ) ; if ( nestedBd != null ) nestedBd = decorateBeanDefinitionIfRequired ( ele , nestedBd , bd ) ; return nestedBd ; } else if ( nodeNameEquals ( ele , REF_ELEMENT ) ) { // A generic reference to any name of any bean. String refName = ele . getAttribute ( BEAN_REF_ATTRIBUTE ) ; boolean toParent = false ; if ( ! StringUtils . hasLength ( refName ) ) { // A reference to the id of another bean in the same XML file. refName = ele . getAttribute ( LOCAL_REF_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( refName ) ) { // A reference to the id of another bean in a parent context. refName = ele . getAttribute ( PARENT_REF_ATTRIBUTE ) ; toParent = true ; if ( ! StringUtils . hasLength ( refName ) ) { error ( "'bean', 'local' or 'parent' is required for <ref> element" , ele ) ; return null ; } } } if ( ! StringUtils . hasText ( refName ) ) { error ( "<ref> element contains empty target attribute" , ele ) ; return null ; } RuntimeBeanReference ref = new RuntimeBeanReference ( refName , toParent ) ; ref . setSource ( extractSource ( ele ) ) ; return ref ; } else if ( nodeNameEquals ( ele , IDREF_ELEMENT ) ) { return parseIdRefElement ( ele ) ; } else if ( nodeNameEquals ( ele , VALUE_ELEMENT ) ) { return parseValueElement ( ele , defaultValueType ) ; } else if ( nodeNameEquals ( ele , NULL_ELEMENT ) ) { // It's a distinguished null value. Let's wrap it in a // TypedStringValue // object in order to preserve the source location. TypedStringValue nullHolder = new TypedStringValue ( null ) ; nullHolder . setSource ( extractSource ( ele ) ) ; return nullHolder ; } else if ( nodeNameEquals ( ele , ARRAY_ELEMENT ) ) { return parseArrayElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , LIST_ELEMENT ) ) { return parseListElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , SET_ELEMENT ) ) { return parseSetElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , MAP_ELEMENT ) ) { return parseMapElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , PROPS_ELEMENT ) ) { return parsePropsElement ( ele ) ; } else { error ( "Unknown property sub-element: [" + ele . getNodeName ( ) + "]" , ele ) ; return null ; } }
Parse a value ref or collection sub - element of a property or constructor - arg element .
730
19