idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
15,800
private void checkIdentity ( SSLSession session , X509Certificate cert ) throws CertificateException { if ( session == null ) { throw new CertificateException ( "No handshake session" ) ; } if ( EndpointIdentificationAlgorithm . HTTPS == identityAlg ) { String hostname = session . getPeerHost ( ) ; APINameChecker . verifyAndThrow ( hostname , cert ) ; } }
check server identify against hostnames . This method is used to enhance X509TrustManager to provide standard identity check .
15,801
public static TrustManager [ ] decorate ( TrustManager [ ] trustManagers , TLSConfig tlsConfig ) { if ( null != trustManagers && trustManagers . length > 0 ) { TrustManager [ ] decoratedTrustManagers = new TrustManager [ trustManagers . length ] ; for ( int i = 0 ; i < trustManagers . length ; ++ i ) { TrustManager trustManager = trustManagers [ i ] ; if ( trustManager instanceof X509TrustManager ) { decoratedTrustManagers [ i ] = new ClientX509ExtendedTrustManager ( ( X509TrustManager ) trustManager , tlsConfig ) ; } else { decoratedTrustManagers [ i ] = trustManager ; } } return decoratedTrustManagers ; } return trustManagers ; }
This method converts existing X509TrustManagers to ClientX509ExtendedTrustManagers .
15,802
protected void putDumpInfoTo ( Map < String , Object > result ) { if ( StringUtils . isNotBlank ( this . url ) ) { result . put ( DumpConstants . URL , this . url ) ; } }
put this . url to result
15,803
public void handleRequest ( final HttpServerExchange exchange ) throws Exception { Map < String , Object > requestHeaderMap = ( Map < String , Object > ) config . get ( REQUEST ) ; if ( requestHeaderMap != null ) { List < String > requestHeaderRemove = ( List < String > ) requestHeaderMap . get ( REMOVE ) ; if ( requestHeaderRemove != null ) { requestHeaderRemove . forEach ( s -> exchange . getRequestHeaders ( ) . remove ( s ) ) ; } Map < String , String > requestHeaderUpdate = ( Map < String , String > ) requestHeaderMap . get ( UPDATE ) ; if ( requestHeaderUpdate != null ) { requestHeaderUpdate . forEach ( ( k , v ) -> exchange . getRequestHeaders ( ) . put ( new HttpString ( k ) , v ) ) ; } } Map < String , Object > responseHeaderMap = ( Map < String , Object > ) config . get ( RESPONSE ) ; if ( responseHeaderMap != null ) { List < String > responseHeaderRemove = ( List < String > ) responseHeaderMap . get ( REMOVE ) ; if ( responseHeaderRemove != null ) { responseHeaderRemove . forEach ( s -> exchange . getResponseHeaders ( ) . remove ( s ) ) ; } Map < String , String > responseHeaderUpdate = ( Map < String , String > ) responseHeaderMap . get ( UPDATE ) ; if ( responseHeaderUpdate != null ) { responseHeaderUpdate . forEach ( ( k , v ) -> exchange . getResponseHeaders ( ) . put ( new HttpString ( k ) , v ) ) ; } } Handler . next ( exchange , next ) ; }
Check iterate the configuration on both request and response section and update headers accordingly .
15,804
public static String getHostName ( SocketAddress socketAddress ) { if ( socketAddress == null ) { return null ; } if ( socketAddress instanceof InetSocketAddress ) { InetAddress addr = ( ( InetSocketAddress ) socketAddress ) . getAddress ( ) ; if ( addr != null ) { return addr . getHostAddress ( ) ; } } return null ; }
return ip to avoid lookup dns
15,805
public static Object mergeObject ( Object config , Class clazz ) { merge ( config ) ; return convertMapToObj ( ( Map < String , Object > ) config , clazz ) ; }
Merge map config with values generated by ConfigInjection . class and return mapping object
15,806
private static void merge ( Object m1 ) { if ( m1 instanceof Map ) { Iterator < Object > fieldNames = ( ( Map < Object , Object > ) m1 ) . keySet ( ) . iterator ( ) ; String fieldName = null ; while ( fieldNames . hasNext ( ) ) { fieldName = String . valueOf ( fieldNames . next ( ) ) ; Object field1 = ( ( Map < String , Object > ) m1 ) . get ( fieldName ) ; if ( field1 != null ) { if ( field1 instanceof Map || field1 instanceof List ) { merge ( field1 ) ; } else if ( field1 instanceof String ) { Object injectValue = ConfigInjection . getInjectValue ( ( String ) field1 ) ; ( ( Map < String , Object > ) m1 ) . put ( fieldName , injectValue ) ; } } } } else if ( m1 instanceof List ) { for ( int i = 0 ; i < ( ( List < Object > ) m1 ) . size ( ) ; i ++ ) { Object field1 = ( ( List < Object > ) m1 ) . get ( i ) ; if ( field1 instanceof Map || field1 instanceof List ) { merge ( field1 ) ; } else if ( field1 instanceof String ) { Object injectValue = ConfigInjection . getInjectValue ( ( String ) field1 ) ; ( ( List < Object > ) m1 ) . set ( i , injectValue ) ; } } } }
Search the config map recursively expand List and Map level by level util no further expand
15,807
private static Object convertMapToObj ( Map < String , Object > map , Class clazz ) { ObjectMapper mapper = new ObjectMapper ( ) ; Object obj = mapper . convertValue ( map , clazz ) ; return obj ; }
Method used to convert map to object based on the reference class provided
15,808
public double getMean ( ) { if ( values . length == 0 ) { return 0 ; } double sum = 0 ; for ( long value : values ) { sum += value ; } return sum / values . length ; }
Returns the arithmetic mean of the values in the snapshot .
15,809
public double getStdDev ( ) { if ( values . length <= 1 ) { return 0 ; } final double mean = getMean ( ) ; double sum = 0 ; for ( long value : values ) { final double diff = value - mean ; sum += diff * diff ; } final double variance = sum / ( values . length - 1 ) ; return Math . sqrt ( variance ) ; }
Returns the standard deviation of the values in the snapshot .
15,810
public void dump ( OutputStream output ) { try ( PrintWriter out = new PrintWriter ( new OutputStreamWriter ( output , UTF_8 ) ) ) { for ( long value : values ) { out . printf ( "%d%n" , value ) ; } } }
Writes the values of the snapshot to the given stream .
15,811
public static Object constructByNamedParams ( Class clazz , Map params ) throws Exception { Object obj = clazz . getConstructor ( ) . newInstance ( ) ; Method [ ] allMethods = clazz . getMethods ( ) ; for ( Method method : allMethods ) { if ( method . getName ( ) . startsWith ( "set" ) ) { Object [ ] o = new Object [ 1 ] ; String propertyName = Introspector . decapitalize ( method . getName ( ) . substring ( 3 ) ) ; if ( params . containsKey ( propertyName ) ) { o [ 0 ] = params . get ( propertyName ) ; method . invoke ( obj , o ) ; } } } return obj ; }
Build an object out of a given class and a map for field names to values .
15,812
public static Object constructByParameterizedConstructor ( Class clazz , List parameters ) throws Exception { Object instance = null ; Constructor [ ] allConstructors = clazz . getDeclaredConstructors ( ) ; boolean hasDefaultConstructor = false ; for ( Constructor ctor : allConstructors ) { Class < ? > [ ] pType = ctor . getParameterTypes ( ) ; if ( pType . length > 0 ) { if ( pType . length == parameters . size ( ) ) { boolean matched = true ; Object [ ] params = new Object [ pType . length ] ; for ( int j = 0 ; j < pType . length ; j ++ ) { Map < String , Object > parameter = ( Map ) parameters . get ( j ) ; Iterator it = parameter . entrySet ( ) . iterator ( ) ; if ( it . hasNext ( ) ) { Map . Entry < String , Object > pair = ( Map . Entry ) it . next ( ) ; String key = pair . getKey ( ) ; Object value = pair . getValue ( ) ; if ( pType [ j ] . getName ( ) . equals ( key ) ) { params [ j ] = value ; } else { matched = false ; break ; } } } if ( matched ) { instance = ctor . newInstance ( params ) ; break ; } } } else { hasDefaultConstructor = true ; } } if ( instance != null ) { return instance ; } else { if ( hasDefaultConstructor ) { return clazz . getConstructor ( ) . newInstance ( ) ; } else { throw new Exception ( "No instance can be created for class " + clazz ) ; } } }
Build an object out of a given class and a list of single element maps of object type to value . A constructor is searched for that matches the given set . If not found the default is attempted .
15,813
public static MetricName name ( String name , String ... names ) { final int length ; if ( names == null ) { length = 0 ; } else { length = names . length ; } final String [ ] parts = new String [ length + 1 ] ; parts [ 0 ] = name ; System . arraycopy ( names , 0 , parts , 1 , length ) ; return MetricName . build ( parts ) ; }
Shorthand method for backwards compatibility in creating metric names .
15,814
public void removeAll ( ) { for ( Iterator < Map . Entry < MetricName , Metric > > it = metrics . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < MetricName , Metric > entry = it . next ( ) ; Metric metric = entry . getValue ( ) ; if ( metric != null ) { onMetricRemoved ( entry . getKey ( ) , metric ) ; } it . remove ( ) ; } }
Removes all the metrics in registry .
15,815
public void stop ( ) { executor . shutdown ( ) ; try { if ( ! executor . awaitTermination ( 1 , TimeUnit . SECONDS ) ) { executor . shutdownNow ( ) ; if ( ! executor . awaitTermination ( 1 , TimeUnit . SECONDS ) ) { LOG . warn ( getClass ( ) . getSimpleName ( ) + ": ScheduledExecutorService did not terminate" ) ; } } } catch ( InterruptedException ie ) { executor . shutdownNow ( ) ; Thread . currentThread ( ) . interrupt ( ) ; } }
Stops the reporter and shuts down its thread of execution .
15,816
public void report ( ) { synchronized ( this ) { report ( registry . getGauges ( filter ) , registry . getCounters ( filter ) , registry . getHistograms ( filter ) , registry . getMeters ( filter ) , registry . getTimers ( filter ) ) ; } }
Report the current values of all metrics in the registry .
15,817
public URL select ( List < URL > urls , String requestKey ) { List < URL > localUrls = searchLocalUrls ( urls , ip ) ; if ( localUrls . size ( ) > 0 ) { if ( localUrls . size ( ) == 1 ) { return localUrls . get ( 0 ) ; } else { return doSelect ( localUrls ) ; } } else { return doSelect ( urls ) ; } }
Local first requestKey is not used as it is ip on the localhost . It first needs to find a list of urls on the localhost for the service and then round robin in the list to pick up one .
15,818
private static void serverOptionInit ( ) { Map < String , Object > mapConfig = Config . getInstance ( ) . getJsonMapConfigNoCache ( SERVER_CONFIG_NAME ) ; ServerOption . serverOptionInit ( mapConfig , getServerConfig ( ) ) ; }
Method used to initialize server options . If the user has configured a valid server option load it into the server configuration otherwise use the default value
15,819
static public void shutdown ( ) { if ( getServerConfig ( ) . enableRegistry && registry != null && serviceUrls != null ) { for ( URL serviceUrl : serviceUrls ) { registry . unregister ( serviceUrl ) ; System . out . println ( "unregister serviceUrl " + serviceUrl ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "unregister serviceUrl " + serviceUrl ) ; } } if ( gracefulShutdownHandler != null ) { logger . info ( "Starting graceful shutdown." ) ; gracefulShutdownHandler . shutdown ( ) ; try { gracefulShutdownHandler . awaitShutdown ( 60 * 1000 ) ; } catch ( InterruptedException e ) { logger . error ( "Error occurred while waiting for pending requests to complete." , e ) ; } logger . info ( "Graceful shutdown complete." ) ; } ShutdownHookProvider [ ] shutdownHookProviders = SingletonServiceFactory . getBeans ( ShutdownHookProvider . class ) ; if ( shutdownHookProviders != null ) Arrays . stream ( shutdownHookProviders ) . forEach ( s -> s . onShutdown ( ) ) ; stop ( ) ; logger . info ( "Cleaning up before server shutdown" ) ; }
implement shutdown hook here .
15,820
protected static void mergeStatusConfig ( ) { Map < String , Object > appStatusConfig = Config . getInstance ( ) . getJsonMapConfigNoCache ( STATUS_CONFIG_NAME [ 1 ] ) ; if ( appStatusConfig == null ) { return ; } Map < String , Object > statusConfig = Config . getInstance ( ) . getJsonMapConfig ( STATUS_CONFIG_NAME [ 0 ] ) ; Set < String > duplicatedStatusSet = new HashSet < > ( statusConfig . keySet ( ) ) ; duplicatedStatusSet . retainAll ( appStatusConfig . keySet ( ) ) ; if ( ! duplicatedStatusSet . isEmpty ( ) ) { logger . error ( "The status code(s): " + duplicatedStatusSet . toString ( ) + " is already in use by light-4j and cannot be overwritten," + " please change to another status code in app-status.yml if necessary." ) ; throw new RuntimeException ( "The status code(s): " + duplicatedStatusSet . toString ( ) + " in status.yml and app-status.yml are duplicated." ) ; } statusConfig . putAll ( appStatusConfig ) ; }
method used to merge status . yml and app - status . yml
15,821
public static URL register ( String serviceId , int port ) { try { registry = SingletonServiceFactory . getBean ( Registry . class ) ; if ( registry == null ) throw new RuntimeException ( "Could not find registry instance in service map" ) ; String ipAddress = System . getenv ( STATUS_HOST_IP ) ; logger . info ( "Registry IP from STATUS_HOST_IP is " + ipAddress ) ; if ( ipAddress == null ) { InetAddress inetAddress = Util . getInetAddress ( ) ; ipAddress = inetAddress . getHostAddress ( ) ; logger . info ( "Could not find IP from STATUS_HOST_IP, use the InetAddress " + ipAddress ) ; } ServerConfig serverConfig = getServerConfig ( ) ; Map parameters = new HashMap < > ( ) ; if ( serverConfig . getEnvironment ( ) != null ) parameters . put ( ENV_PROPERTY_KEY , serverConfig . getEnvironment ( ) ) ; URL serviceUrl = new URLImpl ( "light" , ipAddress , port , serviceId , parameters ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "register service: " + serviceUrl . toFullStr ( ) ) ; registry . register ( serviceUrl ) ; return serviceUrl ; } catch ( Exception e ) { System . out . println ( "Failed to register service, the server stopped." ) ; e . printStackTrace ( ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "Failed to register service, the server stopped." , e ) ; throw new RuntimeException ( e . getMessage ( ) ) ; } }
Register the service to the Consul or other service registry . Make it as a separate static method so that it can be called from light - hybrid - 4j to register individual service .
15,822
public void append ( final String str ) { final String s = str != null ? str : "null" ; final int strlen = s . length ( ) ; final int newlen = this . len + strlen ; if ( newlen > this . array . length ) { expand ( newlen ) ; } s . getChars ( 0 , strlen , this . array , this . len ) ; this . len = newlen ; }
Appends chars of the given string to this buffer . The capacity of the buffer is increased if necessary to accommodate all chars .
15,823
public char [ ] toCharArray ( ) { final char [ ] b = new char [ this . len ] ; if ( this . len > 0 ) { System . arraycopy ( this . array , 0 , b , 0 , this . len ) ; } return b ; }
Converts the content of this buffer to an array of chars .
15,824
protected void putDumpInfoTo ( Map < String , Object > result ) { if ( StringUtils . isNotBlank ( this . bodyContent ) ) { result . put ( DumpConstants . BODY , this . bodyContent ) ; } }
put bodyContent to result
15,825
public void dumpRequest ( Map < String , Object > result ) { String contentType = exchange . getRequestHeaders ( ) . getFirst ( Headers . CONTENT_TYPE ) ; if ( contentType != null && contentType . startsWith ( "application/json" ) ) { Object requestBodyAttachment = exchange . getAttachment ( BodyHandler . REQUEST_BODY ) ; if ( requestBodyAttachment != null ) { dumpBodyAttachment ( requestBodyAttachment ) ; } else { dumpInputStream ( ) ; } } else { logger . info ( "unsupported contentType: {}" , contentType ) ; } this . putDumpInfoTo ( result ) ; }
impl of dumping request body to result
15,826
public void dumpResponse ( Map < String , Object > result ) { byte [ ] responseBodyAttachment = exchange . getAttachment ( StoreResponseStreamSinkConduit . RESPONSE ) ; if ( responseBodyAttachment != null ) { this . bodyContent = config . isMaskEnabled ( ) ? Mask . maskJson ( new ByteArrayInputStream ( responseBodyAttachment ) , "responseBody" ) : new String ( responseBodyAttachment , UTF_8 ) ; } this . putDumpInfoTo ( result ) ; }
impl of dumping response body to result
15,827
private void dumpInputStream ( ) { exchange . startBlocking ( ) ; InputStream inputStream = exchange . getInputStream ( ) ; try { if ( config . isMaskEnabled ( ) && inputStream . available ( ) != - 1 ) { this . bodyContent = Mask . maskJson ( inputStream , "requestBody" ) ; } else { try { this . bodyContent = StringUtils . inputStreamToString ( inputStream , UTF_8 ) ; } catch ( IOException e ) { logger . error ( e . toString ( ) ) ; } } } catch ( IOException e ) { logger . error ( "undertow inputstream error:" + e . getMessage ( ) ) ; } }
read from input stream convert it to string put into this . bodyContent
15,828
private void dumpBodyAttachment ( Object requestBodyAttachment ) { this . bodyContent = config . isMaskEnabled ( ) ? Mask . maskJson ( requestBodyAttachment , "requestBody" ) : requestBodyAttachment . toString ( ) ; }
read from body attachment from Body Handler convert it to string put into this . bodyContent
15,829
static public X509Certificate readCertificate ( String filename ) throws Exception { InputStream inStream = null ; X509Certificate cert = null ; try { inStream = Config . getInstance ( ) . getInputStreamFromFile ( filename ) ; if ( inStream != null ) { CertificateFactory cf = CertificateFactory . getInstance ( "X.509" ) ; cert = ( X509Certificate ) cf . generateCertificate ( inStream ) ; } else { logger . info ( "Certificate " + Encode . forJava ( filename ) + " not found." ) ; } } catch ( Exception e ) { logger . error ( "Exception: " , e ) ; } finally { if ( inStream != null ) { try { inStream . close ( ) ; } catch ( IOException ioe ) { logger . error ( "Exception: " , ioe ) ; } } } return cert ; }
Read certificate from a file and convert it into X509Certificate object
15,830
public static String getJwtFromAuthorization ( String authorization ) { String jwt = null ; if ( authorization != null ) { String [ ] parts = authorization . split ( " " ) ; if ( parts . length == 2 ) { String scheme = parts [ 0 ] ; String credentials = parts [ 1 ] ; Pattern pattern = Pattern . compile ( "^Bearer$" , Pattern . CASE_INSENSITIVE ) ; if ( pattern . matcher ( scheme ) . matches ( ) ) { jwt = credentials ; } } } return jwt ; }
Parse the jwt token from Authorization header .
15,831
public static String inputStreamToString ( InputStream inputStream , Charset charset ) throws IOException { if ( inputStream != null && inputStream . available ( ) != - 1 ) { ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int length ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { result . write ( buffer , 0 , length ) ; } if ( charset != null ) { return result . toString ( charset . name ( ) ) ; } return result . toString ( StandardCharsets . UTF_8 . name ( ) ) ; } return null ; }
Convert an InputStream into a String .
15,832
public void dumpRequest ( Map < String , Object > result ) { Map < String , Cookie > cookiesMap = exchange . getRequestCookies ( ) ; dumpCookies ( cookiesMap , "requestCookies" ) ; this . putDumpInfoTo ( result ) ; }
impl of dumping request cookies to result
15,833
public void dumpResponse ( Map < String , Object > result ) { Map < String , Cookie > cookiesMap = exchange . getResponseCookies ( ) ; dumpCookies ( cookiesMap , "responseCookies" ) ; this . putDumpInfoTo ( result ) ; }
impl of dumping response cookies to result
15,834
private void dumpCookies ( Map < String , Cookie > cookiesMap , String maskKey ) { cookiesMap . forEach ( ( key , cookie ) -> { if ( ! config . getRequestFilteredCookies ( ) . contains ( cookie . getName ( ) ) ) { List < Map < String , String > > cookieInfoList = new ArrayList < > ( ) ; String cookieValue = config . isMaskEnabled ( ) ? Mask . maskRegex ( cookie . getValue ( ) , maskKey , cookie . getName ( ) ) : cookie . getValue ( ) ; cookieInfoList . add ( new HashMap < String , String > ( ) { { put ( DumpConstants . COOKIE_VALUE , cookieValue ) ; } } ) ; cookieInfoList . add ( new HashMap < String , String > ( ) { { put ( DumpConstants . COOKIE_DOMAIN , cookie . getDomain ( ) ) ; } } ) ; cookieInfoList . add ( new HashMap < String , String > ( ) { { put ( DumpConstants . COOKIE_PATH , cookie . getPath ( ) ) ; } } ) ; cookieInfoList . add ( new HashMap < String , String > ( ) { { put ( DumpConstants . COOKIE_EXPIRES , cookie . getExpires ( ) == null ? "" : cookie . getExpires ( ) . toString ( ) ) ; } } ) ; this . cookieMap . put ( key , cookieInfoList ) ; } } ) ; }
put cookies info to cookieMap
15,835
protected void putDumpInfoTo ( Map < String , Object > result ) { if ( this . cookieMap . size ( ) > 0 ) { result . put ( DumpConstants . COOKIES , cookieMap ) ; } }
put cookieMap to result
15,836
public static boolean isSame ( List < URL > urls1 , List < URL > urls2 ) { if ( urls1 == null || urls2 == null ) { return false ; } if ( urls1 . size ( ) != urls2 . size ( ) ) { return false ; } return urls1 . containsAll ( urls2 ) ; }
Check if two lists have the same urls . If any list is empty return false
15,837
public static ConsulService buildService ( URL url ) { ConsulService service = new ConsulService ( ) ; service . setAddress ( url . getHost ( ) ) ; service . setId ( ConsulUtils . convertConsulSerivceId ( url ) ) ; service . setName ( url . getPath ( ) ) ; service . setPort ( url . getPort ( ) ) ; List < String > tags = new ArrayList < String > ( ) ; String env = url . getParameter ( Constants . TAG_ENVIRONMENT ) ; if ( env != null ) tags . add ( env ) ; service . setTags ( tags ) ; return service ; }
build consul service from url
15,838
public static URL buildUrl ( ConsulService service ) { URL url = null ; if ( url == null ) { Map < String , String > params = new HashMap < String , String > ( ) ; if ( ! service . getTags ( ) . isEmpty ( ) ) { params . put ( URLParamType . environment . getName ( ) , service . getTags ( ) . get ( 0 ) ) ; } url = new URLImpl ( ConsulConstants . DEFAULT_PROTOCOL , service . getAddress ( ) , service . getPort ( ) , ConsulUtils . getPathFromServiceId ( service . getId ( ) ) , params ) ; } return url ; }
build url from service
15,839
public static String getPathFromServiceId ( String serviceId ) { return serviceId . substring ( serviceId . indexOf ( ":" ) + 1 , serviceId . lastIndexOf ( ":" ) ) ; }
get path of url from service id in consul
15,840
public static String getJwt ( JwtClaims claims ) throws JoseException { String jwt ; RSAPrivateKey privateKey = ( RSAPrivateKey ) getPrivateKey ( jwtConfig . getKey ( ) . getFilename ( ) , ( String ) secretConfig . get ( JWT_PRIVATE_KEY_PASSWORD ) , jwtConfig . getKey ( ) . getKeyName ( ) ) ; JsonWebSignature jws = new JsonWebSignature ( ) ; jws . setPayload ( claims . toJson ( ) ) ; jws . setKey ( privateKey ) ; String provider_id = "" ; if ( jwtConfig . getProviderId ( ) != null ) { provider_id = jwtConfig . getProviderId ( ) ; if ( provider_id . length ( ) == 1 ) { provider_id = "0" + provider_id ; } else if ( provider_id . length ( ) > 2 ) { logger . error ( "provider_id defined in the security.yml file is invalid; the length should be 2" ) ; provider_id = provider_id . substring ( 0 , 2 ) ; } } jws . setKeyIdHeaderValue ( provider_id + jwtConfig . getKey ( ) . getKid ( ) ) ; jws . setAlgorithmHeaderValue ( AlgorithmIdentifiers . RSA_USING_SHA256 ) ; jwt = jws . getCompactSerialization ( ) ; return jwt ; }
A static method that generate JWT token from JWT claims object
15,841
private static PrivateKey getPrivateKey ( String filename , String password , String key ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "filename = " + filename + " key = " + key ) ; PrivateKey privateKey = null ; try { KeyStore keystore = KeyStore . getInstance ( "JKS" ) ; keystore . load ( Config . getInstance ( ) . getInputStreamFromFile ( filename ) , password . toCharArray ( ) ) ; privateKey = ( PrivateKey ) keystore . getKey ( key , password . toCharArray ( ) ) ; } catch ( Exception e ) { logger . error ( "Exception:" , e ) ; } if ( privateKey == null ) { logger . error ( "Failed to retrieve private key from keystore" ) ; } return privateKey ; }
Get private key from java key store
15,842
public static String toTimePrecision ( final TimeUnit t ) { switch ( t ) { case HOURS : return "h" ; case MINUTES : return "m" ; case SECONDS : return "s" ; case MILLISECONDS : return "ms" ; case MICROSECONDS : return "u" ; case NANOSECONDS : return "n" ; default : EnumSet < TimeUnit > allowedTimeunits = EnumSet . of ( TimeUnit . HOURS , TimeUnit . MINUTES , TimeUnit . SECONDS , TimeUnit . MILLISECONDS , TimeUnit . MICROSECONDS , TimeUnit . NANOSECONDS ) ; throw new IllegalArgumentException ( "time precision must be one of:" + allowedTimeunits ) ; } }
Convert from a TimeUnit to a influxDB timeunit String .
15,843
private synchronized Jwt getJwt ( ICacheStrategy cacheStrategy , Jwt . Key key ) { Jwt result = cacheStrategy . getCachedJwt ( key ) ; if ( result == null ) { result = new Jwt ( key ) ; cacheStrategy . cacheJwt ( key , result ) ; } return result ; }
cache jwt if not exist
15,844
private boolean isSwitcherChange ( boolean switcherStatus ) { boolean ret = false ; if ( switcherStatus != lastHeartBeatSwitcherStatus ) { ret = true ; lastHeartBeatSwitcherStatus = switcherStatus ; logger . info ( "heartbeat switcher change to " + switcherStatus ) ; } return ret ; }
check heart beat switcher status if switcher is changed then change lastHeartBeatSwitcherStatus to the latest status .
15,845
public String getIdentity ( ) { return protocol + Constants . PROTOCOL_SEPARATOR + host + ":" + port + "/" + getParameter ( URLParamType . group . getName ( ) , URLParamType . group . getValue ( ) ) + "/" + getPath ( ) + "/" + getParameter ( URLParamType . version . getName ( ) , URLParamType . version . getValue ( ) ) + "/" + getParameter ( URLParamType . nodeType . getName ( ) , URLParamType . nodeType . getValue ( ) ) ; }
Return service identity if two urls have the same identity then same service
15,846
public boolean canServe ( URL refUrl ) { if ( refUrl == null || ! this . getPath ( ) . equals ( refUrl . getPath ( ) ) ) { return false ; } if ( ! protocol . equals ( refUrl . getProtocol ( ) ) ) { return false ; } if ( ! Constants . NODE_TYPE_SERVICE . equals ( this . getParameter ( URLParamType . nodeType . getName ( ) ) ) ) { return false ; } String version = getParameter ( URLParamType . version . getName ( ) , URLParamType . version . getValue ( ) ) ; String refVersion = refUrl . getParameter ( URLParamType . version . getName ( ) , URLParamType . version . getValue ( ) ) ; if ( ! version . equals ( refVersion ) ) { return false ; } String serialize = getParameter ( URLParamType . serialize . getName ( ) , URLParamType . serialize . getValue ( ) ) ; String refSerialize = refUrl . getParameter ( URLParamType . serialize . getName ( ) , URLParamType . serialize . getValue ( ) ) ; if ( ! serialize . equals ( refSerialize ) ) { return false ; } return true ; }
check if this url can serve the refUrl .
15,847
public MetricName resolve ( String p ) { final String next ; if ( p != null && ! p . isEmpty ( ) ) { if ( key != null && ! key . isEmpty ( ) ) { next = key + SEPARATOR + p ; } else { next = p ; } } else { next = this . key ; } return new MetricName ( next , tags ) ; }
Build the MetricName that is this with another path appended to it .
15,848
public MetricName tagged ( Map < String , String > add ) { final Map < String , String > tags = new HashMap < > ( add ) ; tags . putAll ( this . tags ) ; return new MetricName ( key , tags ) ; }
Add tags to a metric name and return the newly created MetricName .
15,849
public static MetricName join ( MetricName ... parts ) { final StringBuilder nameBuilder = new StringBuilder ( ) ; final Map < String , String > tags = new HashMap < > ( ) ; boolean first = true ; for ( MetricName part : parts ) { final String name = part . getKey ( ) ; if ( name != null && ! name . isEmpty ( ) ) { if ( first ) { first = false ; } else { nameBuilder . append ( SEPARATOR ) ; } nameBuilder . append ( name ) ; } if ( ! part . getTags ( ) . isEmpty ( ) ) tags . putAll ( part . getTags ( ) ) ; } return new MetricName ( nameBuilder . toString ( ) , tags ) ; }
Join the specified set of metric names .
15,850
public static MetricName build ( String ... parts ) { if ( parts == null || parts . length == 0 ) return MetricName . EMPTY ; if ( parts . length == 1 ) return new MetricName ( parts [ 0 ] , EMPTY_TAGS ) ; return new MetricName ( buildName ( parts ) , EMPTY_TAGS ) ; }
Build a new metric name using the specific path components .
15,851
static void initPaths ( ) { if ( config != null && config . getPaths ( ) != null ) { for ( PathChain pathChain : config . getPaths ( ) ) { pathChain . validate ( configName + " config" ) ; if ( pathChain . getPath ( ) == null ) { addSourceChain ( pathChain ) ; } else { addPathChain ( pathChain ) ; } } } }
Build handlerListById and reqTypeMatcherMap from the paths in the config .
15,852
static void initDefaultHandlers ( ) { if ( config != null && config . getDefaultHandlers ( ) != null ) { defaultHandlers = getHandlersFromExecList ( config . getDefaultHandlers ( ) ) ; handlerListById . put ( "defaultHandlers" , defaultHandlers ) ; } }
Build defaultHandlers from the defaultHandlers in the config .
15,853
private static void addSourceChain ( PathChain sourceChain ) { try { Class sourceClass = Class . forName ( sourceChain . getSource ( ) ) ; EndpointSource source = ( EndpointSource ) sourceClass . newInstance ( ) ; for ( EndpointSource . Endpoint endpoint : source . listEndpoints ( ) ) { PathChain sourcedPath = new PathChain ( ) ; sourcedPath . setPath ( endpoint . getPath ( ) ) ; sourcedPath . setMethod ( endpoint . getMethod ( ) ) ; sourcedPath . setExec ( sourceChain . getExec ( ) ) ; sourcedPath . validate ( sourceChain . getSource ( ) ) ; addPathChain ( sourcedPath ) ; } } catch ( Exception e ) { logger . error ( "Failed to inject handler.yml paths from: " + sourceChain ) ; if ( e instanceof RuntimeException ) { throw ( RuntimeException ) e ; } else { throw new RuntimeException ( e ) ; } } }
Add PathChains crated from the EndpointSource given in sourceChain
15,854
public static void next ( HttpServerExchange httpServerExchange ) throws Exception { HttpHandler httpHandler = getNext ( httpServerExchange ) ; if ( httpHandler != null ) { httpHandler . handleRequest ( httpServerExchange ) ; } else if ( lastHandler != null ) { lastHandler . handleRequest ( httpServerExchange ) ; } }
Handle the next request in the chain .
15,855
public static void next ( HttpServerExchange httpServerExchange , HttpHandler next ) throws Exception { if ( next != null ) { next . handleRequest ( httpServerExchange ) ; } else { next ( httpServerExchange ) ; } }
Go to the next handler if the given next is none null . Reason for this is for middleware to provide their instance next if it exists . Since if it exists the server hasn t been able to find the handler . yml .
15,856
public static void next ( HttpServerExchange httpServerExchange , String execName , Boolean returnToOrigFlow ) throws Exception { String currentChainId = httpServerExchange . getAttachment ( CHAIN_ID ) ; Integer currentNextIndex = httpServerExchange . getAttachment ( CHAIN_SEQ ) ; httpServerExchange . putAttachment ( CHAIN_ID , execName ) ; httpServerExchange . putAttachment ( CHAIN_SEQ , 0 ) ; next ( httpServerExchange ) ; if ( returnToOrigFlow ) { httpServerExchange . putAttachment ( CHAIN_ID , currentChainId ) ; httpServerExchange . putAttachment ( CHAIN_SEQ , currentNextIndex ) ; next ( httpServerExchange ) ; } }
Allow nexting directly to a flow .
15,857
public static HttpHandler getNext ( HttpServerExchange httpServerExchange ) { String chainId = httpServerExchange . getAttachment ( CHAIN_ID ) ; List < HttpHandler > handlersForId = handlerListById . get ( chainId ) ; Integer nextIndex = httpServerExchange . getAttachment ( CHAIN_SEQ ) ; if ( nextIndex < handlersForId . size ( ) ) { httpServerExchange . putAttachment ( CHAIN_SEQ , nextIndex + 1 ) ; return handlersForId . get ( nextIndex ) ; } return null ; }
Returns the instance of the next handler rather then calling handleRequest on it .
15,858
public static HttpHandler getNext ( HttpServerExchange httpServerExchange , HttpHandler next ) throws Exception { if ( next != null ) { return next ; } return getNext ( httpServerExchange ) ; }
Returns the instance of the next handler or the given next param if it s not null .
15,859
public static boolean start ( HttpServerExchange httpServerExchange ) { PathTemplateMatcher < String > pathTemplateMatcher = methodToMatcherMap . get ( httpServerExchange . getRequestMethod ( ) ) ; if ( pathTemplateMatcher != null ) { PathTemplateMatcher . PathMatchResult < String > result = pathTemplateMatcher . match ( httpServerExchange . getRequestPath ( ) ) ; if ( result != null ) { httpServerExchange . putAttachment ( ATTACHMENT_KEY , new io . undertow . util . PathTemplateMatch ( result . getMatchedTemplate ( ) , result . getParameters ( ) ) ) ; for ( Map . Entry < String , String > entry : result . getParameters ( ) . entrySet ( ) ) { httpServerExchange . addQueryParam ( entry . getKey ( ) , entry . getValue ( ) ) ; httpServerExchange . addPathParam ( entry . getKey ( ) , entry . getValue ( ) ) ; } String id = result . getValue ( ) ; httpServerExchange . putAttachment ( CHAIN_ID , id ) ; httpServerExchange . putAttachment ( CHAIN_SEQ , 0 ) ; return true ; } } return false ; }
On the first step of the request match the request against the configured paths . If the match is successful store the chain id within the exchange . Otherwise return false .
15,860
public static boolean startDefaultHandlers ( HttpServerExchange httpServerExchange ) { if ( defaultHandlers != null && defaultHandlers . size ( ) > 0 ) { httpServerExchange . putAttachment ( CHAIN_ID , "defaultHandlers" ) ; httpServerExchange . putAttachment ( CHAIN_SEQ , 0 ) ; return true ; } return false ; }
If there is no matching path the OrchestrationHandler is going to try to start the defaultHandlers . If there are default handlers defined store the chain id within the exchange . Otherwise return false .
15,861
private static List < HttpHandler > getHandlersFromExecList ( List < String > execs ) { List < HttpHandler > handlersFromExecList = new ArrayList < > ( ) ; if ( execs != null ) { for ( String exec : execs ) { List < HttpHandler > handlerList = handlerListById . get ( exec ) ; if ( handlerList == null ) throw new RuntimeException ( "Unknown handler or chain: " + exec ) ; for ( HttpHandler handler : handlerList ) { if ( handler instanceof MiddlewareHandler ) { if ( ( ( MiddlewareHandler ) handler ) . isEnabled ( ) ) { handlersFromExecList . add ( handler ) ; } } else { handlersFromExecList . add ( handler ) ; } } } } return handlersFromExecList ; }
Converts the list of chains and handlers to a flat list of handlers . If a chain is named the same as a handler the chain is resolved first .
15,862
private static void registerMiddlewareHandler ( Object handler ) { if ( handler instanceof MiddlewareHandler ) { if ( ( ( MiddlewareHandler ) handler ) . isEnabled ( ) ) { ( ( MiddlewareHandler ) handler ) . register ( ) ; } } }
Detect if the handler is a MiddlewareHandler instance . If yes then register it .
15,863
private static void initMapDefinedHandler ( Map < String , Object > handler ) { for ( Map . Entry < String , Object > entry : handler . entrySet ( ) ) { Tuple < String , Class > namedClass = splitClassAndName ( entry . getKey ( ) ) ; if ( entry . getValue ( ) instanceof Map ) { HttpHandler httpHandler ; try { httpHandler = ( HttpHandler ) ServiceUtil . constructByNamedParams ( namedClass . second , ( Map ) entry . getValue ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Could not construct a handler with values provided as a map: " + namedClass . second ) ; } registerMiddlewareHandler ( httpHandler ) ; handlers . put ( namedClass . first , httpHandler ) ; handlerListById . put ( namedClass . first , Collections . singletonList ( httpHandler ) ) ; } else if ( entry . getValue ( ) instanceof List ) { HttpHandler httpHandler ; try { httpHandler = ( HttpHandler ) ServiceUtil . constructByParameterizedConstructor ( namedClass . second , ( List ) entry . getValue ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Could not construct a handler with values provided as a list: " + namedClass . second ) ; } registerMiddlewareHandler ( httpHandler ) ; handlers . put ( namedClass . first , httpHandler ) ; handlerListById . put ( namedClass . first , Collections . singletonList ( httpHandler ) ) ; } } }
Helper method for generating the instance of a handler from its map definition in config . Ie . No mapped values for setters or list of constructor fields .
15,864
static Tuple < String , Class > splitClassAndName ( String classLabel ) { String [ ] stringNameSplit = classLabel . split ( "@" ) ; if ( stringNameSplit . length == 1 ) { try { return new Tuple < > ( classLabel , Class . forName ( classLabel ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Configured class: " + classLabel + " has not been found" ) ; } } else if ( stringNameSplit . length > 1 ) { try { return new Tuple < > ( stringNameSplit [ 1 ] , Class . forName ( stringNameSplit [ 0 ] ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Configured class: " + stringNameSplit [ 0 ] + " has not been found. Declared label was: " + stringNameSplit [ 1 ] ) ; } } throw new RuntimeException ( "Invalid format provided for class label: " + classLabel ) ; }
To support multiple instances of the same class support a naming
15,865
static void setConfig ( String configName ) throws Exception { Handler . configName = configName ; config = ( HandlerConfig ) Config . getInstance ( ) . getJsonObjectConfig ( configName , HandlerConfig . class ) ; initHandlers ( ) ; initPaths ( ) ; }
Exposed for testing only .
15,866
public IClientRequestComposable getComposer ( ClientRequestComposers composerName ) { IClientRequestComposable composer = composersMap . get ( composerName ) ; if ( composer == null ) { initDefaultComposer ( composerName ) ; } return composersMap . get ( composerName ) ; }
get IClientRequestComposable based on ClientRequestComposers composer name
15,867
public double getMean ( ) { if ( values . length == 0 ) { return 0 ; } double sum = 0 ; for ( int i = 0 ; i < values . length ; i ++ ) { sum += values [ i ] * normWeights [ i ] ; } return sum ; }
Returns the weighted arithmetic mean of the values in the snapshot .
15,868
public double getStdDev ( ) { if ( values . length <= 1 ) { return 0 ; } final double mean = getMean ( ) ; double variance = 0 ; for ( int i = 0 ; i < values . length ; i ++ ) { final double diff = values [ i ] - mean ; variance += normWeights [ i ] * diff * diff ; } return Math . sqrt ( variance ) ; }
Returns the weighted standard deviation of the values in the snapshot .
15,869
public void validate ( String origin ) { List < String > problems = new ArrayList < > ( ) ; if ( source == null ) { if ( path == null ) { problems . add ( "You must specify either path or source" ) ; } else if ( method == null ) { problems . add ( "You must specify method along with path: " + path ) ; } } else { if ( path != null ) { problems . add ( "Conflicting source: " + source + " and path: " + path ) ; } if ( method != null ) { problems . add ( "Conflicting source: " + source + " and method: " + method ) ; } } if ( method != null && ! Util . METHODS . contains ( method . toUpperCase ( ) ) ) { problems . add ( "Invalid HTTP method: " + method ) ; } if ( ! problems . isEmpty ( ) ) { throw new RuntimeException ( "Bad paths element in " + origin + " [ " + String . join ( " | " , problems ) + " ]" ) ; } }
Validate the settings and raise Exception on error . The origin is used to help locate problems .
15,870
private void startListenerThreadIfNewService ( URL url ) { String serviceName = url . getPath ( ) ; if ( ! lookupServices . containsKey ( serviceName ) ) { Long value = lookupServices . putIfAbsent ( serviceName , 0L ) ; if ( value == null ) { ServiceLookupThread lookupThread = new ServiceLookupThread ( serviceName ) ; lookupThread . setDaemon ( true ) ; lookupThread . start ( ) ; } } }
if new service registered start a new lookup thread each serviceName start a lookup thread to discover service
15,871
private ConsulResponse < List < ConsulService > > lookupConsulService ( String serviceName , Long lastConsulIndexId ) { ConsulResponse < List < ConsulService > > response = client . lookupHealthService ( serviceName , null , lastConsulIndexId , getConsulToken ( ) ) ; return response ; }
directly fetch consul service data .
15,872
private void updateServiceCache ( String serviceName , ConcurrentHashMap < String , List < URL > > serviceUrls , boolean needNotify ) { if ( serviceUrls != null && ! serviceUrls . isEmpty ( ) ) { List < URL > urls = serviceCache . get ( serviceName ) ; if ( urls == null ) { if ( logger . isDebugEnabled ( ) ) { try { logger . debug ( "serviceUrls = " + Config . getInstance ( ) . getMapper ( ) . writeValueAsString ( serviceUrls ) ) ; } catch ( Exception e ) { } } serviceCache . put ( serviceName , serviceUrls . get ( serviceName ) ) ; } for ( Map . Entry < String , List < URL > > entry : serviceUrls . entrySet ( ) ) { boolean change = true ; if ( urls != null ) { List < URL > newUrls = entry . getValue ( ) ; if ( newUrls == null || newUrls . isEmpty ( ) || ConsulUtils . isSame ( newUrls , urls ) ) { change = false ; } else { serviceCache . put ( serviceName , newUrls ) ; } } if ( change && needNotify ) { notifyExecutor . execute ( new NotifyService ( entry . getKey ( ) , entry . getValue ( ) ) ) ; logger . info ( "light service notify-service: " + entry . getKey ( ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( URL url : entry . getValue ( ) ) { sb . append ( url . getUri ( ) ) . append ( ";" ) ; } logger . info ( "consul notify urls:" + sb . toString ( ) ) ; } } } }
update service cache of the serviceName . update local cache when service list changed if need notify notify service
15,873
public static void verifyAndThrow ( final Set < String > nameSet , final X509Certificate cert ) throws CertificateException { if ( ! verify ( nameSet , cert ) ) { throw new CertificateException ( "No name matching " + nameSet + " found" ) ; } }
Perform server identify check using given names and throw CertificateException if the check fails .
15,874
public static void verifyAndThrow ( final String name , final X509Certificate cert ) throws CertificateException { if ( ! verify ( name , cert ) ) { throw new CertificateException ( "No name matching " + name + " found" ) ; } }
Perform server identify check using given name and throw CertificateException if the check fails .
15,875
public void addAuthToken ( ClientRequest request , String token ) { if ( token != null && ! token . startsWith ( "Bearer " ) ) { if ( token . toUpperCase ( ) . startsWith ( "BEARER " ) ) { token = "Bearer " + token . substring ( 7 ) ; } else { token = "Bearer " + token ; } } request . getRequestHeaders ( ) . put ( Headers . AUTHORIZATION , token ) ; }
Add Authorization Code grant token the caller app gets from OAuth2 server .
15,876
public void addAuthTokenTrace ( ClientRequest request , String token , String traceabilityId ) { if ( token != null && ! token . startsWith ( "Bearer " ) ) { if ( token . toUpperCase ( ) . startsWith ( "BEARER " ) ) { token = "Bearer " + token . substring ( 7 ) ; } else { token = "Bearer " + token ; } } request . getRequestHeaders ( ) . put ( Headers . AUTHORIZATION , token ) ; request . getRequestHeaders ( ) . put ( HttpStringConstants . TRACEABILITY_ID , traceabilityId ) ; }
Add Authorization Code grant token the caller app gets from OAuth2 server and add traceabilityId
15,877
public Result propagateHeaders ( ClientRequest request , final HttpServerExchange exchange ) { String tid = exchange . getRequestHeaders ( ) . getFirst ( HttpStringConstants . TRACEABILITY_ID ) ; String token = exchange . getRequestHeaders ( ) . getFirst ( Headers . AUTHORIZATION ) ; String cid = exchange . getRequestHeaders ( ) . getFirst ( HttpStringConstants . CORRELATION_ID ) ; return populateHeader ( request , token , cid , tid ) ; }
Support API to API calls with scope token . The token is the original token from consumer and the client credentials token of caller API is added from cache .
15,878
public Result populateHeader ( ClientRequest request , String authToken , String correlationId , String traceabilityId ) { if ( traceabilityId != null ) { addAuthTokenTrace ( request , authToken , traceabilityId ) ; } else { addAuthToken ( request , authToken ) ; } Result < Jwt > result = tokenManager . getJwt ( request ) ; if ( result . isFailure ( ) ) { return Failure . of ( result . getError ( ) ) ; } request . getRequestHeaders ( ) . put ( HttpStringConstants . CORRELATION_ID , correlationId ) ; request . getRequestHeaders ( ) . put ( HttpStringConstants . SCOPE_TOKEN , "Bearer " + result . getResult ( ) . getJwt ( ) ) ; return result ; }
Support API to API calls with scope token . The token is the original token from consumer and the client credentials token of caller API is added from cache . authToken correlationId and traceabilityId are passed in as strings .
15,879
public static SSLContext createSSLContext ( ) throws IOException { Map < String , Object > tlsMap = ( Map < String , Object > ) ClientConfig . get ( ) . getMappedConfig ( ) . get ( TLS ) ; return null == tlsMap ? null : createSSLContext ( ( String ) tlsMap . get ( TLSConfig . DEFAULT_GROUP_KEY ) ) ; }
default method for creating ssl context . trustedNames config is not used .
15,880
public CompletableFuture < ClientConnection > connectAsync ( URI uri ) { return this . connectAsync ( null , uri , com . networknt . client . Http2Client . WORKER , com . networknt . client . Http2Client . SSL , com . networknt . client . Http2Client . BUFFER_POOL , OptionMap . create ( UndertowOptions . ENABLE_HTTP2 , true ) ) ; }
Create async connection with default config value
15,881
static char [ ] toCharArray ( final CharSequence cs ) { if ( cs instanceof String ) { return ( ( String ) cs ) . toCharArray ( ) ; } final int sz = cs . length ( ) ; final char [ ] array = new char [ cs . length ( ) ] ; for ( int i = 0 ; i < sz ; i ++ ) { array [ i ] = cs . charAt ( i ) ; } return array ; }
Green implementation of toCharArray .
15,882
static boolean regionMatches ( final CharSequence cs , final boolean ignoreCase , final int thisStart , final CharSequence substring , final int start , final int length ) { if ( cs instanceof String && substring instanceof String ) { return ( ( String ) cs ) . regionMatches ( ignoreCase , thisStart , ( String ) substring , start , length ) ; } int index1 = thisStart ; int index2 = start ; int tmpLen = length ; final int srcLen = cs . length ( ) - thisStart ; final int otherLen = substring . length ( ) - start ; if ( thisStart < 0 || start < 0 || length < 0 ) { return false ; } if ( srcLen < length || otherLen < length ) { return false ; } while ( tmpLen -- > 0 ) { final char c1 = cs . charAt ( index1 ++ ) ; final char c2 = substring . charAt ( index2 ++ ) ; if ( c1 == c2 ) { continue ; } if ( ! ignoreCase ) { return false ; } if ( Character . toUpperCase ( c1 ) != Character . toUpperCase ( c2 ) && Character . toLowerCase ( c1 ) != Character . toLowerCase ( c2 ) ) { return false ; } } return true ; }
Green implementation of regionMatches .
15,883
private static FileSystem createZipFileSystem ( String zipFilename , boolean create ) throws IOException { final Path path = Paths . get ( zipFilename ) ; if ( Files . notExists ( path . getParent ( ) ) ) { Files . createDirectories ( path . getParent ( ) ) ; } final URI uri = URI . create ( "jar:file:" + path . toUri ( ) . getPath ( ) ) ; final Map < String , String > env = new HashMap < > ( ) ; if ( create ) { env . put ( "create" , "true" ) ; } return FileSystems . newFileSystem ( uri , env ) ; }
Returns a zip file system
15,884
public static void list ( String zipFilename ) throws IOException { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Listing Archive: %s" , zipFilename ) ; try ( FileSystem zipFileSystem = createZipFileSystem ( zipFilename , false ) ) { final Path root = zipFileSystem . getPath ( "/" ) ; Files . walkFileTree ( root , new SimpleFileVisitor < Path > ( ) { public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { print ( file ) ; return FileVisitResult . CONTINUE ; } public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { print ( dir ) ; return FileVisitResult . CONTINUE ; } private void print ( Path file ) throws IOException { final DateFormat df = new SimpleDateFormat ( "MM/dd/yyyy-HH:mm:ss" ) ; final String modTime = df . format ( new Date ( Files . getLastModifiedTime ( file ) . toMillis ( ) ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "%d %s %s" , Files . size ( file ) , modTime , file ) ; } } } ) ; } }
List the contents of the specified zip file
15,885
public static void deleteOldFiles ( String dirPath , int olderThanMinute ) { File folder = new File ( dirPath ) ; if ( folder . exists ( ) ) { File [ ] listFiles = folder . listFiles ( ) ; long eligibleForDeletion = System . currentTimeMillis ( ) - ( olderThanMinute * 60 * 1000L ) ; for ( File listFile : listFiles ) { if ( listFile . lastModified ( ) < eligibleForDeletion ) { if ( ! listFile . delete ( ) ) { logger . error ( "Unable to delete file %s" , listFile ) ; } } } } }
Delele old files
15,886
public static ByteBuffer toByteBuffer ( String s ) { ByteBuffer buffer = ByteBuffer . allocateDirect ( s . length ( ) ) ; buffer . put ( s . getBytes ( UTF_8 ) ) ; buffer . flip ( ) ; return buffer ; }
convert String to ByteBuffer
15,887
public static ByteBuffer toByteBuffer ( File file ) { ByteBuffer buffer = ByteBuffer . allocateDirect ( ( int ) file . length ( ) ) ; try { buffer . put ( toByteArray ( new FileInputStream ( file ) ) ) ; } catch ( IOException e ) { logger . error ( "Failed to write file to byte array: " + e . getMessage ( ) ) ; } buffer . flip ( ) ; return buffer ; }
Convert a File into a ByteBuffer
15,888
public static String getTempDir ( ) { String tempDir = System . getProperty ( "user.home" ) ; try { File temp = File . createTempFile ( "A0393939" , ".tmp" ) ; String absolutePath = temp . getAbsolutePath ( ) ; tempDir = absolutePath . substring ( 0 , absolutePath . lastIndexOf ( File . separator ) ) ; } catch ( IOException e ) { } return tempDir ; }
get temp dir from OS .
15,889
public static byte [ ] toByteArray ( InputStream is ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; try { byte [ ] b = new byte [ BUFFER_SIZE ] ; int n = 0 ; while ( ( n = is . read ( b ) ) != - 1 ) { output . write ( b , 0 , n ) ; } return output . toByteArray ( ) ; } finally { output . close ( ) ; } }
Reads and returns the rest of the given input stream as a byte array . Caller is responsible for closing the given input stream .
15,890
public static Object getInjectValue ( String string ) { Matcher m = pattern . matcher ( string ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { Object value = getValue ( m . group ( 1 ) ) ; if ( ! ( value instanceof String ) ) { return value ; } m . appendReplacement ( sb , ( String ) value ) ; } return m . appendTail ( sb ) . toString ( ) ; }
Method used to generate the values from environment variables or values . yaml
15,891
public static boolean isExclusionConfigFile ( String configName ) { List < Object > exclusionConfigFileList = ( exclusionMap == null ) ? new ArrayList < > ( ) : ( List < Object > ) exclusionMap . get ( EXCLUSION_CONFIG_FILE_LIST ) ; return CENTRALIZED_MANAGEMENT . equals ( configName ) || SCALABLE_CONFIG . equals ( configName ) || exclusionConfigFileList . contains ( configName ) ; }
Double check values and exclusions to ensure no dead loop
15,892
private static Object typeCast ( String str ) { if ( str == null || str . equals ( "" ) ) { return null ; } for ( String trueString : trueArray ) { if ( trueString . equals ( str ) ) { return true ; } } for ( String falseString : falseArray ) { if ( falseString . equals ( str ) ) { return false ; } } try { return Integer . parseInt ( str ) ; } catch ( Exception e1 ) { try { return Double . parseDouble ( str ) ; } catch ( Exception e2 ) { return str ; } } }
Method used to cast string into int double or boolean
15,893
public List < IRequestDumpable > createRequestDumpers ( DumpConfig config , HttpServerExchange exchange ) { RequestDumperFactory factory = new RequestDumperFactory ( ) ; List < IRequestDumpable > dumpers = new ArrayList < > ( ) ; for ( String dumperNames : requestDumpers ) { IRequestDumpable dumper = factory . create ( dumperNames , config , exchange ) ; dumpers . add ( dumper ) ; } return dumpers ; }
use RequestDumperFactory to create dumpers listed in this . requestDumpers
15,894
public List < IResponseDumpable > createResponseDumpers ( DumpConfig config , HttpServerExchange exchange ) { ResponseDumperFactory factory = new ResponseDumperFactory ( ) ; List < IResponseDumpable > dumpers = new ArrayList < > ( ) ; for ( String dumperNames : responseDumpers ) { IResponseDumpable dumper = factory . create ( dumperNames , config , exchange ) ; dumpers . add ( dumper ) ; } return dumpers ; }
use ResponseDumperFactory to create dumpers listed in this . responseDumpers
15,895
public static String defaultOrigin ( HttpServerExchange exchange ) { String host = NetworkUtils . formatPossibleIpv6Address ( exchange . getHostName ( ) ) ; String protocol = exchange . getRequestScheme ( ) ; int port = exchange . getHostPort ( ) ; StringBuilder allowedOrigin = new StringBuilder ( 256 ) ; allowedOrigin . append ( protocol ) . append ( "://" ) . append ( host ) ; if ( ! isDefaultPort ( port , protocol ) ) { allowedOrigin . append ( ':' ) . append ( port ) ; } return allowedOrigin . toString ( ) ; }
Determine the default origin to allow for local access .
15,896
public static String sanitizeDefaultPort ( String url ) { int afterSchemeIndex = url . indexOf ( "://" ) ; if ( afterSchemeIndex < 0 ) { return url ; } String scheme = url . substring ( 0 , afterSchemeIndex ) ; int fromIndex = scheme . length ( ) + 3 ; int ipv6StartIndex = url . indexOf ( '[' , fromIndex ) ; if ( ipv6StartIndex > 0 ) { fromIndex = url . indexOf ( ']' , ipv6StartIndex ) ; } int portIndex = url . indexOf ( ':' , fromIndex ) ; if ( portIndex >= 0 ) { int port = Integer . parseInt ( url . substring ( portIndex + 1 ) ) ; if ( isDefaultPort ( port , scheme ) ) { return url . substring ( 0 , portIndex ) ; } } return url ; }
Removes the port from a URL if this port is the default one for the URL s scheme .
15,897
public void addFirst ( PropertySource < ? > propertySource ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Adding PropertySource '" + propertySource . getName ( ) + "' with highest search precedence" ) ; } removeIfPresent ( propertySource ) ; this . propertySourceList . add ( 0 , propertySource ) ; }
Add the given property source object with highest precedence .
15,898
public void addBefore ( String relativePropertySourceName , PropertySource < ? > propertySource ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Adding PropertySource '" + propertySource . getName ( ) + "' with search precedence immediately higher than '" + relativePropertySourceName + "'" ) ; } assertLegalRelativeAddition ( relativePropertySourceName , propertySource ) ; removeIfPresent ( propertySource ) ; int index = assertPresentAndGetIndex ( relativePropertySourceName ) ; addAtIndex ( index , propertySource ) ; }
Add the given property source object with precedence immediately higher than the named relative property source .
15,899
public void replace ( String name , PropertySource < ? > propertySource ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Replacing PropertySource '" + name + "' with '" + propertySource . getName ( ) + "'" ) ; } int index = assertPresentAndGetIndex ( name ) ; this . propertySourceList . set ( index , propertySource ) ; }
Replace the property source with the given name with the given property source object .