idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,600 | public long [ ] readLongArray ( final int items , final JBBPByteOrder byteOrder ) throws IOException { int pos = 0 ; if ( items < 0 ) { long [ ] buffer = new long [ INITIAL_ARRAY_BUFFER_SIZE ] ; while ( hasAvailableData ( ) ) { final long next = readLong ( byteOrder ) ; if ( buffer . length == pos ) { final long [ ] newbuffer = new long [ buffer . length << 1 ] ; System . arraycopy ( buffer , 0 , newbuffer , 0 , buffer . length ) ; buffer = newbuffer ; } buffer [ pos ++ ] = next ; } if ( buffer . length == pos ) { return buffer ; } final long [ ] result = new long [ pos ] ; System . arraycopy ( buffer , 0 , result , 0 , pos ) ; return result ; } else { final long [ ] buffer = new long [ items ] ; for ( int i = 0 ; i < items ; i ++ ) { buffer [ i ] = readLong ( byteOrder ) ; } return buffer ; } } | Read number of long items from the input stream . |
21,601 | public double [ ] readDoubleArray ( final int items , final JBBPByteOrder byteOrder ) throws IOException { int pos = 0 ; if ( items < 0 ) { double [ ] buffer = new double [ INITIAL_ARRAY_BUFFER_SIZE ] ; while ( hasAvailableData ( ) ) { final long next = readLong ( byteOrder ) ; if ( buffer . length == pos ) { final double [ ] newbuffer = new double [ buffer . length << 1 ] ; System . arraycopy ( buffer , 0 , newbuffer , 0 , buffer . length ) ; buffer = newbuffer ; } buffer [ pos ++ ] = Double . longBitsToDouble ( next ) ; } if ( buffer . length == pos ) { return buffer ; } final double [ ] result = new double [ pos ] ; System . arraycopy ( buffer , 0 , result , 0 , pos ) ; return result ; } else { final double [ ] buffer = new double [ items ] ; for ( int i = 0 ; i < items ; i ++ ) { buffer [ i ] = readDouble ( byteOrder ) ; } return buffer ; } } | Read number of double items from the input stream . |
21,602 | public int readUnsignedShort ( final JBBPByteOrder byteOrder ) throws IOException { final int b0 = this . read ( ) ; if ( b0 < 0 ) { throw new EOFException ( ) ; } final int b1 = this . read ( ) ; if ( b1 < 0 ) { throw new EOFException ( ) ; } return byteOrder == JBBPByteOrder . BIG_ENDIAN ? ( b0 << 8 ) | b1 : ( b1 << 8 ) | b0 ; } | Read a unsigned short value from the stream . |
21,603 | public int readInt ( final JBBPByteOrder byteOrder ) throws IOException { if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { return ( readUnsignedShort ( byteOrder ) << 16 ) | readUnsignedShort ( byteOrder ) ; } else { return readUnsignedShort ( byteOrder ) | ( readUnsignedShort ( byteOrder ) << 16 ) ; } } | Read an integer value from the stream . |
21,604 | public float readFloat ( final JBBPByteOrder byteOrder ) throws IOException { final int value ; if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { value = ( readUnsignedShort ( byteOrder ) << 16 ) | readUnsignedShort ( byteOrder ) ; } else { value = readUnsignedShort ( byteOrder ) | ( readUnsignedShort ( byteOrder ) << 16 ) ; } return Float . intBitsToFloat ( value ) ; } | Read a float value from the stream . |
21,605 | public long readLong ( final JBBPByteOrder byteOrder ) throws IOException { if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { return ( ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) << 32 ) | ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) ; } else { return ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) | ( ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) << 32 ) ; } } | Read a long value from the stream . |
21,606 | public double readDouble ( final JBBPByteOrder byteOrder ) throws IOException { final long value ; if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { value = ( ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) << 32 ) | ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) ; } else { value = ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) | ( ( ( long ) readInt ( byteOrder ) & 0xFFFFFFFFL ) << 32 ) ; } return Double . longBitsToDouble ( value ) ; } | Read a double value from the stream . |
21,607 | public byte readBitField ( final JBBPBitNumber numOfBitsToRead ) throws IOException { final int value = this . readBits ( numOfBitsToRead ) ; if ( value < 0 ) { throw new EOFException ( "Can't read bits from stream [" + numOfBitsToRead + ']' ) ; } return ( byte ) value ; } | Read bit field from the stream if it is impossible then IOException will be thrown . |
21,608 | public int readBits ( final JBBPBitNumber numOfBitsToRead ) throws IOException { int result ; final int numOfBitsAsNumber = numOfBitsToRead . getBitNumber ( ) ; if ( this . bitsInBuffer == 0 && numOfBitsAsNumber == 8 ) { result = this . readByteFromStream ( ) ; if ( result >= 0 ) { this . byteCounter ++ ; } return result ; } else { result = 0 ; if ( numOfBitsAsNumber == this . bitsInBuffer ) { result = this . bitBuffer ; this . bitBuffer = 0 ; this . bitsInBuffer = 0 ; this . byteCounter ++ ; return result ; } int i = numOfBitsAsNumber ; int theBitBuffer = this . bitBuffer ; int theBitBufferCounter = this . bitsInBuffer ; final boolean doIncCounter = theBitBufferCounter != 0 ; while ( i > 0 ) { if ( theBitBufferCounter == 0 ) { if ( doIncCounter ) { this . byteCounter ++ ; } final int nextByte = this . readByteFromStream ( ) ; if ( nextByte < 0 ) { if ( i == numOfBitsAsNumber ) { return nextByte ; } else { break ; } } else { theBitBuffer = nextByte ; theBitBufferCounter = 8 ; } } result = ( result << 1 ) | ( theBitBuffer & 1 ) ; theBitBuffer >>= 1 ; theBitBufferCounter -- ; i -- ; } this . bitBuffer = theBitBuffer ; this . bitsInBuffer = theBitBufferCounter ; return JBBPUtils . reverseBitsInByte ( JBBPBitNumber . decode ( numOfBitsAsNumber - i ) , ( byte ) result ) & 0xFF ; } } | Read number of bits from the input stream . It reads bits from input stream since 0 bit and make reversion to return bits in the right order when 0 bit is 0 bit . if the stream is completed early than the data read then reading is just stopped and read value returned . The First read bit is placed as 0th bit . |
21,609 | public void align ( final long alignByteNumber ) throws IOException { this . alignByte ( ) ; if ( alignByteNumber > 0 ) { long padding = ( alignByteNumber - ( this . byteCounter % alignByteNumber ) ) % alignByteNumber ; while ( padding > 0 ) { final int skippedByte = this . read ( ) ; if ( skippedByte < 0 ) { throw new EOFException ( "Can't align for " + alignByteNumber + " byte(s)" ) ; } padding -- ; } } } | Read padding bytes from the stream and ignore them to align the stream counter . |
21,610 | private int readByteFromStream ( ) throws IOException { int result = this . in . read ( ) ; if ( result >= 0 && this . msb0 ) { result = JBBPUtils . reverseBitsInByte ( ( byte ) result ) & 0xFF ; } return result ; } | Inside method to read a byte from stream . |
21,611 | private int loadNextByteInBuffer ( ) throws IOException { final int value = this . readByteFromStream ( ) ; if ( value < 0 ) { return value ; } this . bitBuffer = value ; this . bitsInBuffer = 8 ; return value ; } | Read the next stream byte into bit buffer . |
21,612 | public String readString ( final JBBPByteOrder byteOrder ) throws IOException { final int prefix = this . readByte ( ) ; final int len ; if ( prefix == 0 ) { len = 0 ; } else if ( prefix == 0xFF ) { len = - 1 ; } else if ( prefix < 0x80 ) { len = prefix ; } else if ( ( prefix & 0xF0 ) == 0x80 ) { switch ( prefix & 0x0F ) { case 1 : { len = this . readByte ( ) ; } break ; case 2 : { len = this . readUnsignedShort ( byteOrder ) ; } break ; case 3 : { int buffer ; if ( byteOrder == JBBPByteOrder . BIG_ENDIAN ) { buffer = ( this . readByte ( ) << 16 ) | ( this . readByte ( ) << 8 ) | this . readByte ( ) ; } else { buffer = this . readByte ( ) | ( this . readByte ( ) << 8 ) | ( this . readByte ( ) << 16 ) ; } len = buffer ; } break ; case 4 : { len = this . readInt ( byteOrder ) ; } break ; default : { throw makeIOExceptionForWrongPrefix ( prefix ) ; } } } else { throw makeIOExceptionForWrongPrefix ( prefix ) ; } final String result ; if ( len < 0 ) { result = null ; } else if ( len == 0 ) { result = "" ; } else { result = JBBPUtils . utf8ToStr ( this . readByteArray ( len ) ) ; } return result ; } | Read string in UTF8 format . |
21,613 | public String [ ] readStringArray ( final int items , final JBBPByteOrder byteOrder ) throws IOException { int pos = 0 ; if ( items < 0 ) { String [ ] buffer = new String [ INITIAL_ARRAY_BUFFER_SIZE ] ; while ( hasAvailableData ( ) ) { final String next = readString ( byteOrder ) ; if ( buffer . length == pos ) { final String [ ] newbuffer = new String [ buffer . length << 1 ] ; System . arraycopy ( buffer , 0 , newbuffer , 0 , buffer . length ) ; buffer = newbuffer ; } buffer [ pos ++ ] = next ; } if ( buffer . length == pos ) { return buffer ; } final String [ ] result = new String [ pos ] ; System . arraycopy ( buffer , 0 , result , 0 , pos ) ; return result ; } else { final String [ ] buffer = new String [ items ] ; for ( int i = 0 ; i < items ; i ++ ) { buffer [ i ] = readString ( byteOrder ) ; } return buffer ; } } | Read array of srings from stream . |
21,614 | public JBBPNamedFieldInfo findFieldForPath ( final String fieldPath ) { JBBPNamedFieldInfo result = null ; for ( final JBBPNamedFieldInfo f : this . namedFieldData ) { if ( f . getFieldPath ( ) . equals ( fieldPath ) ) { result = f ; break ; } } return result ; } | Find a field for its path . |
21,615 | public int findFieldOffsetForPath ( final String fieldPath ) { for ( final JBBPNamedFieldInfo f : this . namedFieldData ) { if ( f . getFieldPath ( ) . equals ( fieldPath ) ) { return f . getFieldOffsetInCompiledBlock ( ) ; } } throw new JBBPIllegalArgumentException ( "Unknown field path [" + fieldPath + ']' ) ; } | Find offset of a field in the compiled block for its field path . |
21,616 | public void sendEvent ( String eventId , String ymlPrivileges ) { SystemEvent event = buildSystemEvent ( eventId , ymlPrivileges ) ; serializeEvent ( event ) . ifPresent ( this :: send ) ; } | Build message for kafka s event and send it . |
21,617 | public void sendEvent ( String eventId , Set < Privilege > privileges ) { String ymlPrivileges = PrivilegeMapper . privilegesToYml ( privileges ) ; SystemEvent event = buildSystemEvent ( eventId , ymlPrivileges ) ; serializeEvent ( event ) . ifPresent ( this :: send ) ; } | Build MS_PRIVILEGES message for system queue event and send it . |
21,618 | private void send ( String content ) { if ( ! StringUtils . isBlank ( content ) ) { log . info ( "Sending system queue event to kafka-topic = '{}', data = '{}'" , topicName , content ) ; template . send ( topicName , content ) ; } } | Send event to system queue . |
21,619 | public static void createSchema ( DataSource dataSource , String name ) { try ( Connection connection = dataSource . getConnection ( ) ; Statement statement = connection . createStatement ( ) ) { statement . executeUpdate ( String . format ( Constants . DDL_CREATE_SCHEMA , name ) ) ; } catch ( SQLException e ) { throw new RuntimeException ( "Can not connect to database" , e ) ; } } | Creates new database scheme . |
21,620 | @ SuppressWarnings ( "unchecked" ) public Map < String , Object > getDataMap ( ) { if ( data instanceof Map ) { return ( Map < String , Object > ) data ; } return Collections . emptyMap ( ) ; } | Get data as Map . |
21,621 | public String getMessage ( String code , Map < String , String > substitutes , boolean firstFindInMessageBundle , String defaultMessage ) { Locale locale = authContextHolder . getContext ( ) . getDetailsValue ( LANGUAGE ) . map ( Locale :: forLanguageTag ) . orElse ( LocaleContextHolder . getLocale ( ) ) ; String localizedMessage = getFromConfig ( code , locale ) . orElseGet ( ( ) -> { if ( firstFindInMessageBundle ) { return messageSource . getMessage ( code , null , defaultMessage , locale ) ; } else { return defaultMessage != null ? defaultMessage : messageSource . getMessage ( code , null , locale ) ; } } ) ; if ( MapUtils . isNotEmpty ( substitutes ) ) { localizedMessage = new StringSubstitutor ( substitutes ) . replace ( localizedMessage ) ; } return localizedMessage ; } | Finds localized message template by code and current locale from config . If not found it takes message from message bundle or from default message first depends on flag . |
21,622 | public String getMessage ( String code , Map < String , String > substitutes ) { return getMessage ( code , substitutes , true , null ) ; } | Finds localized message template by code and current locale from config . If not found it takes message from message bundle and replaces all the occurrences of variables with their matching values from the substitute map . |
21,623 | public Map < String , Role > getRoles ( String tenant ) { if ( ! roles . containsKey ( tenant ) ) { return new HashMap < > ( ) ; } return roles . get ( tenant ) ; } | Get roles configuration for tenant . Map key is ROLE_KEY and value is role . |
21,624 | public static String printExceptionWithStackInfo ( Throwable throwable ) { StringBuilder out = new StringBuilder ( ) ; printExceptionWithStackInfo ( throwable , out ) ; return out . toString ( ) ; } | Builds log string for exception with stack trace . |
21,625 | public static < T > String joinUrlPaths ( final T [ ] arr , final T ... arr2 ) { try { T [ ] url = ArrayUtils . addAll ( arr , arr2 ) ; String res = StringUtils . join ( url ) ; return ( res == null ) ? "" : res ; } catch ( IndexOutOfBoundsException | IllegalArgumentException | ArrayStoreException e ) { log . warn ( "Error while join URL paths from: {}, {}" , arr , arr2 ) ; return "printerror:" + e ; } } | Join URL path into one string . |
21,626 | public static String getCallMethod ( JoinPoint joinPoint ) { if ( joinPoint != null && joinPoint . getSignature ( ) != null ) { Class < ? > declaringType = joinPoint . getSignature ( ) . getDeclaringType ( ) ; String className = ( declaringType != null ) ? declaringType . getSimpleName ( ) : PRINT_QUESTION ; String methodName = joinPoint . getSignature ( ) . getName ( ) ; return className + PRINT_SEMICOLON + methodName ; } return PRINT_EMPTY_METHOD ; } | Gets method description string from join point . |
21,627 | public static String printInputParams ( JoinPoint joinPoint , String ... includeParamNames ) { try { if ( joinPoint == null ) { return "joinPoint is null" ; } Signature signature = joinPoint . getSignature ( ) ; if ( ! ( signature instanceof MethodSignature ) ) { return PRINT_EMPTY_LIST ; } Optional < LoggingAspectConfig > config = AopAnnotationUtils . getConfigAnnotation ( joinPoint ) ; String [ ] includeParams = includeParamNames ; String [ ] excludeParams = EMPTY_ARRAY ; boolean inputCollectionAware = LoggingAspectConfig . DEFAULT_INPUT_COLLECTION_AWARE ; if ( config . isPresent ( ) ) { if ( ! config . get ( ) . inputDetails ( ) ) { return PRINT_HIDDEN ; } inputCollectionAware = config . get ( ) . inputCollectionAware ( ) ; if ( ArrayUtils . isNotEmpty ( config . get ( ) . inputIncludeParams ( ) ) ) { includeParams = config . get ( ) . inputIncludeParams ( ) ; } if ( ArrayUtils . isEmpty ( includeParams ) && ArrayUtils . isNotEmpty ( config . get ( ) . inputExcludeParams ( ) ) ) { excludeParams = config . get ( ) . inputExcludeParams ( ) ; } } MethodSignature ms = ( MethodSignature ) signature ; String [ ] params = ms . getParameterNames ( ) ; return ArrayUtils . isNotEmpty ( params ) ? renderParams ( joinPoint , params , includeParams , excludeParams , inputCollectionAware ) : PRINT_EMPTY_LIST ; } catch ( IndexOutOfBoundsException | IllegalArgumentException e ) { log . warn ( "Error while print params: {}, params = {}" , e , joinPoint . getArgs ( ) ) ; return "printerror: " + e ; } } | Gets join point input params description string . |
21,628 | public static String printCollectionAware ( final Object object , final boolean printBody ) { if ( ! printBody ) { return PRINT_HIDDEN ; } if ( object == null ) { return String . valueOf ( object ) ; } Class < ? > clazz = object . getClass ( ) ; if ( ! Collection . class . isAssignableFrom ( clazz ) ) { return String . valueOf ( object ) ; } return new StringBuilder ( ) . append ( "[<" ) . append ( clazz . getSimpleName ( ) ) . append ( "> size = " ) . append ( Collection . class . cast ( object ) . size ( ) ) . append ( "]" ) . toString ( ) ; } | Gets object representation with size for collection case . |
21,629 | private static String replaceOperators ( String spel ) { if ( StringUtils . isBlank ( spel ) ) { return spel ; } return spel . replaceAll ( "==" , " = " ) . replaceAll ( "&&" , " and " ) . replaceAll ( "\\|\\|" , " or " ) ; } | Replace SPEL == && || to SQL = and or . |
21,630 | public static void checkSecurity ( ) { SecurityManager securityManager = System . getSecurityManager ( ) ; if ( securityManager != null ) { securityManager . checkPermission ( new ManagementPermission ( PERMISSION_NAME_CONTROL ) ) ; } } | If JVM security manager exists then checks JVM security control permission . |
21,631 | protected final < T > String getString ( final IKey < T > key ) { final Object value = config . get ( key . key ( ) ) ; return String . valueOf ( value != null ? value : key . getDefaultValue ( ) ) ; } | returns the value as string according to given key . If no value is set the default value will be returned . |
21,632 | @ SuppressWarnings ( "unchecked" ) public final < T > T get ( final IKey < T > key ) { T value = ( T ) config . get ( key . key ( ) ) ; return value != null ? value : key . getDefaultValue ( ) ; } | returns the value for the given key . If no value is set the default value will be returned . |
21,633 | protected static < T > IKey < T > newKey ( final String key , final T defaultValue ) { return new Key < T > ( key , defaultValue ) ; } | creates a new key . |
21,634 | public Resource getResource ( String location ) { String cfgPath = StringUtils . removeStart ( location , XM_MS_CONFIG_URL_PREFIX ) ; return scriptResources . getOrDefault ( cfgPath , XmLepScriptResource . nonExist ( ) ) ; } | Get LEP script resource . |
21,635 | public void updateConfigurations ( String commit , Collection < String > paths ) { Map < String , Configuration > configurationsMap = getConfigurationMap ( commit , paths ) ; paths . forEach ( path -> notifyUpdated ( configurationsMap . getOrDefault ( path , new Configuration ( path , null ) ) ) ) ; } | Update configuration from config service |
21,636 | 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 . |
21,637 | 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 ) ; executionContext . setValue ( BINDING_KEY_TENANT_CONTEXT , tenantContext ) ; executionContext . setValue ( BINDING_KEY_AUTH_CONTEXT , authContext ) ; bindExecutionContext ( executionContext ) ; } | Init execution context for script variables bindings . |
21,638 | @ SuppressWarnings ( "squid:S00112" ) 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 ) ; LepKeyResolver keyResolver = getKeyResolver ( methodLep ) ; LepKey baseLepKey = getBaseLepKey ( typeLepService , methodLep , method ) ; LepMethod lepMethod = buildLepMethod ( targetType , target , method , args ) ; 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 . |
21,639 | @ 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 . |
21,640 | static Object executeScript ( UrlLepResourceKey scriptResourceKey , ProceedingLep proceedingLep , LepMethod method , LepManagerService managerService , Supplier < GroovyScriptRunner > resourceExecutorSupplier , LepMethodResult methodResult , 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 . |
21,641 | 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 ( ) ; ScopedContext executionContext = managerService . getContext ( ContextScopes . EXECUTION ) ; if ( executionContext != null ) { executionContext . getValues ( ) . forEach ( lepContext :: put ) ; } 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 ) ; lepContext . put ( XmLepScriptConstants . BINDING_KEY_LEP , proceedingLep ) ; if ( lepMethodResult != null ) { lepContext . put ( XmLepScriptConstants . BINDING_KEY_RETURNED_VALUE , lepMethodResult . getReturnedValue ( ) ) ; } lepContext . put ( XmLepScriptConstants . BINDING_KEY_METHOD_RESULT , lepMethodResult ) ; binding . setVariable ( XmLepScriptConstants . BINDING_VAR_LEP_SCRIPT_CONTEXT , lepContext ) ; return binding ; } | Build scripts bindings . |
21,642 | protected Map < String , Object > decode ( String token ) { try { 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 . |
21,643 | 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 . |
21,644 | 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 . |
21,645 | 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 . |
21,646 | 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 . |
21,647 | 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 . |
21,648 | 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 |
21,649 | 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 . |
21,650 | 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 . |
21,651 | 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 |
21,652 | 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 . |
21,653 | 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 . |
21,654 | 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 . |
21,655 | 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 . |
21,656 | 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 . |
21,657 | 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 |
21,658 | 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 . |
21,659 | 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 . |
21,660 | 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 . |
21,661 | 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 . |
21,662 | 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 . |
21,663 | 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 . |
21,664 | @ 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 . |
21,665 | 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 . |
21,666 | 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 |
21,667 | 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 . |
21,668 | 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 . |
21,669 | 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 . |
21,670 | public < T > List < T > findAll ( Class < T > entityClass , String privilegeKey ) { return findAll ( null , entityClass , privilegeKey ) . getContent ( ) ; } | Find all permitted entities . |
21,671 | 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 . |
21,672 | 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 . |
21,673 | 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 . |
21,674 | 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 |
21,675 | 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 . |
21,676 | 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 . |
21,677 | public String logicalCollectionTableName ( String tableName , String ownerEntityTable , String associatedEntityTable , String propertyName ) { if ( tableName == null ) { 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 |
21,678 | protected final void addMessage ( String msgKey , Object ... args ) { getFlash ( ) . addMessageNow ( getTextInternal ( msgKey , args ) ) ; } | Add action message . |
21,679 | protected final void addError ( String msgKey , Object ... args ) { getFlash ( ) . addErrorNow ( getTextInternal ( msgKey , args ) ) ; } | Add action error . |
21,680 | protected final void addFlashError ( String msgKey , Object ... args ) { getFlash ( ) . addError ( getTextInternal ( msgKey , args ) ) ; } | Add error to next action . |
21,681 | protected final void addFlashMessage ( String msgKey , Object ... args ) { getFlash ( ) . addMessage ( getTextInternal ( msgKey , args ) ) ; } | Add message to next action . |
21,682 | 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 . |
21,683 | 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 |
21,684 | 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 . |
21,685 | 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 |
21,686 | 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 . |
21,687 | private void addEntry ( K key , V value ) { EntryImpl < K , V > entry = _poolFirst ; if ( entry != null ) { _poolFirst = entry . _after ; entry . _after = null ; } else { entry = new EntryImpl < K , V > ( ) ; } entry . _key = key ; entry . _value = value ; int index = keyHash ( key ) & _mask ; entry . _index = index ; EntryImpl < K , V > next = _entries [ index ] ; entry . _next = next ; if ( next != null ) { next . _previous = entry ; } _entries [ index ] = entry ; if ( _mapLast != null ) { entry . _before = _mapLast ; _mapLast . _after = entry ; } else { _mapFirst = entry ; } _mapLast = entry ; _size ++ ; sizeChanged ( ) ; } | Adds a new entry for the specified key and value . |
21,688 | private void removeEntry ( EntryImpl < K , V > entry ) { EntryImpl < K , V > previous = entry . _previous ; EntryImpl < K , V > next = entry . _next ; if ( previous != null ) { previous . _next = next ; entry . _previous = null ; } else { _entries [ entry . _index ] = next ; } if ( next != null ) { next . _previous = previous ; entry . _next = null ; } EntryImpl < K , V > before = entry . _before ; EntryImpl < K , V > after = entry . _after ; if ( before != null ) { before . _after = after ; entry . _before = null ; } else { _mapFirst = after ; } if ( after != null ) { after . _before = before ; } else { _mapLast = before ; } entry . _key = null ; entry . _value = null ; entry . _after = _poolFirst ; _poolFirst = entry ; _size -- ; sizeChanged ( ) ; } | Removes the specified entry from the map . |
21,689 | @ 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 . |
21,690 | 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 . |
21,691 | static Set < JClass > discoverDirectClasses ( Outline outline , Set < ClassOutline > classes ) throws IllegalAccessException { Set < String > directClassNames = new LinkedHashSet < > ( ) ; for ( ClassOutline classOutline : classes ) { 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 |
21,692 | 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 . |
21,693 | 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! |
21,694 | 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 |
21,695 | static boolean isJAXBElement ( JType type ) { 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 . |
21,696 | static List < JClass > allConcreteClasses ( Set < ClassOutline > classes ) { return allConcreteClasses ( classes , Collections . emptySet ( ) ) ; } | Returns all of the concrete classes in the system |
21,697 | 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 |
21,698 | 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 . |
21,699 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.