idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
20,300
public static Jwt decode ( String token ) { int firstPeriod = token . indexOf ( '.' ) ; int lastPeriod = token . lastIndexOf ( '.' ) ; if ( firstPeriod <= 0 || lastPeriod <= firstPeriod ) { throw new IllegalArgumentException ( "JWT must have 3 tokens" ) ; } CharBuffer buffer = CharBuffer . wrap ( token , 0 , firstPeriod ) ; JwtHeader header = JwtHeaderHelper . create ( buffer . toString ( ) ) ; buffer . limit ( lastPeriod ) . position ( firstPeriod + 1 ) ; byte [ ] claims = b64UrlDecode ( buffer ) ; boolean emptyCrypto = lastPeriod == token . length ( ) - 1 ; byte [ ] crypto ; if ( emptyCrypto ) { if ( ! "none" . equals ( header . parameters . alg ) ) { throw new IllegalArgumentException ( "Signed or encrypted token must have non-empty crypto segment" ) ; } crypto = new byte [ 0 ] ; } else { buffer . limit ( token . length ( ) ) . position ( lastPeriod + 1 ) ; crypto = b64UrlDecode ( buffer ) ; } return new JwtImpl ( header , claims , crypto ) ; }
Creates a token from an encoded token string .
20,301
public byte [ ] bytes ( ) { return concat ( b64UrlEncode ( header . bytes ( ) ) , JwtHelper . PERIOD , b64UrlEncode ( content ) , JwtHelper . PERIOD , b64UrlEncode ( crypto ) ) ; }
Allows retrieval of the full token .
20,302
protected String extractHeaderToken ( HttpServletRequest request ) { Enumeration < String > headers = request . getHeaders ( "Authorization" ) ; while ( headers . hasMoreElements ( ) ) { String value = headers . nextElement ( ) ; if ( ( value . toLowerCase ( ) . startsWith ( OAuth2AccessToken . BEARER_TYPE . toLowerCase ( ) ) ) ) { String authHeaderValue = value . substring ( OAuth2AccessToken . BEARER_TYPE . length ( ) ) . trim ( ) ; request . setAttribute ( OAuth2AuthenticationDetails . ACCESS_TOKEN_TYPE , value . substring ( 0 , OAuth2AccessToken . BEARER_TYPE . length ( ) ) . trim ( ) ) ; int commaIndex = authHeaderValue . indexOf ( ',' ) ; if ( commaIndex > 0 ) { authHeaderValue = authHeaderValue . substring ( 0 , commaIndex ) ; } return authHeaderValue ; } } return null ; }
Extract the OAuth bearer token from a header .
20,303
protected boolean isExpired ( OAuthProviderTokenImpl authToken ) { if ( authToken . isAccessToken ( ) ) { if ( ( authToken . getTimestamp ( ) + ( getAccessTokenValiditySeconds ( ) * 1000L ) ) < System . currentTimeMillis ( ) ) { return true ; } } else { if ( ( authToken . getTimestamp ( ) + ( getRequestTokenValiditySeconds ( ) * 1000L ) ) < System . currentTimeMillis ( ) ) { return true ; } } return false ; }
Whether the auth token is expired .
20,304
private boolean matchQueryParams ( MultiValueMap < String , String > registeredRedirectUriQueryParams , MultiValueMap < String , String > requestedRedirectUriQueryParams ) { Iterator < String > iter = registeredRedirectUriQueryParams . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String key = iter . next ( ) ; List < String > registeredRedirectUriQueryParamsValues = registeredRedirectUriQueryParams . get ( key ) ; List < String > requestedRedirectUriQueryParamsValues = requestedRedirectUriQueryParams . get ( key ) ; if ( ! registeredRedirectUriQueryParamsValues . equals ( requestedRedirectUriQueryParamsValues ) ) { return false ; } } return true ; }
Checks whether the registered redirect uri query params key and values contains match the requested set
20,305
private boolean isEqual ( String str1 , String str2 ) { if ( StringUtils . isEmpty ( str1 ) && StringUtils . isEmpty ( str2 ) ) { return true ; } else if ( ! StringUtils . isEmpty ( str1 ) ) { return str1 . equals ( str2 ) ; } else { return false ; } }
Compares two strings but treats empty string or null equal
20,306
protected boolean hostMatches ( String registered , String requested ) { if ( matchSubdomains ) { return registered . equals ( requested ) || requested . endsWith ( "." + registered ) ; } return registered . equals ( requested ) ; }
Check if host matches the registered value .
20,307
public static String oauthEncode ( String value ) { if ( value == null ) { return "" ; } try { return new String ( URLCodec . encodeUrl ( SAFE_CHARACTERS , value . getBytes ( "UTF-8" ) ) , "US-ASCII" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Encode the specified value .
20,308
public static String oauthDecode ( String value ) throws DecoderException { if ( value == null ) { return "" ; } try { return new String ( URLCodec . decodeUrl ( value . getBytes ( "US-ASCII" ) ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Decode the specified value .
20,309
public ProviderConfiguration discover ( ) { Map responseAttributes = this . restTemplate . getForObject ( this . providerLocation , Map . class ) ; ProviderConfiguration . Builder builder = new ProviderConfiguration . Builder ( ) ; builder . issuer ( ( String ) responseAttributes . get ( ISSUER_ATTR_NAME ) ) ; builder . authorizationEndpoint ( ( String ) responseAttributes . get ( AUTHORIZATION_ENDPOINT_ATTR_NAME ) ) ; if ( responseAttributes . containsKey ( TOKEN_ENDPOINT_ATTR_NAME ) ) { builder . tokenEndpoint ( ( String ) responseAttributes . get ( TOKEN_ENDPOINT_ATTR_NAME ) ) ; } if ( responseAttributes . containsKey ( USERINFO_ENDPOINT_ATTR_NAME ) ) { builder . userInfoEndpoint ( ( String ) responseAttributes . get ( USERINFO_ENDPOINT_ATTR_NAME ) ) ; } if ( responseAttributes . containsKey ( JWK_SET_URI_ATTR_NAME ) ) { builder . jwkSetUri ( ( String ) responseAttributes . get ( JWK_SET_URI_ATTR_NAME ) ) ; } return builder . build ( ) ; }
Discover the provider configuration information .
20,310
public Map < String , String > getKey ( ) { Map < String , String > result = new LinkedHashMap < String , String > ( ) ; result . put ( "alg" , signer . algorithm ( ) ) ; result . put ( "value" , verifierKey ) ; return result ; }
Get the verification key for the token signatures .
20,311
public OAuth2Request createOAuth2Request ( Map < String , String > parameters ) { return new OAuth2Request ( parameters , getClientId ( ) , authorities , approved , getScope ( ) , resourceIds , redirectUri , responseTypes , extensions ) ; }
Update the request parameters and return a new object with the same properties except the parameters .
20,312
public String getGrantType ( ) { if ( getRequestParameters ( ) . containsKey ( OAuth2Utils . GRANT_TYPE ) ) { return getRequestParameters ( ) . get ( OAuth2Utils . GRANT_TYPE ) ; } if ( getRequestParameters ( ) . containsKey ( OAuth2Utils . RESPONSE_TYPE ) ) { String response = getRequestParameters ( ) . get ( OAuth2Utils . RESPONSE_TYPE ) ; if ( response . contains ( "token" ) ) { return "implicit" ; } } return null ; }
Tries to discover the grant type requested for the token associated with this request .
20,313
public String sign ( String signatureBaseString ) { try { Mac mac = Mac . getInstance ( MAC_NAME ) ; mac . init ( key ) ; byte [ ] text = signatureBaseString . getBytes ( "UTF-8" ) ; byte [ ] signatureBytes = mac . doFinal ( text ) ; signatureBytes = Base64 . encodeBase64 ( signatureBytes ) ; String signature = new String ( signatureBytes , "UTF-8" ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "signature base: " + signatureBaseString ) ; LOG . debug ( "signature: " + signature ) ; } return signature ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( e ) ; } catch ( InvalidKeyException e ) { throw new IllegalStateException ( e ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Sign the signature base string . The signature is the digest octet string first base64 - encoded per RFC2045 section 6 . 8 then URL - encoded per OAuth Parameter Encoding .
20,314
public Authentication createAuthentication ( HttpServletRequest request , ConsumerAuthentication authentication , OAuthAccessProviderToken authToken ) { if ( authToken != null ) { Authentication userAuthentication = authToken . getUserAuthentication ( ) ; if ( userAuthentication instanceof AbstractAuthenticationToken ) { ( ( AbstractAuthenticationToken ) userAuthentication ) . setDetails ( new OAuthAuthenticationDetails ( request , authentication . getConsumerDetails ( ) ) ) ; } return userAuthentication ; } return authentication ; }
Default implementation returns the user authentication associated with the auth token if the token is provided . Otherwise the consumer authentication is returned .
20,315
protected boolean parametersAreAdequate ( Map < String , String > oauthParams ) { return oauthParams . containsKey ( OAuthConsumerParameter . oauth_consumer_key . toString ( ) ) ; }
By default OAuth parameters are adequate if a consumer key is present .
20,316
protected void validateSignature ( ConsumerAuthentication authentication ) throws AuthenticationException { SignatureSecret secret = authentication . getConsumerDetails ( ) . getSignatureSecret ( ) ; String token = authentication . getConsumerCredentials ( ) . getToken ( ) ; OAuthProviderToken authToken = null ; if ( token != null && ! "" . equals ( token ) ) { authToken = getTokenServices ( ) . getToken ( token ) ; } String signatureMethod = authentication . getConsumerCredentials ( ) . getSignatureMethod ( ) ; OAuthSignatureMethod method ; try { method = getSignatureMethodFactory ( ) . getSignatureMethod ( signatureMethod , secret , authToken != null ? authToken . getSecret ( ) : null ) ; } catch ( UnsupportedSignatureMethodException e ) { throw new OAuthException ( e . getMessage ( ) , e ) ; } String signatureBaseString = authentication . getConsumerCredentials ( ) . getSignatureBaseString ( ) ; String signature = authentication . getConsumerCredentials ( ) . getSignature ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Verifying signature " + signature + " for signature base string " + signatureBaseString + " with method " + method . getName ( ) + "." ) ; } method . verify ( signatureBaseString , signature ) ; }
Validate the signature of the request given the authentication request .
20,317
protected void validateOAuthParams ( ConsumerDetails consumerDetails , Map < String , String > oauthParams ) throws InvalidOAuthParametersException { String version = oauthParams . get ( OAuthConsumerParameter . oauth_version . toString ( ) ) ; if ( ( version != null ) && ( ! "1.0" . equals ( version ) ) ) { throw new OAuthVersionUnsupportedException ( "Unsupported OAuth version: " + version ) ; } String realm = oauthParams . get ( "realm" ) ; realm = realm == null || "" . equals ( realm ) ? null : realm ; if ( ( realm != null ) && ( ! realm . equals ( this . authenticationEntryPoint . getRealmName ( ) ) ) ) { throw new InvalidOAuthParametersException ( messages . getMessage ( "OAuthProcessingFilter.incorrectRealm" , new Object [ ] { realm , this . getAuthenticationEntryPoint ( ) . getRealmName ( ) } , "Response realm name '{0}' does not match system realm name of '{1}'" ) ) ; } String signatureMethod = oauthParams . get ( OAuthConsumerParameter . oauth_signature_method . toString ( ) ) ; if ( signatureMethod == null ) { throw new InvalidOAuthParametersException ( messages . getMessage ( "OAuthProcessingFilter.missingSignatureMethod" , "Missing signature method." ) ) ; } String signature = oauthParams . get ( OAuthConsumerParameter . oauth_signature . toString ( ) ) ; if ( signature == null ) { throw new InvalidOAuthParametersException ( messages . getMessage ( "OAuthProcessingFilter.missingSignature" , "Missing signature." ) ) ; } String timestamp = oauthParams . get ( OAuthConsumerParameter . oauth_timestamp . toString ( ) ) ; if ( timestamp == null ) { throw new InvalidOAuthParametersException ( messages . getMessage ( "OAuthProcessingFilter.missingTimestamp" , "Missing timestamp." ) ) ; } String nonce = oauthParams . get ( OAuthConsumerParameter . oauth_nonce . toString ( ) ) ; if ( nonce == null ) { throw new InvalidOAuthParametersException ( messages . getMessage ( "OAuthProcessingFilter.missingNonce" , "Missing nonce." ) ) ; } try { getNonceServices ( ) . validateNonce ( consumerDetails , Long . parseLong ( timestamp ) , nonce ) ; } catch ( NumberFormatException e ) { throw new InvalidOAuthParametersException ( messages . getMessage ( "OAuthProcessingFilter.invalidTimestamp" , new Object [ ] { timestamp } , "Timestamp must be a positive integer. Invalid value: {0}" ) ) ; } validateAdditionalParameters ( consumerDetails , oauthParams ) ; }
Validates the OAuth parameters for the given consumer . Base implementation validates only those parameters that are required for all OAuth requests . This includes the nonce and timestamp but not the signature .
20,318
protected void fail ( HttpServletRequest request , HttpServletResponse response , AuthenticationException failure ) throws IOException , ServletException { SecurityContextHolder . getContext ( ) . setAuthentication ( null ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( failure ) ; } authenticationEntryPoint . commence ( request , response , failure ) ; }
Common logic for OAuth failed .
20,319
protected boolean requiresAuthentication ( HttpServletRequest request , HttpServletResponse response , FilterChain filterChain ) { String uri = request . getRequestURI ( ) ; int pathParamIndex = uri . indexOf ( ';' ) ; if ( pathParamIndex > 0 ) { uri = uri . substring ( 0 , pathParamIndex ) ; } if ( "" . equals ( request . getContextPath ( ) ) ) { return uri . endsWith ( filterProcessesUrl ) ; } boolean match = uri . endsWith ( request . getContextPath ( ) + filterProcessesUrl ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( uri + ( match ? " matches " : " does not match " ) + filterProcessesUrl ) ; } return match ; }
Whether this filter is configured to process the specified request .
20,320
protected boolean skipProcessing ( HttpServletRequest request ) { return ( ( request . getAttribute ( OAUTH_PROCESSING_HANDLED ) != null ) && ( Boolean . TRUE . equals ( request . getAttribute ( OAUTH_PROCESSING_HANDLED ) ) ) ) ; }
Whether to skip processing for the specified request .
20,321
public void setAllowedMethods ( List < String > allowedMethods ) { this . allowedMethods . clear ( ) ; if ( allowedMethods != null ) { for ( String allowedMethod : allowedMethods ) { this . allowedMethods . add ( allowedMethod . toUpperCase ( ) ) ; } } }
The allowed set of HTTP methods .
20,322
protected Map < String , String > parseHeaderParameters ( HttpServletRequest request ) { String header = null ; Enumeration < String > headers = request . getHeaders ( "Authorization" ) ; while ( headers . hasMoreElements ( ) ) { String value = headers . nextElement ( ) ; if ( ( value . toLowerCase ( ) . startsWith ( "oauth " ) ) ) { header = value ; break ; } } Map < String , String > parameters = null ; if ( header != null ) { parameters = new HashMap < String , String > ( ) ; String authHeaderValue = header . substring ( 6 ) ; String [ ] headerEntries = StringSplitUtils . splitIgnoringQuotes ( authHeaderValue , ',' ) ; for ( Object o : StringSplitUtils . splitEachArrayElementAndCreateMap ( headerEntries , "=" , "\"" ) . entrySet ( ) ) { Map . Entry entry = ( Map . Entry ) o ; try { String key = oauthDecode ( ( String ) entry . getKey ( ) ) ; String value = oauthDecode ( ( String ) entry . getValue ( ) ) ; parameters . put ( key , value ) ; } catch ( DecoderException e ) { throw new IllegalStateException ( e ) ; } } } return parameters ; }
Parse the OAuth header parameters . The parameters will be oauth - decoded .
20,323
protected String normalizeUrl ( String url ) { try { URL requestURL = new URL ( url ) ; StringBuilder normalized = new StringBuilder ( requestURL . getProtocol ( ) . toLowerCase ( ) ) . append ( "://" ) . append ( requestURL . getHost ( ) . toLowerCase ( ) ) ; if ( ( requestURL . getPort ( ) >= 0 ) && ( requestURL . getPort ( ) != requestURL . getDefaultPort ( ) ) ) { normalized . append ( ":" ) . append ( requestURL . getPort ( ) ) ; } normalized . append ( requestURL . getPath ( ) ) ; return normalized . toString ( ) ; } catch ( MalformedURLException e ) { throw new IllegalStateException ( "Illegal URL for calculating the OAuth signature." , e ) ; } }
Normalize the URL for use in the signature . The OAuth spec says the URL protocol and host are to be lower - case and the query and fragments are to be stripped .
20,324
protected OAuthProviderToken createOAuthToken ( ConsumerAuthentication authentication ) { return getTokenServices ( ) . createUnauthorizedRequestToken ( authentication . getConsumerDetails ( ) . getConsumerKey ( ) , authentication . getOAuthParameters ( ) . get ( OAuthConsumerParameter . oauth_callback . toString ( ) ) ) ; }
Create the OAuth token for the specified consumer key .
20,325
protected Map < String , Object > decode ( String token ) { Map < String , String > headers = this . jwtHeaderConverter . convert ( token ) ; String keyIdHeader = headers . get ( KEY_ID ) ; if ( keyIdHeader == null ) { throw new InvalidTokenException ( "Invalid JWT/JWS: " + KEY_ID + " is a required JOSE Header" ) ; } JwkDefinitionSource . JwkDefinitionHolder jwkDefinitionHolder = this . jwkDefinitionSource . getDefinitionLoadIfNecessary ( keyIdHeader ) ; if ( jwkDefinitionHolder == null ) { throw new InvalidTokenException ( "Invalid JOSE Header " + KEY_ID + " (" + keyIdHeader + ")" ) ; } JwkDefinition jwkDefinition = jwkDefinitionHolder . getJwkDefinition ( ) ; String algorithmHeader = headers . get ( ALGORITHM ) ; if ( algorithmHeader == null ) { throw new InvalidTokenException ( "Invalid JWT/JWS: " + ALGORITHM + " is a required JOSE Header" ) ; } if ( jwkDefinition . getAlgorithm ( ) != null && ! algorithmHeader . equals ( jwkDefinition . getAlgorithm ( ) . headerParamValue ( ) ) ) { throw new InvalidTokenException ( "Invalid JOSE Header " + ALGORITHM + " (" + algorithmHeader + ")" + " does not match algorithm associated to JWK with " + KEY_ID + " (" + keyIdHeader + ")" ) ; } SignatureVerifier verifier = jwkDefinitionHolder . getSignatureVerifier ( ) ; Jwt jwt = JwtHelper . decode ( token ) ; jwt . verifySignature ( verifier ) ; Map < String , Object > claims = this . jsonParser . parseMap ( jwt . getClaims ( ) ) ; if ( claims . containsKey ( EXP ) && claims . get ( EXP ) instanceof Integer ) { Integer expiryInt = ( Integer ) claims . get ( EXP ) ; claims . put ( EXP , new Long ( expiryInt ) ) ; } this . getJwtClaimsSetVerifier ( ) . verify ( claims ) ; return claims ; }
Decodes and validates the supplied JWT followed by signature verification before returning the Claims from the JWT Payload .
20,326
public URL configureURLForProtectedAccess ( URL url , OAuthConsumerToken accessToken , String httpMethod , Map < String , String > additionalParameters ) throws OAuthRequestFailedException { return configureURLForProtectedAccess ( url , accessToken , getProtectedResourceDetailsService ( ) . loadProtectedResourceDetailsById ( accessToken . getResourceId ( ) ) , httpMethod , additionalParameters ) ; }
Create a configured URL . If the HTTP method to access the resource is POST or PUT and the Authorization header isn t supported then the OAuth parameters will be expected to be sent in the body of the request . Otherwise you can assume that the given URL is ready to be used without further work .
20,327
protected URL configureURLForProtectedAccess ( URL url , OAuthConsumerToken requestToken , ProtectedResourceDetails details , String httpMethod , Map < String , String > additionalParameters ) { String file ; if ( ! "POST" . equalsIgnoreCase ( httpMethod ) && ! "PUT" . equalsIgnoreCase ( httpMethod ) && ! details . isAcceptsAuthorizationHeader ( ) ) { StringBuilder fileb = new StringBuilder ( url . getPath ( ) ) ; String queryString = getOAuthQueryString ( details , requestToken , url , httpMethod , additionalParameters ) ; fileb . append ( '?' ) . append ( queryString ) ; file = fileb . toString ( ) ; } else { file = url . getFile ( ) ; } try { if ( "http" . equalsIgnoreCase ( url . getProtocol ( ) ) ) { URLStreamHandler streamHandler = getStreamHandlerFactory ( ) . getHttpStreamHandler ( details , requestToken , this , httpMethod , additionalParameters ) ; return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , file , streamHandler ) ; } else if ( "https" . equalsIgnoreCase ( url . getProtocol ( ) ) ) { URLStreamHandler streamHandler = getStreamHandlerFactory ( ) . getHttpsStreamHandler ( details , requestToken , this , httpMethod , additionalParameters ) ; return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , file , streamHandler ) ; } else { throw new OAuthRequestFailedException ( "Unsupported OAuth protocol: " + url . getProtocol ( ) ) ; } } catch ( MalformedURLException e ) { throw new IllegalStateException ( e ) ; } }
Internal use of configuring the URL for protected access the resource details already having been loaded .
20,328
protected String findValidHeaderValue ( Set < CharSequence > paramValues ) { String selectedValue = null ; if ( paramValues != null && ! paramValues . isEmpty ( ) ) { CharSequence value = paramValues . iterator ( ) . next ( ) ; if ( ! ( value instanceof QueryParameterValue ) ) { selectedValue = value . toString ( ) ; } } return selectedValue ; }
Finds a valid header value that is valid for the OAuth header .
20,329
protected OAuthConsumerToken getTokenFromProvider ( ProtectedResourceDetails details , URL tokenURL , String httpMethod , OAuthConsumerToken requestToken , Map < String , String > additionalParameters ) { boolean isAccessToken = requestToken != null ; if ( ! isAccessToken ) { requestToken = new OAuthConsumerToken ( ) ; } TreeMap < String , String > requestHeaders = new TreeMap < String , String > ( ) ; if ( "POST" . equalsIgnoreCase ( httpMethod ) ) { requestHeaders . put ( "Content-Type" , "application/x-www-form-urlencoded" ) ; } InputStream inputStream = readResource ( details , tokenURL , httpMethod , requestToken , additionalParameters , requestHeaders ) ; String tokenInfo ; try { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int len = inputStream . read ( buffer ) ; while ( len >= 0 ) { out . write ( buffer , 0 , len ) ; len = inputStream . read ( buffer ) ; } tokenInfo = new String ( out . toByteArray ( ) , "UTF-8" ) ; } catch ( IOException e ) { throw new OAuthRequestFailedException ( "Unable to read the token." , e ) ; } StringTokenizer tokenProperties = new StringTokenizer ( tokenInfo , "&" ) ; Map < String , String > tokenPropertyValues = new TreeMap < String , String > ( ) ; while ( tokenProperties . hasMoreElements ( ) ) { try { String tokenProperty = ( String ) tokenProperties . nextElement ( ) ; int equalsIndex = tokenProperty . indexOf ( '=' ) ; if ( equalsIndex > 0 ) { String propertyName = OAuthCodec . oauthDecode ( tokenProperty . substring ( 0 , equalsIndex ) ) ; String propertyValue = OAuthCodec . oauthDecode ( tokenProperty . substring ( equalsIndex + 1 ) ) ; tokenPropertyValues . put ( propertyName , propertyValue ) ; } else { tokenProperty = OAuthCodec . oauthDecode ( tokenProperty ) ; tokenPropertyValues . put ( tokenProperty , null ) ; } } catch ( DecoderException e ) { throw new OAuthRequestFailedException ( "Unable to decode token parameters." ) ; } } String tokenValue = tokenPropertyValues . remove ( OAuthProviderParameter . oauth_token . toString ( ) ) ; if ( tokenValue == null ) { throw new OAuthRequestFailedException ( "OAuth provider failed to return a token." ) ; } String tokenSecret = tokenPropertyValues . remove ( OAuthProviderParameter . oauth_token_secret . toString ( ) ) ; if ( tokenSecret == null ) { throw new OAuthRequestFailedException ( "OAuth provider failed to return a token secret." ) ; } OAuthConsumerToken consumerToken = new OAuthConsumerToken ( ) ; consumerToken . setValue ( tokenValue ) ; consumerToken . setSecret ( tokenSecret ) ; consumerToken . setResourceId ( details . getId ( ) ) ; consumerToken . setAccessToken ( isAccessToken ) ; if ( ! tokenPropertyValues . isEmpty ( ) ) { consumerToken . setAdditionalParameters ( tokenPropertyValues ) ; } return consumerToken ; }
Get the consumer token with the given parameters and URL . The determination of whether the retrieved token is an access token depends on whether a request token is provided .
20,330
protected String urlDecode ( String token ) { try { return URLDecoder . decode ( token , "utf-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
URL - decode a token .
20,331
protected HttpURLConnection openConnection ( URL requestTokenURL ) { try { HttpURLConnection connection = ( HttpURLConnection ) requestTokenURL . openConnection ( selectProxy ( requestTokenURL ) ) ; connection . setConnectTimeout ( getConnectionTimeout ( ) ) ; connection . setReadTimeout ( getReadTimeout ( ) ) ; return connection ; } catch ( IOException e ) { throw new OAuthRequestFailedException ( "Failed to open an OAuth connection." , e ) ; } }
Open a connection to the given URL .
20,332
protected Proxy selectProxy ( URL requestTokenURL ) { try { List < Proxy > selectedProxies = getProxySelector ( ) . select ( requestTokenURL . toURI ( ) ) ; return selectedProxies . isEmpty ( ) ? Proxy . NO_PROXY : selectedProxies . get ( 0 ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } }
Selects a proxy for the given URL .
20,333
protected String getSignatureBaseString ( Map < String , Set < CharSequence > > oauthParams , URL requestURL , String httpMethod ) { TreeMap < String , TreeSet < String > > sortedParameters = new TreeMap < String , TreeSet < String > > ( ) ; for ( Map . Entry < String , Set < CharSequence > > param : oauthParams . entrySet ( ) ) { String key = oauthEncode ( param . getKey ( ) ) ; TreeSet < String > sortedValues = sortedParameters . get ( key ) ; if ( sortedValues == null ) { sortedValues = new TreeSet < String > ( ) ; sortedParameters . put ( key , sortedValues ) ; } for ( CharSequence value : param . getValue ( ) ) { sortedValues . add ( oauthEncode ( value . toString ( ) ) ) ; } } StringBuilder queryString = new StringBuilder ( ) ; Iterator < Map . Entry < String , TreeSet < String > > > sortedIt = sortedParameters . entrySet ( ) . iterator ( ) ; while ( sortedIt . hasNext ( ) ) { Map . Entry < String , TreeSet < String > > sortedParameter = sortedIt . next ( ) ; for ( Iterator < String > sortedParametersIterator = sortedParameter . getValue ( ) . iterator ( ) ; sortedParametersIterator . hasNext ( ) ; ) { String parameterValue = sortedParametersIterator . next ( ) ; if ( parameterValue == null ) { parameterValue = "" ; } queryString . append ( sortedParameter . getKey ( ) ) . append ( '=' ) . append ( parameterValue ) ; if ( sortedIt . hasNext ( ) || sortedParametersIterator . hasNext ( ) ) { queryString . append ( '&' ) ; } } } StringBuilder url = new StringBuilder ( requestURL . getProtocol ( ) . toLowerCase ( ) ) . append ( "://" ) . append ( requestURL . getHost ( ) . toLowerCase ( ) ) ; if ( ( requestURL . getPort ( ) >= 0 ) && ( requestURL . getPort ( ) != requestURL . getDefaultPort ( ) ) ) { url . append ( ":" ) . append ( requestURL . getPort ( ) ) ; } url . append ( requestURL . getPath ( ) ) ; return new StringBuilder ( httpMethod . toUpperCase ( ) ) . append ( '&' ) . append ( oauthEncode ( url . toString ( ) ) ) . append ( '&' ) . append ( oauthEncode ( queryString . toString ( ) ) ) . toString ( ) ; }
Get the signature base string for the specified parameters . It is presumed the parameters are NOT OAuth - encoded .
20,334
protected void redirectUser ( UserRedirectRequiredException e , HttpServletRequest request , HttpServletResponse response ) throws IOException { String redirectUri = e . getRedirectUri ( ) ; UriComponentsBuilder builder = UriComponentsBuilder . fromHttpUrl ( redirectUri ) ; Map < String , String > requestParams = e . getRequestParams ( ) ; for ( Map . Entry < String , String > param : requestParams . entrySet ( ) ) { builder . queryParam ( param . getKey ( ) , param . getValue ( ) ) ; } if ( e . getStateKey ( ) != null ) { builder . queryParam ( "state" , e . getStateKey ( ) ) ; } this . redirectStrategy . sendRedirect ( request , response , builder . build ( ) . encode ( ) . toUriString ( ) ) ; }
Redirect the user according to the specified exception .
20,335
protected String calculateCurrentUri ( HttpServletRequest request ) throws UnsupportedEncodingException { ServletUriComponentsBuilder builder = ServletUriComponentsBuilder . fromRequest ( request ) ; String queryString = request . getQueryString ( ) ; boolean legalSpaces = queryString != null && queryString . contains ( "+" ) ; if ( legalSpaces ) { builder . replaceQuery ( queryString . replace ( "+" , "%20" ) ) ; } UriComponents uri = null ; try { uri = builder . replaceQueryParam ( "code" ) . build ( true ) ; } catch ( IllegalArgumentException ex ) { return null ; } String query = uri . getQuery ( ) ; if ( legalSpaces ) { query = query . replace ( "%20" , "+" ) ; } return ServletUriComponentsBuilder . fromUri ( uri . toUri ( ) ) . replaceQuery ( query ) . build ( ) . toString ( ) ; }
Calculate the current URI given the request .
20,336
public void tokenEndpointAuthenticationFilters ( List < Filter > filters ) { Assert . notNull ( filters , "Custom authentication filter list must not be null" ) ; this . tokenEndpointAuthenticationFilters = new ArrayList < Filter > ( filters ) ; }
Sets a new list of custom authentication filters for the TokenEndpoint . Filters will be set upstream of the default BasicAuthenticationFilter .
20,337
public int vote ( Authentication authentication , Object object , Collection < ConfigAttribute > configAttributes ) { int result = ACCESS_ABSTAIN ; if ( authentication . getDetails ( ) instanceof OAuthAuthenticationDetails ) { OAuthAuthenticationDetails details = ( OAuthAuthenticationDetails ) authentication . getDetails ( ) ; for ( Object configAttribute : configAttributes ) { ConfigAttribute attribute = ( ConfigAttribute ) configAttribute ; if ( ConsumerSecurityConfig . PERMIT_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_GRANTED ; } else if ( ConsumerSecurityConfig . DENY_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_DENIED ; } else if ( supports ( attribute ) ) { ConsumerSecurityConfig config = ( ConsumerSecurityConfig ) attribute ; if ( ( config . getSecurityType ( ) == ConsumerSecurityConfig . ConsumerSecurityType . CONSUMER_KEY ) && ( config . getAttribute ( ) . equals ( details . getConsumerDetails ( ) . getConsumerKey ( ) ) ) ) { return ACCESS_GRANTED ; } else if ( config . getSecurityType ( ) == ConsumerSecurityConfig . ConsumerSecurityType . CONSUMER_ROLE ) { List < GrantedAuthority > authorities = details . getConsumerDetails ( ) . getAuthorities ( ) ; if ( authorities != null ) { for ( GrantedAuthority authority : authorities ) { if ( authority . getAuthority ( ) . equals ( config . getAttribute ( ) ) ) { return ACCESS_GRANTED ; } } } } } } } return result ; }
Votes on giving access to the specified authentication based on the security attributes .
20,338
public AdminController adminController ( TokenStore tokenStore , @ Qualifier ( "consumerTokenServices" ) ConsumerTokenServices tokenServices , SparklrUserApprovalHandler userApprovalHandler ) { AdminController adminController = new AdminController ( ) ; adminController . setTokenStore ( tokenStore ) ; adminController . setTokenServices ( tokenServices ) ; adminController . setUserApprovalHandler ( userApprovalHandler ) ; return adminController ; }
N . B . the
20,339
public boolean revokeApprovals ( Collection < Approval > approvals ) { boolean success = true ; for ( Approval approval : approvals ) { Collection < OAuth2AccessToken > tokens = store . findTokensByClientIdAndUserName ( approval . getClientId ( ) , approval . getUserId ( ) ) ; for ( OAuth2AccessToken token : tokens ) { OAuth2Authentication authentication = store . readAuthentication ( token ) ; if ( authentication != null && approval . getClientId ( ) . equals ( authentication . getOAuth2Request ( ) . getClientId ( ) ) ) { store . removeAccessToken ( token ) ; } } } return success ; }
Revoke all tokens that match the client and user in the approvals supplied .
20,340
public Collection < Approval > getApprovals ( String userId , String clientId ) { Collection < Approval > result = new HashSet < Approval > ( ) ; Collection < OAuth2AccessToken > tokens = store . findTokensByClientIdAndUserName ( clientId , userId ) ; for ( OAuth2AccessToken token : tokens ) { OAuth2Authentication authentication = store . readAuthentication ( token ) ; if ( authentication != null ) { Date expiresAt = token . getExpiration ( ) ; for ( String scope : token . getScope ( ) ) { result . add ( new Approval ( userId , clientId , scope , expiresAt , ApprovalStatus . APPROVED ) ) ; } } } return result ; }
Extract the implied approvals from any tokens associated with the user and client id supplied .
20,341
protected ProtectedResourceDetails checkForResourceThatNeedsAuthorization ( Exception ex ) throws ServletException , IOException { Throwable [ ] causeChain = getThrowableAnalyzer ( ) . determineCauseChain ( ex ) ; AccessTokenRequiredException ase = ( AccessTokenRequiredException ) getThrowableAnalyzer ( ) . getFirstThrowableOfType ( AccessTokenRequiredException . class , causeChain ) ; ProtectedResourceDetails resourceThatNeedsAuthorization ; if ( ase != null ) { resourceThatNeedsAuthorization = ase . getResource ( ) ; if ( resourceThatNeedsAuthorization == null ) { throw new OAuthRequestFailedException ( ase . getMessage ( ) ) ; } } else { if ( ex instanceof ServletException ) { throw ( ServletException ) ex ; } if ( ex instanceof IOException ) { throw ( IOException ) ex ; } else if ( ex instanceof RuntimeException ) { throw ( RuntimeException ) ex ; } throw new RuntimeException ( ex ) ; } return resourceThatNeedsAuthorization ; }
Check the given exception for the resource that needs authorization . If the exception was not thrown because a resource needed authorization then rethrow the exception .
20,342
protected String getUserAuthorizationRedirectURL ( ProtectedResourceDetails details , OAuthConsumerToken requestToken , String callbackURL ) { try { String baseURL = details . getUserAuthorizationURL ( ) ; StringBuilder builder = new StringBuilder ( baseURL ) ; char appendChar = baseURL . indexOf ( '?' ) < 0 ? '?' : '&' ; builder . append ( appendChar ) . append ( "oauth_token=" ) ; builder . append ( URLEncoder . encode ( requestToken . getValue ( ) , "UTF-8" ) ) ; if ( ! details . isUse10a ( ) ) { builder . append ( '&' ) . append ( "oauth_callback=" ) ; builder . append ( URLEncoder . encode ( callbackURL , "UTF-8" ) ) ; } return builder . toString ( ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } }
Get the URL to which to redirect the user for authorization of protected resources .
20,343
private OAuth2Authentication createRefreshedAuthentication ( OAuth2Authentication authentication , TokenRequest request ) { OAuth2Authentication narrowed = authentication ; Set < String > scope = request . getScope ( ) ; OAuth2Request clientAuth = authentication . getOAuth2Request ( ) . refresh ( request ) ; if ( scope != null && ! scope . isEmpty ( ) ) { Set < String > originalScope = clientAuth . getScope ( ) ; if ( originalScope == null || ! originalScope . containsAll ( scope ) ) { throw new InvalidScopeException ( "Unable to narrow the scope of the client authentication to " + scope + "." , originalScope ) ; } else { clientAuth = clientAuth . narrowScope ( scope ) ; } } narrowed = new OAuth2Authentication ( clientAuth , authentication . getUserAuthentication ( ) ) ; return narrowed ; }
Create a refreshed authentication .
20,344
protected int getAccessTokenValiditySeconds ( OAuth2Request clientAuth ) { if ( clientDetailsService != null ) { ClientDetails client = clientDetailsService . loadClientByClientId ( clientAuth . getClientId ( ) ) ; Integer validity = client . getAccessTokenValiditySeconds ( ) ; if ( validity != null ) { return validity ; } } return accessTokenValiditySeconds ; }
The access token validity period in seconds
20,345
protected int getRefreshTokenValiditySeconds ( OAuth2Request clientAuth ) { if ( clientDetailsService != null ) { ClientDetails client = clientDetailsService . loadClientByClientId ( clientAuth . getClientId ( ) ) ; Integer validity = client . getRefreshTokenValiditySeconds ( ) ; if ( validity != null ) { return validity ; } } return refreshTokenValiditySeconds ; }
The refresh token validity period in seconds
20,346
public void validateNonce ( ConsumerDetails consumerDetails , long timestamp , String nonce ) throws AuthenticationException { long nowSeconds = ( System . currentTimeMillis ( ) / 1000 ) ; if ( ( nowSeconds - timestamp ) > getValidityWindowSeconds ( ) ) { throw new CredentialsExpiredException ( "Expired timestamp." ) ; } }
we ll default to a 12 - hour validity window .
20,347
public void verify ( String signatureBaseString , String signature ) throws InvalidSignatureException { if ( this . encoder != null ) { if ( ! this . encoder . isPasswordValid ( this . secret , signature , this . salt ) ) { throw new InvalidSignatureException ( "Invalid signature for signature method " + getName ( ) ) ; } } else if ( ! signature . equals ( this . secret ) ) { throw new InvalidSignatureException ( "Invalid signature for signature method " + getName ( ) ) ; } }
Validates that the signature is the same as the secret .
20,348
public boolean hasAnyScope ( String ... scopes ) { boolean result = OAuth2ExpressionUtils . hasAnyScope ( authentication , scopes ) ; if ( ! result ) { missingScopes . addAll ( Arrays . asList ( scopes ) ) ; } return result ; }
Check if the current OAuth2 authentication has one of the scopes specified .
20,349
public boolean hasAnyScopeMatching ( String ... scopesRegex ) { boolean result = OAuth2ExpressionUtils . hasAnyScopeMatching ( authentication , scopesRegex ) ; if ( ! result ) { missingScopes . addAll ( Arrays . asList ( scopesRegex ) ) ; } return result ; }
Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression .
20,350
public static PublicKey createPublicKey ( byte [ ] publicKey ) { if ( publicKey == null ) { return null ; } try { KeyFactory fac = KeyFactory . getInstance ( "RSA" ) ; EncodedKeySpec spec = new X509EncodedKeySpec ( publicKey ) ; return fac . generatePublic ( spec ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( e ) ; } catch ( InvalidKeySpecException e ) { throw new IllegalStateException ( e ) ; } }
Creates a public key from the X509 - encoded value of the given bytes .
20,351
private static byte [ ] base64Decode ( String value ) { if ( value == null ) { return null ; } try { return Base64 . decodeBase64 ( value . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Utility method for decoding a base - 64 - encoded string .
20,352
public void addAdditionalInformation ( String key , String value ) { if ( this . additionalInformation == null ) { this . additionalInformation = new TreeMap < String , String > ( ) ; } this . additionalInformation . put ( key , value ) ; }
Add some additional information with this OAuth error .
20,353
public static OAuth2Exception create ( String errorCode , String errorMessage ) { if ( errorMessage == null ) { errorMessage = errorCode == null ? "OAuth Error" : errorCode ; } if ( INVALID_CLIENT . equals ( errorCode ) ) { return new InvalidClientException ( errorMessage ) ; } else if ( UNAUTHORIZED_CLIENT . equals ( errorCode ) ) { return new UnauthorizedClientException ( errorMessage ) ; } else if ( INVALID_GRANT . equals ( errorCode ) ) { return new InvalidGrantException ( errorMessage ) ; } else if ( INVALID_SCOPE . equals ( errorCode ) ) { return new InvalidScopeException ( errorMessage ) ; } else if ( INVALID_TOKEN . equals ( errorCode ) ) { return new InvalidTokenException ( errorMessage ) ; } else if ( INVALID_REQUEST . equals ( errorCode ) ) { return new InvalidRequestException ( errorMessage ) ; } else if ( REDIRECT_URI_MISMATCH . equals ( errorCode ) ) { return new RedirectMismatchException ( errorMessage ) ; } else if ( UNSUPPORTED_GRANT_TYPE . equals ( errorCode ) ) { return new UnsupportedGrantTypeException ( errorMessage ) ; } else if ( UNSUPPORTED_RESPONSE_TYPE . equals ( errorCode ) ) { return new UnsupportedResponseTypeException ( errorMessage ) ; } else if ( ACCESS_DENIED . equals ( errorCode ) ) { return new UserDeniedAuthorizationException ( errorMessage ) ; } else { return new OAuth2Exception ( errorMessage ) ; } }
Creates the appropriate subclass of OAuth2Exception given the errorCode .
20,354
public URI getURI ( ) throws URIException { StringBuffer buffer = new StringBuffer ( ) ; if ( this . httphost != null ) { buffer . append ( this . httphost . getProtocol ( ) . getScheme ( ) ) ; buffer . append ( "://" ) ; buffer . append ( this . httphost . getHostName ( ) ) ; int port = this . httphost . getPort ( ) ; if ( port != - 1 && port != this . httphost . getProtocol ( ) . getDefaultPort ( ) ) { buffer . append ( ":" ) ; buffer . append ( port ) ; } } buffer . append ( this . path ) ; if ( this . queryString != null ) { buffer . append ( '?' ) ; buffer . append ( this . queryString ) ; } String charset = getParams ( ) . getUriCharset ( ) ; return new URI ( buffer . toString ( ) , true , charset ) ; }
Returns the URI of the HTTP method
20,355
public void setURI ( URI uri ) throws URIException { if ( uri . isAbsoluteURI ( ) ) { this . httphost = new HttpHost ( uri ) ; } setPath ( uri . getPath ( ) == null ? "/" : uri . getEscapedPath ( ) ) ; setQueryString ( uri . getEscapedQuery ( ) ) ; }
Sets the URI for this method .
20,356
public void setHttp11 ( boolean http11 ) { if ( http11 ) { this . params . setVersion ( HttpVersion . HTTP_1_1 ) ; } else { this . params . setVersion ( HttpVersion . HTTP_1_0 ) ; } }
Sets whether version 1 . 1 of the HTTP protocol should be used per default .
20,357
public void setQueryString ( NameValuePair [ ] params ) { LOG . trace ( "enter HttpMethodBase.setQueryString(NameValuePair[])" ) ; queryString = EncodingUtil . formUrlEncode ( params , "UTF-8" ) ; }
Sets the query string of this HTTP method . The pairs are encoded as UTF - 8 characters . To use a different charset the parameters can be encoded manually using EncodingUtil and set as a single String .
20,358
public void setRequestHeader ( String headerName , String headerValue ) { Header header = new Header ( headerName , headerValue ) ; setRequestHeader ( header ) ; }
Set the specified request header overwriting any previous value . Note that header - name matching is case - insensitive .
20,359
public void setRequestHeader ( Header header ) { Header [ ] headers = getRequestHeaderGroup ( ) . getHeaders ( header . getName ( ) ) ; for ( int i = 0 ; i < headers . length ; i ++ ) { getRequestHeaderGroup ( ) . removeHeader ( headers [ i ] ) ; } getRequestHeaderGroup ( ) . addHeader ( header ) ; }
Sets the specified request header overwriting any previous value . Note that header - name matching is case insensitive .
20,360
private void checkExecuteConditions ( HttpState state , HttpConnection conn ) throws HttpException { if ( state == null ) { throw new IllegalArgumentException ( "HttpState parameter may not be null" ) ; } if ( conn == null ) { throw new IllegalArgumentException ( "HttpConnection parameter may not be null" ) ; } if ( this . aborted ) { throw new IllegalStateException ( "Method has been aborted" ) ; } if ( ! validate ( ) ) { throw new ProtocolException ( "HttpMethodBase object not valid" ) ; } }
Tests if the this method is ready to be executed .
20,361
public void abort ( ) { if ( this . aborted ) { return ; } this . aborted = true ; HttpConnection conn = this . responseConnection ; if ( conn != null ) { conn . close ( ) ; } }
Aborts the execution of this method .
20,362
public void recycle ( ) { LOG . trace ( "enter HttpMethodBase.recycle()" ) ; releaseConnection ( ) ; path = null ; followRedirects = false ; doAuthentication = true ; queryString = null ; getRequestHeaderGroup ( ) . clear ( ) ; getResponseHeaderGroup ( ) . clear ( ) ; getResponseTrailerHeaderGroup ( ) . clear ( ) ; statusLine = null ; effectiveVersion = null ; aborted = false ; used = false ; params = new HttpMethodParams ( ) ; responseBody = null ; recoverableExceptionCount = 0 ; connectionCloseForced = false ; hostAuthState . invalidate ( ) ; proxyAuthState . invalidate ( ) ; cookiespec = null ; requestSent = false ; }
Recycles the HTTP method so that it can be used again . Note that all of the instance variables will be reset once this method has been called . This method will also release the connection being used by this HTTP method .
20,363
public void removeRequestHeader ( String headerName ) { Header [ ] headers = getRequestHeaderGroup ( ) . getHeaders ( headerName ) ; for ( int i = 0 ; i < headers . length ; i ++ ) { getRequestHeaderGroup ( ) . removeHeader ( headers [ i ] ) ; } }
Remove the request header associated with the given name . Note that header - name matching is case insensitive .
20,364
@ SuppressWarnings ( "deprecation" ) private CookieSpec getCookieSpec ( final HttpState state ) { if ( this . cookiespec == null ) { int i = state . getCookiePolicy ( ) ; if ( i == - 1 ) { this . cookiespec = CookiePolicy . getCookieSpec ( this . params . getCookiePolicy ( ) ) ; } else { this . cookiespec = CookiePolicy . getSpecByPolicy ( i ) ; } this . cookiespec . setValidDateFormats ( ( Collection ) this . params . getParameter ( HttpMethodParams . DATE_PATTERNS ) ) ; } return this . cookiespec ; }
Returns the actual cookie policy
20,365
private void putAllCookiesInASingleHeader ( String host , CookieSpec matcher , Cookie [ ] cookies ) { LOG . trace ( "enter putAllCookiesInASingleHeader(String host, CookieSpec matcher, Cookie[] cookies)" ) ; HashMap < String , Cookie > mergedCookies = new HashMap < String , Cookie > ( ) ; Header [ ] cookieLineHeaders = getRequestHeaderGroup ( ) . getHeaders ( HttpHeader . COOKIE ) ; for ( Header cookieLineHeader : cookieLineHeaders ) { List < Cookie > cookiesHeader = parseCookieHeader ( host , cookieLineHeader . getValue ( ) ) ; for ( Cookie cookieHeader : cookiesHeader ) { mergedCookies . put ( cookieHeader . getName ( ) , cookieHeader ) ; } getRequestHeaderGroup ( ) . removeHeader ( cookieLineHeader ) ; } for ( Cookie cookie : cookies ) { mergedCookies . put ( cookie . getName ( ) , cookie ) ; } cookies = mergedCookies . values ( ) . toArray ( new Cookie [ mergedCookies . size ( ) ] ) ; String s = matcher . formatCookies ( cookies ) ; getRequestHeaderGroup ( ) . addHeader ( new Header ( HttpHeader . COOKIE , s , true ) ) ; }
Put all the cookies in a single header line .
20,366
static List < Cookie > parseCookieHeader ( String host , String cookieHeaderValue ) { if ( StringUtils . isEmpty ( cookieHeaderValue ) ) { return Collections . emptyList ( ) ; } String [ ] cookies = cookieHeaderValue . split ( ";" ) ; List < Cookie > cookiesList = new ArrayList < Cookie > ( ) ; for ( String cookie : cookies ) { String [ ] parts = cookie . split ( "=" ) ; if ( parts . length == 1 ) { cookiesList . add ( new Cookie ( host , parts [ 0 ] . trim ( ) , "" ) ) ; } else { cookiesList . add ( new Cookie ( host , parts [ 0 ] . trim ( ) , parts [ 1 ] . trim ( ) ) ) ; } } return cookiesList ; }
Parse a cookie header to return a list of cookies .
20,367
protected static String generateRequestLine ( HttpConnection connection , String name , String requestPath , String query , String version ) { LOG . trace ( "enter HttpMethodBase.generateRequestLine(HttpConnection, " + "String, String, String, String)" ) ; StringBuffer buf = new StringBuffer ( ) ; buf . append ( name ) ; buf . append ( " " ) ; if ( ! connection . isTransparent ( ) ) { Protocol protocol = connection . getProtocol ( ) ; buf . append ( protocol . getScheme ( ) . toLowerCase ( Locale . ENGLISH ) ) ; buf . append ( "://" ) ; buf . append ( connection . getHost ( ) ) ; if ( ( connection . getPort ( ) != - 1 ) && ( connection . getPort ( ) != protocol . getDefaultPort ( ) ) ) { buf . append ( ":" ) ; buf . append ( connection . getPort ( ) ) ; } } if ( requestPath == null ) { buf . append ( "/" ) ; } else { if ( ! connection . isTransparent ( ) && ! requestPath . startsWith ( "/" ) ) { buf . append ( "/" ) ; } buf . append ( requestPath ) ; } if ( query != null ) { buf . append ( "?" ) ; buf . append ( query ) ; } buf . append ( " " ) ; buf . append ( version ) ; buf . append ( "\r\n" ) ; return buf . toString ( ) ; }
Generates HTTP request line according to the specified attributes .
20,368
private String getRequestLine ( HttpConnection conn ) { return HttpMethodBase . generateRequestLine ( conn , getName ( ) , getPath ( ) , getQueryString ( ) , this . effectiveVersion . toString ( ) ) ; }
Returns the request line .
20,369
private static boolean canResponseHaveBody ( int status ) { LOG . trace ( "enter HttpMethodBase.canResponseHaveBody(int)" ) ; boolean result = true ; if ( ( status >= 100 && status <= 199 ) || ( status == 204 ) || ( status == 304 ) ) { result = false ; } return result ; }
Per RFC 2616 section 4 . 3 some response can never contain a message body .
20,370
protected void responseBodyConsumed ( ) { responseStream = null ; if ( responseConnection != null ) { responseConnection . setLastResponseInputStream ( null ) ; if ( shouldCloseConnection ( responseConnection ) ) { responseConnection . close ( ) ; } else { try { if ( responseConnection . isResponseAvailable ( ) ) { boolean logExtraInput = getParams ( ) . isParameterTrue ( HttpMethodParams . WARN_EXTRA_INPUT ) ; if ( logExtraInput ) { LOG . warn ( "Extra response data detected - closing connection" ) ; } responseConnection . close ( ) ; } } catch ( IOException e ) { LOG . warn ( e . getMessage ( ) ) ; responseConnection . close ( ) ; } } } this . connectionCloseForced = false ; ensureConnectionRelease ( ) ; }
A response has been consumed .
20,371
protected void addSeed ( URI uri , String method ) { String visitedURI ; try { visitedURI = URLCanonicalizer . buildCleanedParametersURIRepresentation ( uri , spider . getSpiderParam ( ) . getHandleParameters ( ) , spider . getSpiderParam ( ) . isHandleODataParametersVisited ( ) ) ; } catch ( URIException e ) { return ; } synchronized ( visitedGet ) { if ( visitedGet . contains ( visitedURI ) ) { log . debug ( "URI already visited: " + visitedURI ) ; return ; } else { visitedGet . add ( visitedURI ) ; } } SpiderTask task = new SpiderTask ( spider , null , uri , 0 , method ) ; spider . submitTask ( task ) ; spider . notifyListenersFoundURI ( uri . toString ( ) , method , FetchStatus . SEED ) ; }
Adds a new seed if it wasn t already processed .
20,372
public void addFetchFilter ( FetchFilter filter ) { log . debug ( "Loading fetch filter: " + filter . getClass ( ) . getSimpleName ( ) ) ; fetchFilters . add ( filter ) ; }
Adds a new fetch filter to the spider .
20,373
public void addParseFilter ( ParseFilter filter ) { log . debug ( "Loading parse filter: " + filter . getClass ( ) . getSimpleName ( ) ) ; parseFilters . add ( filter ) ; }
Adds the parse filter to the spider controller .
20,374
public void reset ( ) { visitedGet . clear ( ) ; visitedPost . clear ( ) ; for ( SpiderParser parser : parsers ) { parser . removeSpiderParserListener ( this ) ; } }
Clears the previous process .
20,375
private boolean arrayKeyValueExists ( String key , String value ) { if ( visitedPost . containsKey ( key ) ) { for ( String s : visitedPost . get ( key ) ) { if ( s . equals ( value ) ) { return true ; } } } return false ; }
Checks whether the value exists in an ArrayList of certain key .
20,376
public void setSummaryContent ( String content ) { Logger . getRootLogger ( ) . info ( "New summary: " + content ) ; summaryArea . setText ( "<html><b>" + summaryTitleText + "</b><br/><br/>" + content + "</html>" ) ; }
Sets the summary content .
20,377
private JSlider getSliderHostPerScan ( ) { if ( sliderHostPerScan == null ) { sliderHostPerScan = new JSlider ( ) ; sliderHostPerScan . setMaximum ( 5 ) ; sliderHostPerScan . setMinimum ( 1 ) ; sliderHostPerScan . setMinorTickSpacing ( 1 ) ; sliderHostPerScan . setPaintTicks ( true ) ; sliderHostPerScan . setPaintLabels ( true ) ; sliderHostPerScan . setName ( "" ) ; sliderHostPerScan . setMajorTickSpacing ( 1 ) ; sliderHostPerScan . setSnapToTicks ( true ) ; sliderHostPerScan . setPaintTrack ( true ) ; } return sliderHostPerScan ; }
This method initializes sliderHostPerScan
20,378
private JSlider getSliderThreadsPerHost ( ) { if ( sliderThreadsPerHost == null ) { sliderThreadsPerHost = new PositiveValuesSlider ( Constant . MAX_THREADS_PER_SCAN ) ; sliderThreadsPerHost . addChangeListener ( new ChangeListener ( ) { public void stateChanged ( ChangeEvent e ) { setLabelThreadsPerHostValue ( getSliderThreadsPerHost ( ) . getValue ( ) ) ; } } ) ; } return sliderThreadsPerHost ; }
This method initializes sliderThreadsPerHost
20,379
private static JScrollPane createScrollableTreeAddOnsNotRunnable ( final AddOnCollection availableAddOns , AddOn ... addOnsNotRunnable ) { AddOnSearcher addOnSearcher = new AddOnSearcher ( ) { public AddOn searchAddOn ( String id ) { return availableAddOns . getAddOn ( id ) ; } } ; DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode ( "" ) ; for ( AddOn addOn : addOnsNotRunnable ) { DefaultMutableTreeNode addOnNode = new DefaultMutableTreeNode ( addOn . getName ( ) ) ; AddOn . AddOnRunRequirements requirements = addOn . calculateRunRequirements ( availableAddOns . getAddOns ( ) ) ; List < String > issues = getUiRunningIssues ( requirements , addOnSearcher ) ; if ( issues . isEmpty ( ) ) { issues . addAll ( getUiExtensionsRunningIssues ( requirements , addOnSearcher ) ) ; } for ( String issue : issues ) { addOnNode . add ( new DefaultMutableTreeNode ( issue ) ) ; } rootNode . add ( addOnNode ) ; } JXTree tree = new JXTree ( new DefaultTreeModel ( rootNode ) ) ; tree . setVisibleRowCount ( 5 ) ; tree . setEditable ( false ) ; tree . setRootVisible ( false ) ; tree . setShowsRootHandles ( true ) ; tree . expandAll ( ) ; return new JScrollPane ( tree ) ; }
Creates a scrollable tree with the given add - ons as root nodes and its issues as child nodes .
20,380
private void applyConnectionParams ( final HttpMethod method ) throws IOException { int timeout = 0 ; Object param = method . getParams ( ) . getParameter ( HttpMethodParams . SO_TIMEOUT ) ; if ( param == null ) { param = this . conn . getParams ( ) . getParameter ( HttpConnectionParams . SO_TIMEOUT ) ; } if ( param != null ) { timeout = ( ( Integer ) param ) . intValue ( ) ; } this . conn . setSocketTimeout ( timeout ) ; }
Applies connection parameters specified for a given method
20,381
private boolean executeConnect ( ) throws IOException , HttpException { this . connectMethod = new ConnectMethod ( this . hostConfiguration ) ; this . connectMethod . getParams ( ) . setDefaults ( this . hostConfiguration . getParams ( ) ) ; String agent = ( String ) getParams ( ) . getParameter ( PARAM_DEFAULT_USER_AGENT_CONNECT_REQUESTS ) ; if ( agent != null ) { this . connectMethod . setRequestHeader ( "User-Agent" , agent ) ; } int code ; for ( ; ; ) { if ( ! this . conn . isOpen ( ) ) { this . conn . open ( ) ; } if ( this . params . isAuthenticationPreemptive ( ) || this . state . isAuthenticationPreemptive ( ) ) { LOG . debug ( "Preemptively sending default basic credentials" ) ; this . connectMethod . getProxyAuthState ( ) . setPreemptive ( ) ; this . connectMethod . getProxyAuthState ( ) . setAuthAttempted ( true ) ; } try { authenticateProxy ( this . connectMethod ) ; } catch ( AuthenticationException e ) { LOG . error ( e . getMessage ( ) , e ) ; } applyConnectionParams ( this . connectMethod ) ; this . connectMethod . execute ( state , this . conn ) ; code = this . connectMethod . getStatusCode ( ) ; boolean retry = false ; AuthState authstate = this . connectMethod . getProxyAuthState ( ) ; authstate . setAuthRequested ( code == HttpStatus . SC_PROXY_AUTHENTICATION_REQUIRED ) ; if ( authstate . isAuthRequested ( ) ) { if ( processAuthenticationResponse ( this . connectMethod ) ) { retry = true ; } } if ( ! retry ) { break ; } if ( this . connectMethod . getResponseBodyAsStream ( ) != null ) { this . connectMethod . getResponseBodyAsStream ( ) . close ( ) ; } } if ( ( code >= 200 ) && ( code < 300 ) ) { this . conn . tunnelCreated ( ) ; this . connectMethod = null ; return true ; } else { return false ; } }
Executes a ConnectMethod to establish a tunneled connection .
20,382
private boolean processRedirectResponse ( final HttpMethod method ) throws RedirectException { Header locationHeader = method . getResponseHeader ( "location" ) ; if ( locationHeader == null ) { LOG . error ( "Received redirect response " + method . getStatusCode ( ) + " but no location header" ) ; return false ; } String location = locationHeader . getValue ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Redirect requested to location '" + location + "'" ) ; } URI redirectUri = null ; URI currentUri = null ; try { currentUri = new URI ( this . conn . getProtocol ( ) . getScheme ( ) , null , this . conn . getHost ( ) , this . conn . getPort ( ) , method . getPath ( ) ) ; String charset = method . getParams ( ) . getUriCharset ( ) ; redirectUri = new URI ( location , true , charset ) ; if ( redirectUri . isRelativeURI ( ) ) { if ( this . params . isParameterTrue ( HttpClientParams . REJECT_RELATIVE_REDIRECT ) ) { LOG . warn ( "Relative redirect location '" + location + "' not allowed" ) ; return false ; } else { LOG . debug ( "Redirect URI is not absolute - parsing as relative" ) ; redirectUri = new URI ( currentUri , redirectUri ) ; } } else { method . getParams ( ) . setDefaults ( this . params ) ; } method . setURI ( redirectUri ) ; hostConfiguration . setHost ( redirectUri ) ; } catch ( URIException ex ) { throw new InvalidRedirectLocationException ( "Invalid redirect location: " + location , location , ex ) ; } if ( this . params . isParameterFalse ( HttpClientParams . ALLOW_CIRCULAR_REDIRECTS ) ) { if ( this . redirectLocations == null ) { this . redirectLocations = new HashSet < URI > ( ) ; } this . redirectLocations . add ( currentUri ) ; try { if ( redirectUri . hasQuery ( ) ) { redirectUri . setQuery ( null ) ; } } catch ( URIException e ) { return false ; } if ( this . redirectLocations . contains ( redirectUri ) ) { throw new CircularRedirectException ( "Circular redirect to '" + redirectUri + "'" ) ; } } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Redirecting from '" + currentUri . getEscapedURI ( ) + "' to '" + redirectUri . getEscapedURI ( ) ) ; } method . getHostAuthState ( ) . invalidate ( ) ; method . getProxyAuthState ( ) . invalidate ( ) ; return true ; }
Process the redirect response .
20,383
private boolean processAuthenticationResponse ( final HttpMethod method ) { LOG . trace ( "enter HttpMethodBase.processAuthenticationResponse(" + "HttpState, HttpConnection)" ) ; try { switch ( method . getStatusCode ( ) ) { case HttpStatus . SC_UNAUTHORIZED : return processWWWAuthChallenge ( method ) ; case HttpStatus . SC_PROXY_AUTHENTICATION_REQUIRED : return processProxyAuthChallenge ( method ) ; default : return false ; } } catch ( Exception e ) { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( e . getMessage ( ) , e ) ; } return false ; } }
Processes a response that requires authentication
20,384
public boolean isSelectedPartially ( TreePath path ) { CheckedNode cn = nodesCheckingState . get ( path ) ; return cn . isSelected && cn . hasChildren && ! cn . allChildrenSelected ; }
Returns true in case that the node is selected has children but not all of them are selected
20,385
private void addSubtreeToCheckingStateTracking ( DefaultMutableTreeNode node ) { TreeNode [ ] path = node . getPath ( ) ; TreePath tp = new TreePath ( path ) ; CheckedNode cn = new CheckedNode ( false , node . getChildCount ( ) > 0 , false ) ; nodesCheckingState . put ( tp , cn ) ; for ( int i = 0 ; i < node . getChildCount ( ) ; i ++ ) { addSubtreeToCheckingStateTracking ( ( DefaultMutableTreeNode ) tp . pathByAddingChild ( node . getChildAt ( i ) ) . getLastPathComponent ( ) ) ; } }
Creating data structure of the current model for the checking mechanism
20,386
private JCheckBox getChkShowPassword ( ) { if ( chkShowPassword == null ) { chkShowPassword = new JCheckBox ( ) ; chkShowPassword . setText ( Constant . messages . getString ( "conn.options.proxy.auth.showpass" ) ) ; chkShowPassword . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent e ) { if ( chkShowPassword . isSelected ( ) ) { txtProxyChainPassword . setEchoChar ( ( char ) 0 ) ; } else { txtProxyChainPassword . setEchoChar ( '*' ) ; } } } ) ; } return chkShowPassword ; }
This method initializes chkShowPassword
20,387
private JCheckBox getChkUseProxyChain ( ) { if ( chkUseProxyChain == null ) { chkUseProxyChain = new JCheckBox ( ) ; chkUseProxyChain . setText ( Constant . messages . getString ( "conn.options.useProxy" ) ) ; chkUseProxyChain . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent e ) { setProxyChainEnabled ( chkUseProxyChain . isSelected ( ) ) ; } } ) ; } return chkUseProxyChain ; }
This method initializes chkUseProxyChain
20,388
private JCheckBox getChkProxyChainAuth ( ) { if ( chkProxyChainAuth == null ) { chkProxyChainAuth = new JCheckBox ( ) ; chkProxyChainAuth . setText ( Constant . messages . getString ( "conn.options.proxy.auth.required" ) ) ; chkProxyChainAuth . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent e ) { setProxyChainAuthEnabled ( chkProxyChainAuth . isSelected ( ) ) ; } } ) ; } return chkProxyChainAuth ; }
This method initializes chkProxyChainAuth
20,389
public static void addFile ( String s ) throws IOException { File f = new File ( s ) ; addFile ( f ) ; }
Add file to CLASSPATH
20,390
public static void addURL ( URL u ) throws IOException { if ( ! ( ClassLoader . getSystemClassLoader ( ) instanceof URLClassLoader ) ) { return ; } URLClassLoader sysLoader = ( URLClassLoader ) ClassLoader . getSystemClassLoader ( ) ; URL [ ] urls = sysLoader . getURLs ( ) ; for ( int i = 0 ; i < urls . length ; i ++ ) { if ( StringUtils . equalsIgnoreCase ( urls [ i ] . toString ( ) , u . toString ( ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "URL " + u + " is already in the CLASSPATH" ) ; } return ; } } Class < URLClassLoader > sysclass = URLClassLoader . class ; try { Method method = sysclass . getDeclaredMethod ( "addURL" , parameters ) ; method . setAccessible ( true ) ; method . invoke ( sysLoader , new Object [ ] { u } ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; throw new IOException ( "Error, could not add URL to system classloader" ) ; } }
Add URL to CLASSPATH
20,391
protected JComboBox < SessionManagementMethodType > getSessionManagementMethodsComboBox ( ) { if ( sessionManagementMethodsComboBox == null ) { Vector < SessionManagementMethodType > methods = new Vector < > ( extension . getSessionManagementMethodTypes ( ) ) ; sessionManagementMethodsComboBox = new JComboBox < > ( methods ) ; sessionManagementMethodsComboBox . setSelectedItem ( null ) ; sessionManagementMethodsComboBox . addItemListener ( new ItemListener ( ) { public void itemStateChanged ( ItemEvent e ) { if ( e . getStateChange ( ) == ItemEvent . SELECTED ) { log . debug ( "Selected new Session Management type: " + e . getItem ( ) ) ; SessionManagementMethodType type = ( ( SessionManagementMethodType ) e . getItem ( ) ) ; if ( selectedMethod == null || ! type . isTypeForMethod ( selectedMethod ) ) { selectedMethod = type . createSessionManagementMethod ( getContextIndex ( ) ) ; } changeMethodConfigPanel ( type ) ; if ( type . hasOptionsPanel ( ) ) shownConfigPanel . bindMethod ( selectedMethod ) ; } } } ) ; } return sessionManagementMethodsComboBox ; }
Gets the session management methods combo box .
20,392
private JPanel getConfigContainerPanel ( ) { if ( configContainerPanel == null ) { configContainerPanel = new JPanel ( new BorderLayout ( ) ) ; configContainerPanel . setBorder ( javax . swing . BorderFactory . createTitledBorder ( null , Constant . messages . getString ( "sessionmanagement.panel.config.title" ) , javax . swing . border . TitledBorder . DEFAULT_JUSTIFICATION , javax . swing . border . TitledBorder . DEFAULT_POSITION , FontUtils . getFont ( FontUtils . Size . standard ) , java . awt . Color . black ) ) ; } return configContainerPanel ; }
Gets the configuration container panel .
20,393
private static < T > List < T > unmodifiableList ( List < T > list ) { if ( list == null ) { return Collections . emptyList ( ) ; } return Collections . unmodifiableList ( list ) ; }
Gets an unmodifiable list from the given list .
20,394
private static void warnAddOnsAndExtensionsNoLongerRunnable ( ) { final AddOnLoader addOnLoader = ExtensionFactory . getAddOnLoader ( ) ; List < String > idsAddOnsNoLongerRunning = addOnLoader . getIdsAddOnsWithRunningIssuesSinceLastRun ( ) ; if ( idsAddOnsNoLongerRunning . isEmpty ( ) ) { return ; } List < AddOn > addOnsNoLongerRunning = new ArrayList < > ( idsAddOnsNoLongerRunning . size ( ) ) ; for ( String id : idsAddOnsNoLongerRunning ) { addOnsNoLongerRunning . add ( addOnLoader . getAddOnCollection ( ) . getAddOn ( id ) ) ; } AddOnRunIssuesUtils . showWarningMessageAddOnsNotRunnable ( Constant . messages . getString ( "start.gui.warn.addOnsOrExtensionsNoLongerRunning" ) , addOnLoader . getAddOnCollection ( ) , addOnsNoLongerRunning ) ; }
Warns through a dialogue about add - ons and extensions that are no longer runnable because of changes in its dependencies .
20,395
private static boolean isFirstTime ( ) { Path acceptedLicenseFile = Paths . get ( Constant . getInstance ( ) . ACCEPTED_LICENSE ) ; return Files . notExists ( acceptedLicenseFile ) ; }
Tells whether or not ZAP is being started for first time . It does so by checking if the license was not yet been accepted .
20,396
private void setDefaultList ( ) { final String defaultListArray [ ] [ ] = { { "^.*\\.(?:gif|jpe?g|png|ico|icns|bmp)$" , "Extension - Image (ends with .extension)" , "false" } , { "^.*\\.(?:mp[34]|mpe?g|m4[ap]|aac|avi|mov|wmv|og[gav])$" , "Extension - Audio/Video (ends with .extension)" , "false" } , { "^.*\\.(?:pdf|docx?|xlsx?|pptx?)$" , "Extension - PDF & Office (ends with .extension)" , "false" } , { "^.*\\.(?:css|js)$" , "Extension - Stylesheet, JavaScript (ends with .extension)" , "false" } , { "^.*\\.(?:sw[fa]|flv)$" , "Extension - Flash & related (ends with .extension)" , "false" } , { "^[^\\?]*\\.(?:gif|jpe?g|png|ico|icns|bmp)\\?.*$" , "ExtParam - Image (extension plus ?params=values)" , "false" } , { "^[^\\?]*\\.(?:mp[34]|mpe?g|m4[ap]|aac|avi|mov|wmv|og[gav])\\?.*$" , "ExtParam - Audio/Video (extension plus ?params=values)" , "false" } , { "^[^\\?]*\\.(?:pdf|docx?|xlsx?|pptx?)\\?.*$" , "ExtParam - PDF & Office (extension plus ?params=values)" , "false" } , { "^[^\\?]*\\.(?:css|js)\\?.*$" , "ExtParam - Stylesheet, JavaScript (extension plus ?params=values)" , "false" } , { "^[^\\?]*\\.(?:sw[fa]|flv)\\?.*$" , "ExtParam - Flash & related (extension plus ?params=values)" , "false" } , { "^[^\\?]*/(?:WebResource|ScriptResource)\\.axd\\?d=.*$" , "ExtParam - .NET adx resources (SR/WR.adx?d=)" , "false" } , { "^https?://api\\.bing\\.com/qsml\\.aspx?query=.*$" , "Site - Bing API queries" , "false" } , { "^https?://(?:safebrowsing-cache|sb-ssl|sb|safebrowsing).*\\.(?:google|googleapis)\\.com/.*$" , "Site - Google malware detector updates" , "false" } , { "^https?://(?:[^/])*\\.?lastpass\\.com" , "Site - Lastpass manager" , "false" } , { "^https?://(?:.*addons|aus[0-9])\\.mozilla\\.(?:org|net|com)/.*$" , "Site - Firefox browser updates" , "false" } , { "^https?://(?:[^/])*\\.?(?:getfoxyproxy\\.org|getfirebug\\.com|noscript\\.net)" , "Site - Firefox extensions phoning home" , "false" } , { "^https?://(?:.*update\\.microsoft|.*\\.windowsupdate)\\.com/.*$" , "Site - Microsoft Windows updates" , "false" } , { "^https?://clients2\\.google\\.com/service/update2/crx.*$" , "Site - Google Chrome extension updates" , "false" } , { "^https?://detectportal\\.firefox\\.com.*$" , "Site - Firefox captive portal detection" , "false" } , { "^https?://www\\.google-analytics\\.com.*$" , "Site - Google Analytics" , "false" } , { "^https?://ciscobinary\\.openh264\\.org.*$" , "Site - Firefox h264 codec download" , "false" } , { "^https?://fonts.*$" , "Site - Fonts CDNs such as fonts.gstatic.com, etc" , "false" } , { "^https?://.*\\.cdn\\.mozilla\\.(?:com|org|net)/.*$" , "Site - Mozilla CDN (requests such as getpocket)" , "false" } , { "^https?://.*\\.telemetry\\.mozilla\\.(?:com|org|net)/.*$" , "Site - Firefox browser telemetry" , "false" } , { "^https?://.*\\.adblockplus\\.org.*$" , "Site - Adblockplus updates and notifications" , "false" } , { "^https?://.*\\.services\\.mozilla\\.com.*$" , "Site - Firefox services" , "false" } , { "^https?://.*\\.gvt1\\.com.*$" , "Site - Google updates" , "false" } } ; for ( String row [ ] : defaultListArray ) { boolean b = row [ 2 ] . equalsIgnoreCase ( "true" ) ? true : false ; defaultList . add ( new GlobalExcludeURLParamToken ( row [ 0 ] , row [ 1 ] , b ) ) ; } }
Fills in the list of default regexs to ignore . In a future version this could be read from a system - wide default HierarchicalConfiguration xml config file instead or even a HierarchicalConfiguration string directly embedded in this file .
20,397
private GenericScanner2 getSpiderScan ( JSONObject params ) throws ApiException { GenericScanner2 spiderScan ; int id = getParam ( params , PARAM_SCAN_ID , - 1 ) ; if ( id == - 1 ) { spiderScan = extension . getLastScan ( ) ; } else { spiderScan = extension . getScan ( id ) ; } if ( spiderScan == null ) { throw new ApiException ( ApiException . Type . DOES_NOT_EXIST , PARAM_SCAN_ID ) ; } return spiderScan ; }
Returns the specified GenericScanner2 or the last scan available .
20,398
public void setUseSystemsLocaleForFormat ( boolean useSystemsLocale ) { if ( useSystemsLocaleForFormat != useSystemsLocale ) { useSystemsLocaleForFormat = useSystemsLocale ; getConfig ( ) . setProperty ( USE_SYSTEMS_LOCALE_FOR_FORMAT_KEY , useSystemsLocaleForFormat ) ; } }
Sets whether or not the system s locale should be used for formatting .
20,399
public boolean matches ( String domain ) { if ( pattern != null ) { return pattern . matcher ( domain ) . matches ( ) ; } return this . domain . equals ( domain ) ; }
Tells whether or not the given domain is considered always in scope .