Input: Get the result of an Object path expression as a float . [CODESPLIT] public float getFloat ( String path ) { final Object value = get ( path ) ; //Groovy will always return a Double for floating point values. if ( value instanceof Double ) { return ( ( Double ) value ) . floatValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Float . class ) ; } }


Input: Get the result of an Object path expression as a double . [CODESPLIT] public double getDouble ( String path ) { final Object value = get ( path ) ; if ( value instanceof Double ) { return ( Double ) value ; } return ObjectConverter . convertObjectTo ( value , Double . class ) ; }


Input: Get the result of an Object path expression as a long . [CODESPLIT] public long getLong ( String path ) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get ( path ) ; if ( value instanceof Long ) { return ( Long ) value ; } else if ( value instanceof Short ) { return ( ( Short ) value ) . longValue ( ) ; } else if ( value instanceof Integer ) { return ( ( Integer ) value ) . longValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Long . class ) ; } }


Input: Get the result of an Object path expression as a list . [CODESPLIT] public < T > List < T > getList ( String path , Class < T > genericType ) { if ( genericType == null ) { throw new IllegalArgumentException ( "Generic type cannot be null" ) ; } final List < T > original = get ( path ) ; final List < T > newList = new LinkedList < T > ( ) ; if ( original != null ) { for ( T t : original ) { T e ; if ( t instanceof Map && ! genericType . isAssignableFrom ( Map . class ) ) { // TODO Avoid double parsing String str = objectToString ( t ) ; //noinspection unchecked e = ( T ) jsonStringToObject ( str , genericType ) ; } else { e = ObjectConverter . convertObjectTo ( t , genericType ) ; } newList . add ( e ) ; } } return Collections . unmodifiableList ( newList ) ; }


Input: Get the result of an Object path expression as a map . [CODESPLIT] public < K , V > Map < K , V > getMap ( String path ) { return get ( path ) ; }


Input: Get the result of a Object path expression as a java Object . E . g . given the following Object document : <pre > { store : { book : [ { category : reference author : Nigel Rees title : Sayings of the Century price : 8 . 95 } { category : fiction author : Evelyn Waugh title : Sword of Honour price : 12 . 99 } { category : fiction author : Herman Melville title : Moby Dick isbn : 0 - 553 - 21311 - 3 price : 8 . 99 } { category : fiction author : J . R . R . Tolkien title : The Lord of the Rings isbn : 0 - 395 - 19395 - 8 price : 22 . 99 } ] bicycle : { color : red price : 19 . 95 } } } < / pre > And a Java object like this : <p / > <pre > public class Book { private String category ; private String author ; private String title ; private String isbn ; private float price ; [CODESPLIT] public < T > T getObject ( String path , Class < T > objectType ) { Object object = getJsonObject ( path ) ; if ( object == null ) { return null ; } else if ( object instanceof List || object instanceof Map ) { // TODO Avoid double parsing object = objectToString ( object ) ; } else { return ObjectConverter . convertObjectTo ( object , objectType ) ; } if ( ! ( object instanceof String ) ) { throw new IllegalStateException ( "Internal error: Json object was not an instance of String, please report to the REST Assured mailing-list." ) ; } return ( T ) jsonStringToObject ( ( String ) object , objectType ) ; }


Input: Get the result of a Object path expression as a java Object with generic type . E . g . given the following Object document : <pre > { store : { book : [ { category : reference author : Nigel Rees title : Sayings of the Century price : 8 . 95 } { category : fiction author : Evelyn Waugh title : Sword of Honour price : 12 . 99 } { category : fiction author : Herman Melville title : Moby Dick isbn : 0 - 553 - 21311 - 3 price : 8 . 99 } { category : fiction author : J . R . R . Tolkien title : The Lord of the Rings isbn : 0 - 395 - 19395 - 8 price : 22 . 99 } ] bicycle : { color : red price : 19 . 95 } } } < / pre > And you want to get a book as a <code > Map&lt ; String Object&gt ; < / code > : <p / > Then <pre > Map&lt ; String Object&gt ; book = from ( Object ) . getObject ( store . book [ 2 ] new TypeRef&lt ; Map&lt ; String Object&gt ; &gt ; () {} ) ; < / pre > <p / > maps the second book to a Book instance . [CODESPLIT] public < T > T getObject ( String path , TypeRef < T > typeRef ) { AssertParameter . notNull ( "objectType" , "Type ref" ) ; return getObject ( path , typeRef . getTypeAsClass ( ) ) ; }


Input: Add a parameter for the expression . Example : <pre > String name = System . console () . readLine () ; List&lt ; Map&gt ; books = with ( Object ) . param ( name name ) . get ( store . book . findAll { book - > book . author == name } ) ; < / pre > [CODESPLIT] public JsonPath param ( String key , Object value ) { JsonPath newP = new JsonPath ( this , config ) ; if ( newP . params == null ) { newP . params = new HashMap < String , Object > ( ) ; } newP . params . put ( key , value ) ; return newP ; }


Input: Get and print the JSON as a prettified string . <p > Note that the content is not guaranteed to be looking exactly like the it does at the source . This is because once you peek the content has been downloaded and transformed into another data structure ( used by JsonPath ) and the JSON is rendered from this data structure . < / p > [CODESPLIT] public String prettyPrint ( ) { final String pretty = prettify ( ) ; System . out . println ( pretty ) ; return pretty ; }


Input: Specify features that will be used when parsing XML . [CODESPLIT] public XmlConfig features ( Map < String , Boolean > features ) { return new XmlConfig ( features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Specify properties that will be used when parsing XML . [CODESPLIT] public XmlConfig properties ( Map < String , Object > properties ) { return new XmlConfig ( features , declaredNamespaces , this . properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Set a value of a feature flag . [CODESPLIT] public XmlConfig feature ( String uri , boolean enabled ) { Validate . notEmpty ( uri , "URI cannot be empty" ) ; Map < String , Boolean > newFeatures = new HashMap < String , Boolean > ( features ) ; newFeatures . put ( uri , enabled ) ; return new XmlConfig ( newFeatures , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Set a value of a property . [CODESPLIT] public XmlConfig property ( String name , Object value ) { Validate . notEmpty ( name , "Name cannot be empty" ) ; Map < String , Object > newProperties = new HashMap < String , Object > ( properties ) ; newProperties . put ( name , value ) ; return new XmlConfig ( features , declaredNamespaces , newProperties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Specify declared namespaces that will be used when parsing XML . Will also set { @link #namespaceAware ( boolean ) } to <code > true< / code > of namespaces are not empty . <p > Note that you cannot use this to add namespaces for the { @link org . hamcrest . xml . HasXPath } matcher . This has to be done by providing a { @link javax . xml . namespace . NamespaceContext } to the matcher instance . < / p > [CODESPLIT] public XmlConfig declareNamespaces ( Map < String , String > namespacesToDeclare ) { final boolean shouldBeNamespaceAware = namespacesToDeclare == null ? namespaceAware : ! namespacesToDeclare . isEmpty ( ) ; return new XmlConfig ( features , namespacesToDeclare , properties , validating , shouldBeNamespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Declares a namespace and also sets { @link #namespaceAware ( boolean ) } to <code > true< / code > . <p / > <p > Note that you cannot use this to add namespaces for the { @link org . hamcrest . xml . HasXPath } matcher . This has to be done by providing a { @link javax . xml . namespace . NamespaceContext } to the matcher instance . < / p > [CODESPLIT] public XmlConfig declareNamespace ( String prefix , String namespaceURI ) { Validate . notEmpty ( prefix , "Prefix cannot be empty" ) ; Validate . notEmpty ( namespaceURI , "Namespace URI cannot be empty" ) ; Map < String , String > updatedNamespaces = new HashMap < String , String > ( declaredNamespaces ) ; updatedNamespaces . put ( prefix , namespaceURI ) ; return new XmlConfig ( features , updatedNamespaces , properties , validating , true , allowDocTypeDeclaration , true ) ; }


Input: Disables external DTD loading . <p > This is a shortcut for doing : <br > <pre > setFeature ( http : // apache . org / xml / features / nonvalidating / load - external - dtd false ) ; < / pre > < / p > [CODESPLIT] public XmlConfig disableLoadingOfExternalDtd ( ) { Map < String , Boolean > newFeatures = new HashMap < String , Boolean > ( features ) ; newFeatures . put ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; return new XmlConfig ( newFeatures , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Configure if XmlPath should validate documents as they are parsed ( default is { @value #DEFAULT_VALIDATING } ) . Note that this is only applicable when { @link XmlPath . CompatibilityMode } is equal to { @link XmlPath . CompatibilityMode#XML } . [CODESPLIT] public XmlConfig validating ( boolean isValidating ) { return new XmlConfig ( features , declaredNamespaces , properties , isValidating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Configure whether or not REST Assured should be aware of namespaces when parsing XML ( default is { @value #DEFAULT_NAMESPACE_AWARE } ) . Note that this is only applicable when { @link XmlPath . CompatibilityMode } is equal to { @link XmlPath . CompatibilityMode#XML } . [CODESPLIT] public XmlConfig namespaceAware ( boolean shouldBeAwareOfNamespaces ) { return new XmlConfig ( features , declaredNamespaces , properties , validating , shouldBeAwareOfNamespaces , allowDocTypeDeclaration , true ) ; }


Input: Configure if XmlPath should provide support for DOCTYPE declarations ( default is { @value #DEFAULT_ALLOW_DOC_TYPE_DECLARATION } ) . Note that this is only applicable when { @link XmlPath . CompatibilityMode } is equal to { @link XmlPath . CompatibilityMode#XML } . [CODESPLIT] public XmlConfig allowDocTypeDeclaration ( boolean allowDocTypeDeclaration ) { return new XmlConfig ( features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }


Input: Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public DecoderConfig defaultCharsetForContentType ( String charset , String contentType ) { notNull ( charset , "Charset" ) ; notNull ( contentType , "ContentType" ) ; Map < String , String > map = new HashMap < String , String > ( contentTypeToDefaultCharset ) ; map . put ( trim ( contentType ) . toLowerCase ( ) , trim ( charset ) ) ; return new DecoderConfig ( charset , useNoWrapForInflateDecoding , true , contentDecoders , map ) ; }


Input: Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public DecoderConfig defaultCharsetForContentType ( Charset charset , String contentType ) { notNull ( charset , "Charset" ) ; return defaultCharsetForContentType ( charset . toString ( ) , contentType ) ; }


Input: Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public DecoderConfig defaultCharsetForContentType ( Charset charset , ContentType contentType ) { notNull ( charset , "Charset" ) ; return defaultCharsetForContentType ( charset . toString ( ) , contentType ) ; }


Input: Specify the default charset of the content in the response that s assumed if no charset is explicitly specified in the response . [CODESPLIT] @ SuppressWarnings ( "UnusedDeclaration" ) public DecoderConfig defaultContentCharset ( String charset ) { return new DecoderConfig ( charset , useNoWrapForInflateDecoding , true , contentDecoders , contentTypeToDefaultCharset ) ; }


Input: Specify the default charset of the content in the response that s assumed if no charset is explicitly specified in the response . [CODESPLIT] @ SuppressWarnings ( "UnusedDeclaration" ) public DecoderConfig defaultContentCharset ( Charset charset ) { String charsetAsString = notNull ( charset , Charset . class ) . toString ( ) ; return new DecoderConfig ( charsetAsString , useNoWrapForInflateDecoding , true , contentDecoders , contentTypeToDefaultCharset ) ; }


Input: Specify the content decoders that will be presented to the server when making a request ( using the <code > Accept - Encoding< / code > header ) . If the server supports any of these encodings then REST Assured will automatically perform decoding of the response accordingly . <p > By default { @link ContentDecoder#GZIP } and { @link ContentDecoder#DEFLATE } are used . < / p > [CODESPLIT] public DecoderConfig contentDecoders ( ContentDecoder contentDecoder , ContentDecoder ... additionalContentDecoders ) { return new DecoderConfig ( defaultContentCharset , useNoWrapForInflateDecoding , true , contentTypeToDefaultCharset , merge ( contentDecoder , additionalContentDecoders ) ) ; }


Input: Get the result of an XML path expression . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public < T > T get ( String path ) { AssertParameter . notNull ( path , "path" ) ; return getFromPath ( path , true ) ; }


Input: Get the result of an XML path expression as a list . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public < T > List < T > getList ( String path , Class < T > genericType ) { return getAsList ( path , genericType ) ; }


Input: Get the result of an XML path expression as a map . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public < K , V > Map < K , V > getMap ( String path , Class < K > keyType , Class < V > valueType ) { final Map < K , V > originalMap = get ( path ) ; final Map < K , V > newMap = new HashMap < K , V > ( ) ; for ( Entry < K , V > entry : originalMap . entrySet ( ) ) { final K key = entry . getKey ( ) == null ? null : convertObjectTo ( entry . getKey ( ) , keyType ) ; final V value = entry . getValue ( ) == null ? null : convertObjectTo ( entry . getValue ( ) , valueType ) ; newMap . put ( key , value ) ; } return Collections . unmodifiableMap ( newMap ) ; }


Input: Get an XML document as a Java Object . [CODESPLIT] public < T > T getObject ( String path , Class < T > objectType ) { Object object = getFromPath ( path , false ) ; return getObjectAsType ( object , objectType ) ; }


Input: Get the result of an XML path expression as an int . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public int getInt ( String path ) { final Object object = get ( path ) ; return convertObjectTo ( object , Integer . class ) ; }


Input: Get the result of an XML path expression as a boolean . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public boolean getBoolean ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Boolean . class ) ; }


Input: Get the result of an XML path expression as a char . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public char getChar ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Character . class ) ; }


Input: Get the result of an XML path expression as a byte . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public byte getByte ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Byte . class ) ; }


Input: Get the result of an XML path expression as a short . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public short getShort ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Short . class ) ; }


Input: Get the result of an XML path expression as a float . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public float getFloat ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Float . class ) ; }


Input: Get the result of an XML path expression as a double . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public double getDouble ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Double . class ) ; }


Input: Get the result of an XML path expression as a long . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public long getLong ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Long . class ) ; }


Input: Get the result of an XML path expression as a string . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public String getString ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , String . class ) ; }


Input: Get the result of an XML path expression as a UUID . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public UUID getUUID ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , UUID . class ) ; }


Input: Add a parameter for the expression . Example : <pre > String type = System . console () . readLine () ; List&lt ; Map&gt ; books = with ( Object ) . param ( type type ) . get ( shopping . category . findAll { it . @type == type } ) ; < / pre > [CODESPLIT] public XmlPath param ( String key , Object value ) { XmlPath newP = new XmlPath ( this , getXmlPathConfig ( ) ) ; if ( newP . params == null ) { newP . params = new HashMap < String , Object > ( ) ; } newP . params . put ( key , value ) ; return newP ; }


Input: Peeks into the XML / HTML that XmlPath will parse by printing it to the console . You can continue working with XmlPath afterwards . This is mainly for debug purposes . If you want to return a prettified version of the content see { @link #prettify () } . If you want to return a prettified version of the content and also print it to the console use { @link #prettyPrint () } . <p / > <p > Note that the content is not guaranteed to be looking exactly like the it does at the source . This is because once you peek the content has been downloaded and transformed into another data structure ( used by XmlPath ) and the XML is rendered from this data structure . < / p > [CODESPLIT] public XmlPath peek ( ) { final GPathResult result = lazyXmlParser . invoke ( ) ; final String render = XmlRenderer . render ( result ) ; System . out . println ( render ) ; return this ; }


Input: Peeks into the XML / HTML that XmlPath will parse by printing it to the console in a prettified manner . You can continue working with XmlPath afterwards . This is mainly for debug purposes . If you want to return a prettified version of the content see { @link #prettify () } . If you want to return a prettified version of the content and also print it to the console use { @link #prettyPrint () } . <p / > <p > Note that the content is not guaranteed to be looking exactly like the it does at the source . This is because once you peek the content has been downloaded and transformed into another data structure ( used by XmlPath ) and the XML is rendered from this data structure . < / p > [CODESPLIT] public XmlPath prettyPeek ( ) { final GPathResult result = lazyXmlParser . invoke ( ) ; final String prettify = XmlPrettifier . prettify ( result ) ; System . out . println ( prettify ) ; return this ; }


Input: Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper . This works for the POST PATCH and PUT methods only . Trying to do this for the other http methods will cause an exception to be thrown . [CODESPLIT] public RequestSpecBuilder setBody ( Object object , ObjectMapper mapper ) { spec . body ( object , mapper ) ; return this ; }


Input: Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper type . This works for the POST PATCH and PUT methods only . Trying to do this for the other http methods will cause an exception to be thrown . <p > Example of use : <pre > Message message = new Message () ; message . setMessage ( My beautiful message ) ; [CODESPLIT] public RequestSpecBuilder setBody ( Object object , ObjectMapperType mapperType ) { spec . body ( object , mapperType ) ; return this ; }


Input: Add a cookie to be sent with the request . [CODESPLIT] public RequestSpecBuilder addCookie ( String key , Object value , Object ... cookieNameValuePairs ) { spec . cookie ( key , value , cookieNameValuePairs ) ; return this ; }


Input: Add a parameter to be sent with the request . [CODESPLIT] public RequestSpecBuilder addParam ( String parameterName , Object ... parameterValues ) { spec . param ( parameterName , parameterValues ) ; return this ; }


Input: Add a multi - value parameter to be sent with the request . [CODESPLIT] public RequestSpecBuilder addParam ( String parameterName , Collection < ? > parameterValues ) { spec . param ( parameterName , parameterValues ) ; return this ; }


Input: Add a query parameter to be sent with the request . This method is the same as { @link #addParam ( String java . util . Collection ) } for all HTTP methods except POST where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addQueryParam ( String parameterName , Collection < ? > parameterValues ) { spec . queryParam ( parameterName , parameterValues ) ; return this ; }


Input: Add a query parameter to be sent with the request . This method is the same as { @link #addParam ( String Object ... ) } ) } for all HTTP methods except POST where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addQueryParam ( String parameterName , Object ... parameterValues ) { spec . queryParam ( parameterName , parameterValues ) ; return this ; }


Input: Add a form parameter to be sent with the request . This method is the same as { @link #addParam ( String java . util . Collection ) } for all HTTP methods except PUT where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addFormParam ( String parameterName , Collection < ? > parameterValues ) { spec . formParam ( parameterName , parameterValues ) ; return this ; }


Input: Add a form parameter to be sent with the request . This method is the same as { @link #addParam ( String Object ... ) } ) } for all HTTP methods except PUT where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addFormParam ( String parameterName , Object ... parameterValues ) { spec . formParam ( parameterName , parameterValues ) ; return this ; }


Input: Specify a path parameter . Path parameters are used to improve readability of the request path . E . g . instead of writing : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / + myItem . getItemNumber () + / buy / + 2 ) ; < / pre > you can write : <pre > given () . pathParam ( itemNumber myItem . getItemNumber () ) . pathParam ( amount 2 ) . expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } ) ; < / pre > <p / > which improves readability and allows the path to be reusable in many tests . Another alternative is to use : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } myItem . getItemNumber () 2 ) ; < / pre > [CODESPLIT] public RequestSpecBuilder addPathParam ( String parameterName , Object parameterValue ) { spec . pathParam ( parameterName , parameterValue ) ; return this ; }


Input: Specify multiple path parameter name - value pairs . Path parameters are used to improve readability of the request path . E . g . instead of writing : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / + myItem . getItemNumber () + / buy / + 2 ) ; < / pre > you can write : <pre > given () . pathParam ( itemNumber myItem . getItemNumber () amount 2 ) . expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } ) ; < / pre > <p / > which improves readability and allows the path to be reusable in many tests . Another alternative is to use : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } myItem . getItemNumber () 2 ) ; < / pre > [CODESPLIT] public RequestSpecBuilder addPathParams ( String firstParameterName , Object firstParameterValue , Object ... parameterNameValuePairs ) { spec . pathParams ( firstParameterName , firstParameterValue , parameterNameValuePairs ) ; return this ; }


