idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
31,000 | public SimpleUriRouter < I , O > addUriRegex ( String uriRegEx , RequestHandler < I , O > handler ) { routes . add ( new Route ( new RegexUriConstraintKey < I > ( uriRegEx ) , handler ) ) ; return this ; } | Add a new URI regex - < ; Handler route to this router . |
31,001 | public DynaTreeNode getDomainTree ( String domainName ) { DynaTreeNode domainNode = new DynaTreeNode ( ) . setTitle ( domainName ) . setKey ( domainName ) . setMode ( MODE_DOMAIN ) ; try { ObjectName name = new ObjectName ( domainName + ":*" ) ; Set < ObjectName > objs = mBeanServer . queryNames ( name , null ) ; for ( ObjectName objName : objs ) { MBeanInfo info = mBeanServer . getMBeanInfo ( objName ) ; Matcher m = csvRE . matcher ( objName . getKeyPropertyListString ( ) ) ; DynaTreeNode node = domainNode ; StringBuilder innerKey = new StringBuilder ( ) ; innerKey . append ( domainName ) . append ( ":" ) ; while ( m . find ( ) ) { String title = StringUtils . removeEnd ( m . group ( ) , "," ) ; String key = StringUtils . substringBefore ( title , "=" ) ; String value = StringUtils . substringAfter ( title , "=" ) ; value = StringUtils . removeStart ( value , "\"" ) ; value = StringUtils . removeEnd ( value , "\"" ) ; innerKey . append ( title ) . append ( "," ) ; DynaTreeNode next = node . getChild ( value ) ; if ( next == null ) { next = new DynaTreeNode ( ) . setTitle ( value ) . setMode ( MODE_INNER ) . setKey ( innerKey . toString ( ) + "*" ) . setNoLink ( false ) ; node . putChild ( next ) ; } node = next ; } node . setKey ( objName . getCanonicalName ( ) ) . setMode ( MODE_LEAF ) ; if ( info . getAttributes ( ) != null || info . getOperations ( ) != null || info . getNotifications ( ) != null ) { node . setNoLink ( false ) ; } } } catch ( MalformedObjectNameException e ) { LOG . error ( "Exception in getDomainTree " , e ) ; } catch ( IntrospectionException e ) { LOG . error ( "Exception in getDomainTree " , e ) ; } catch ( ReflectionException e ) { LOG . error ( "Exception in getDomainTree " , e ) ; } catch ( InstanceNotFoundException e ) { LOG . error ( "Exception in getDomainTree " , e ) ; } catch ( RuntimeException e ) { LOG . error ( "Exception in getDomainTree " , e ) ; } return domainNode ; } | Return subtree of nodes for a domain |
31,002 | public List < String > getKeysFromRegex ( String regex ) { List < String > keys = Lists . newArrayList ( ) ; try { ObjectName name = new ObjectName ( regex ) ; Set < ObjectName > objs = mBeanServer . queryNames ( name , null ) ; for ( ObjectName objName : objs ) { MBeanInfo info = mBeanServer . getMBeanInfo ( objName ) ; keys . add ( objName . getCanonicalName ( ) ) ; } } catch ( Exception e ) { LOG . error ( "Exception in getKeysFromRegex " , e ) ; } return keys ; } | Return the list of all keys matching a regex |
31,003 | public Map < String , Map < String , String > > getMBeanAttributesByRegex ( String regex ) throws Exception { Map < String , Map < String , String > > result = Maps . newLinkedHashMap ( ) ; ObjectName name = new ObjectName ( regex ) ; Set < ObjectName > objs = mBeanServer . queryNames ( name , null ) ; for ( ObjectName objName : objs ) { result . put ( objName . getCanonicalName ( ) , getMBeanAttributes ( objName ) ) ; } return result ; } | Return a map of all attributes for objects matching the regex . |
31,004 | public Map < String , String > getMBeanAttributes ( String key ) throws Exception { return getMBeanAttributes ( new ObjectName ( key ) ) ; } | Get list of all attributes of the specified key |
31,005 | private Map < String , String > getMBeanAttributes ( ObjectName objName ) throws Exception { Map < String , String > response = Maps . newLinkedHashMap ( ) ; MBeanInfo mBeanInfo = mBeanServer . getMBeanInfo ( objName ) ; if ( mBeanInfo != null ) { MBeanAttributeInfo [ ] attrs = mBeanInfo . getAttributes ( ) ; if ( attrs != null ) { List < String > attrNames = Lists . newArrayList ( ) ; for ( MBeanAttributeInfo attr : attrs ) { attrNames . add ( attr . getName ( ) ) ; } AttributeList attrList = mBeanServer . getAttributes ( objName , attrNames . toArray ( new String [ 0 ] ) ) ; for ( Attribute attr : attrList . asList ( ) ) { String attrName = attr . getName ( ) ; Object value = attr . getValue ( ) ; String attrValue = null ; if ( value != null ) { if ( value instanceof CompositeDataSupport ) { CompositeDataSupport compositeValue = ( CompositeDataSupport ) value ; if ( compositeValue != null ) { try { if ( compositeValue . containsKey ( CURRENT_VALUE ) ) { Object curValue = compositeValue . get ( CURRENT_VALUE ) ; attrValue = ( curValue == null ? "null" : curValue . toString ( ) ) ; } } catch ( Exception e ) { attrValue = compositeValue . toString ( ) ; } } } if ( attrValue == null ) { attrValue = value . toString ( ) ; } } else { value = "none" ; } response . put ( attrName , attrValue ) ; } } } return response ; } | Get list of all attributes of an object |
31,006 | public MBeanOperationInfo [ ] getMBeanOperations ( String name ) throws Exception { MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; MBeanInfo mBeanInfo = mBeanServer . getMBeanInfo ( new ObjectName ( name ) ) ; return mBeanInfo . getOperations ( ) ; } | Return all operations for the specified mbean name |
31,007 | private Iterable < Binding < ? > > getBindings ( Injector injector , Set < Key < ? > > root ) { Set < Key < ? > > keys = Sets . newHashSet ( root ) ; Set < Key < ? > > visitedKeys = Sets . newHashSet ( ) ; List < Binding < ? > > bindings = Lists . newArrayList ( ) ; TransitiveDependencyVisitor keyVisitor = new TransitiveDependencyVisitor ( ) ; while ( ! keys . isEmpty ( ) ) { Iterator < Key < ? > > iterator = keys . iterator ( ) ; Key < ? > key = iterator . next ( ) ; iterator . remove ( ) ; if ( ! visitedKeys . contains ( key ) ) { try { Binding < ? > binding = injector . getBinding ( key ) ; bindings . add ( binding ) ; visitedKeys . add ( key ) ; keys . addAll ( binding . acceptTargetVisitor ( keyVisitor ) ) ; } catch ( ConfigurationException e ) { System . out . println ( "Missing binding for : " + key ) ; visitedKeys . add ( key ) ; } } } return bindings ; } | Returns the bindings for the root keys and their transitive dependencies . |
31,008 | public Response getMBeans ( @ QueryParam ( "key" ) @ DefaultValue ( "root" ) String key , @ QueryParam ( "mode" ) @ DefaultValue ( "" ) String mode , @ QueryParam ( "jsonp" ) @ DefaultValue ( "" ) String jsonp ) throws Exception { LOG . info ( "key" + key ) ; DynaTreeNode root = new DynaTreeNode ( ) ; for ( String domain : jmx . getDomainList ( ) ) { root . putChild ( jmx . getDomainTree ( domain ) . setTitle ( domain ) . setMode ( "domain" ) ) ; } StringWriter out = new StringWriter ( ) ; if ( jsonp . isEmpty ( ) ) { root . getChildrenJSONArray ( ) . write ( out ) ; } else { out . append ( jsonp ) . append ( "(" ) ; root . getChildrenJSONArray ( ) . write ( out ) ; out . append ( ");" ) ; } return Response . ok ( out . toString ( ) ) . header ( "Pragma" , "no-cache" ) . header ( "Cache-Control" , "no-cache" ) . header ( "Expires" , "0" ) . build ( ) ; } | Return JSON representing the entire tree of MBeans in DynaTree format . |
31,009 | @ Path ( "{key}" ) public Response getMBean ( @ PathParam ( "key" ) String key , @ QueryParam ( "jsonp" ) @ DefaultValue ( "" ) String jsonp ) throws Exception { LOG . info ( "key: " + key ) ; JSONObject json = new JSONObject ( ) ; ObjectName name = new ObjectName ( key ) ; json . put ( "domain" , name . getDomain ( ) ) ; json . put ( "property" , name . getKeyPropertyList ( ) ) ; if ( key . contains ( "*" ) ) { JSONObject keys = new JSONObject ( ) ; for ( Entry < String , Map < String , String > > attrs : jmx . getMBeanAttributesByRegex ( key ) . entrySet ( ) ) { keys . put ( attrs . getKey ( ) , attrs . getValue ( ) ) ; } json . put ( "attributes" , keys ) ; json . put ( "multikey" , true ) ; } else { json . put ( "attributes" , jmx . getMBeanAttributes ( key ) ) ; json . put ( "multikey" , false ) ; MBeanOperationInfo [ ] operations = jmx . getMBeanOperations ( key ) ; JSONArray ar = new JSONArray ( ) ; for ( MBeanOperationInfo operation : operations ) { JSONObject obj = new JSONObject ( ) ; obj . put ( "name" , operation . getName ( ) ) ; obj . put ( "description" , operation . getDescription ( ) ) ; obj . put ( "returnType" , operation . getReturnType ( ) ) ; obj . put ( "impact" , operation . getImpact ( ) ) ; JSONArray params = new JSONArray ( ) ; for ( MBeanParameterInfo param : operation . getSignature ( ) ) { JSONObject p = new JSONObject ( ) ; p . put ( "name" , param . getName ( ) ) ; p . put ( "type" , param . getType ( ) ) ; params . put ( p ) ; } obj . put ( "params" , params ) ; ar . put ( obj ) ; } json . put ( "operations" , ar ) ; } StringWriter out = new StringWriter ( ) ; if ( jsonp . isEmpty ( ) ) { json . write ( out ) ; } else { out . append ( jsonp ) . append ( "(" ) ; json . write ( out ) ; out . append ( ");" ) ; } return Response . ok ( out . toString ( ) ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } | Return all the attributes and operations for a single mbean |
31,010 | @ Consumes ( MediaType . APPLICATION_FORM_URLENCODED ) @ Path ( "{key}/{op}" ) public Response invokeMbeanOperation ( MultivaluedMap < String , String > formParams , @ PathParam ( "key" ) String key , @ QueryParam ( "jsonp" ) String jsonp , @ PathParam ( "op" ) String name ) throws Exception { LOG . info ( "invoke " + key + " op=" + name ) ; MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; Map < String , String > params = new TreeMap < String , String > ( ) ; for ( Entry < String , List < String > > entry : formParams . entrySet ( ) ) { if ( entry . getKey ( ) . equals ( "op" ) ) continue ; if ( entry . getValue ( ) . size ( ) > 0 ) params . put ( entry . getKey ( ) , entry . getValue ( ) . get ( 0 ) ) ; else params . put ( entry . getKey ( ) , "" ) ; } ObjectName objName = new ObjectName ( key ) ; MBeanInfo info = mBeanServer . getMBeanInfo ( objName ) ; for ( MBeanOperationInfo op : info . getOperations ( ) ) { if ( op . getName ( ) . equals ( name ) ) { List < String > signature = new ArrayList < String > ( ) ; for ( MBeanParameterInfo s : op . getSignature ( ) ) { signature . add ( s . getType ( ) ) ; } Object result = mBeanServer . invoke ( objName , name , params . values ( ) . toArray ( new String [ params . size ( ) ] ) , signature . toArray ( new String [ signature . size ( ) ] ) ) ; JSONObject json = new JSONObject ( ) ; json . put ( "key" , key ) ; json . put ( "operation" , name ) ; if ( result != null ) { json . put ( "response" , result . toString ( ) ) ; } json . put ( "type" , op . getReturnType ( ) ) ; StringWriter out = new StringWriter ( ) ; if ( jsonp . isEmpty ( ) ) { json . write ( out ) ; } else { out . append ( jsonp ) . append ( "(" ) ; json . write ( out ) ; out . append ( ");" ) ; } return Response . ok ( out . toString ( ) ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } } return Response . serverError ( ) . build ( ) ; } | Execute an operation on an mbean . |
31,011 | private JSONObject emitAttributes ( ObjectName objName ) throws Exception { MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; MBeanInfo mBeanInfo = mBeanServer . getMBeanInfo ( objName ) ; JSONObject resp = new JSONObject ( ) ; if ( mBeanInfo != null ) { MBeanAttributeInfo [ ] attrs = mBeanInfo . getAttributes ( ) ; if ( attrs != null ) { List < String > attrNames = new ArrayList < String > ( attrs . length ) ; for ( MBeanAttributeInfo attr : attrs ) { attrNames . add ( attr . getName ( ) ) ; } AttributeList attrList = mBeanServer . getAttributes ( objName , attrNames . toArray ( new String [ 0 ] ) ) ; for ( Attribute attr : attrList . asList ( ) ) { Object value = attr . getValue ( ) ; String attrName = attr . getName ( ) ; if ( attrName != null && value != null ) { String attrValue = null ; if ( value instanceof CompositeDataSupport ) { CompositeDataSupport compositeValue = ( CompositeDataSupport ) value ; if ( compositeValue != null ) { try { if ( compositeValue . containsKey ( CURRENT_VALUE ) ) { Object curValue = compositeValue . get ( CURRENT_VALUE ) ; attrValue = ( curValue == null ? "null" : curValue . toString ( ) ) ; } } catch ( Exception e ) { attrValue = compositeValue . toString ( ) ; } } } if ( attrValue == null ) { attrValue = value . toString ( ) ; } resp . put ( attrName , ( attrValue == null ? "null" : attrValue ) ) ; } } } } return resp ; } | Generate JSON for the MBean attributes |
31,012 | private JSONArray emitOperations ( ObjectName objName ) throws Exception { MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; MBeanInfo mBeanInfo = mBeanServer . getMBeanInfo ( objName ) ; JSONArray ar = new JSONArray ( ) ; MBeanOperationInfo [ ] operations = mBeanInfo . getOperations ( ) ; for ( MBeanOperationInfo operation : operations ) { JSONObject obj = new JSONObject ( ) ; obj . put ( "name" , operation . getName ( ) ) ; obj . put ( "description" , operation . getDescription ( ) ) ; obj . put ( "returnType" , operation . getReturnType ( ) ) ; obj . put ( "impact" , operation . getImpact ( ) ) ; JSONArray params = new JSONArray ( ) ; for ( MBeanParameterInfo param : operation . getSignature ( ) ) { JSONObject p = new JSONObject ( ) ; p . put ( "name" , param . getName ( ) ) ; p . put ( "type" , param . getType ( ) ) ; params . put ( p ) ; } obj . put ( "params" , params ) ; ar . put ( obj ) ; } return ar ; } | Generate JSON for the MBean operations |
31,013 | public static void link ( File source , File target ) throws IOException { if ( UtilJNI . ON_WINDOWS == 1 ) { if ( UtilJNI . CreateHardLinkW ( target . getCanonicalPath ( ) , source . getCanonicalPath ( ) , 0 ) == 0 ) { throw new IOException ( "link failed" ) ; } } else { if ( UtilJNI . link ( source . getCanonicalPath ( ) , target . getCanonicalPath ( ) ) != 0 ) { throw new IOException ( "link failed: " + strerror ( ) ) ; } } } | Creates a hard link from source to target . |
31,014 | private void stopBluetooth ( ) { Log . d ( TAG , "stopBluetooth" ) ; if ( mIsCountDownOn ) { mIsCountDownOn = false ; mCountDown . cancel ( ) ; } mContext . unregisterReceiver ( mBroadcastReceiver ) ; mAudioManager . stopBluetoothSco ( ) ; mAudioManager . setMode ( AudioManager . MODE_NORMAL ) ; } | Unregister broadcast receivers and stop Sco audio connection and cancel count down . |
31,015 | public static AIService getService ( final Context context , final AIConfiguration config ) { if ( config . getRecognitionEngine ( ) == AIConfiguration . RecognitionEngine . Google ) { return new GoogleRecognitionServiceImpl ( context , config ) ; } if ( config . getRecognitionEngine ( ) == AIConfiguration . RecognitionEngine . System ) { return new GoogleRecognitionServiceImpl ( context , config ) ; } else if ( config . getRecognitionEngine ( ) == AIConfiguration . RecognitionEngine . Speaktoit ) { return new SpeaktoitRecognitionServiceImpl ( context , config ) ; } else { throw new UnsupportedOperationException ( "This engine still not supported" ) ; } } | Use this method to get ready to work instance |
31,016 | private void updateStopRunnable ( final int action ) { if ( stopRunnable != null ) { if ( action == 0 ) { handler . removeCallbacks ( stopRunnable ) ; } else if ( action == 1 ) { handler . removeCallbacks ( stopRunnable ) ; handler . postDelayed ( stopRunnable , STOP_DELAY ) ; } } } | Manage recognizer cancellation runnable . |
31,017 | public View findChildView ( float x , float y ) { final int count = getChildCount ( ) ; if ( y <= 0 && count > 0 ) { return getChildAt ( 0 ) ; } for ( int i = count - 1 ; i >= 0 ; i -- ) { final View child = getChildAt ( i ) ; MarginLayoutParams params = ( MarginLayoutParams ) child . getLayoutParams ( ) ; if ( x >= child . getLeft ( ) - params . leftMargin && x <= child . getRight ( ) + params . rightMargin && y >= child . getTop ( ) - params . topMargin && y <= child . getBottom ( ) + params . bottomMargin ) { return child ; } } return null ; } | Returns the child view under the specific x y coordinate . This method will take margins of the child into account when finding it . |
31,018 | public void setCustomDragItem ( DragItem dragItem ) { DragItem newDragItem = dragItem != null ? dragItem : new DragItem ( getContext ( ) ) ; newDragItem . setSnapToTouch ( mDragItem . isSnapToTouch ( ) ) ; mDragItem = newDragItem ; mRootLayout . removeViewAt ( 1 ) ; mRootLayout . addView ( mDragItem . getDragItemView ( ) ) ; } | Set a custom drag item to control the visuals and animations when dragging a list item . |
31,019 | public Map < String , List < String > > getHeaders ( ) { final Map < String , List < String > > headerMap = new TreeMap < > ( String . CASE_INSENSITIVE_ORDER ) ; final HttpHeaders headers = ahcResponse . getHeaders ( ) ; for ( String name : headers . names ( ) ) { final List < String > values = headers . getAll ( name ) ; headerMap . put ( name , values ) ; } return headerMap ; } | Get all the HTTP headers of the response as a case - insensitive map |
31,020 | public List < WSCookie > getCookies ( ) { return ahcResponse . getCookies ( ) . stream ( ) . map ( this :: asCookie ) . collect ( toList ( ) ) ; } | Get all the cookies . |
31,021 | public Optional < WSCookie > getCookie ( String name ) { for ( Cookie ahcCookie : ahcResponse . getCookies ( ) ) { if ( ahcCookie . name ( ) . equals ( name ) ) { return Optional . of ( asCookie ( ahcCookie ) ) ; } } return Optional . empty ( ) ; } | Get only one cookie using the cookie name . |
31,022 | public RequestToken retrieveRequestToken ( String callbackURL ) { OAuthConsumer consumer = new DefaultOAuthConsumer ( info . key . key , info . key . secret ) ; try { provider . retrieveRequestToken ( consumer , callbackURL ) ; return new RequestToken ( consumer . getToken ( ) , consumer . getTokenSecret ( ) ) ; } catch ( OAuthException ex ) { throw new RuntimeException ( ex ) ; } } | Request the request token and secret . |
31,023 | public RequestToken retrieveAccessToken ( RequestToken token , String verifier ) { OAuthConsumer consumer = new DefaultOAuthConsumer ( info . key . key , info . key . secret ) ; consumer . setTokenWithSecret ( token . token , token . secret ) ; try { provider . retrieveAccessToken ( consumer , verifier ) ; return new RequestToken ( consumer . getToken ( ) , consumer . getTokenSecret ( ) ) ; } catch ( OAuthException ex ) { throw new RuntimeException ( ex ) ; } } | Exchange a request token for an access token . |
31,024 | public String redirectUrl ( String token ) { return play . shaded . oauth . oauth . signpost . OAuth . addQueryParameters ( provider . getAuthorizationWebsiteUrl ( ) , play . shaded . oauth . oauth . signpost . OAuth . OAUTH_TOKEN , token ) ; } | The URL where the user needs to be redirected to grant authorization to your application . |
31,025 | public String getSubProtocolsAsCSV ( ) { if ( subProtocols == null ) { return null ; } String subProtocolsAsCSV = "" ; for ( String subProtocol : subProtocols ) { subProtocolsAsCSV = subProtocolsAsCSV . concat ( subProtocol + "," ) ; } subProtocolsAsCSV = subProtocolsAsCSV . substring ( 0 , subProtocolsAsCSV . length ( ) - 1 ) ; return subProtocolsAsCSV ; } | Get sub protocols as a comma separated values string . |
31,026 | public void setSubProtocols ( String [ ] subProtocols ) { if ( subProtocols == null || subProtocols . length == 0 ) { this . subProtocols = null ; return ; } this . subProtocols = Arrays . asList ( subProtocols ) ; } | Add sub protocols . |
31,027 | public void check ( Certificate cert , Collection < String > unresolvedCritExts ) throws CertPathValidatorException { RevocationStatus status ; try { status = verifier . checkRevocationStatus ( ( X509Certificate ) cert , nextIssuer ( ) ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Certificate status is: {}" , status . getMessage ( ) ) ; } if ( status != RevocationStatus . GOOD ) { throw new CertPathValidatorException ( "Revocation Status is Not Good" ) ; } } catch ( CertificateVerificationException e ) { throw new CertPathValidatorException ( e ) ; } } | Used by CertPathValidator to pass the certificates one by one from the certificate chain . |
31,028 | public static SenderConfiguration getSenderConfiguration ( TransportsConfiguration transportsConfiguration , String scheme ) { Map < String , SenderConfiguration > senderConfigurations = transportsConfiguration . getSenderConfigurations ( ) . stream ( ) . collect ( Collectors . toMap ( senderConf -> senderConf . getScheme ( ) . toLowerCase ( Locale . getDefault ( ) ) , config -> config ) ) ; return Constants . HTTPS_SCHEME . equals ( scheme ) ? senderConfigurations . get ( Constants . HTTPS_SCHEME ) : senderConfigurations . get ( Constants . HTTP_SCHEME ) ; } | Extract sender configuration from transport configuration . |
31,029 | public static Map < String , Object > getTransportProperties ( TransportsConfiguration transportsConfiguration ) { Map < String , Object > transportProperties = new HashMap < > ( ) ; Set < TransportProperty > transportPropertiesSet = transportsConfiguration . getTransportProperties ( ) ; if ( transportPropertiesSet != null && ! transportPropertiesSet . isEmpty ( ) ) { transportProperties = transportPropertiesSet . stream ( ) . collect ( Collectors . toMap ( TransportProperty :: getName , TransportProperty :: getValue ) ) ; } return transportProperties ; } | Extract transport properties from transport configurations . |
31,030 | public static ServerBootstrapConfiguration getServerBootstrapConfiguration ( Set < TransportProperty > transportPropertiesSet ) { Map < String , Object > transportProperties = new HashMap < > ( ) ; if ( transportPropertiesSet != null && ! transportPropertiesSet . isEmpty ( ) ) { transportProperties = transportPropertiesSet . stream ( ) . collect ( Collectors . toMap ( TransportProperty :: getName , TransportProperty :: getValue ) ) ; } return new ServerBootstrapConfiguration ( transportProperties ) ; } | Create server bootstrap configuration from given transport property set . |
31,031 | private boolean containsUpgradeHeaders ( HttpRequest httpRequest ) { HttpHeaders headers = httpRequest . headers ( ) ; return headers . containsValue ( HttpHeaderNames . CONNECTION , HttpHeaderValues . UPGRADE , true ) && headers . containsValue ( HttpHeaderNames . UPGRADE , HttpHeaderValues . WEBSOCKET , true ) ; } | Check the basic headers needed for WebSocket upgrade are contained in the request . |
31,032 | private void handleWebSocketHandshake ( FullHttpRequest fullHttpRequest , ChannelHandlerContext ctx ) throws WebSocketConnectorException { String extensionsHeader = fullHttpRequest . headers ( ) . getAsString ( HttpHeaderNames . SEC_WEBSOCKET_EXTENSIONS ) ; DefaultWebSocketHandshaker webSocketHandshaker = new DefaultWebSocketHandshaker ( ctx , serverConnectorFuture , fullHttpRequest , fullHttpRequest . uri ( ) , extensionsHeader != null ) ; webSocketHandshaker . setHttpCarbonRequest ( setupHttpCarbonRequest ( fullHttpRequest , ctx ) ) ; ctx . channel ( ) . config ( ) . setAutoRead ( false ) ; serverConnectorFuture . notifyWebSocketListener ( webSocketHandshaker ) ; } | Handle the WebSocket handshake . |
31,033 | public TargetChannel borrowTargetChannel ( HttpRoute httpRoute , SourceHandler sourceHandler , Http2SourceHandler http2SourceHandler , SenderConfiguration senderConfig , BootstrapConfiguration bootstrapConfig , EventLoopGroup clientEventGroup ) throws Exception { GenericObjectPool trgHlrConnPool ; String trgHlrConnPoolId = httpRoute . toString ( ) + connectionManagerId ; if ( sourceHandler != null ) { ChannelHandlerContext inboundChannelContext = sourceHandler . getInboundChannelContext ( ) ; trgHlrConnPool = getTrgHlrPoolFromGlobalPoolWithSrcPool ( httpRoute , senderConfig , bootstrapConfig , trgHlrConnPoolId , inboundChannelContext . channel ( ) . eventLoop ( ) , inboundChannelContext . channel ( ) . getClass ( ) , sourceHandler . getTargetChannelPool ( ) ) ; } else if ( http2SourceHandler != null ) { ChannelHandlerContext inboundChannelContext = http2SourceHandler . getInboundChannelContext ( ) ; trgHlrConnPool = getTrgHlrPoolFromGlobalPoolWithSrcPool ( httpRoute , senderConfig , bootstrapConfig , trgHlrConnPoolId , inboundChannelContext . channel ( ) . eventLoop ( ) , inboundChannelContext . channel ( ) . getClass ( ) , http2SourceHandler . getTargetChannelPool ( ) ) ; } else { trgHlrConnPool = getTrgHlrPoolFromGlobalPool ( httpRoute , senderConfig , bootstrapConfig , clientEventGroup ) ; } return getTargetChannel ( sourceHandler , http2SourceHandler , trgHlrConnPool , trgHlrConnPoolId ) ; } | Gets the client target channel pool . |
31,034 | public void validatePath ( ) throws CertificateVerificationException { Security . addProvider ( new BouncyCastleProvider ( ) ) ; CollectionCertStoreParameters params = new CollectionCertStoreParameters ( fullCertChain ) ; try { CertStore store = CertStore . getInstance ( "Collection" , params , Constants . BOUNCY_CASTLE_PROVIDER ) ; CertificateFactory fact = CertificateFactory . getInstance ( Constants . X_509 , Constants . BOUNCY_CASTLE_PROVIDER ) ; CertPath certPath = fact . generateCertPath ( certChain ) ; TrustAnchor trustAnchor = new TrustAnchor ( fullCertChain . get ( fullCertChain . size ( ) - 1 ) , null ) ; Set < TrustAnchor > trust = Collections . singleton ( trustAnchor ) ; CertPathValidator validator = CertPathValidator . getInstance ( Constants . ALGORITHM , Constants . BOUNCY_CASTLE_PROVIDER ) ; PKIXParameters param = new PKIXParameters ( trust ) ; param . addCertPathChecker ( pathChecker ) ; param . setRevocationEnabled ( false ) ; param . addCertStore ( store ) ; param . setDate ( new Date ( ) ) ; validator . validate ( certPath , param ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Certificate path validated" ) ; } } catch ( CertPathValidatorException e ) { throw new CertificateVerificationException ( "Certificate path validation failed on certificate number " + e . getIndex ( ) + ", details: " + e . getMessage ( ) , e ) ; } catch ( Exception e ) { throw new CertificateVerificationException ( "Certificate path validation failed" , e ) ; } } | Certificate Path Validation process |
31,035 | public synchronized void addHttpContent ( HttpContent httpContent ) { contentObservable . notifyAddListener ( httpContent ) ; if ( messageFuture != null ) { if ( ioException != null ) { blockingEntityCollector . addHttpContent ( new DefaultLastHttpContent ( ) ) ; messageFuture . notifyMessageListener ( blockingEntityCollector . getHttpContent ( ) ) ; removeMessageFuture ( ) ; throw new RuntimeException ( this . getIoException ( ) ) ; } contentObservable . notifyGetListener ( httpContent ) ; blockingEntityCollector . addHttpContent ( httpContent ) ; if ( messageFuture . isMessageListenerSet ( ) ) { messageFuture . notifyMessageListener ( blockingEntityCollector . getHttpContent ( ) ) ; } if ( httpContent instanceof LastHttpContent ) { removeMessageFuture ( ) ; } } else { if ( ioException != null ) { blockingEntityCollector . addHttpContent ( new DefaultLastHttpContent ( ) ) ; throw new RuntimeException ( this . getIoException ( ) ) ; } else { blockingEntityCollector . addHttpContent ( httpContent ) ; } } } | Add http content to HttpCarbonMessage . |
31,036 | public HttpContent getHttpContent ( ) { HttpContent httpContent = this . blockingEntityCollector . getHttpContent ( ) ; this . contentObservable . notifyGetListener ( httpContent ) ; return httpContent ; } | Get the available content of HttpCarbonMessage . |
31,037 | public void setHeader ( String key , Object value ) { this . httpMessage . headers ( ) . set ( key , value ) ; } | Set the header value for the given name . |
31,038 | public HttpResponseFuture pushResponse ( HttpCarbonMessage httpCarbonMessage , Http2PushPromise pushPromise ) throws ServerConnectorException { httpOutboundRespFuture . notifyHttpListener ( httpCarbonMessage , pushPromise ) ; return httpOutboundRespStatusFuture ; } | Sends a push response message back to the client . |
31,039 | public HttpCarbonMessage cloneCarbonMessageWithOutData ( ) { HttpCarbonMessage newCarbonMessage = getNewHttpCarbonMessage ( ) ; Map < String , Object > propertiesMap = this . getProperties ( ) ; propertiesMap . forEach ( newCarbonMessage :: setProperty ) ; return newCarbonMessage ; } | Copy Message properties and transport headers . |
31,040 | public void putInFlightMessage ( int streamId , OutboundMsgHolder inFlightMessage ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "In flight message added to channel: {} with stream id: {} " , this , streamId ) ; } inFlightMessages . put ( streamId , inFlightMessage ) ; } | Adds a in - flight message . |
31,041 | public OutboundMsgHolder getInFlightMessage ( int streamId ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Getting in flight message for stream id: {} from channel: {}" , streamId , this ) ; } return inFlightMessages . get ( streamId ) ; } | Gets the in - flight message associated with the a particular stream id . |
31,042 | public void removeInFlightMessage ( int streamId ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "In flight message for stream id: {} removed from channel: {}" , streamId , this ) ; } inFlightMessages . remove ( streamId ) ; } | Removes a in - flight message . |
31,043 | void destroy ( ) { this . connection . removeListener ( streamCloseListener ) ; inFlightMessages . clear ( ) ; promisedMessages . clear ( ) ; http2ConnectionManager . removeClientChannel ( httpRoute , this ) ; } | Destroys the Http2 client channel . |
31,044 | private void triggerPipeliningLogic ( HttpCarbonMessage outboundResponseMsg ) { String httpVersion = ( String ) inboundRequestMsg . getProperty ( Constants . HTTP_VERSION ) ; if ( outboundResponseMsg . isPipeliningEnabled ( ) && Constants . HTTP_1_1_VERSION . equalsIgnoreCase ( httpVersion ) ) { Queue responseQueue ; synchronized ( sourceContext . channel ( ) . attr ( Constants . RESPONSE_QUEUE ) . get ( ) ) { responseQueue = sourceContext . channel ( ) . attr ( Constants . RESPONSE_QUEUE ) . get ( ) ; Long nextSequenceNumber = sourceContext . channel ( ) . attr ( Constants . NEXT_SEQUENCE_NUMBER ) . get ( ) ; nextSequenceNumber ++ ; sourceContext . channel ( ) . attr ( Constants . NEXT_SEQUENCE_NUMBER ) . set ( nextSequenceNumber ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Current sequence id of the response : {}" , outboundResponseMsg . getSequenceId ( ) ) ; LOG . debug ( "Updated next sequence id to : {}" , nextSequenceNumber ) ; } } if ( ! responseQueue . isEmpty ( ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Pipelining logic is triggered from transport" ) ; } if ( outboundResponseMsg . getPipeliningFuture ( ) != null ) { EventExecutorGroup pipeliningExecutor = sourceContext . channel ( ) . attr ( Constants . PIPELINING_EXECUTOR ) . get ( ) ; pipeliningExecutor . execute ( ( ) -> outboundResponseMsg . getPipeliningFuture ( ) . notifyPipeliningListener ( sourceContext ) ) ; } } } } | Increment the next expected sequence number and trigger the pipelining logic . |
31,045 | public ClientHandshakeFuture handshake ( ) { final DefaultClientHandshakeFuture handshakeFuture = new DefaultClientHandshakeFuture ( ) ; try { URI uri = new URI ( url ) ; String scheme = uri . getScheme ( ) ; if ( ! Constants . WS_SCHEME . equalsIgnoreCase ( scheme ) && ! Constants . WSS_SCHEME . equalsIgnoreCase ( scheme ) ) { LOG . error ( "Only WS(S) is supported." ) ; throw new URISyntaxException ( url , "WebSocket client supports only WS(S) scheme" ) ; } final String host = uri . getHost ( ) == null ? "127.0.0.1" : uri . getHost ( ) ; final int port = getPort ( uri ) ; final boolean ssl = Constants . WSS_SCHEME . equalsIgnoreCase ( scheme ) ; WebSocketClientHandshaker webSocketHandshaker = WebSocketClientHandshakerFactory . newHandshaker ( uri , WebSocketVersion . V13 , subProtocols , true , headers , maxFrameSize ) ; MessageQueueHandler messageQueueHandler = new MessageQueueHandler ( ) ; clientHandshakeHandler = new WebSocketClientHandshakeHandler ( webSocketHandshaker , handshakeFuture , messageQueueHandler , ssl , autoRead , url , handshakeFuture ) ; Bootstrap clientBootstrap = initClientBootstrap ( host , port , handshakeFuture ) ; clientBootstrap . connect ( uri . getHost ( ) , port ) . sync ( ) ; } catch ( Exception throwable ) { handleHandshakeError ( handshakeFuture , throwable ) ; } return handshakeFuture ; } | Handle the handshake with the server . |
31,046 | public synchronized ManageableCacheValue getNextCacheValue ( ) { if ( iterator . hasNext ( ) ) { return hashMap . get ( iterator . next ( ) . getKey ( ) ) ; } else { resetIterator ( ) ; return null ; } } | This method is needed by the cache Manager to go through the cache entries to remove invalid values or to remove LRU cache values if the cache has reached its max size . |
31,047 | public static OCSPReq generateOCSPRequest ( X509Certificate issuerCert , BigInteger serialNumber ) throws CertificateVerificationException { Security . addProvider ( new BouncyCastleProvider ( ) ) ; try { byte [ ] issuerCertEnc = issuerCert . getEncoded ( ) ; X509CertificateHolder certificateHolder = new X509CertificateHolder ( issuerCertEnc ) ; DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder ( ) . setProvider ( Constants . BOUNCY_CASTLE_PROVIDER ) . build ( ) ; CertificateID id = new CertificateID ( digCalcProv . get ( CertificateID . HASH_SHA1 ) , certificateHolder , serialNumber ) ; OCSPReqBuilder builder = new OCSPReqBuilder ( ) ; builder . addRequest ( id ) ; BigInteger nonce = BigInteger . valueOf ( System . currentTimeMillis ( ) ) ; builder . setRequestExtensions ( new Extensions ( new Extension ( OCSPObjectIdentifiers . id_pkix_ocsp_nonce , false , new DEROctetString ( nonce . toByteArray ( ) ) ) ) ) ; return builder . build ( ) ; } catch ( OCSPException | OperatorCreationException | IOException | CertificateEncodingException e ) { throw new CertificateVerificationException ( "Cannot generate OCSP Request with the given certificate" , e ) ; } } | This method generates an OCSP Request to be sent to an OCSP authority access endpoint . |
31,048 | public SSLContext createSSLContextFromKeystores ( boolean isServer ) { String protocol = sslConfig . getSSLProtocol ( ) ; try { KeyManager [ ] keyManagers = null ; if ( sslConfig . getKeyStore ( ) != null ) { KeyStore ks = getKeyStore ( sslConfig . getKeyStore ( ) , sslConfig . getKeyStorePass ( ) ) ; kmf = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; if ( ks != null ) { kmf . init ( ks , sslConfig . getCertPass ( ) != null ? sslConfig . getCertPass ( ) . toCharArray ( ) : sslConfig . getKeyStorePass ( ) . toCharArray ( ) ) ; keyManagers = kmf . getKeyManagers ( ) ; } } TrustManager [ ] trustManagers = null ; if ( sslConfig . getTrustStore ( ) != null ) { KeyStore tks = getKeyStore ( sslConfig . getTrustStore ( ) , sslConfig . getTrustStorePass ( ) ) ; tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; tmf . init ( tks ) ; trustManagers = tmf . getTrustManagers ( ) ; } sslContext = SSLContext . getInstance ( protocol ) ; sslContext . init ( keyManagers , trustManagers , null ) ; int sessionTimeout = sslConfig . getSessionTimeOut ( ) ; if ( isServer ) { if ( sessionTimeout > 0 ) { sslContext . getServerSessionContext ( ) . setSessionTimeout ( sessionTimeout ) ; } } else { if ( sessionTimeout > 0 ) { sslContext . getClientSessionContext ( ) . setSessionTimeout ( sessionTimeout ) ; } } return sslContext ; } catch ( UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e ) { throw new IllegalArgumentException ( "Failed to initialize the SSLContext" , e ) ; } } | This is uset to create the sslContext from keystores . |
31,049 | public SSLEngine buildServerSSLEngine ( SSLContext sslContext ) { SSLEngine engine = sslContext . createSSLEngine ( ) ; engine . setUseClientMode ( false ) ; if ( needClientAuth ) { engine . setNeedClientAuth ( true ) ; } else if ( wantClientAuth ) { engine . setWantClientAuth ( true ) ; } return addCommonConfigs ( engine ) ; } | Build the server ssl engine using the ssl context . |
31,050 | public ReferenceCountedOpenSslContext getServerReferenceCountedOpenSslContext ( boolean enableOcsp ) throws SSLException { if ( sslConfig . getKeyStore ( ) != null ) { sslContextBuilder = serverContextBuilderWithKs ( SslProvider . OPENSSL ) ; } else { sslContextBuilder = serverContextBuilderWithCerts ( SslProvider . OPENSSL ) ; } setOcspStapling ( sslContextBuilder , enableOcsp ) ; if ( sslConfig . getCipherSuites ( ) != null ) { List < String > ciphers = Arrays . asList ( sslConfig . getCipherSuites ( ) ) ; setCiphers ( sslContextBuilder , ciphers ) ; } setSslProtocol ( sslContextBuilder ) ; ReferenceCountedOpenSslContext referenceCountedOpenSslCtx = ( ReferenceCountedOpenSslContext ) sslContextBuilder . build ( ) ; int sessionTimeout = sslConfig . getSessionTimeOut ( ) ; if ( sessionTimeout > 0 ) { referenceCountedOpenSslCtx . sessionContext ( ) . setSessionTimeout ( sessionTimeout ) ; } return referenceCountedOpenSslCtx ; } | This used to create the open ssl context when ocsp stapling is enabled for server . |
31,051 | public ReferenceCountedOpenSslContext buildClientReferenceCountedOpenSslContext ( ) throws SSLException { if ( sslConfig . getTrustStore ( ) != null ) { sslContextBuilder = clientContextBuilderWithKs ( SslProvider . OPENSSL ) ; } else { sslContextBuilder = clientContextBuilderWithCerts ( SslProvider . OPENSSL ) ; } setOcspStapling ( sslContextBuilder , true ) ; if ( sslConfig . getCipherSuites ( ) != null ) { List < String > ciphers = Arrays . asList ( sslConfig . getCipherSuites ( ) ) ; setCiphers ( sslContextBuilder , ciphers ) ; } setSslProtocol ( sslContextBuilder ) ; ReferenceCountedOpenSslContext referenceCountedOpenSslCtx = ( ReferenceCountedOpenSslContext ) sslContextBuilder . build ( ) ; int sessionTimeout = sslConfig . getSessionTimeOut ( ) ; if ( sessionTimeout > 0 ) { referenceCountedOpenSslCtx . sessionContext ( ) . setSessionTimeout ( sessionTimeout ) ; } return referenceCountedOpenSslCtx ; } | This used to create the open ssl context when ocsp stapling is enabled for client . |
31,052 | public SSLEngine buildClientSSLEngine ( String host , int port ) { SSLEngine engine = sslContext . createSSLEngine ( host , port ) ; engine . setUseClientMode ( true ) ; return addCommonConfigs ( engine ) ; } | Build ssl engine for client side . |
31,053 | public SSLEngine addCommonConfigs ( SSLEngine engine ) { if ( sslConfig . getCipherSuites ( ) != null && sslConfig . getCipherSuites ( ) . length > 0 ) { engine . setEnabledCipherSuites ( sslConfig . getCipherSuites ( ) ) ; } if ( sslConfig . getEnableProtocols ( ) != null && sslConfig . getEnableProtocols ( ) . length > 0 ) { engine . setEnabledProtocols ( sslConfig . getEnableProtocols ( ) ) ; } engine . setEnableSessionCreation ( sslConfig . isEnableSessionCreation ( ) ) ; return engine ; } | Add common configs for both client and server ssl engines . |
31,054 | public SslContext createHttpTLSContextForServer ( ) throws SSLException { SslProvider provider = SslProvider . JDK ; SslContext certsSslContext = serverContextBuilderWithCerts ( provider ) . build ( ) ; int sessionTimeout = sslConfig . getSessionTimeOut ( ) ; if ( sessionTimeout > 0 ) { certsSslContext . sessionContext ( ) . setSessionTimeout ( sessionTimeout ) ; } return certsSslContext ; } | This method will provide netty ssl context which supports HTTP over TLS using . |
31,055 | public SslContext createHttpTLSContextForClient ( ) throws SSLException { SslProvider provider = SslProvider . JDK ; SslContext certsSslContext = clientContextBuilderWithCerts ( provider ) . build ( ) ; int sessionTimeout = sslConfig . getSessionTimeOut ( ) ; if ( sessionTimeout > 0 ) { certsSslContext . sessionContext ( ) . setSessionTimeout ( sessionTimeout ) ; } return certsSslContext ; } | This method will provide netty ssl context which supports HTTP over TLS using certificates and keys . |
31,056 | private void setRequestProperties ( ) { inboundRequestMsg . setPipeliningEnabled ( pipeliningEnabled ) ; String connectionHeaderValue = inboundRequestMsg . getHeader ( HttpHeaderNames . CONNECTION . toString ( ) ) ; String httpVersion = ( String ) inboundRequestMsg . getProperty ( Constants . HTTP_VERSION ) ; inboundRequestMsg . setKeepAlive ( isKeepAliveConnection ( keepAliveConfig , connectionHeaderValue , httpVersion ) ) ; } | These properties are needed in ballerina side for pipelining checks . |
31,057 | private void setPipeliningProperties ( ) { if ( ctx . channel ( ) . attr ( Constants . MAX_RESPONSES_ALLOWED_TO_BE_QUEUED ) . get ( ) == null ) { ctx . channel ( ) . attr ( Constants . MAX_RESPONSES_ALLOWED_TO_BE_QUEUED ) . set ( pipeliningLimit ) ; } if ( ctx . channel ( ) . attr ( Constants . RESPONSE_QUEUE ) . get ( ) == null ) { ctx . channel ( ) . attr ( Constants . RESPONSE_QUEUE ) . set ( holdingQueue ) ; } if ( ctx . channel ( ) . attr ( Constants . NEXT_SEQUENCE_NUMBER ) . get ( ) == null ) { ctx . channel ( ) . attr ( Constants . NEXT_SEQUENCE_NUMBER ) . set ( EXPECTED_SEQUENCE_NUMBER ) ; } if ( ctx . channel ( ) . attr ( Constants . PIPELINING_EXECUTOR ) . get ( ) == null ) { ctx . channel ( ) . attr ( Constants . PIPELINING_EXECUTOR ) . set ( pipeliningGroup ) ; } } | Set pipeline related properties . These should be set only once per connection . |
31,058 | private void setSequenceNumber ( ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Sequence id of the request is set to : {}" , sequenceId ) ; } inboundRequestMsg . setSequenceId ( sequenceId ) ; sequenceId ++ ; } | Sequence number should be incremented per request . |
31,059 | public static boolean shouldEnforceChunkingforHttpOneZero ( ChunkConfig chunkConfig , String httpVersion ) { return chunkConfig == ChunkConfig . ALWAYS && Float . valueOf ( httpVersion ) >= Constants . HTTP_1_0 ; } | Returns whether to enforce chunking on HTTP 1 . 0 requests . |
31,060 | public static SSLEngine configureHttpPipelineForSSL ( SocketChannel socketChannel , String host , int port , SSLConfig sslConfig ) throws SSLException { LOG . debug ( "adding ssl handler" ) ; SSLEngine sslEngine = null ; SslHandler sslHandler ; ChannelPipeline pipeline = socketChannel . pipeline ( ) ; SSLHandlerFactory sslHandlerFactory = new SSLHandlerFactory ( sslConfig ) ; if ( sslConfig . isOcspStaplingEnabled ( ) ) { sslHandlerFactory . createSSLContextFromKeystores ( false ) ; ReferenceCountedOpenSslContext referenceCountedOpenSslContext = sslHandlerFactory . buildClientReferenceCountedOpenSslContext ( ) ; if ( referenceCountedOpenSslContext != null ) { sslHandler = referenceCountedOpenSslContext . newHandler ( socketChannel . alloc ( ) ) ; sslEngine = sslHandler . engine ( ) ; setSslHandshakeTimeOut ( sslConfig , sslHandler ) ; socketChannel . pipeline ( ) . addLast ( sslHandler ) ; socketChannel . pipeline ( ) . addLast ( new OCSPStaplingHandler ( ( ReferenceCountedOpenSslEngine ) sslEngine ) ) ; } } else { if ( sslConfig . getTrustStore ( ) != null ) { sslHandlerFactory . createSSLContextFromKeystores ( false ) ; sslEngine = instantiateAndConfigSSL ( sslConfig , host , port , sslConfig . isHostNameVerificationEnabled ( ) , sslHandlerFactory ) ; } else { sslEngine = getSslEngineForCerts ( socketChannel , host , port , sslConfig , sslHandlerFactory ) ; } sslHandler = new SslHandler ( sslEngine ) ; setSslHandshakeTimeOut ( sslConfig , sslHandler ) ; pipeline . addLast ( Constants . SSL_HANDLER , sslHandler ) ; if ( sslConfig . isValidateCertEnabled ( ) ) { pipeline . addLast ( Constants . HTTP_CERT_VALIDATION_HANDLER , new CertificateValidationHandler ( sslEngine , sslConfig . getCacheValidityPeriod ( ) , sslConfig . getCacheSize ( ) ) ) ; } } return sslEngine ; } | Configure outbound HTTP pipeline for SSL configuration . |
31,061 | private static SSLEngine instantiateAndConfigSSL ( SSLConfig sslConfig , String host , int port , boolean hostNameVerificationEnabled , SSLHandlerFactory sslHandlerFactory ) { SSLEngine sslEngine = null ; if ( sslConfig != null ) { sslEngine = sslHandlerFactory . buildClientSSLEngine ( host , port ) ; sslEngine . setUseClientMode ( true ) ; sslHandlerFactory . setSNIServerNames ( sslEngine , host ) ; if ( hostNameVerificationEnabled ) { sslHandlerFactory . setHostNameVerfication ( sslEngine ) ; } } return sslEngine ; } | Set configurations to create ssl engine . |
31,062 | private static String getSystemVariableValue ( String variableName , String defaultValue ) { String value ; if ( System . getProperty ( variableName ) != null ) { value = System . getProperty ( variableName ) ; } else if ( System . getenv ( variableName ) != null ) { value = System . getenv ( variableName ) ; } else { value = defaultValue ; } return value ; } | A utility which allows reading variables from the environment or System properties . If the variable in available in the environment as well as a System property the System property takes precedence . |
31,063 | public static void resetChannelAttributes ( ChannelHandlerContext ctx ) { ctx . channel ( ) . attr ( Constants . RESPONSE_FUTURE_OF_ORIGINAL_CHANNEL ) . set ( null ) ; ctx . channel ( ) . attr ( Constants . ORIGINAL_REQUEST ) . set ( null ) ; ctx . channel ( ) . attr ( Constants . REDIRECT_COUNT ) . set ( null ) ; ctx . channel ( ) . attr ( Constants . RESOLVED_REQUESTED_URI_ATTR ) . set ( null ) ; ctx . channel ( ) . attr ( Constants . ORIGINAL_CHANNEL_START_TIME ) . set ( null ) ; ctx . channel ( ) . attr ( Constants . ORIGINAL_CHANNEL_TIMEOUT ) . set ( null ) ; } | Reset channel attributes . |
31,064 | public static void sendAndCloseNoEntityBodyResp ( ChannelHandlerContext ctx , HttpResponseStatus status , HttpVersion httpVersion , String serverName ) { HttpResponse outboundResponse = new DefaultHttpResponse ( httpVersion , status ) ; outboundResponse . headers ( ) . set ( HttpHeaderNames . CONTENT_LENGTH , 0 ) ; outboundResponse . headers ( ) . set ( HttpHeaderNames . CONNECTION . toString ( ) , Constants . CONNECTION_CLOSE ) ; outboundResponse . headers ( ) . set ( HttpHeaderNames . SERVER . toString ( ) , serverName ) ; ChannelFuture outboundRespFuture = ctx . channel ( ) . writeAndFlush ( outboundResponse ) ; outboundRespFuture . addListener ( ( ChannelFutureListener ) channelFuture -> LOG . warn ( "Failed to send {}" , status . reasonPhrase ( ) ) ) ; ctx . channel ( ) . close ( ) ; } | Send back no entity body response and close the connection . This function is mostly used when we send back error messages . |
31,065 | public static void checkForResponseWriteStatus ( HttpCarbonMessage inboundRequestMsg , HttpResponseFuture outboundRespStatusFuture , ChannelFuture channelFuture ) { channelFuture . addListener ( writeOperationPromise -> { Throwable throwable = writeOperationPromise . cause ( ) ; if ( throwable != null ) { if ( throwable instanceof ClosedChannelException ) { throwable = new IOException ( REMOTE_CLIENT_CLOSED_WHILE_WRITING_OUTBOUND_RESPONSE_HEADERS ) ; } outboundRespStatusFuture . notifyHttpListener ( throwable ) ; } else { outboundRespStatusFuture . notifyHttpListener ( inboundRequestMsg ) ; } } ) ; } | Checks for status of the response write operation . |
31,066 | public static void addResponseWriteFailureListener ( HttpResponseFuture outboundRespStatusFuture , ChannelFuture channelFuture ) { channelFuture . addListener ( writeOperationPromise -> { Throwable throwable = writeOperationPromise . cause ( ) ; if ( throwable != null ) { if ( throwable instanceof ClosedChannelException ) { throwable = new IOException ( REMOTE_CLIENT_CLOSED_WHILE_WRITING_OUTBOUND_RESPONSE_HEADERS ) ; } outboundRespStatusFuture . notifyHttpListener ( throwable ) ; } } ) ; } | Adds a listener to notify the outbound response future if an error occurs while writing the response message . |
31,067 | public static HttpCarbonMessage createHTTPCarbonMessage ( HttpMessage httpMessage , ChannelHandlerContext ctx ) { Listener contentListener = new DefaultListener ( ctx ) ; return new HttpCarbonMessage ( httpMessage , contentListener ) ; } | Creates HTTP carbon message . |
31,068 | public static void safelyRemoveHandlers ( ChannelPipeline pipeline , String ... handlerNames ) { for ( String name : handlerNames ) { if ( pipeline . get ( name ) != null ) { pipeline . remove ( name ) ; } else { LOG . debug ( "Trying to remove not engaged {} handler from the pipeline" , name ) ; } } } | Removes handlers from the pipeline if they are present . |
31,069 | public static HttpCarbonMessage createInboundReqCarbonMsg ( HttpRequest httpRequestHeaders , ChannelHandlerContext ctx , SourceHandler sourceHandler ) { HttpCarbonMessage inboundRequestMsg = new HttpCarbonRequest ( httpRequestHeaders , new DefaultListener ( ctx ) ) ; inboundRequestMsg . setProperty ( Constants . POOLED_BYTE_BUFFER_FACTORY , new PooledDataStreamerFactory ( ctx . alloc ( ) ) ) ; inboundRequestMsg . setProperty ( Constants . CHNL_HNDLR_CTX , ctx ) ; inboundRequestMsg . setProperty ( Constants . SRC_HANDLER , sourceHandler ) ; HttpVersion protocolVersion = httpRequestHeaders . protocolVersion ( ) ; inboundRequestMsg . setProperty ( Constants . HTTP_VERSION , protocolVersion . majorVersion ( ) + "." + protocolVersion . minorVersion ( ) ) ; inboundRequestMsg . setProperty ( Constants . HTTP_METHOD , httpRequestHeaders . method ( ) . name ( ) ) ; InetSocketAddress localAddress = null ; if ( ctx . channel ( ) . localAddress ( ) instanceof InetSocketAddress ) { localAddress = ( InetSocketAddress ) ctx . channel ( ) . localAddress ( ) ; } inboundRequestMsg . setProperty ( Constants . LISTENER_PORT , localAddress != null ? localAddress . getPort ( ) : null ) ; inboundRequestMsg . setProperty ( Constants . LISTENER_INTERFACE_ID , sourceHandler . getInterfaceId ( ) ) ; inboundRequestMsg . setProperty ( Constants . PROTOCOL , Constants . HTTP_SCHEME ) ; boolean isSecuredConnection = false ; if ( ctx . channel ( ) . pipeline ( ) . get ( Constants . SSL_HANDLER ) != null ) { isSecuredConnection = true ; } inboundRequestMsg . setProperty ( Constants . IS_SECURED_CONNECTION , isSecuredConnection ) ; inboundRequestMsg . setProperty ( Constants . LOCAL_ADDRESS , ctx . channel ( ) . localAddress ( ) ) ; inboundRequestMsg . setProperty ( Constants . REMOTE_ADDRESS , sourceHandler . getRemoteAddress ( ) ) ; inboundRequestMsg . setProperty ( Constants . REQUEST_URL , httpRequestHeaders . uri ( ) ) ; inboundRequestMsg . setProperty ( Constants . TO , httpRequestHeaders . uri ( ) ) ; inboundRequestMsg . setProperty ( MUTUAL_SSL_HANDSHAKE_RESULT , ctx . channel ( ) . attr ( Constants . MUTUAL_SSL_RESULT_ATTRIBUTE ) . get ( ) ) ; return inboundRequestMsg ; } | Create a HttpCarbonMessage using the netty inbound http request . |
31,070 | public static HttpCarbonMessage createInboundRespCarbonMsg ( ChannelHandlerContext ctx , HttpResponse httpResponseHeaders , HttpCarbonMessage outboundRequestMsg ) { HttpCarbonMessage inboundResponseMsg = new HttpCarbonResponse ( httpResponseHeaders , new DefaultListener ( ctx ) ) ; inboundResponseMsg . setProperty ( Constants . POOLED_BYTE_BUFFER_FACTORY , new PooledDataStreamerFactory ( ctx . alloc ( ) ) ) ; inboundResponseMsg . setProperty ( Constants . DIRECTION , Constants . DIRECTION_RESPONSE ) ; inboundResponseMsg . setProperty ( Constants . HTTP_STATUS_CODE , httpResponseHeaders . status ( ) . code ( ) ) ; inboundResponseMsg . setProperty ( Constants . EXECUTOR_WORKER_POOL , outboundRequestMsg . getProperty ( Constants . EXECUTOR_WORKER_POOL ) ) ; return inboundResponseMsg ; } | Create a HttpCarbonMessage using the netty inbound response message . |
31,071 | public static boolean isKeepAlive ( KeepAliveConfig keepAliveConfig , HttpCarbonMessage outboundRequestMsg ) throws ConfigurationException { switch ( keepAliveConfig ) { case AUTO : return Float . valueOf ( ( String ) outboundRequestMsg . getProperty ( Constants . HTTP_VERSION ) ) > Constants . HTTP_1_0 ; case ALWAYS : return true ; case NEVER : return false ; default : throw new ConfigurationException ( "Invalid keep-alive configuration value : " + keepAliveConfig . toString ( ) ) ; } } | Check whether a connection should alive or not . |
31,072 | public static boolean is100ContinueRequest ( HttpCarbonMessage inboundRequestMsg ) { return HEADER_VAL_100_CONTINUE . equalsIgnoreCase ( inboundRequestMsg . getHeader ( HttpHeaderNames . EXPECT . toString ( ) ) ) ; } | Check whether a particular request is expecting continue . |
31,073 | public static boolean isKeepAliveConnection ( KeepAliveConfig keepAliveConfig , String requestConnectionHeader , String httpVersion ) { if ( keepAliveConfig == null || keepAliveConfig == KeepAliveConfig . AUTO ) { if ( Float . valueOf ( httpVersion ) <= Constants . HTTP_1_0 ) { return requestConnectionHeader != null && requestConnectionHeader . equalsIgnoreCase ( Constants . CONNECTION_KEEP_ALIVE ) ; } else { return requestConnectionHeader == null || ! requestConnectionHeader . equalsIgnoreCase ( Constants . CONNECTION_CLOSE ) ; } } else { return keepAliveConfig == KeepAliveConfig . ALWAYS ; } } | Decide whether the connection should be kept open . |
31,074 | public static void setBackPressureListener ( boolean passthrough , BackPressureHandler backpressureHandler , ChannelHandlerContext inContext ) { if ( backpressureHandler != null ) { if ( inContext != null && passthrough ) { backpressureHandler . getBackPressureObservable ( ) . setListener ( new PassthroughBackPressureListener ( inContext ) ) ; } else { backpressureHandler . getBackPressureObservable ( ) . setListener ( new DefaultBackPressureListener ( ) ) ; } } } | Sets the backPressure listener the to the Observable of the handler . |
31,075 | public static void checkUnWritabilityAndNotify ( ChannelHandlerContext context , BackPressureHandler backpressureHandler ) { if ( backpressureHandler != null ) { Channel channel = context . channel ( ) ; if ( ! channel . isWritable ( ) && channel . isActive ( ) ) { backpressureHandler . getBackPressureObservable ( ) . notifyUnWritable ( ) ; } } } | Checks if channel is unWritable and notifies BackPressure observable . |
31,076 | private void configureProxyServer ( ChannelPipeline clientPipeline ) { if ( proxyServerConfiguration != null && sslConfig != null ) { if ( proxyServerConfiguration . getProxyUsername ( ) != null && proxyServerConfiguration . getProxyPassword ( ) != null ) { clientPipeline . addLast ( Constants . PROXY_HANDLER , new HttpProxyHandler ( proxyServerConfiguration . getInetSocketAddress ( ) , proxyServerConfiguration . getProxyUsername ( ) , proxyServerConfiguration . getProxyPassword ( ) ) ) ; } else { clientPipeline . addLast ( Constants . PROXY_HANDLER , new HttpProxyHandler ( proxyServerConfiguration . getInetSocketAddress ( ) ) ) ; } } } | Use netty proxy handler only if scheme is https |
31,077 | private void configureHttp2UpgradePipeline ( ChannelPipeline pipeline , HttpClientCodec sourceCodec , TargetHandler targetHandler ) { pipeline . addLast ( sourceCodec ) ; addCommonHandlers ( pipeline ) ; Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec ( http2ConnectionHandler ) ; HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler ( sourceCodec , upgradeCodec , Integer . MAX_VALUE ) ; pipeline . addLast ( Constants . HTTP2_UPGRADE_HANDLER , upgradeHandler ) ; pipeline . addLast ( Constants . TARGET_HANDLER , targetHandler ) ; } | Creates the pipeline for handing http2 upgrade . |
31,078 | private void configureHttp2Pipeline ( ChannelPipeline pipeline ) { pipeline . addLast ( Constants . CONNECTION_HANDLER , http2ConnectionHandler ) ; pipeline . addLast ( Constants . HTTP2_TARGET_HANDLER , http2TargetHandler ) ; pipeline . addLast ( Constants . DECOMPRESSOR_HANDLER , new HttpContentDecompressor ( ) ) ; } | Creates the pipeline for http2 requests which does not involve a connection upgrade . |
31,079 | public void configureHttpPipeline ( ChannelPipeline pipeline , TargetHandler targetHandler ) { pipeline . addLast ( Constants . HTTP_CLIENT_CODEC , new HttpClientCodec ( ) ) ; addCommonHandlers ( pipeline ) ; pipeline . addLast ( Constants . BACK_PRESSURE_HANDLER , new BackPressureHandler ( ) ) ; pipeline . addLast ( Constants . TARGET_HANDLER , targetHandler ) ; } | Creates pipeline for http requests . |
31,080 | private void addCommonHandlers ( ChannelPipeline pipeline ) { pipeline . addLast ( Constants . DECOMPRESSOR_HANDLER , new HttpContentDecompressor ( ) ) ; if ( httpTraceLogEnabled ) { pipeline . addLast ( Constants . HTTP_TRACE_LOG_HANDLER , new HttpTraceLoggingHandler ( Constants . TRACE_LOG_UPSTREAM ) ) ; } } | Add common handlers used in both http2 and http . |
31,081 | public void addPushResponse ( int streamId , HttpCarbonResponse pushResponse ) { pushResponsesMap . put ( streamId , pushResponse ) ; responseFuture . notifyPushResponse ( streamId , pushResponse ) ; } | Adds a push response message . |
31,082 | public void init ( int size , int delay ) { if ( cacheManager == null ) { synchronized ( OCSPCache . class ) { if ( cacheManager == null ) { cacheManager = new CacheManager ( cache , size , delay ) ; CacheController mbean = new CacheController ( cache , cacheManager ) ; MBeanRegistrar . getInstance ( ) . registerMBean ( mbean , "CacheController" , "OCSPCacheController" ) ; } } } } | This lazy initializes the cache with a CacheManager . If this method is not called a cache manager will not be used . |
31,083 | public void shutdownNow ( ) { allChannels . close ( ) ; workerGroup . shutdownGracefully ( ) ; bossGroup . shutdownGracefully ( ) ; clientGroup . shutdownGracefully ( ) ; if ( pipeliningGroup != null ) { pipeliningGroup . shutdownGracefully ( ) ; } } | This method is for shutting down the connectors without a delay . |
31,084 | protected X509CRL downloadCRLFromWeb ( String crlURL ) throws IOException , CertificateVerificationException { URL url = new URL ( crlURL ) ; try ( InputStream crlStream = url . openStream ( ) ) { CertificateFactory cf = CertificateFactory . getInstance ( Constants . X_509 ) ; return ( X509CRL ) cf . generateCRL ( crlStream ) ; } catch ( MalformedURLException e ) { throw new CertificateVerificationException ( "CRL URL is malformed" , e ) ; } catch ( IOException e ) { throw new CertificateVerificationException ( "Cant reach URI: " + crlURL + " - only support HTTP" , e ) ; } catch ( CertificateException e ) { throw new CertificateVerificationException ( e ) ; } catch ( CRLException e ) { throw new CertificateVerificationException ( "Cannot generate X509CRL from the stream data" , e ) ; } } | Downloads CRL from the crlUrl . Does not support HTTPS . |
31,085 | private List < String > getCrlDistributionPoints ( X509Certificate cert ) throws CertificateVerificationException { byte [ ] crlDPExtensionValue = cert . getExtensionValue ( Extension . cRLDistributionPoints . getId ( ) ) ; if ( crlDPExtensionValue == null ) { throw new CertificateVerificationException ( "Certificate doesn't have CRL distribution points" ) ; } ASN1InputStream asn1In = new ASN1InputStream ( crlDPExtensionValue ) ; CRLDistPoint distPoint ; try { DEROctetString crlDEROctetString = ( DEROctetString ) asn1In . readObject ( ) ; distPoint = getOctetInputStream ( crlDEROctetString ) ; } catch ( IOException e ) { throw new CertificateVerificationException ( "Cannot read certificate to get CRL URLs" , e ) ; } finally { try { asn1In . close ( ) ; } catch ( IOException e ) { LOG . error ( "Cannot close input stream" , e ) ; } } List < String > crlUrls = new ArrayList < > ( ) ; for ( DistributionPoint dp : distPoint . getDistributionPoints ( ) ) { DistributionPointName dpn = dp . getDistributionPoint ( ) ; if ( dpn != null && dpn . getType ( ) == DistributionPointName . FULL_NAME ) { GeneralName [ ] genNames = GeneralNames . getInstance ( dpn . getName ( ) ) . getNames ( ) ; for ( GeneralName genName : genNames ) { if ( genName . getTagNo ( ) == GeneralName . uniformResourceIdentifier ) { String url = DERIA5String . getInstance ( genName . getName ( ) ) . getString ( ) . trim ( ) ; crlUrls . add ( url ) ; } } } } if ( crlUrls . isEmpty ( ) ) { throw new CertificateVerificationException ( "Cant get CRL urls from certificate" ) ; } return crlUrls ; } | Extracts all CRL distribution point URLs from the CRL Distribution Point extension in a X . 509 certificate . If CRL distribution point extension is unavailable returns an empty list . |
31,086 | public static KeyStore getKeyStore ( File keyStoreFile , String keyStorePassword , String tlsStoreType ) throws IOException { KeyStore keyStore = null ; if ( keyStoreFile != null && keyStorePassword != null ) { try ( InputStream inputStream = new FileInputStream ( keyStoreFile ) ) { keyStore = KeyStore . getInstance ( tlsStoreType ) ; keyStore . load ( inputStream , keyStorePassword . toCharArray ( ) ) ; } catch ( CertificateException | NoSuchAlgorithmException | KeyStoreException e ) { throw new IOException ( e ) ; } } return keyStore ; } | Method to create a keystore and return . |
31,087 | public static List < String > getAIALocations ( X509Certificate userCertificate ) throws CertificateVerificationException { List < String > locations ; try { locations = OCSPVerifier . getAIALocations ( userCertificate ) ; } catch ( CertificateVerificationException e ) { throw new CertificateVerificationException ( "Failed to find AIA locations in the cetificate" , e ) ; } return locations ; } | List Certificate authority url information . |
31,088 | public static OCSPResp getOCSPResponse ( List < String > locations , OCSPReq request , X509Certificate userCertificate , OCSPCache ocspCache ) throws CertificateVerificationException { SingleResp [ ] responses ; BasicOCSPResp basicResponse ; CertificateStatus certificateStatus ; for ( String serviceUrl : locations ) { OCSPResp response ; try { response = OCSPVerifier . getOCSPResponce ( serviceUrl , request ) ; if ( OCSPResponseStatus . SUCCESSFUL != response . getStatus ( ) ) { continue ; } basicResponse = ( BasicOCSPResp ) response . getResponseObject ( ) ; responses = ( basicResponse == null ) ? null : basicResponse . getResponses ( ) ; } catch ( OCSPException | CertificateVerificationException e ) { LOG . debug ( "OCSP response failed for url{}. Hence trying the next url" , serviceUrl ) ; continue ; } if ( responses != null && responses . length == 1 ) { SingleResp singleResponse = responses [ 0 ] ; certificateStatus = singleResponse . getCertStatus ( ) ; if ( certificateStatus != null ) { throw new IllegalStateException ( "certificate-status=" + certificateStatus ) ; } if ( ! userCertificate . getSerialNumber ( ) . equals ( singleResponse . getCertID ( ) . getSerialNumber ( ) ) ) { throw new IllegalStateException ( "Bad Serials=" + userCertificate . getSerialNumber ( ) + " vs. " + singleResponse . getCertID ( ) . getSerialNumber ( ) ) ; } ocspCache . setCacheValue ( response , userCertificate . getSerialNumber ( ) , singleResponse , request , serviceUrl ) ; return response ; } } throw new CertificateVerificationException ( "Could not get revocation status from OCSP." ) ; } | Get OCSP response from cache . |
31,089 | public boolean verifyRevocationStatus ( javax . security . cert . X509Certificate [ ] peerCertificates ) throws CertificateVerificationException { X509Certificate [ ] convertedCertificates = convert ( peerCertificates ) ; long start = System . currentTimeMillis ( ) ; OCSPCache ocspCache = OCSPCache . getCache ( ) ; ocspCache . init ( cacheSize , cacheDelayMins ) ; CRLCache crlCache = CRLCache . getCache ( ) ; crlCache . init ( cacheSize , cacheDelayMins ) ; RevocationVerifier [ ] verifiers = { new OCSPVerifier ( ocspCache ) , new CRLVerifier ( crlCache ) } ; for ( RevocationVerifier verifier : verifiers ) { try { CertificatePathValidator pathValidator = new CertificatePathValidator ( convertedCertificates , verifier ) ; pathValidator . validatePath ( ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Path verification is successful. Took {} ms." , System . currentTimeMillis ( ) - start ) ; } return true ; } catch ( Exception e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "{} failed." , verifier . getClass ( ) . getSimpleName ( ) ) ; LOG . debug ( "Certificate verification with {} failed. " , verifier . getClass ( ) . getSimpleName ( ) , e ) ; } } } throw new CertificateVerificationException ( "Path verification failed for both OCSP and CRL" ) ; } | This method first tries to verify the given certificate chain using OCSP since OCSP verification is faster . If that fails it tries to do the verification using CRL . |
31,090 | private X509Certificate [ ] convert ( javax . security . cert . X509Certificate [ ] certs ) throws CertificateVerificationException { X509Certificate [ ] certChain = new X509Certificate [ certs . length ] ; Throwable exceptionThrown ; for ( int i = 0 ; i < certs . length ; i ++ ) { try { byte [ ] encoded = certs [ i ] . getEncoded ( ) ; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( encoded ) ; CertificateFactory certificateFactory = CertificateFactory . getInstance ( Constants . X_509 ) ; certChain [ i ] = ( ( X509Certificate ) certificateFactory . generateCertificate ( byteArrayInputStream ) ) ; continue ; } catch ( CertificateEncodingException | CertificateException e ) { exceptionThrown = e ; } throw new CertificateVerificationException ( "Cant Convert certificates from javax to java" , exceptionThrown ) ; } return certChain ; } | Convert certificates and create a certificate chain . |
31,091 | public void addHeader ( String name , String value ) { httpRequest . headers ( ) . add ( name , value ) ; } | Adds a header to the push promise . This will not replace the value of an already exists header . |
31,092 | public String [ ] getHeaders ( String name ) { List < String > headerList = httpRequest . headers ( ) . getAll ( name ) ; return headerList . toArray ( new String [ 0 ] ) ; } | Gets all header values for a given header name . |
31,093 | public void setHeader ( String name , String value ) { httpRequest . headers ( ) . set ( name , value ) ; } | Sets a header value for a given header name . This replaces the value of an already existing header . |
31,094 | private boolean start ( ) { if ( scheduledFuture == null || scheduledFuture . isCancelled ( ) ) { scheduledFuture = scheduler . scheduleWithFixedDelay ( cacheManagingTask , delay , delay , TimeUnit . MINUTES ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "{} Cache Manager Started." , cache . getClass ( ) . getSimpleName ( ) ) ; } return true ; } return false ; } | To Start the CacheManager it needs to be called only once . Because of that calls in constructor . CacheManager will run its TimerTask every delay number of seconds . |
31,095 | public boolean stop ( ) { if ( scheduledFuture != null && ! scheduledFuture . isCancelled ( ) ) { scheduledFuture . cancel ( DO_NOT_INTERRUPT_IF_RUNNING ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "{} Cache Manager stopped." , cache . getClass ( ) . getSimpleName ( ) ) ; } return true ; } return false ; } | Gracefully stop cacheManager . |
31,096 | public void setForwardedHeader ( ) { StringBuilder headerValue = new StringBuilder ( ) ; if ( forwardedHeader == null ) { Object remoteAddressProperty = httpOutboundRequest . getProperty ( Constants . REMOTE_ADDRESS ) ; if ( remoteAddressProperty != null ) { String remoteAddress = ( ( InetSocketAddress ) remoteAddressProperty ) . getAddress ( ) . getHostAddress ( ) ; headerValue . append ( FOR ) . append ( resolveIP ( remoteAddress ) ) . append ( SEMI_COLON ) . append ( " " ) ; } headerValue . append ( BY ) . append ( resolveIP ( localAddress ) ) ; Object hostHeader = httpOutboundRequest . getProperty ( Constants . ORIGIN_HOST ) ; if ( hostHeader != null ) { headerValue . append ( SEMI_COLON + " " + HOST ) . append ( hostHeader . toString ( ) ) ; } Object protocolHeader = httpOutboundRequest . getProperty ( Constants . PROTOCOL ) ; if ( protocolHeader != null ) { headerValue . append ( SEMI_COLON + " " + PROTO ) . append ( protocolHeader . toString ( ) ) ; } httpOutboundRequest . setHeader ( Constants . FORWARDED , headerValue . toString ( ) ) ; return ; } String [ ] parts = forwardedHeader . split ( SEMI_COLON ) ; String previousForValue = null ; String previousByValue = null ; String previousHostValue = null ; String previousProtoValue = null ; for ( String part : parts ) { if ( part . toLowerCase ( Locale . getDefault ( ) ) . contains ( FOR ) ) { previousForValue = part . trim ( ) ; } else if ( part . toLowerCase ( Locale . getDefault ( ) ) . contains ( BY ) ) { previousByValue = part . trim ( ) . substring ( 3 ) ; } else if ( part . toLowerCase ( Locale . getDefault ( ) ) . contains ( HOST ) ) { previousHostValue = part . substring ( 5 ) ; } else if ( part . toLowerCase ( Locale . getDefault ( ) ) . contains ( PROTO ) ) { previousProtoValue = part . substring ( 6 ) ; } } if ( previousForValue == null ) { previousForValue = previousByValue != null ? FOR + previousByValue : null ; } else { previousForValue = previousByValue == null ? previousForValue : previousForValue + COMMA + " " + FOR + previousByValue ; } headerValue . append ( previousForValue != null ? previousForValue + SEMI_COLON + " " : null ) ; headerValue . append ( BY ) . append ( resolveIP ( localAddress ) ) ; if ( previousHostValue != null ) { headerValue . append ( SEMI_COLON + " " + HOST ) . append ( previousHostValue ) ; } if ( previousProtoValue != null ) { headerValue . append ( SEMI_COLON + " " + PROTO ) . append ( previousProtoValue ) ; } httpOutboundRequest . setHeader ( Constants . FORWARDED , headerValue . toString ( ) ) ; } | Set forwarded header to outbound request . |
31,097 | void resetStream ( ChannelHandlerContext ctx , int streamId , Http2Error http2Error ) { encoder . writeRstStream ( ctx , streamId , http2Error . code ( ) , ctx . newPromise ( ) ) ; http2ClientChannel . getDataEventListeners ( ) . forEach ( dataEventListener -> dataEventListener . onStreamReset ( streamId ) ) ; ctx . flush ( ) ; } | Terminates a stream . |
31,098 | public static void notifyRequestListener ( Http2SourceHandler http2SourceHandler , HttpCarbonMessage httpRequestMsg , int streamId ) { if ( http2SourceHandler . getServerConnectorFuture ( ) != null ) { try { ServerConnectorFuture outboundRespFuture = httpRequestMsg . getHttpResponseFuture ( ) ; outboundRespFuture . setHttpConnectorListener ( new Http2OutboundRespListener ( http2SourceHandler . getServerChannelInitializer ( ) , httpRequestMsg , http2SourceHandler . getChannelHandlerContext ( ) , http2SourceHandler . getConnection ( ) , http2SourceHandler . getEncoder ( ) , streamId , http2SourceHandler . getServerName ( ) , http2SourceHandler . getRemoteAddress ( ) ) ) ; http2SourceHandler . getServerConnectorFuture ( ) . notifyHttpListener ( httpRequestMsg ) ; } catch ( Exception e ) { LOG . error ( "Error while notifying listeners" , e ) ; } } else { LOG . error ( "Cannot find registered listener to forward the message" ) ; } } | Notifies the registered listeners which listen for the incoming carbon messages . |
31,099 | public static void writeHttp2Headers ( ChannelHandlerContext ctx , Http2ConnectionEncoder encoder , HttpResponseFuture outboundRespStatusFuture , int streamId , Http2Headers http2Headers , boolean endStream ) throws Http2Exception { ChannelFuture channelFuture = encoder . writeHeaders ( ctx , streamId , http2Headers , 0 , endStream , ctx . newPromise ( ) ) ; encoder . flowController ( ) . writePendingBytes ( ) ; ctx . flush ( ) ; Util . addResponseWriteFailureListener ( outboundRespStatusFuture , channelFuture ) ; } | Writes HTTP2 headers to outbound response . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.