Input: Specify a keystore . <pre > RestAssured . keyStore ( / truststore_javanet . jks test1234 ) ; < / pre > or <pre > given () . keyStore ( / truststore_javanet . jks test1234 ) . .. < / pre > < / p > [CODESPLIT] public RequestSpecBuilder setKeyStore ( String pathToJks , String password ) { spec . keyStore ( pathToJks , password ) ; return this ; }


Input: The following documentation is taken from <a href = HTTP Builder > https : // github . com / jgritman / httpbuilder / wiki / SSL< / a > : <p > <h1 > SSL Configuration< / h1 > <p / > SSL should for the most part just work . There are a few situations where it is not completely intuitive . You can follow the example below or see HttpClient s SSLSocketFactory documentation for more information . <p / > <h1 > SSLPeerUnverifiedException< / h1 > <p / > If you can t connect to an SSL website it is likely because the certificate chain is not trusted . This is an Apache HttpClient issue but explained here for convenience . To correct the untrusted certificate you need to import a certificate into an SSL truststore . <p / > First export a certificate from the website using your browser . For example if you go to https : // dev . java . net in Firefox you will probably get a warning in your browser . Choose Add Exception Get Certificate View Details tab . Choose a certificate in the chain and export it as a PEM file . You can view the details of the exported certificate like so : <pre > $ keytool - printcert - file EquifaxSecureGlobaleBusinessCA - 1 . crt Owner : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Issuer : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Serial number : 1 Valid from : Mon Jun 21 00 : 00 : 00 EDT 1999 until : Sun Jun 21 00 : 00 : 00 EDT 2020 Certificate fingerprints : MD5 : 8F : 5D : 77 : 06 : 27 : C4 : 98 : 3C : 5B : 93 : 78 : E7 : D7 : 7D : 9B : CC SHA1 : 7E : 78 : 4A : 10 : 1C : 82 : 65 : CC : 2D : E1 : F1 : 6D : 47 : B4 : 40 : CA : D9 : 0A : 19 : 45 Signature algorithm name : MD5withRSA Version : 3 .... < / pre > Now import that into a Java keystore file : <pre > $ keytool - importcert - alias equifax - ca - file EquifaxSecureGlobaleBusinessCA - 1 . crt - keystore truststore_javanet . jks - storepass test1234 Owner : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Issuer : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Serial number : 1 Valid from : Mon Jun 21 00 : 00 : 00 EDT 1999 until : Sun Jun 21 00 : 00 : 00 EDT 2020 Certificate fingerprints : MD5 : 8F : 5D : 77 : 06 : 27 : C4 : 98 : 3C : 5B : 93 : 78 : E7 : D7 : 7D : 9B : CC SHA1 : 7E : 78 : 4A : 10 : 1C : 82 : 65 : CC : 2D : E1 : F1 : 6D : 47 : B4 : 40 : CA : D9 : 0A : 19 : 45 Signature algorithm name : MD5withRSA Version : 3 ... Trust this certificate? [ no ] : yes Certificate was added to keystore < / pre > Now you want to use this truststore in your client : <pre > RestAssured . trustStore ( / truststore_javanet . jks test1234 ) ; < / pre > or <pre > given () . trustStore ( / truststore_javanet . jks test1234 ) . .. < / pre > < / p > [CODESPLIT] public RequestSpecBuilder setTrustStore ( String pathToJks , String password ) { spec . trustStore ( pathToJks , password ) ; return this ; }


Input: Add a header to be sent with the request e . g : [CODESPLIT] public RequestSpecBuilder addHeader ( String headerName , String headerValue ) { spec . header ( headerName , headerValue ) ; return this ; }


Input: Specify an inputstream to upload to the server using multi - part form data . It will use the content - type <tt > application / octet - stream< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public RequestSpecBuilder addMultiPart ( String controlName , String fileName , InputStream stream ) { spec . multiPart ( controlName , fileName , stream ) ; return this ; }


Input: Specify a string to send to the server using multi - part form data . It will use the content - type <tt > text / plain< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public RequestSpecBuilder addMultiPart ( String controlName , String contentBody ) { spec . multiPart ( controlName , contentBody ) ; return this ; }


Input: Set the session id name and value for this request . It ll override the default session id name from the configuration ( by default this is { @value SessionConfig#DEFAULT_SESSION_ID_NAME } ) . You can configure the default session id name by using : <pre > RestAssured . config = newConfig () . sessionConfig ( new SessionConfig () . sessionIdName ( &lt ; sessionIdName&gt ; )) ; < / pre > and then you can use the { @link RequestSpecBuilder#setSessionId ( String ) } method to set the session id value without specifying the name for each request . [CODESPLIT] public RequestSpecBuilder setSessionId ( String sessionIdName , String sessionIdValue ) { spec . sessionId ( sessionIdName , sessionIdValue ) ; return this ; }


Input: Merge this builder with settings from another specification . Note that the supplied specification can overwrite data in the current specification . The following settings are overwritten : <ul > <li > Port< / li > <li > Authentication scheme< / <li > Content type< / li > <li > Request body< / li > < / ul > The following settings are merged : <ul > <li > Parameters< / li > <li > Cookies< / li > <li > Headers< / li > <li > Filters< / li > < / ul > [CODESPLIT] public RequestSpecBuilder addRequestSpecification ( RequestSpecification specification ) { if ( ! ( specification instanceof RequestSpecificationImpl ) ) { throw new IllegalArgumentException ( "Specification must be of type " + RequestSpecificationImpl . class . getClass ( ) + "." ) ; } RequestSpecificationImpl rs = ( RequestSpecificationImpl ) specification ; SpecificationMerger . merge ( ( RequestSpecificationImpl ) spec , rs ) ; return this ; }


Input: Enabled logging with the specified log detail . Set a { @link LogConfig } to configure the print stream and pretty printing options . [CODESPLIT] public RequestSpecBuilder log ( LogDetail logDetail ) { notNull ( logDetail , LogDetail . class ) ; RestAssuredConfig restAssuredConfig = spec . getConfig ( ) ; LogConfig logConfig ; if ( restAssuredConfig == null ) { logConfig = new RestAssuredConfig ( ) . getLogConfig ( ) ; } else { logConfig = restAssuredConfig . getLogConfig ( ) ; } PrintStream printStream = logConfig . defaultStream ( ) ; boolean prettyPrintingEnabled = logConfig . isPrettyPrintingEnabled ( ) ; boolean shouldUrlEncodeRequestUri = logConfig . shouldUrlEncodeRequestUri ( ) ; spec . filter ( new RequestLoggingFilter ( logDetail , prettyPrintingEnabled , printStream , shouldUrlEncodeRequestUri ) ) ; return this ; }


Input: Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme . [CODESPLIT] public RequestSpecBuilder setProxy ( String host , int port , String scheme ) { spec . proxy ( host , port , scheme ) ; return this ; }


Input: Set form parameter update strategy to the given value . [CODESPLIT] public MockMvcParamConfig formParamsUpdateStrategy ( UpdateStrategy updateStrategy ) { return new MockMvcParamConfig ( queryParamsUpdateStrategy , updateStrategy , requestParameterUpdateStrategy , attributeUpdateStrategy , sessionUpdateStrategy , true ) ; }


Input: Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id playerId : my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( userId equalToPath ( playerId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > equalToPath ( final String path ) { return response -> equalTo ( response . path ( path ) ) ; }


Input: Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href endsWithPath ( userId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > endsWithPath ( final String path ) { return response -> endsWith ( response . < String > path ( path ) ) ; }


Input: Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id baseUri : http : // localhost : 8080 href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href startsWithPath ( baseUri )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > startsWithPath ( final String path ) { return response -> startsWith ( response . < String > path ( path ) ) ; }


Input: Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href containsPath ( userId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > containsPath ( final String path ) { return response -> containsString ( response . < String > path ( path ) ) ; }


Input: Create a new logging filter without using the new operator . Will make the DSL look nicer . [CODESPLIT] public static Filter logResponseToIfMatches ( PrintStream stream , Matcher < Integer > matcher ) { return new ResponseLoggingFilter ( stream , matcher ) ; }


Input: Use a keystore located on the file - system . See { @link #keyStore ( String String ) } for more details . [CODESPLIT] public SSLConfig keyStore ( File pathToJks , String password ) { Validate . notNull ( pathToJks , "Path to JKS on the file system cannot be null" ) ; Validate . notEmpty ( password , "Password cannot be empty" ) ; return new SSLConfig ( pathToJks , pathToTrustStore , password , trustStorePassword , keyStoreType , trustStoreType , port , keyStore , trustStore , x509HostnameVerifier , sslSocketFactory , true ) ; }


Input: Uses the user default keystore stored in &lt ; user . home&gt ; / . keystore [CODESPLIT] public SSLConfig keyStore ( String password ) { Validate . notEmpty ( password , "Password cannot be empty" ) ; return keyStore ( System . getProperty ( "user.home" ) + File . separatorChar + ".keystore" , password ) ; }


Input: The certificate type will use { @link java . security . KeyStore#getDefaultType () } by default . [CODESPLIT] public SSLConfig keystoreType ( String keystoreType ) { return new SSLConfig ( pathToKeyStore , pathToTrustStore , keyStorePassword , trustStorePassword , keystoreType , trustStoreType , port , keyStore , trustStore , x509HostnameVerifier , sslSocketFactory , true ) ; }


Input: Use relaxed HTTP validation . This means that you ll trust all hosts regardless if the SSL certificate is invalid . By using this method you don t need to specify a keystore ( see { @link #keyStore ( String String ) } or trust store ( see { @link #trustStore ( java . security . KeyStore ) } . [CODESPLIT] public SSLConfig relaxedHTTPSValidation ( String protocol ) { AssertParameter . notNull ( protocol , "Protocol" ) ; SSLContext sslContext ; try { sslContext = SSLContext . getInstance ( protocol ) ; } catch ( NoSuchAlgorithmException e ) { return SafeExceptionRethrower . safeRethrow ( e ) ; } // Set up a TrustManager that trusts everything try { sslContext . init ( null , new TrustManager [ ] { new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } } } , new SecureRandom ( ) ) ; } catch ( KeyManagementException e ) { return SafeExceptionRethrower . safeRethrow ( e ) ; } SSLSocketFactory sf = new SSLSocketFactory ( sslContext , ALLOW_ALL_HOSTNAME_VERIFIER ) ; return sslSocketFactory ( sf ) ; }


Input: Specify a { @link org . apache . http . conn . ssl . SSLSocketFactory } . This will override settings from trust store as well as keystore and password . [CODESPLIT] public SSLConfig sslSocketFactory ( SSLSocketFactory sslSocketFactory ) { AssertParameter . notNull ( sslSocketFactory , SSLSocketFactory . class ) ; return new SSLConfig ( pathToKeyStore , pathToTrustStore , keyStorePassword , trustStorePassword , keyStoreType , trustStoreType , port , keyStore , trustStore , x509HostnameVerifier , sslSocketFactory , true ) ; }


Input: Get a single cookie with the supplied name . If there are several cookies match the <code > cookieName< / code > then the first one is returned . [CODESPLIT] public Cookie get ( String cookieName ) { AssertParameter . notNull ( cookieName , "Cookie name" ) ; return cookies . get ( cookieName ) ; }


Input: Get a single cookie <i > value< / i > with the supplied name . If there are several cookies matching the <code > cookieName< / code > then the first one is returned . [CODESPLIT] public String getValue ( String cookieName ) { AssertParameter . notNull ( cookieName , "Cookie name" ) ; return cookies . getValue ( cookieName ) ; }


Input: An alternative way to create a Cookies object from the constructor . [CODESPLIT] public static Cookies cookies ( Cookie cookie , Cookie ... additionalCookies ) { AssertParameter . notNull ( cookie , "Cookie" ) ; final List < Cookie > cookieList = new LinkedList < Cookie > ( ) ; cookieList . add ( cookie ) ; Collections . addAll ( cookieList , additionalCookies ) ; return new Cookies ( cookieList ) ; }


Input: Creates a provider which looks up objects in JNDI using the given name . Example usage : [CODESPLIT] public static < T > Provider < T > fromJndi ( Class < T > type , String name ) { return new JndiProvider < T > ( type , name ) ; }


Input: There may be multiple child injectors blacklisting a certain key so only remove the source that s relevant . [CODESPLIT] private void cleanUpForCollectedState ( Set < KeyAndSource > keysAndSources ) { synchronized ( lock ) { for ( KeyAndSource keyAndSource : keysAndSources ) { Multiset < Object > set = backingMap . get ( keyAndSource . key ) ; if ( set != null ) { set . remove ( keyAndSource . source ) ; if ( set . isEmpty ( ) ) { backingMap . remove ( keyAndSource . key ) ; } } } } }


Input: Indexes bindings by type . [CODESPLIT] void index ( ) { for ( Binding < ? > binding : state . getExplicitBindingsThisLevel ( ) . values ( ) ) { bindingsMultimap . put ( binding . getKey ( ) . getTypeLiteral ( ) , binding ) ; } }


Input: Returns the binding for { [CODESPLIT] @ Override public < T > BindingImpl < T > getBinding ( Key < T > key ) { Errors errors = new Errors ( checkNotNull ( key , "key" ) ) ; try { BindingImpl < T > result = getBindingOrThrow ( key , errors , JitLimitation . EXISTING_JIT ) ; errors . throwConfigurationExceptionIfErrorsExist ( ) ; return result ; } catch ( ErrorsException e ) { throw new ConfigurationException ( errors . merge ( e . getErrors ( ) ) . getMessages ( ) ) ; } }


Input: Gets a binding implementation . First it check to see if the parent has a binding . If the parent has a binding and the binding is scoped it will use that binding . Otherwise this checks for an explicit binding . If no explicit binding is found it looks for a just - in - time binding . [CODESPLIT] < T > BindingImpl < T > getBindingOrThrow ( Key < T > key , Errors errors , JitLimitation jitType ) throws ErrorsException { // Check explicit bindings, i.e. bindings created by modules. BindingImpl < T > binding = state . getExplicitBinding ( key ) ; if ( binding != null ) { return binding ; } // Look for an on-demand binding. return getJustInTimeBinding ( key , errors , jitType ) ; }


Input: Returns a just - in - time binding for { @code key } creating it if necessary . [CODESPLIT] private < T > BindingImpl < T > getJustInTimeBinding ( Key < T > key , Errors errors , JitLimitation jitType ) throws ErrorsException { boolean jitOverride = isProvider ( key ) || isTypeLiteral ( key ) || isMembersInjector ( key ) ; synchronized ( state . lock ( ) ) { // first try to find a JIT binding that we've already created for ( InjectorImpl injector = this ; injector != null ; injector = injector . parent ) { @ SuppressWarnings ( "unchecked" ) // we only store bindings that match their key BindingImpl < T > binding = ( BindingImpl < T > ) injector . jitBindings . get ( key ) ; if ( binding != null ) { // If we found a JIT binding and we don't allow them, // fail.  (But allow bindings created through TypeConverters.) if ( options . jitDisabled && jitType == JitLimitation . NO_JIT && ! jitOverride && ! ( binding instanceof ConvertedConstantBindingImpl ) ) { throw errors . jitDisabled ( key ) . toException ( ) ; } else { return binding ; } } } // If we previously failed creating this JIT binding and our Errors has // already recorded an error, then just directly throw that error. // We need to do this because it's possible we already cleaned up the // entry in jitBindings (during cleanup), and we may be trying // to create it again (in the case of a recursive JIT binding). // We need both of these guards for different reasons // failedJitBindings.contains: We want to continue processing if we've never //   failed before, so that our initial error message contains //   as much useful information as possible about what errors exist. // errors.hasErrors: If we haven't already failed, then it's OK to //   continue processing, to make sure the ultimate error message //   is the correct one. // See: ImplicitBindingsTest#testRecursiveJitBindingsCleanupCorrectly // for where this guard compes into play. if ( failedJitBindings . contains ( key ) && errors . hasErrors ( ) ) { throw errors . toException ( ) ; } return createJustInTimeBindingRecursive ( key , errors , options . jitDisabled , jitType ) ; } // end synchronized(state.lock()) }


Input: Returns true if the key type is MembersInjector ( but not a subclass of MembersInjector ) . [CODESPLIT] private static boolean isMembersInjector ( Key < ? > key ) { return key . getTypeLiteral ( ) . getRawType ( ) . equals ( MembersInjector . class ) && key . getAnnotationType ( ) == null ; }


Input: Creates a synthetic binding to { [CODESPLIT] private < T > BindingImpl < Provider < T > > createProviderBinding ( Key < Provider < T > > key , Errors errors ) throws ErrorsException { Key < T > providedKey = getProvidedKey ( key , errors ) ; BindingImpl < T > delegate = getBindingOrThrow ( providedKey , errors , JitLimitation . NO_JIT ) ; return new ProviderBindingImpl < T > ( this , key , delegate ) ; }


Input: Converts a constant string binding to the required type . [CODESPLIT] private < T > BindingImpl < T > convertConstantStringBinding ( Key < T > key , Errors errors ) throws ErrorsException { // Find a constant string binding. Key < String > stringKey = key . ofType ( STRING_TYPE ) ; BindingImpl < String > stringBinding = state . getExplicitBinding ( stringKey ) ; if ( stringBinding == null || ! stringBinding . isConstant ( ) ) { return null ; } // We can't call getProvider().get() because this InstanceBinding may not have been inintialized // yet (because we may have been called during InternalInjectorCreator.initializeStatically and // instance binding validation hasn't happened yet.) @ SuppressWarnings ( "unchecked" ) String stringValue = ( ( InstanceBinding < String > ) stringBinding ) . getInstance ( ) ; Object source = stringBinding . getSource ( ) ; // Find a matching type converter. TypeLiteral < T > type = key . getTypeLiteral ( ) ; TypeConverterBinding typeConverterBinding = state . getConverter ( stringValue , type , errors , source ) ; if ( typeConverterBinding == null ) { // No converter can handle the given type. return null ; } // Try to convert the string. A failed conversion results in an error. try { @ SuppressWarnings ( "unchecked" ) // This cast is safe because we double check below. T converted = ( T ) typeConverterBinding . getTypeConverter ( ) . convert ( stringValue , type ) ; if ( converted == null ) { throw errors . converterReturnedNull ( stringValue , source , type , typeConverterBinding ) . toException ( ) ; } if ( ! type . getRawType ( ) . isInstance ( converted ) ) { throw errors . conversionTypeError ( stringValue , source , type , typeConverterBinding , converted ) . toException ( ) ; } return new ConvertedConstantBindingImpl < T > ( this , key , converted , stringBinding , typeConverterBinding ) ; } catch ( ErrorsException e ) { throw e ; } catch ( RuntimeException e ) { throw errors . conversionError ( stringValue , source , type , typeConverterBinding , e ) . toException ( ) ; } }


Input: Iterates through the binding s dependencies to clean up any stray bindings that were leftover from a failed JIT binding . This is required because the bindings are eagerly & optimistically added to allow circular dependency support so dependencies may pass where they should have failed . [CODESPLIT] private boolean cleanup ( BindingImpl < ? > binding , Set < Key > encountered ) { boolean bindingFailed = false ; Set < Dependency < ? > > deps = getInternalDependencies ( binding ) ; for ( Dependency dep : deps ) { Key < ? > depKey = dep . getKey ( ) ; InjectionPoint ip = dep . getInjectionPoint ( ) ; if ( encountered . add ( depKey ) ) { // only check if we haven't looked at this key yet BindingImpl depBinding = jitBindings . get ( depKey ) ; if ( depBinding != null ) { // if the binding still exists, validate boolean failed = cleanup ( depBinding , encountered ) ; // if children fail, we fail if ( depBinding instanceof ConstructorBindingImpl ) { ConstructorBindingImpl ctorBinding = ( ConstructorBindingImpl ) depBinding ; ip = ctorBinding . getInternalConstructor ( ) ; if ( ! ctorBinding . isInitialized ( ) ) { failed = true ; } } if ( failed ) { removeFailedJitBinding ( depBinding , ip ) ; bindingFailed = true ; } } else if ( state . getExplicitBinding ( depKey ) == null ) { // ignore keys if they were explicitly bound, but if neither JIT // nor explicit, it's also invalid & should let parent know. bindingFailed = true ; } } } return bindingFailed ; }


Input: Cleans up any state that may have been cached when constructing the JIT binding . [CODESPLIT] private void removeFailedJitBinding ( Binding < ? > binding , InjectionPoint ip ) { failedJitBindings . add ( binding . getKey ( ) ) ; jitBindings . remove ( binding . getKey ( ) ) ; membersInjectorStore . remove ( binding . getKey ( ) . getTypeLiteral ( ) ) ; provisionListenerStore . remove ( binding ) ; if ( ip != null ) { constructors . remove ( ip ) ; } }


Input: Safely gets the dependencies of possibly not initialized bindings . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private Set < Dependency < ? > > getInternalDependencies ( BindingImpl < ? > binding ) { if ( binding instanceof ConstructorBindingImpl ) { return ( ( ConstructorBindingImpl ) binding ) . getInternalDependencies ( ) ; } else if ( binding instanceof HasDependencies ) { return ( ( HasDependencies ) binding ) . getDependencies ( ) ; } else { return ImmutableSet . of ( ) ; } }


Input: Creates a binding for an injectable type with the given scope . Looks for a scope on the type if none is specified . [CODESPLIT] < T > BindingImpl < T > createUninitializedBinding ( Key < T > key , Scoping scoping , Object source , Errors errors , boolean jitBinding ) throws ErrorsException { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; ImplementedBy implementedBy = rawType . getAnnotation ( ImplementedBy . class ) ; // Don't try to inject arrays or enums annotated with @ImplementedBy. if ( rawType . isArray ( ) || ( rawType . isEnum ( ) && implementedBy != null ) ) { throw errors . missingImplementationWithHint ( key , this ) . toException ( ) ; } // Handle TypeLiteral<T> by binding the inner type if ( rawType == TypeLiteral . class ) { @ SuppressWarnings ( "unchecked" ) // we have to fudge the inner type as Object BindingImpl < T > binding = ( BindingImpl < T > ) createTypeLiteralBinding ( ( Key < TypeLiteral < Object > > ) key , errors ) ; return binding ; } // Handle @ImplementedBy if ( implementedBy != null ) { Annotations . checkForMisplacedScopeAnnotations ( rawType , source , errors ) ; return createImplementedByBinding ( key , scoping , implementedBy , errors ) ; } // Handle @ProvidedBy. ProvidedBy providedBy = rawType . getAnnotation ( ProvidedBy . class ) ; if ( providedBy != null ) { Annotations . checkForMisplacedScopeAnnotations ( rawType , source , errors ) ; return createProvidedByBinding ( key , scoping , providedBy , errors ) ; } return ConstructorBindingImpl . create ( this , key , null , /* use default constructor */ source , scoping , errors , jitBinding && options . jitDisabled , options . atInjectRequired ) ; }


Input: Converts a binding for a { [CODESPLIT] private < T > BindingImpl < TypeLiteral < T > > createTypeLiteralBinding ( Key < TypeLiteral < T > > key , Errors errors ) throws ErrorsException { Type typeLiteralType = key . getTypeLiteral ( ) . getType ( ) ; if ( ! ( typeLiteralType instanceof ParameterizedType ) ) { throw errors . cannotInjectRawTypeLiteral ( ) . toException ( ) ; } ParameterizedType parameterizedType = ( ParameterizedType ) typeLiteralType ; Type innerType = parameterizedType . getActualTypeArguments ( ) [ 0 ] ; // this is unforunate. We don't support building TypeLiterals for type variable like 'T'. If // this proves problematic, we can probably fix TypeLiteral to support type variables if ( ! ( innerType instanceof Class ) && ! ( innerType instanceof GenericArrayType ) && ! ( innerType instanceof ParameterizedType ) ) { throw errors . cannotInjectTypeLiteralOf ( innerType ) . toException ( ) ; } @ SuppressWarnings ( "unchecked" ) // by definition, innerType == T, so this is safe TypeLiteral < T > value = ( TypeLiteral < T > ) TypeLiteral . get ( innerType ) ; InternalFactory < TypeLiteral < T > > factory = new ConstantFactory < TypeLiteral < T > > ( Initializables . of ( value ) ) ; return new InstanceBindingImpl < TypeLiteral < T > > ( this , key , SourceProvider . UNKNOWN_SOURCE , factory , ImmutableSet . < InjectionPoint > of ( ) , value ) ; }


Input: Creates a binding for a type annotated with [CODESPLIT] < T > BindingImpl < T > createProvidedByBinding ( Key < T > key , Scoping scoping , ProvidedBy providedBy , Errors errors ) throws ErrorsException { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; Class < ? extends javax . inject . Provider < ? > > providerType = providedBy . value ( ) ; // Make sure it's not the same type. TODO: Can we check for deeper loops? if ( providerType == rawType ) { throw errors . recursiveProviderType ( ) . toException ( ) ; } // Assume the provider provides an appropriate type. We double check at runtime. @ SuppressWarnings ( "unchecked" ) Key < ? extends Provider < T > > providerKey = ( Key < ? extends Provider < T > > ) Key . get ( providerType ) ; ProvidedByInternalFactory < T > internalFactory = new ProvidedByInternalFactory < T > ( rawType , providerType , providerKey ) ; Object source = rawType ; BindingImpl < T > binding = LinkedProviderBindingImpl . createWithInitializer ( this , key , source , Scoping . < T > scope ( key , this , internalFactory , source , scoping ) , scoping , providerKey , internalFactory ) ; internalFactory . setProvisionListenerCallback ( provisionListenerStore . get ( binding ) ) ; return binding ; }


Input: Creates a binding for a type annotated with [CODESPLIT] private < T > BindingImpl < T > createImplementedByBinding ( Key < T > key , Scoping scoping , ImplementedBy implementedBy , Errors errors ) throws ErrorsException { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; Class < ? > implementationType = implementedBy . value ( ) ; // Make sure it's not the same type. TODO: Can we check for deeper cycles? if ( implementationType == rawType ) { throw errors . recursiveImplementationType ( ) . toException ( ) ; } // Make sure implementationType extends type. if ( ! rawType . isAssignableFrom ( implementationType ) ) { throw errors . notASubtype ( implementationType , rawType ) . toException ( ) ; } @ SuppressWarnings ( "unchecked" ) // After the preceding check, this cast is safe. Class < ? extends T > subclass = ( Class < ? extends T > ) implementationType ; // Look up the target binding. final Key < ? extends T > targetKey = Key . get ( subclass ) ; Object source = rawType ; FactoryProxy < T > factory = new FactoryProxy <> ( this , key , targetKey , source ) ; factory . notify ( errors ) ; // causes the factory to initialize itself internally return new LinkedBindingImpl < T > ( this , key , source , Scoping . < T > scope ( key , this , factory , source , scoping ) , scoping , targetKey ) ; }


Input: Attempts to create a just - in - time binding for { [CODESPLIT] private < T > BindingImpl < T > createJustInTimeBindingRecursive ( Key < T > key , Errors errors , boolean jitDisabled , JitLimitation jitType ) throws ErrorsException { // ask the parent to create the JIT binding if ( parent != null ) { if ( jitType == JitLimitation . NEW_OR_EXISTING_JIT && jitDisabled && ! parent . options . jitDisabled ) { // If the binding would be forbidden here but allowed in a parent, report an error instead throw errors . jitDisabledInParent ( key ) . toException ( ) ; } try { return parent . createJustInTimeBindingRecursive ( key , new Errors ( ) , jitDisabled , parent . options . jitDisabled ? JitLimitation . NO_JIT : jitType ) ; } catch ( ErrorsException ignored ) { } } // Retrieve the sources before checking for blacklisting to guard against sources becoming null // due to a full GC happening after calling state.isBlacklisted and // state.getSourcesForBlacklistedKey. // TODO(user): Consolidate these two APIs. Set < Object > sources = state . getSourcesForBlacklistedKey ( key ) ; if ( state . isBlacklisted ( key ) ) { throw errors . childBindingAlreadySet ( key , sources ) . toException ( ) ; } key = MoreTypes . canonicalizeKey ( key ) ; // before storing the key long-term, canonicalize it. BindingImpl < T > binding = createJustInTimeBinding ( key , errors , jitDisabled , jitType ) ; state . parent ( ) . blacklist ( key , state , binding . getSource ( ) ) ; jitBindings . put ( key , binding ) ; return binding ; }


Input: Returns a new just - in - time binding created by resolving { @code key } . The strategies used to create just - in - time bindings are : [CODESPLIT] private < T > BindingImpl < T > createJustInTimeBinding ( Key < T > key , Errors errors , boolean jitDisabled , JitLimitation jitType ) throws ErrorsException { int numErrorsBefore = errors . size ( ) ; // Retrieve the sources before checking for blacklisting to guard against sources becoming null // due to a full GC happening after calling state.isBlacklisted and // state.getSourcesForBlacklistedKey. // TODO(user): Consolidate these two APIs. Set < Object > sources = state . getSourcesForBlacklistedKey ( key ) ; if ( state . isBlacklisted ( key ) ) { throw errors . childBindingAlreadySet ( key , sources ) . toException ( ) ; } // Handle cases where T is a Provider<?>. if ( isProvider ( key ) ) { // These casts are safe. We know T extends Provider<X> and that given Key<Provider<X>>, // createProviderBinding() will return BindingImpl<Provider<X>>. @ SuppressWarnings ( { "unchecked" , "cast" } ) BindingImpl < T > binding = ( BindingImpl < T > ) createProviderBinding ( ( Key ) key , errors ) ; return binding ; } // Handle cases where T is a MembersInjector<?> if ( isMembersInjector ( key ) ) { // These casts are safe. T extends MembersInjector<X> and that given Key<MembersInjector<X>>, // createMembersInjectorBinding() will return BindingImpl<MembersInjector<X>>. @ SuppressWarnings ( { "unchecked" , "cast" } ) BindingImpl < T > binding = ( BindingImpl < T > ) createMembersInjectorBinding ( ( Key ) key , errors ) ; return binding ; } // Try to convert a constant string binding to the requested type. BindingImpl < T > convertedBinding = convertConstantStringBinding ( key , errors ) ; if ( convertedBinding != null ) { return convertedBinding ; } if ( ! isTypeLiteral ( key ) && jitDisabled && jitType != JitLimitation . NEW_OR_EXISTING_JIT ) { throw errors . jitDisabled ( key ) . toException ( ) ; } // If the key has an annotation... if ( key . getAnnotationType ( ) != null ) { // Look for a binding without annotation attributes or return null. if ( key . hasAttributes ( ) && ! options . exactBindingAnnotationsRequired ) { try { Errors ignored = new Errors ( ) ; return getBindingOrThrow ( key . withoutAttributes ( ) , ignored , JitLimitation . NO_JIT ) ; } catch ( ErrorsException ignored ) { // throw with a more appropriate message below } } throw errors . missingImplementationWithHint ( key , this ) . toException ( ) ; } Object source = key . getTypeLiteral ( ) . getRawType ( ) ; BindingImpl < T > binding = createUninitializedBinding ( key , Scoping . UNSCOPED , source , errors , true ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; initializeJitBinding ( binding , errors ) ; return binding ; }


Input: Returns parameter injectors or { [CODESPLIT] SingleParameterInjector < ? > [ ] getParametersInjectors ( List < Dependency < ? > > parameters , Errors errors ) throws ErrorsException { if ( parameters . isEmpty ( ) ) { return null ; } int numErrorsBefore = errors . size ( ) ; SingleParameterInjector < ? > [ ] result = new SingleParameterInjector < ? > [ parameters . size ( ) ] ; int i = 0 ; for ( Dependency < ? > parameter : parameters ) { try { result [ i ++ ] = createParameterInjector ( parameter , errors . withSource ( parameter ) ) ; } catch ( ErrorsException rethrownBelow ) { // rethrown below } } errors . throwIfNewErrors ( numErrorsBefore ) ; return result ; }


Input: Looks up thread local context and { @link InternalContext#enter () enters } it or creates a new context if necessary . [CODESPLIT] InternalContext enterContext ( ) { Object [ ] reference = localContext . get ( ) ; if ( reference == null ) { reference = new Object [ 1 ] ; localContext . set ( reference ) ; } InternalContext ctx = ( InternalContext ) reference [ 0 ] ; if ( ctx == null ) { reference [ 0 ] = ctx = new InternalContext ( options , reference ) ; } else { ctx . enter ( ) ; } return ctx ; }


Input: Returns an array of parameter values . [CODESPLIT] static Object [ ] getAll ( InternalContext context , SingleParameterInjector < ? > [ ] parameterInjectors ) throws InternalProvisionException { if ( parameterInjectors == null ) { return NO_ARGUMENTS ; } int size = parameterInjectors . length ; Object [ ] parameters = new Object [ size ] ; // optimization: use manual for/each to save allocating an iterator here for ( int i = 0 ; i < size ; i ++ ) { parameters [ i ] = parameterInjectors [ i ] . inject ( context ) ; } return parameters ; }


Input:
Creates the label for a node . This is a string of HTML that defines a table with a heading at the top and ( in the case of { [CODESPLIT] protected String getNodeLabel ( GraphvizNode node ) { String cellborder = node . getStyle ( ) == NodeStyle . INVISIBLE ? "1" : "0" ; StringBuilder html = new StringBuilder ( ) ; html . append ( "<" ) ; html . append ( "
" ) ; html . append ( "
" ) . append ( "" ) ; String subtitle = Joiner . on ( "
" ) . join ( node . getSubtitles ( ) ) ; if ( subtitle . length ( ) != 0 ) { html . append ( "" ) ; html . append ( subtitle ) . append ( "
" ) . append ( "" ) ; } html . append ( "" ) ; html . append ( htmlEscape ( node . getTitle ( ) ) ) . append ( "
" ) ; html . append ( "" ) . append ( "	" ) . append ( "
" ) ; for ( Map . Entry < String , String > field : node . getFields ( ) . entrySet ( ) ) { html . append ( "
" ) ; html . append ( "" ) ; html . append ( htmlEscape ( field . getValue ( ) ) ) ; html . append ( "	" ) . append ( "
" ) ; } html . append ( "
" ) ; html . append ( ">" ) ; return html . toString ( ) ; }


Input: Returns a new multibinder that collects instances of the key s type in a { @link Set } that is itself bound with the annotation ( if any ) of the key . [CODESPLIT] public static < T > Multibinder < T > newSetBinder ( Binder binder , Key < T > key ) { return new Multibinder < T > ( newRealSetBinder ( binder . skipSources ( Multibinder . class ) , key ) ) ; }


Input: Returns a new multibinder that collects instances of { [CODESPLIT] public static < T > Multibinder < T > newSetBinder ( Binder binder , Class < T > type , Class < ? extends Annotation > annotationType ) { return newSetBinder ( binder , Key . get ( type , annotationType ) ) ; }


Input: See the factory configuration examples at { [CODESPLIT] public < T > FactoryModuleBuilder implement ( Class < T > source , Class < ? extends T > target ) { return implement ( source , TypeLiteral . get ( target ) ) ; }


Input: See the factory configuration examples at { [CODESPLIT] public < F > Module build ( Class < F > factoryInterface ) { return build ( TypeLiteral . get ( factoryInterface ) ) ; }


Input: See the factory configuration examples at { [CODESPLIT] public < F > Module build ( TypeLiteral < F > factoryInterface ) { return build ( Key . get ( factoryInterface ) ) ; }


Input: The Injector is a special case because we allow both parent and child injectors to both have a binding for that key . [CODESPLIT] private static void bindInjector ( InjectorImpl injector ) { Key < Injector > key = Key . get ( Injector . class ) ; InjectorFactory injectorFactory = new InjectorFactory ( injector ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Injector > ( injector , key , SourceProvider . UNKNOWN_SOURCE , injectorFactory , Scoping . UNSCOPED , injectorFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; }


Input: The Logger is a special case because it knows the injection point of the injected member . It s the only binding that does this . [CODESPLIT] private static void bindLogger ( InjectorImpl injector ) { Key < Logger > key = Key . get ( Logger . class ) ; LoggerFactory loggerFactory = new LoggerFactory ( ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Logger > ( injector , key , SourceProvider . UNKNOWN_SOURCE , loggerFactory , Scoping . UNSCOPED , loggerFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; }


Input: This metohd is necessary to create a Dependency<T > with proper generic type information [CODESPLIT] private < T > Dependency < T > newDependency ( Key < T > key , boolean allowsNull , int parameterIndex ) { return new Dependency < T > ( this , key , allowsNull , parameterIndex ) ; }


Input: Returns a new injection point for the specified constructor . If the declaring type of { @code constructor } is parameterized ( such as { @code List<T > } ) prefer the overload that includes a type literal . [CODESPLIT] public static < T > InjectionPoint forConstructor ( Constructor < T > constructor ) { return new InjectionPoint ( TypeLiteral . get ( constructor . getDeclaringClass ( ) ) , constructor ) ; }


Input: Returns a new injection point for the specified constructor of { @code type } . [CODESPLIT] public static < T > InjectionPoint forConstructor ( Constructor < T > constructor , TypeLiteral < ? extends T > type ) { if ( type . getRawType ( ) != constructor . getDeclaringClass ( ) ) { new Errors ( type ) . constructorNotDefinedByType ( constructor , type ) . throwConfigurationExceptionIfErrorsExist ( ) ; } return new InjectionPoint ( type , constructor ) ; }


Input: Returns a new injection point for the injectable constructor of { @code type } . [CODESPLIT] public static InjectionPoint forConstructorOf ( TypeLiteral < ? > type ) { Class < ? > rawType = getRawType ( type . getType ( ) ) ; Errors errors = new Errors ( rawType ) ; Constructor < ? > injectableConstructor = null ; for ( Constructor < ? > constructor : rawType . getDeclaredConstructors ( ) ) { boolean optional ; Inject guiceInject = constructor . getAnnotation ( Inject . class ) ; if ( guiceInject == null ) { javax . inject . Inject javaxInject = constructor . getAnnotation ( javax . inject . Inject . class ) ; if ( javaxInject == null ) { continue ; } optional = false ; } else { optional = guiceInject . optional ( ) ; } if ( optional ) { errors . optionalConstructor ( constructor ) ; } if ( injectableConstructor != null ) { errors . tooManyConstructors ( rawType ) ; } injectableConstructor = constructor ; checkForMisplacedBindingAnnotations ( injectableConstructor , errors ) ; } errors . throwConfigurationExceptionIfErrorsExist ( ) ; if ( injectableConstructor != null ) { return new InjectionPoint ( type , injectableConstructor ) ; } // If no annotated constructor is found, look for a no-arg constructor instead. try { Constructor < ? > noArgConstructor = rawType . getDeclaredConstructor ( ) ; // Disallow private constructors on non-private classes (unless they have @Inject) if ( Modifier . isPrivate ( noArgConstructor . getModifiers ( ) ) && ! Modifier . isPrivate ( rawType . getModifiers ( ) ) ) { errors . missingConstructor ( rawType ) ; throw new ConfigurationException ( errors . getMessages ( ) ) ; } checkForMisplacedBindingAnnotations ( noArgConstructor , errors ) ; return new InjectionPoint ( type , noArgConstructor ) ; } catch ( NoSuchMethodException e ) { errors . missingConstructor ( rawType ) ; throw new ConfigurationException ( errors . getMessages ( ) ) ; } }


Input: Returns a new injection point for the specified method of { @code type } . This is useful for extensions that need to build dependency graphs from arbitrary methods . [CODESPLIT] public static < T > InjectionPoint forMethod ( Method method , TypeLiteral < T > type ) { return new InjectionPoint ( type , method , false ) ; }


Input: Returns all static method and field injection points on { @code type } . [CODESPLIT] public static Set < InjectionPoint > forStaticMethodsAndFields ( TypeLiteral < ? > type ) { Errors errors = new Errors ( ) ; Set < InjectionPoint > result ; if ( type . getRawType ( ) . isInterface ( ) ) { errors . staticInjectionOnInterface ( type . getRawType ( ) ) ; result = null ; } else { result = getInjectionPoints ( type , true , errors ) ; } if ( errors . hasErrors ( ) ) { throw new ConfigurationException ( errors . getMessages ( ) ) . withPartialValue ( result ) ; } return result ; }


Input: Returns all instance method and field injection points on { @code type } . [CODESPLIT] public static Set < InjectionPoint > forInstanceMethodsAndFields ( TypeLiteral < ? > type ) { Errors errors = new Errors ( ) ; Set < InjectionPoint > result = getInjectionPoints ( type , false , errors ) ; if ( errors . hasErrors ( ) ) { throw new ConfigurationException ( errors . getMessages ( ) ) . withPartialValue ( result ) ; } return result ; }


Input: Returns true if the binding annotation is in the wrong place . [CODESPLIT] private static boolean checkForMisplacedBindingAnnotations ( Member member , Errors errors ) { Annotation misplacedBindingAnnotation = Annotations . findBindingAnnotation ( errors , member , ( ( AnnotatedElement ) member ) . getAnnotations ( ) ) ; if ( misplacedBindingAnnotation == null ) { return false ; } // don't warn about misplaced binding annotations on methods when there's a field with the same // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242. if ( member instanceof Method ) { try { if ( member . getDeclaringClass ( ) . getDeclaredField ( member . getName ( ) ) != null ) { return false ; } } catch ( NoSuchFieldException ignore ) { } } errors . misplacedBindingAnnotation ( member , misplacedBindingAnnotation ) ; return true ; }


Input:
Returns an ordered immutable set of injection points for the given type . Members in superclasses come before members in subclasses . Within a class fields come before methods . Overridden methods are filtered out . The order of fields / methods within a class is consistent but undefined . [CODESPLIT] private static Set < InjectionPoint > getInjectionPoints ( final TypeLiteral < ? > type , boolean statics , Errors errors ) { InjectableMembers injectableMembers = new InjectableMembers ( ) ; OverrideIndex overrideIndex = null ; List < TypeLiteral < ? > > hierarchy = hierarchyFor ( type ) ; int topIndex = hierarchy . size ( ) - 1 ; for ( int i = topIndex ; i >= 0 ; i -- ) { if ( overrideIndex != null && i < topIndex ) { // Knowing the position within the hierarchy helps us make optimizations. if ( i == 0 ) { overrideIndex . position = Position . BOTTOM ; } else { overrideIndex . position = Position . MIDDLE ; } } TypeLiteral < ? > current = hierarchy . get ( i ) ; for ( Field field : getDeclaredFields ( current ) ) { if ( Modifier . isStatic ( field . getModifiers ( ) ) == statics ) { Annotation atInject = getAtInject ( field ) ; if ( atInject != null ) { InjectableField injectableField = new InjectableField ( current , field , atInject ) ; if ( injectableField . jsr330 && Modifier . isFinal ( field . getModifiers ( ) ) ) { errors . cannotInjectFinalField ( field ) ; } injectableMembers . add ( injectableField ) ; } } } for ( Method method : getDeclaredMethods ( current ) ) { if ( isEligibleForInjection ( method , statics ) ) { Annotation atInject = getAtInject ( method ) ; if ( atInject != null ) { InjectableMethod injectableMethod = new InjectableMethod ( current , method , atInject ) ; if ( checkForMisplacedBindingAnnotations ( method , errors ) || ! isValidMethod ( injectableMethod , errors ) ) { if ( overrideIndex != null ) { boolean removed = overrideIndex . removeIfOverriddenBy ( method , false , injectableMethod ) ; if ( removed ) { logger . log ( Level . WARNING , "Method: {0} is not a valid injectable method (" + "because it either has misplaced binding annotations " + "or specifies type parameters) but is overriding a method that is " + "valid. Because it is not valid, the method will not be injected. " + "To fix this, make the method a valid injectable method." , method ) ; } } continue ; } if ( statics ) { injectableMembers . add ( injectableMethod ) ; } else { if ( overrideIndex == null ) { /*
                 * Creating the override index lazily means that the first type in the hierarchy
                 * with injectable methods (not necessarily the top most type) will be treated as
                 * the TOP position and will enjoy the same optimizations (no checks for overridden
                 * methods, etc.).
                 */ overrideIndex = new OverrideIndex ( injectableMembers ) ; } else { // Forcibly remove the overridden method, otherwise we'll inject // it twice. overrideIndex . removeIfOverriddenBy ( method , true , injectableMethod ) ; } overrideIndex . add ( injectableMethod ) ; } } else { if ( overrideIndex != null ) { boolean removed = overrideIndex . removeIfOverriddenBy ( method , false , null ) ; if ( removed ) { logger . log ( Level . WARNING , "Method: {0} is not annotated with @Inject but " + "is overriding a method that is annotated with @javax.inject.Inject." + "Because it is not annotated with @Inject, the method will not be " + "injected. To fix this, annotate the method with @Inject." , method ) ; } } } } } } if ( injectableMembers . isEmpty ( ) ) { return Collections . emptySet ( ) ; } ImmutableSet . Builder < InjectionPoint > builder = ImmutableSet . builder ( ) ; for ( InjectableMember im = injectableMembers . head ; im != null ; im = im . next ) { try { builder . add ( im . toInjectionPoint ( ) ) ; } catch ( ConfigurationException ignorable ) { if ( ! im . optional ) { errors . merge ( ignorable . getErrorMessages ( ) ) ; } } } return builder . build ( ) ; }


Input: Returns true if the method is eligible to be injected . This is different than { @link #isValidMethod } because ineligibility will not drop a method from being injected if a superclass was eligible & valid . Bridge & synthetic methods are excluded from eligibility for two reasons : [CODESPLIT] private static boolean isEligibleForInjection ( Method method , boolean statics ) { return Modifier . isStatic ( method . getModifiers ( ) ) == statics && ! method . isBridge ( ) && ! method . isSynthetic ( ) ; }


Input: Returns true if a overrides b . Assumes signatures of a and b are the same and a s declaring class is a subclass of b s declaring class . [CODESPLIT] private static boolean overrides ( Method a , Method b ) { // See JLS section 8.4.8.1 int modifiers = b . getModifiers ( ) ; if ( Modifier . isPublic ( modifiers ) || Modifier . isProtected ( modifiers ) ) { return true ; } if ( Modifier . isPrivate ( modifiers ) ) { return false ; } // b must be package-private return a . getDeclaringClass ( ) . getPackage ( ) . equals ( b . getDeclaringClass ( ) . getPackage ( ) ) ; }


Input: Sets the actual members injector . [CODESPLIT] public void initializeDelegate ( MembersInjector < T > delegate ) { checkState ( this . delegate == null , "delegate already initialized" ) ; this . delegate = checkNotNull ( delegate , "delegate" ) ; }


Input: Returns the looked up members injector . The result is not valid until this lookup has been initialized which usually happens when the injector is created . The members injector will throw an { [CODESPLIT] public MembersInjector < T > getMembersInjector ( ) { return new MembersInjector < T > ( ) { @ Override public void injectMembers ( T instance ) { MembersInjector < T > local = delegate ; if ( local == null ) { throw new IllegalStateException ( "This MembersInjector cannot be used until the Injector has been created." ) ; } local . injectMembers ( instance ) ; } @ Override public String toString ( ) { return "MembersInjector<" + type + ">" ; } } ; }


Input: Returns a { @link CheckedProvider } which always provides { @code instance } . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P of ( TypeLiteral < P > providerType , @ Nullable T instance ) { return generateProvider ( providerType , Optional . fromNullable ( instance ) , new ReturningHandler < T > ( instance ) ) ; }


Input: Returns a { @link CheckedProvider } which always provides { @code instance } . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P of ( Class < P > providerType , @ Nullable T instance ) { return of ( TypeLiteral . get ( providerType ) , instance ) ; }


Input: Returns a { @link CheckedProvider } which always throws exceptions . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P throwing ( TypeLiteral < P > providerType , Class < ? extends Throwable > throwable ) { // TODO(eatnumber1): Understand why TypeLiteral#getRawType returns a Class<? super T> rather // than a Class<T> and remove this unsafe cast. Class < P > providerRaw = ( Class ) providerType . getRawType ( ) ; checkThrowable ( providerRaw , throwable ) ; return generateProvider ( providerType , Optional . < T > absent ( ) , ThrowingHandler . forClass ( throwable ) ) ; }


Input: Returns a { @link CheckedProvider } which always throws exceptions . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P throwing ( Class < P > providerType , Class < ? extends Throwable > throwable ) { return throwing ( TypeLiteral . get ( providerType ) , throwable ) ; }


Input: Returns the type from super class s type parameter in { [CODESPLIT] static Type getSuperclassTypeParameter ( Class < ? > subclass ) { Type superclass = subclass . getGenericSuperclass ( ) ; if ( superclass instanceof Class ) { throw new RuntimeException ( "Missing type parameter." ) ; } ParameterizedType parameterized = ( ParameterizedType ) superclass ; return canonicalize ( parameterized . getActualTypeArguments ( ) [ 0 ] ) ; }


Input: Gets the type of this type s provider . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) final TypeLiteral < Provider < T > > providerType ( ) { // This cast is safe and wouldn't generate a warning if Type had a type // parameter. return ( TypeLiteral < Provider < T > > ) get ( Types . providerOf ( getType ( ) ) ) ; }


Input: Gets type literal for the given { [CODESPLIT] public static < T > TypeLiteral < T > get ( Class < T > type ) { return new TypeLiteral < T > ( type ) ; }


Input: Returns an immutable list of the resolved types . [CODESPLIT] private List < TypeLiteral < ? > > resolveAll ( Type [ ] types ) { TypeLiteral < ? > [ ] result = new TypeLiteral < ? > [ types . length ] ; for ( int t = 0 ; t < types . length ; t ++ ) { result [ t ] = resolve ( types [ t ] ) ; } return ImmutableList . copyOf ( result ) ; }


Input: Returns the generic form of { @code supertype } . For example if this is { @code ArrayList<String > } this returns { @code Iterable<String > } given the input { @code Iterable . class } . [CODESPLIT] public TypeLiteral < ? > getSupertype ( Class < ? > supertype ) { checkArgument ( supertype . isAssignableFrom ( rawType ) , "%s is not a supertype of %s" , supertype , this . type ) ; return resolve ( MoreTypes . getGenericSupertype ( type , rawType , supertype ) ) ; }


Input: Returns the resolved generic type of { @code field } . [CODESPLIT] public TypeLiteral < ? > getFieldType ( Field field ) { checkArgument ( field . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , "%s is not defined by a supertype of %s" , field , type ) ; return resolve ( field . getGenericType ( ) ) ; }


Input: Returns the resolved generic parameter types of { @code methodOrConstructor } . [CODESPLIT] public List < TypeLiteral < ? > > getParameterTypes ( Member methodOrConstructor ) { Type [ ] genericParameterTypes ; if ( methodOrConstructor instanceof Method ) { Method method = ( Method ) methodOrConstructor ; checkArgument ( method . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , "%s is not defined by a supertype of %s" , method , type ) ; genericParameterTypes = method . getGenericParameterTypes ( ) ; } else if ( methodOrConstructor instanceof Constructor ) { Constructor < ? > constructor = ( Constructor < ? > ) methodOrConstructor ; checkArgument ( constructor . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , "%s does not construct a supertype of %s" , constructor , type ) ; genericParameterTypes = constructor . getGenericParameterTypes ( ) ; } else { throw new IllegalArgumentException ( "Not a method or a constructor: " + methodOrConstructor ) ; } return resolveAll ( genericParameterTypes ) ; }


Input: Returns the resolved generic exception types thrown by { @code constructor } . [CODESPLIT] public List < TypeLiteral < ? > > getExceptionTypes ( Member methodOrConstructor ) { Type [ ] genericExceptionTypes ; if ( methodOrConstructor instanceof Method ) { Method method = ( Method ) methodOrConstructor ; checkArgument ( method . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , "%s is not defined by a supertype of %s" , method , type ) ; genericExceptionTypes = method . getGenericExceptionTypes ( ) ; } else if ( methodOrConstructor instanceof Constructor ) { Constructor < ? > constructor = ( Constructor < ? > ) methodOrConstructor ; checkArgument ( constructor . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , "%s does not construct a supertype of %s" , constructor , type ) ; genericExceptionTypes = constructor . getGenericExceptionTypes ( ) ; } else { throw new IllegalArgumentException ( "Not a method or a constructor: " + methodOrConstructor ) ; } return resolveAll ( genericExceptionTypes ) ; }


Input: Returns the resolved generic return type of { @code method } . [CODESPLIT] public TypeLiteral < ? > getReturnType ( Method method ) { checkArgument ( method . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , "%s is not defined by a supertype of %s" , method , type ) ; return resolve ( method . getGenericReturnType ( ) ) ; }


Input: Returns a key that doesn t hold any references to parent classes . This is necessary for anonymous keys so ensure we don t hold a ref to the containing module ( or class ) forever . [CODESPLIT] public static < T > Key < T > canonicalizeKey ( Key < T > key ) { // If we know this isn't a subclass, return as-is. // Otherwise, recreate the key to avoid the subclass if ( key . getClass ( ) == Key . class ) { return key ; } else if ( key . getAnnotation ( ) != null ) { return Key . get ( key . getTypeLiteral ( ) , key . getAnnotation ( ) ) ; } else if ( key . getAnnotationType ( ) != null ) { return Key . get ( key . getTypeLiteral ( ) , key . getAnnotationType ( ) ) ; } else { return Key . get ( key . getTypeLiteral ( ) ) ; } }


Input: Returns an type that s appropriate for use in a key . [CODESPLIT] public static < T > TypeLiteral < T > canonicalizeForKey ( TypeLiteral < T > typeLiteral ) { Type type = typeLiteral . getType ( ) ; if ( ! isFullySpecified ( type ) ) { Errors errors = new Errors ( ) . keyNotFullySpecified ( typeLiteral ) ; throw new ConfigurationException ( errors . getMessages ( ) ) ; } if ( typeLiteral . getRawType ( ) == javax . inject . Provider . class ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; // the following casts are generally unsafe, but com.google.inject.Provider extends // javax.inject.Provider and is covariant @ SuppressWarnings ( "unchecked" ) TypeLiteral < T > guiceProviderType = ( TypeLiteral < T > ) TypeLiteral . get ( Types . providerOf ( parameterizedType . getActualTypeArguments ( ) [ 0 ] ) ) ; return guiceProviderType ; } @ SuppressWarnings ( "unchecked" ) TypeLiteral < T > wrappedPrimitives = ( TypeLiteral < T > ) PRIMITIVE_TO_WRAPPER . get ( typeLiteral ) ; if ( wrappedPrimitives != null ) { return wrappedPrimitives ; } // If we know this isn't a subclass, return as-is. if ( typeLiteral . getClass ( ) == TypeLiteral . class ) { return typeLiteral ; } // recreate the TypeLiteral to avoid anonymous TypeLiterals from holding refs to their // surrounding classes. @ SuppressWarnings ( "unchecked" ) TypeLiteral < T > recreated = ( TypeLiteral < T > ) TypeLiteral . get ( typeLiteral . getType ( ) ) ; return recreated ; }


Input: Returns true if { [CODESPLIT] private static boolean isFullySpecified ( Type type ) { if ( type instanceof Class ) { return true ; } else if ( type instanceof CompositeType ) { return ( ( CompositeType ) type ) . isFullySpecified ( ) ; } else if ( type instanceof TypeVariable ) { return false ; } else { return ( ( CompositeType ) canonicalize ( type ) ) . isFullySpecified ( ) ; } }


Input: Returns a type that is functionally equal but not necessarily equal according to { [CODESPLIT] public static Type canonicalize ( Type type ) { if ( type instanceof Class ) { Class < ? > c = ( Class < ? > ) type ; return c . isArray ( ) ? new GenericArrayTypeImpl ( canonicalize ( c . getComponentType ( ) ) ) : c ; } else if ( type instanceof CompositeType ) { return type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType p = ( ParameterizedType ) type ; return new ParameterizedTypeImpl ( p . getOwnerType ( ) , p . getRawType ( ) , p . getActualTypeArguments ( ) ) ; } else if ( type instanceof GenericArrayType ) { GenericArrayType g = ( GenericArrayType ) type ; return new GenericArrayTypeImpl ( g . getGenericComponentType ( ) ) ; } else if ( type instanceof WildcardType ) { WildcardType w = ( WildcardType ) type ; return new WildcardTypeImpl ( w . getUpperBounds ( ) , w . getLowerBounds ( ) ) ; } else { // type is either serializable as-is or unsupported return type ; } }


Input: Returns the declaring class of { [CODESPLIT] private static Class < ? > declaringClassOf ( TypeVariable typeVariable ) { GenericDeclaration genericDeclaration = typeVariable . getGenericDeclaration ( ) ; return genericDeclaration instanceof Class ? ( Class < ? > ) genericDeclaration : null ; }


Input: Introspects the injector and collects all instances of bound { @code List<ServletDefinition > } into a master list . [CODESPLIT] private ServletDefinition [ ] collectServletDefinitions ( Injector injector ) { List < ServletDefinition > servletDefinitions = Lists . newArrayList ( ) ; for ( Binding < ServletDefinition > entry : injector . findBindingsByType ( SERVLET_DEFS ) ) { servletDefinitions . add ( entry . getProvider ( ) . get ( ) ) ; } // Copy to a fixed size array for speed. return servletDefinitions . toArray ( new ServletDefinition [ servletDefinitions . size ( ) ] ) ; }


Input: Installs default converters for primitives enums and class literals . [CODESPLIT] static void prepareBuiltInConverters ( InjectorImpl injector ) { // Configure type converters. convertToPrimitiveType ( injector , int . class , Integer . class ) ; convertToPrimitiveType ( injector , long . class , Long . class ) ; convertToPrimitiveType ( injector , boolean . class , Boolean . class ) ; convertToPrimitiveType ( injector , byte . class , Byte . class ) ; convertToPrimitiveType ( injector , short . class , Short . class ) ; convertToPrimitiveType ( injector , float . class , Float . class ) ; convertToPrimitiveType ( injector , double . class , Double . class ) ; convertToClass ( injector , Character . class , new TypeConverter ( ) { @ Override public Object convert ( String value , TypeLiteral < ? > toType ) { value = value . trim ( ) ; if ( value . length ( ) != 1 ) { throw new RuntimeException ( "Length != 1." ) ; } return value . charAt ( 0 ) ; } @ Override public String toString ( ) { return "TypeConverter<Character>" ; } } ) ; convertToClasses ( injector , Matchers . subclassesOf ( Enum . class ) , new TypeConverter ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public Object convert ( String value , TypeLiteral < ? > toType ) { return Enum . valueOf ( ( Class ) toType . getRawType ( ) , value ) ; } @ Override public String toString ( ) { return "TypeConverter<E extends Enum<E>>" ; } } ) ; internalConvertToTypes ( injector , new AbstractMatcher < TypeLiteral < ? > > ( ) { @ Override public boolean matches ( TypeLiteral < ? > typeLiteral ) { return typeLiteral . getRawType ( ) == Class . class ; } @ Override public String toString ( ) { return "Class<?>" ; } } , new TypeConverter ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public Object convert ( String value , TypeLiteral < ? > toType ) { try { return Class . forName ( value ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e . getMessage ( ) ) ; } } @ Override public String toString ( ) { return "TypeConverter<Class<?>>" ; } } ) ; }


Input: Attempts to canonicalize null references to the system class loader . May return null if for some reason the system loader is unavailable . [CODESPLIT] private static ClassLoader canonicalize ( ClassLoader classLoader ) { return classLoader != null ? classLoader : SystemBridgeHolder . SYSTEM_BRIDGE . getParent ( ) ; }


Input: Returns a FastClass proxy for invoking the given member or { @code null } if access rules disallow it . [CODESPLIT] public static net . sf . cglib . reflect . FastClass newFastClassForMember ( Member member ) { return newFastClassForMember ( member . getDeclaringClass ( ) , member ) ; }


Input: Returns a FastClass proxy for invoking the given member or { @code null } if access rules disallow it . [CODESPLIT] public static net . sf . cglib . reflect . FastClass newFastClassForMember ( Class < ? > type , Member member ) { if ( ! new net . sf . cglib . core . VisibilityPredicate ( type , false ) . evaluate ( member ) ) { // the member cannot be indexed by fast class.  Bail out. return null ; } boolean publiclyCallable = isPubliclyCallable ( member ) ; if ( ! publiclyCallable && ! hasSameVersionOfCglib ( type . getClassLoader ( ) ) ) { // The type is in a classloader with a different version of cglib and is not publicly visible // (so we can't use the bridge classloader to work around).  Bail out. return null ; } net . sf . cglib . reflect . FastClass . Generator generator = new net . sf . cglib . reflect . FastClass . Generator ( ) ; if ( publiclyCallable ) { // Use the bridge classloader if we can generator . setClassLoader ( getClassLoader ( type ) ) ; } generator . setType ( type ) ; generator . setNamingPolicy ( FASTCLASS_NAMING_POLICY ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Loading " + type + " FastClass with " + generator . getClassLoader ( ) ) ; } return generator . create ( ) ; }


Input: Returns true if the types classloader has the same version of cglib that BytecodeGen has . This only returns false in strange OSGI situations but it prevents us from using FastClass for non public members . [CODESPLIT] private static boolean hasSameVersionOfCglib ( ClassLoader classLoader ) { Class < ? > fc = net . sf . cglib . reflect . FastClass . class ; try { return classLoader . loadClass ( fc . getName ( ) ) == fc ; } catch ( ClassNotFoundException e ) { return false ; } }


Input: Returns true if the member can be called by a fast class generated in a different classloader . [CODESPLIT] private static boolean isPubliclyCallable ( Member member ) { if ( ! Modifier . isPublic ( member . getModifiers ( ) ) ) { return false ; } Class < ? > [ ] parameterTypes ; if ( member instanceof Constructor ) { parameterTypes = ( ( Constructor ) member ) . getParameterTypes ( ) ; } else { Method method = ( Method ) member ; if ( ! Modifier . isPublic ( method . getReturnType ( ) . getModifiers ( ) ) ) { return false ; } parameterTypes = method . getParameterTypes ( ) ; } for ( Class < ? > type : parameterTypes ) { if ( ! Modifier . isPublic ( type . getModifiers ( ) ) ) { return false ; } } return true ; }


Input: Creates a { @link ProviderMethod } . [CODESPLIT] static < T > ProviderMethod < T > create ( Key < T > key , Method method , Object instance , ImmutableSet < Dependency < ? > > dependencies , Class < ? extends Annotation > scopeAnnotation , boolean skipFastClassGeneration , Annotation annotation ) { int modifiers = method . getModifiers ( ) ; /*if[AOP]*/ if ( ! skipFastClassGeneration ) { try { net . sf . cglib . reflect . FastClass fc = BytecodeGen . newFastClassForMember ( method ) ; if ( fc != null ) { return new FastClassProviderMethod < T > ( key , fc , method , instance , dependencies , scopeAnnotation , annotation ) ; } } catch ( net . sf . cglib . core . CodeGenerationException e ) { /* fall-through */ } } /*end[AOP]*/ if ( ! Modifier . isPublic ( modifiers ) || ! Modifier . isPublic ( method . getDeclaringClass ( ) . getModifiers ( ) ) ) { method . setAccessible ( true ) ; } return new ReflectionProviderMethod < T > ( key , method , instance , dependencies , scopeAnnotation , annotation ) ; }


Input: Returns the Guice { [CODESPLIT] public Object getValue ( Injector injector ) { if ( null == provider ) { synchronized ( this ) { if ( null == provider ) { provider = isProvider ? injector . getProvider ( getBindingForType ( getProvidedType ( type ) ) ) : injector . getProvider ( getPrimaryBindingKey ( ) ) ; } } } return isProvider ? provider : provider . get ( ) ; }


Input: Replace annotation instances with annotation types this is only appropriate for testing if a key is bound and not for injecting . [CODESPLIT] public Key < ? > fixAnnotations ( Key < ? > key ) { return key . getAnnotation ( ) == null ? key : Key . get ( key . getTypeLiteral ( ) , key . getAnnotation ( ) . annotationType ( ) ) ; }


Input: Returns the unique binding annotation from the specified list or { @code null } if there are none . [CODESPLIT] private Annotation getBindingAnnotation ( Annotation [ ] annotations ) { Annotation bindingAnnotation = null ; for ( Annotation annotation : annotations ) { if ( Annotations . isBindingAnnotation ( annotation . annotationType ( ) ) ) { checkArgument ( bindingAnnotation == null , "Parameter has multiple binding annotations: %s and %s" , bindingAnnotation , annotation ) ; bindingAnnotation = annotation ; } } return bindingAnnotation ; }


Input: Registers an instance for member injection when that step is performed . [CODESPLIT] < T > Initializable < T > requestInjection ( InjectorImpl injector , T instance , Binding < T > binding , Object source , Set < InjectionPoint > injectionPoints ) { checkNotNull ( source ) ; Preconditions . checkState ( ! validationStarted , "Member injection could not be requested after validation is started" ) ; ProvisionListenerStackCallback < T > provisionCallback = binding == null ? null : injector . provisionListenerStore . get ( binding ) ; // short circuit if the object has no injections or listeners. if ( instance == null || ( injectionPoints . isEmpty ( ) && ! injector . membersInjectorStore . hasTypeListeners ( ) && provisionCallback == null ) ) { return Initializables . of ( instance ) ; } if ( initializablesCache . containsKey ( instance ) ) { @ SuppressWarnings ( "unchecked" ) // Map from T to InjectableReference<T> Initializable < T > cached = ( Initializable < T > ) initializablesCache . get ( instance ) ; return cached ; } InjectableReference < T > injectableReference = new InjectableReference < T > ( injector , instance , binding == null ? null : binding . getKey ( ) , provisionCallback , source , cycleDetectingLockFactory . create ( instance . getClass ( ) ) ) ; initializablesCache . put ( instance , injectableReference ) ; pendingInjections . add ( injectableReference ) ; return injectableReference ; }


Input: Prepares member injectors for all injected instances . This prompts Guice to do static analysis on the injected instances . [CODESPLIT] void validateOustandingInjections ( Errors errors ) { validationStarted = true ; initializablesCache . clear ( ) ; for ( InjectableReference < ? > reference : pendingInjections ) { try { reference . validate ( errors ) ; } catch ( ErrorsException e ) { errors . merge ( e . getErrors ( ) ) ; } } }


Input: Performs creation - time injections on all objects that require it . Whenever fulfilling an injection depends on another object that requires injection we inject it first . If the two instances are codependent ( directly or transitively ) ordering of injection is arbitrary . [CODESPLIT] void injectAll ( final Errors errors ) { Preconditions . checkState ( validationStarted , "Validation should be done before injection" ) ; for ( InjectableReference < ? > reference : pendingInjections ) { try { reference . get ( ) ; } catch ( InternalProvisionException ipe ) { errors . merge ( ipe ) ; } } pendingInjections . clear ( ) ; }


Input: Returns an instance of T constructed using this constructor with the supplied arguments . [CODESPLIT] public T newInstance ( Object [ ] args ) throws Throwable { constructor . setAccessible ( true ) ; try { return constructor . newInstance ( args ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } }


Input: Introspects the injector and collects all instances of bound { @code List<FilterDefinition > } into a master list . [CODESPLIT] private FilterDefinition [ ] collectFilterDefinitions ( Injector injector ) { List < FilterDefinition > filterDefinitions = Lists . newArrayList ( ) ; for ( Binding < FilterDefinition > entry : injector . findBindingsByType ( FILTER_DEFS ) ) { filterDefinitions . add ( entry . getProvider ( ) . get ( ) ) ; } // Copy to a fixed-size array for speed of iteration. return filterDefinitions . toArray ( new FilterDefinition [ filterDefinitions . size ( ) ] ) ; }


Input: Used to create an proxy that dispatches either to the guice - servlet pipeline or the regular pipeline based on uri - path match . This proxy also provides minimal forwarding support . [CODESPLIT] @ SuppressWarnings ( { "JavaDoc" , "deprecation" } ) private ServletRequest withDispatcher ( ServletRequest servletRequest , final ManagedServletPipeline servletPipeline ) { // don't wrap the request if there are no servlets mapped. This prevents us from inserting our // wrapper unless it's actually going to be used. This is necessary for compatibility for apps // that downcast their HttpServletRequests to a concrete implementation. if ( ! servletPipeline . hasServletsMapped ( ) ) { return servletRequest ; } HttpServletRequest request = ( HttpServletRequest ) servletRequest ; //noinspection OverlyComplexAnonymousInnerClass return new HttpServletRequestWrapper ( request ) { @ Override public RequestDispatcher getRequestDispatcher ( String path ) { final RequestDispatcher dispatcher = servletPipeline . getRequestDispatcher ( path ) ; return ( null != dispatcher ) ? dispatcher : super . getRequestDispatcher ( path ) ; } } ; }