Input: Checks if an array of Classes can be assigned to another array of Classes . [CODESPLIT] public static boolean isAssignable ( Class < ? > [ ] classArray , Class < ? > [ ] toClassArray , boolean autoboxing ) { if ( arrayGetLength ( classArray ) != arrayGetLength ( toClassArray ) ) { return false ; } if ( classArray == null ) { classArray = EMPTY_CLASS_ARRAY ; } if ( toClassArray == null ) { toClassArray = EMPTY_CLASS_ARRAY ; } for ( int i = 0 ; i < classArray . length ; i ++ ) { if ( isAssignable ( classArray [ i ] , toClassArray [ i ] , autoboxing ) == false ) { return false ; } } return true ; }


Input: Parses a CRON expression . [CODESPLIT] public static Date parseCRONExpression ( String cron ) { try { return new CronExpression ( cron ) . getNextValidTimeAfter ( new Date ( ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Invalid CRON pattern : " + cron , e ) ; } }


Input: Compute the number of milliseconds between the next valid date and the one after . [CODESPLIT] public static long cronInterval ( String cron , Date date ) { try { return new CronExpression ( cron ) . getNextInterval ( date ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Invalid CRON pattern : " + cron , e ) ; } }


Input: Creates WS client manually from configuration internally creating a new instance of AsyncHttpClient and managing its own thread pool . [CODESPLIT] public static AhcWSClient create ( AhcWSClientConfig config , AhcHttpCache cache , Materializer materializer ) { final StandaloneAhcWSClient client = StandaloneAhcWSClient . create ( config , cache , materializer ) ; return new AhcWSClient ( client , materializer ) ; }


Input: #inject [CODESPLIT] @ Test public void createNewRoutingDsl ( ) { play . mvc . BodyParser . Default bodyParser = app . injector ( ) . instanceOf ( play . mvc . BodyParser . Default . class ) ; JavaContextComponents javaContextComponents = app . injector ( ) . instanceOf ( JavaContextComponents . class ) ; // #new-routing-dsl RoutingDsl routingDsl = new RoutingDsl ( bodyParser , javaContextComponents ) ; // #new-routing-dsl Router router = routingDsl . GET ( "/hello/:to" ) . routingTo ( ( request , to ) -> ok ( "Hello " + to ) ) . build ( ) ; assertThat ( makeRequest ( router , "GET" , "/hello/world" ) , equalTo ( "Hello world" ) ) ; }


Input: Construct a builder to use for loading the given context . [CODESPLIT] public GuiceApplicationBuilder builder ( ApplicationLoader . Context context ) { return initialBuilder . in ( context . environment ( ) ) . loadConfig ( context . initialConfig ( ) ) . overrides ( overrides ( context ) ) ; }


Input: Identify some bindings that should be used as overrides when loading an application using this context . The default implementation of this method provides bindings that most applications should include . [CODESPLIT] protected GuiceableModule [ ] overrides ( ApplicationLoader . Context context ) { scala . collection . Seq < GuiceableModule > seq = play . api . inject . guice . GuiceApplicationLoader $ . MODULE $ . defaultOverrides ( context . asScala ( ) ) ; return Scala . asArray ( GuiceableModule . class , seq ) ; }


Input: Generates a 501 NOT_IMPLEMENTED simple result . [CODESPLIT] public static Result TODO ( Request request ) { return status ( NOT_IMPLEMENTED , views . html . defaultpages . todo . render ( request . asScala ( ) ) ) ; }


Input: Puts a new value into the current session . [CODESPLIT] @ Deprecated public static void session ( String key , String value ) { session ( ) . put ( key , value ) ; }


Input: Puts a new value into the flash scope . [CODESPLIT] @ Deprecated public static void flash ( String key , String value ) { flash ( ) . put ( key , value ) ; }


Input: #pass - arg - action - index [CODESPLIT] @ With ( PassArgAction . class ) public static Result passArgIndex ( Http . Request request ) { User user = request . attrs ( ) . get ( Attrs . USER ) ; return ok ( Json . toJson ( user ) ) ; }


Input: Qualify this binding key with the given instance of an annotation . [CODESPLIT] public < A extends Annotation > BindingKey < T > qualifiedWith ( final A instance ) { return underlying . qualifiedWith ( instance ) . asJava ( ) ; }


Input: Qualify this binding key with the given annotation . [CODESPLIT] public < A extends Annotation > BindingKey < T > qualifiedWith ( final Class < A > annotation ) { return underlying . qualifiedWith ( annotation ) . asJava ( ) ; }


Input: Bind this binding key to the given implementation class . [CODESPLIT] public Binding < T > to ( final Class < ? extends T > implementation ) { return underlying . to ( implementation ) . asJava ( ) ; }


Input: Bind this binding key to the given provider instance . [CODESPLIT] public Binding < T > to ( final Provider < ? extends T > provider ) { return underlying . to ( provider ) . asJava ( ) ; }


Input: Bind this binding key to the given instance . [CODESPLIT] public < A extends T > Binding < T > to ( final Supplier < A > instance ) { return underlying . to ( new FromJavaSupplier <> ( instance ) ) . asJava ( ) ; }


Input: Bind this binding key to another binding key . [CODESPLIT] public Binding < T > to ( final BindingKey < ? extends T > key ) { return underlying . to ( key . asScala ( ) ) . asJava ( ) ; }


Input: Bind this binding key to the given provider class . [CODESPLIT] public < P extends Provider < ? extends T > > Binding < T > toProvider ( final Class < P > provider ) { return underlying . toProvider ( provider ) . asJava ( ) ; }


Input: Returns a configured { [CODESPLIT] public static Caffeine < Object , Object > from ( Config config ) { CaffeineParser parser = new CaffeineParser ( config ) ; config . entrySet ( ) . stream ( ) . map ( Map . Entry :: getKey ) . forEach ( parser :: parse ) ; return parser . cacheBuilder ; }


Input: Create a Lang value from a code ( such as fr or en - US ) . [CODESPLIT] public static Lang forCode ( String code ) { try { return new Lang ( play . api . i18n . Lang . apply ( code ) ) ; } catch ( Exception e ) { return null ; } }


Input: Retrieve Lang availables from the application configuration . [CODESPLIT] public static List < Lang > availables ( Application app ) { play . api . i18n . Langs langs = app . injector ( ) . instanceOf ( play . api . i18n . Langs . class ) ; List < play . api . i18n . Lang > availableLangs = Scala . asJava ( langs . availables ( ) ) ; return availableLangs . stream ( ) . map ( Lang :: new ) . collect ( toList ( ) ) ; }


Input: Guess the preferred lang in the langs set passed as argument . The first Lang that matches an available Lang wins otherwise returns the first Lang available in this application . [CODESPLIT] public static Lang preferred ( Application app , List < Lang > availableLangs ) { play . api . i18n . Langs langs = app . injector ( ) . instanceOf ( play . api . i18n . Langs . class ) ; Stream < Lang > stream = availableLangs . stream ( ) ; List < play . api . i18n . Lang > langSeq = stream . map ( l -> new play . api . i18n . Lang ( l . toLocale ( ) ) ) . collect ( toList ( ) ) ; return new Lang ( langs . preferred ( Scala . toSeq ( langSeq ) ) ) ; }


Input: Create an evolutions reader that reads evolution files from a classloader . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader fromClassLoader ( ClassLoader classLoader ) { return fromClassLoader ( classLoader , "" ) ; }


Input: Create an evolutions reader that reads evolution files from a classloader . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader fromClassLoader ( ClassLoader classLoader , String prefix ) { return new play . api . db . evolutions . ClassLoaderEvolutionsReader ( classLoader , prefix ) ; }


Input: Create an evolutions reader based on a simple map of database names to evolutions . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader fromMap ( Map < String , List < Evolution > > evolutions ) { return new SimpleEvolutionsReader ( evolutions ) ; }


Input: Create an evolutions reader for the default database from a list of evolutions . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader forDefault ( Evolution ... evolutions ) { Map < String , List < Evolution > > map = new HashMap < String , List < Evolution > > ( ) ; map . put ( "default" , Arrays . asList ( evolutions ) ) ; return fromMap ( map ) ; }


Input: Apply evolutions for the given database . [CODESPLIT] public static void applyEvolutions ( Database database , play . api . db . evolutions . EvolutionsReader reader , boolean autocommit , String schema ) { DatabaseEvolutions evolutions = new DatabaseEvolutions ( database . asScala ( ) , schema ) ; evolutions . evolve ( evolutions . scripts ( reader ) , autocommit ) ; }


Input: Apply evolutions for the given database . [CODESPLIT] public static void applyEvolutions ( Database database , play . api . db . evolutions . EvolutionsReader reader , String schema ) { applyEvolutions ( database , reader , true , schema ) ; }


Input: Cleanup evolutions for the given database . [CODESPLIT] public static void cleanupEvolutions ( Database database , boolean autocommit , String schema ) { DatabaseEvolutions evolutions = new DatabaseEvolutions ( database . asScala ( ) , schema ) ; evolutions . evolve ( evolutions . resetScripts ( ) , autocommit ) ; }


Input: Set the initial configuration loader . Overrides the default or any previously configured values . [CODESPLIT] public GuiceApplicationBuilder withConfigLoader ( Function < Environment , Config > load ) { return newBuilder ( delegate . loadConfig ( func ( ( play . api . Environment env ) -> new play . api . Configuration ( load . apply ( new Environment ( env ) ) ) ) ) ) ; }


Input: Set the module loader . Overrides the default or any previously configured values . [CODESPLIT] public GuiceApplicationBuilder withModuleLoader ( BiFunction < Environment , Config , List < GuiceableModule > > loader ) { return newBuilder ( delegate . load ( func ( ( play . api . Environment env , play . api . Configuration conf ) -> Scala . toSeq ( loader . apply ( new Environment ( env ) , conf . underlying ( ) ) ) ) ) ) ; }


Input: Override the module loader with the given guiceable modules . [CODESPLIT] public GuiceApplicationBuilder load ( GuiceableModule ... modules ) { return newBuilder ( delegate . load ( Scala . varargs ( modules ) ) ) ; }


Input: Override the module loader with the given Guice modules . [CODESPLIT] public GuiceApplicationBuilder load ( com . google . inject . Module ... modules ) { return load ( Guiceable . modules ( modules ) ) ; }


Input: Override the module loader with the given Play modules . [CODESPLIT] public GuiceApplicationBuilder load ( play . api . inject . Module ... modules ) { return load ( Guiceable . modules ( modules ) ) ; }


Input: Override the module loader with the given Play bindings . [CODESPLIT] public GuiceApplicationBuilder load ( play . api . inject . Binding < ? > ... bindings ) { return load ( Guiceable . bindings ( bindings ) ) ; }


Input: Implementation of Self creation for GuiceBuilder . [CODESPLIT] protected GuiceApplicationBuilder newBuilder ( play . api . inject . guice . GuiceApplicationBuilder builder ) { return new GuiceApplicationBuilder ( builder ) ; }


Input: Encodes the specified cookie into a Cookie header value . [CODESPLIT] public String encode ( Cookie cookie ) { if ( cookie == null ) { throw new NullPointerException ( "cookie" ) ; } StringBuilder buf = new StringBuilder ( ) ; encode ( buf , cookie ) ; return stripTrailingSeparator ( buf ) ; }


Input: Encodes the specified cookies into a single Cookie header value . [CODESPLIT] public String encode ( Cookie ... cookies ) { if ( cookies == null ) { throw new NullPointerException ( "cookies" ) ; } if ( cookies . length == 0 ) { return null ; } StringBuilder buf = new StringBuilder ( ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encode ( buf , c ) ; } return stripTrailingSeparatorOrNull ( buf ) ; }


Input: Encodes the specified cookies into a single Cookie header value . [CODESPLIT] public String encode ( Iterable < ? extends Cookie > cookies ) { if ( cookies == null ) { throw new NullPointerException ( "cookies" ) ; } Iterator < ? extends Cookie > cookiesIt = cookies . iterator ( ) ; if ( ! cookiesIt . hasNext ( ) ) { return null ; } StringBuilder buf = new StringBuilder ( ) ; while ( cookiesIt . hasNext ( ) ) { Cookie c = cookiesIt . next ( ) ; if ( c == null ) { break ; } encode ( buf , c ) ; } return stripTrailingSeparatorOrNull ( buf ) ; }


Input: Get the default EntityManager for this thread . [CODESPLIT] public EntityManager em ( ) { Deque < EntityManager > ems = this . emStack ( true ) ; if ( ems . isEmpty ( ) ) { Http . Context . safeCurrent ( ) . map ( ctx -> { throw new RuntimeException ( "No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional" ) ; } ) . orElseGet ( ( ) -> { throw new RuntimeException ( "No EntityManager bound to this thread. Try wrapping this call in JPAApi.withTransaction, or ensure that the HTTP context is setup on this thread." ) ; } ) ; } return ems . peekFirst ( ) ; }


Input: Get the EntityManager stack . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public Deque < EntityManager > emStack ( boolean threadLocalFallback ) { return Http . Context . safeCurrent ( ) . map ( context -> { Object emsObject = context . args . get ( CURRENT_ENTITY_MANAGER ) ; if ( emsObject != null ) { return ( Deque < EntityManager > ) emsObject ; } else { Deque < EntityManager > ems = new ArrayDeque <> ( ) ; context . args . put ( CURRENT_ENTITY_MANAGER , ems ) ; return ems ; } } ) . orElseGet ( ( ) -> { // Not a web request if ( threadLocalFallback ) { return this . get ( ) ; } else { throw new RuntimeException ( "No Http.Context is present. If you want to invoke this method outside of a HTTP request, you need to wrap the call with JPA.withTransaction instead." ) ; } } ) ; }


Input: Pushes or pops the EntityManager stack depending on the value of the em argument . If em is null then the current EntityManager is popped . If em is non - null then em is pushed onto the stack and becomes the current EntityManager . [CODESPLIT] void pushOrPopEm ( EntityManager em , boolean threadLocalFallback ) { Deque < EntityManager > ems = this . emStack ( threadLocalFallback ) ; if ( em != null ) { ems . push ( em ) ; } else { if ( ems . isEmpty ( ) ) { throw new IllegalStateException ( "Tried to remove the EntityManager, but none was set." ) ; } ems . pop ( ) ; } }


Input: #person - class [CODESPLIT] @ Test public void fromJson ( ) { // #from-json // parse the JSON as a JsonNode JsonNode json = Json . parse ( "{\"firstName\":\"Foo\", \"lastName\":\"Bar\", \"age\":13}" ) ; // read the JsonNode as a Person Person person = Json . fromJson ( json , Person . class ) ; // #from-json assertThat ( person . firstName , equalTo ( "Foo" ) ) ; assertThat ( person . lastName , equalTo ( "Bar" ) ) ; assertThat ( person . age , equalTo ( 13 ) ) ; }


Input: #xml - hello [CODESPLIT] public Result sayHello ( Http . Request request ) { Document dom = request . body ( ) . asXml ( ) ; if ( dom == null ) { return badRequest ( "Expecting Xml data" ) ; } else { String name = XPath . selectText ( "//name" , dom ) ; if ( name == null ) { return badRequest ( "Missing parameter [name]" ) ; } else { return ok ( "Hello " + name ) ; } } }


Input: #xml - hello - bodyparser [CODESPLIT] @ BodyParser . Of ( BodyParser . Xml . class ) public Result sayHelloBP ( Http . Request request ) { Document dom = request . body ( ) . asXml ( ) ; if ( dom == null ) { return badRequest ( "Expecting Xml data" ) ; } else { String name = XPath . selectText ( "//name" , dom ) ; if ( name == null ) { return badRequest ( "Missing parameter [name]" ) ; } else { return ok ( "Hello " + name ) ; } } }


Input: Bypass the given flow using the given splitter function . [CODESPLIT] public static < In , FlowIn , Out > Flow < In , Out , ? > bypassWith ( Function < In , F . Either < FlowIn , Out > > splitter , Flow < FlowIn , Out , ? > flow ) { return bypassWith ( Flow . < In > create ( ) . map ( splitter :: apply ) , play . api . libs . streams . AkkaStreams . onlyFirstCanFinishMerge ( 2 ) , flow ) ; }


Input: Using the given splitter flow allow messages to bypass a flow . [CODESPLIT] public static < In , FlowIn , Out > Flow < In , Out , ? > bypassWith ( Flow < In , F . Either < FlowIn , Out > , ? > splitter , Graph < UniformFanInShape < Out , Out > , ? > mergeStrategy , Flow < FlowIn , Out , ? > flow ) { return splitter . via ( Flow . fromGraph ( GraphDSL . < FlowShape < F . Either < FlowIn , Out > , Out > > create ( builder -> { // Eager cancel must be true so that if the flow cancels, that will be propagated // upstream. // However, that means the bypasser must block cancel, since when this flow // finishes, the merge // will result in a cancel flowing up through the bypasser, which could lead to // dropped messages. // Using scaladsl here because of https://github.com/akka/akka/issues/18384 UniformFanOutShape < F . Either < FlowIn , Out > , F . Either < FlowIn , Out > > broadcast = builder . add ( Broadcast . create ( 2 , true ) ) ; UniformFanInShape < Out , Out > merge = builder . add ( mergeStrategy ) ; Flow < F . Either < FlowIn , Out > , FlowIn , ? > collectIn = Flow . < F . Either < FlowIn , Out > > create ( ) . collect ( Scala . partialFunction ( x -> { if ( x . left . isPresent ( ) ) { return x . left . get ( ) ; } else { throw Scala . noMatch ( ) ; } } ) ) ; Flow < F . Either < FlowIn , Out > , Out , ? > collectOut = Flow . < F . Either < FlowIn , Out > > create ( ) . collect ( Scala . partialFunction ( x -> { if ( x . right . isPresent ( ) ) { return x . right . get ( ) ; } else { throw Scala . noMatch ( ) ; } } ) ) ; Flow < F . Either < FlowIn , Out > , F . Either < FlowIn , Out > , ? > blockCancel = play . api . libs . streams . AkkaStreams . < F . Either < FlowIn , Out > > ignoreAfterCancellation ( ) . asJava ( ) ; // Normal flow builder . from ( broadcast . out ( 0 ) ) . via ( builder . add ( collectIn ) ) . via ( builder . add ( flow ) ) . toInlet ( merge . in ( 0 ) ) ; // Bypass flow, need to ignore downstream finish builder . from ( broadcast . out ( 1 ) ) . via ( builder . add ( blockCancel ) ) . via ( builder . add ( collectOut ) ) . toInlet ( merge . in ( 1 ) ) ; return new FlowShape <> ( broadcast . in ( ) , merge . out ( ) ) ; } ) ) ) ; }


Input: Create a flow that is handled by an actor . [CODESPLIT] public static < In , Out > Flow < In , Out , ? > actorRef ( Function < ActorRef , Props > props , int bufferSize , OverflowStrategy overflowStrategy , ActorRefFactory factory , Materializer mat ) { return play . api . libs . streams . ActorFlow . < In , Out > actorRef ( new AbstractFunction1 < ActorRef , Props > ( ) { @ Override public Props apply ( ActorRef v1 ) { return props . apply ( v1 ) ; } } , bufferSize , overflowStrategy , factory , mat ) . asJava ( ) ; }


Input: Binds request data to this form - that is handles form submission . [CODESPLIT] @ Deprecated public Form < T > bindFromRequest ( String ... allowedFields ) { return bind ( play . mvc . Controller . ctx ( ) . messages ( ) . lang ( ) , play . mvc . Controller . request ( ) . attrs ( ) , requestData ( play . mvc . Controller . request ( ) ) , requestFileData ( play . mvc . Controller . request ( ) ) , allowedFields ) ; }


Input: Binds request data to this form - that is handles form submission . [CODESPLIT] public Form < T > bindFromRequest ( Http . Request request , String ... allowedFields ) { return bind ( this . messagesApi . preferred ( request ) . lang ( ) , request . attrs ( ) , requestData ( request ) , requestFileData ( request ) , allowedFields ) ; }


Input: Binds request data to this form - that is handles form submission . [CODESPLIT] @ Deprecated public Form < T > bindFromRequest ( Map < String , String [ ] > requestData , String ... allowedFields ) { return bindFromRequestData ( ctxLang ( ) , ctxRequestAttrs ( ) , requestData , allowedFields ) ; }


Input: Binds request data to this form - that is handles form submission . [CODESPLIT] public Form < T > bindFromRequestData ( Lang lang , TypedMap attrs , Map < String , String [ ] > requestData , String ... allowedFields ) { return bindFromRequestData ( lang , attrs , requestData , Collections . emptyMap ( ) , allowedFields ) ; }


Input: Binds Json data to this form - that is handles form submission . [CODESPLIT] @ Deprecated public Form < T > bind ( JsonNode data , String ... allowedFields ) { return bind ( ctxLang ( ) , ctxRequestAttrs ( ) , data , allowedFields ) ; }


Input: Binds Json data to this form - that is handles form submission . [CODESPLIT] public Form < T > bind ( Lang lang , TypedMap attrs , JsonNode data , String ... allowedFields ) { return bind ( lang , attrs , play . libs . Scala . asJava ( play . api . data . FormUtils . fromJson ( "" , play . api . libs . json . Json . parse ( play . libs . Json . stringify ( data ) ) ) ) , allowedFields ) ; }


Input: When dealing with @ValidateWith or @ValidatePayloadWith annotations and message parameter is not used in the annotation extract the message from validator s getErrorMessageKey () method [CODESPLIT] protected String getMessageForConstraintViolation ( ConstraintViolation < Object > violation ) { String errorMessage = violation . getMessage ( ) ; Annotation annotation = violation . getConstraintDescriptor ( ) . getAnnotation ( ) ; if ( annotation instanceof Constraints . ValidateWith ) { Constraints . ValidateWith validateWithAnnotation = ( Constraints . ValidateWith ) annotation ; if ( violation . getMessage ( ) . equals ( Constraints . ValidateWithValidator . defaultMessage ) ) { Constraints . ValidateWithValidator validateWithValidator = new Constraints . ValidateWithValidator ( ) ; validateWithValidator . initialize ( validateWithAnnotation ) ; Tuple < String , Object [ ] > errorMessageKey = validateWithValidator . getErrorMessageKey ( ) ; if ( errorMessageKey != null && errorMessageKey . _1 != null ) { errorMessage = errorMessageKey . _1 ; } } } if ( annotation instanceof Constraints . ValidatePayloadWith ) { Constraints . ValidatePayloadWith validatePayloadWithAnnotation = ( Constraints . ValidatePayloadWith ) annotation ; if ( violation . getMessage ( ) . equals ( Constraints . ValidatePayloadWithValidator . defaultMessage ) ) { Constraints . ValidatePayloadWithValidator validatePayloadWithValidator = new Constraints . ValidatePayloadWithValidator ( ) ; validatePayloadWithValidator . initialize ( validatePayloadWithAnnotation ) ; Tuple < String , Object [ ] > errorMessageKey = validatePayloadWithValidator . getErrorMessageKey ( ) ; if ( errorMessageKey != null && errorMessageKey . _1 != null ) { errorMessage = errorMessageKey . _1 ; } } } return errorMessage ; }


Input: Binds data to this form - that is handles form submission . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Deprecated public Form < T > bind ( Map < String , String > data , String ... allowedFields ) { return bind ( ctxLang ( ) , ctxRequestAttrs ( ) , data , allowedFields ) ; }


Input: Binds data to this form - that is handles form submission . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public Form < T > bind ( Lang lang , TypedMap attrs , Map < String , String > data , String ... allowedFields ) { return bind ( lang , attrs , data , Collections . emptyMap ( ) , allowedFields ) ; }


Input: Binds data to this form - that is handles form submission . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public Form < T > bind ( Lang lang , TypedMap attrs , Map < String , String > data , Map < String , Http . MultipartFormData . FilePart < ? > > files , String ... allowedFields ) { final DataBinder dataBinder = dataBinder ( allowedFields ) ; final Map < String , Object > objectDataFinal = getObjectData ( data , files ) ; final Set < ConstraintViolation < Object > > validationErrors = runValidation ( lang , attrs , dataBinder , objectDataFinal ) ; final BindingResult result = dataBinder . getBindingResult ( ) ; validationErrors . forEach ( violation -> addConstraintViolationToBindingResult ( violation , result ) ) ; boolean hasAnyError = result . hasErrors ( ) || result . getGlobalErrorCount ( ) > 0 ; if ( hasAnyError ) { final List < ValidationError > errors = getFieldErrorsAsValidationErrors ( lang , result ) ; final List < ValidationError > globalErrors = globalErrorsAsValidationErrors ( result ) ; errors . addAll ( globalErrors ) ; return new Form <> ( rootName , backedType , data , files , errors , Optional . ofNullable ( ( T ) result . getTarget ( ) ) , groups , messagesApi , formatters , this . validatorFactory , config , lang , directFieldAccess ) ; } return new Form <> ( rootName , backedType , data , files , errors , Optional . ofNullable ( ( T ) result . getTarget ( ) ) , groups , messagesApi , formatters , this . validatorFactory , config , lang , directFieldAccess ) ; }


Input: Convert the error arguments . [CODESPLIT] private List < Object > convertErrorArguments ( Object [ ] arguments ) { if ( arguments == null ) { return Collections . emptyList ( ) ; } List < Object > converted = Arrays . stream ( arguments ) . filter ( arg -> ! ( arg instanceof org . springframework . context . support . DefaultMessageSourceResolvable ) ) . collect ( Collectors . toList ( ) ) ; return Collections . unmodifiableList ( converted ) ; }


Input: Populates this form with an existing value used for edit forms . [CODESPLIT] public Form < T > fill ( T value ) { if ( value == null ) { throw new RuntimeException ( "Cannot fill a form with a null value" ) ; } return new Form <> ( rootName , backedType , new HashMap <> ( ) , new HashMap <> ( ) , new ArrayList <> ( ) , Optional . ofNullable ( value ) , groups , messagesApi , formatters , validatorFactory , config , lang , directFieldAccess ) ; }


Input: Retrieve all global errors - errors without a key . [CODESPLIT] public List < ValidationError > globalErrors ( ) { return Collections . unmodifiableList ( errors . stream ( ) . filter ( error -> error . key ( ) . isEmpty ( ) ) . collect ( Collectors . toList ( ) ) ) ; }


Input: Returns the form errors serialized as Json using the given Lang . [CODESPLIT] public JsonNode errorsAsJson ( Lang lang ) { Map < String , List < String > > allMessages = new HashMap <> ( ) ; errors . forEach ( error -> { if ( error != null ) { final List < String > messages = new ArrayList <> ( ) ; if ( messagesApi != null && lang != null ) { final List < String > reversedMessages = new ArrayList <> ( error . messages ( ) ) ; Collections . reverse ( reversedMessages ) ; messages . add ( messagesApi . get ( lang , reversedMessages , translateMsgArg ( error . arguments ( ) , messagesApi , lang ) ) ) ; } else { messages . add ( error . message ( ) ) ; } allMessages . put ( error . key ( ) , messages ) ; } } ) ; return play . libs . Json . toJson ( allMessages ) ; }


Input: Gets the concrete value only if the submission was a success . If the form is invalid because of validation errors this method will throw an exception . If you want to retrieve the value even when the form is invalid use { @link #value () } instead . [CODESPLIT] public T get ( Lang lang ) { if ( ! errors . isEmpty ( ) ) { throw new IllegalStateException ( "Error(s) binding form: " + errorsAsJson ( lang ) ) ; } return value . get ( ) ; }


Input: Retrieves a field . [CODESPLIT] public Field field ( final String key , final Lang lang ) { // Value String fieldValue = null ; Http . MultipartFormData . FilePart file = null ; if ( rawData . containsKey ( key ) ) { fieldValue = rawData . get ( key ) ; } else if ( files . containsKey ( key ) ) { file = files . get ( key ) ; } else { if ( value . isPresent ( ) ) { BeanWrapper beanWrapper = new BeanWrapperImpl ( value . get ( ) ) ; beanWrapper . setAutoGrowNestedPaths ( true ) ; String objectKey = key ; if ( rootName != null && key . startsWith ( rootName + "." ) ) { objectKey = key . substring ( rootName . length ( ) + 1 ) ; } if ( beanWrapper . isReadableProperty ( objectKey ) ) { Object oValue = beanWrapper . getPropertyValue ( objectKey ) ; if ( oValue != null ) { if ( oValue instanceof Http . MultipartFormData . FilePart < ? > ) { file = ( Http . MultipartFormData . FilePart < ? > ) oValue ; } else { if ( formatters != null ) { final String objectKeyFinal = objectKey ; fieldValue = withRequestLocale ( lang , ( ) -> formatters . print ( beanWrapper . getPropertyTypeDescriptor ( objectKeyFinal ) , oValue ) ) ; } else { fieldValue = oValue . toString ( ) ; } } } } } } // Format Tuple < String , List < Object > > format = null ; BeanWrapper beanWrapper = new BeanWrapperImpl ( blankInstance ( ) ) ; beanWrapper . setAutoGrowNestedPaths ( true ) ; try { for ( Annotation a : beanWrapper . getPropertyTypeDescriptor ( key ) . getAnnotations ( ) ) { Class < ? > annotationType = a . annotationType ( ) ; if ( annotationType . isAnnotationPresent ( play . data . Form . Display . class ) ) { play . data . Form . Display d = annotationType . getAnnotation ( play . data . Form . Display . class ) ; if ( d . name ( ) . startsWith ( "format." ) ) { List < Object > attributes = new ArrayList <> ( ) ; for ( String attr : d . attributes ( ) ) { Object attrValue = null ; try { attrValue = a . getClass ( ) . getDeclaredMethod ( attr ) . invoke ( a ) ; } catch ( Exception e ) { // do nothing } attributes . add ( attrValue ) ; } format = Tuple ( d . name ( ) , Collections . unmodifiableList ( attributes ) ) ; } } } } catch ( NullPointerException e ) { // do nothing } // Constraints List < Tuple < String , List < Object > > > constraints = new ArrayList <> ( ) ; Class < ? > classType = backedType ; String leafKey = key ; if ( rootName != null && leafKey . startsWith ( rootName + "." ) ) { leafKey = leafKey . substring ( rootName . length ( ) + 1 ) ; } int p = leafKey . lastIndexOf ( ' ' ) ; if ( p > 0 ) { classType = beanWrapper . getPropertyType ( leafKey . substring ( 0 , p ) ) ; leafKey = leafKey . substring ( p + 1 ) ; } if ( classType != null && this . validatorFactory != null ) { BeanDescriptor beanDescriptor = this . validatorFactory . getValidator ( ) . getConstraintsForClass ( classType ) ; if ( beanDescriptor != null ) { PropertyDescriptor property = beanDescriptor . getConstraintsForProperty ( leafKey ) ; if ( property != null ) { Annotation [ ] orderedAnnotations = null ; for ( Class < ? > c = classType ; c != null ; c = c . getSuperclass ( ) ) { // we also check the fields of all superclasses java . lang . reflect . Field field = null ; try { field = c . getDeclaredField ( leafKey ) ; } catch ( NoSuchFieldException | SecurityException e ) { continue ; } // getDeclaredAnnotations also looks for private fields; also it provides the // annotations in a guaranteed order orderedAnnotations = AnnotationUtils . unwrapContainerAnnotations ( field . getDeclaredAnnotations ( ) ) ; break ; } constraints = Constraints . displayableConstraint ( property . findConstraints ( ) . unorderedAndMatchingGroups ( groups != null ? groups : new Class [ ] { Default . class } ) . getConstraintDescriptors ( ) , orderedAnnotations ) ; } } } return new Field ( this , key , constraints , format , errors ( key ) , fieldValue , file ) ; }


Input: A copy of this form with the given lang set which is used for formatting when retrieving a field ( via { [CODESPLIT] public Form < T > withLang ( Lang lang ) { return new Form < T > ( this . rootName , this . backedType , this . rawData , this . files , this . errors , this . value , this . groups , this . messagesApi , this . formatters , this . validatorFactory , this . config , lang , this . directFieldAccess ) ; }


Input: Sets the locale of the current request ( if there is one ) into Spring s LocaleContextHolder . [CODESPLIT] private static < T > T withRequestLocale ( Lang lang , Supplier < T > code ) { try { LocaleContextHolder . setLocale ( lang != null ? lang . toLocale ( ) : null ) ; } catch ( Exception e ) { // Just continue (Maybe there is no context or some internal error in LocaleContextHolder). // System default locale will be used. } try { return code . get ( ) ; } finally { LocaleContextHolder . resetLocaleContext ( ) ; // Clean up ThreadLocal } }


Input: Gets the concrete value only if the submission was a success . If the form is invalid because of validation errors or you try to access a file field this method will return null . If you want to retrieve the value even when the form is invalid use { @link #value ( String ) } instead . If you want to retrieve a file field use { @link #file ( String ) } instead . [CODESPLIT] public String get ( String key ) { try { return ( String ) get ( ) . getData ( ) . get ( asNormalKey ( key ) ) ; } catch ( Exception e ) { return null ; } }


Input: Gets the concrete value only if the submission was a success . If the form is invalid because of validation errors or you try to access a non - file field this method will return null . If you want to retrieve the value even when the form is invalid use { @link #value ( String ) } instead . If you want to retrieve a non - file field use { @link #get ( String ) } instead . [CODESPLIT] public < A > Http . MultipartFormData . FilePart < A > file ( String key ) { try { return ( Http . MultipartFormData . FilePart < A > ) get ( ) . getData ( ) . get ( asNormalKey ( key ) ) ; } catch ( Exception e ) { return null ; } }


Input: Gets the concrete value [CODESPLIT] public Optional < Object > value ( String key ) { return super . value ( ) . map ( v -> v . getData ( ) . get ( asNormalKey ( key ) ) ) ; }


Input: Fills the form with existing data . [CODESPLIT] public DynamicForm fill ( Map < String , Object > value ) { Form < Dynamic > form = super . fill ( new Dynamic ( value ) ) ; return new DynamicForm ( form . rawData ( ) , form . files ( ) , form . errors ( ) , form . value ( ) , messagesApi , formatters , validatorFactory , config , lang ( ) . orElse ( null ) ) ; }


Input: -- tools [CODESPLIT] static String asDynamicKey ( String key ) { if ( key . isEmpty ( ) || MATCHES_DATA . matcher ( key ) . matches ( ) ) { return key ; } else { return "data[" + key + "]" ; } }


Input: Parses this string as instance of the given class . [CODESPLIT] public < T > T parse ( String text , Class < T > clazz ) { return conversion . convert ( text , clazz ) ; }


Input: Parses this string as instance of a specific field [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < T > T parse ( Field field , String text ) { return ( T ) conversion . convert ( text , new TypeDescriptor ( field ) ) ; }


Input: Computes the display string for any value . [CODESPLIT] public < T > String print ( T t ) { if ( t == null ) { return "" ; } if ( conversion . canConvert ( t . getClass ( ) , String . class ) ) { return conversion . convert ( t , String . class ) ; } else { return t . toString ( ) ; } }


Input: Computes the display string for any value for a specific field . [CODESPLIT] public < T > String print ( Field field , T t ) { return print ( new TypeDescriptor ( field ) , t ) ; }


Input: Computes the display string for any value for a specific type . [CODESPLIT] public < T > String print ( TypeDescriptor desc , T t ) { if ( t == null ) { return "" ; } if ( desc != null && conversion . canConvert ( desc , TypeDescriptor . valueOf ( String . class ) ) ) { return ( String ) conversion . convert ( t , desc , TypeDescriptor . valueOf ( String . class ) ) ; } else if ( conversion . canConvert ( t . getClass ( ) , String . class ) ) { return conversion . convert ( t , String . class ) ; } else { return t . toString ( ) ; } }


Input: Converter for String - > Optional and Optional - > String [CODESPLIT] private Formatters registerOptional ( ) { conversion . addConverter ( new GenericConverter ( ) { public Object convert ( Object source , TypeDescriptor sourceType , TypeDescriptor targetType ) { if ( sourceType . getObjectType ( ) . equals ( String . class ) ) { // From String to Optional Object element = conversion . convert ( source , sourceType , targetType . elementTypeDescriptor ( source ) ) ; return Optional . ofNullable ( element ) ; } else if ( targetType . getObjectType ( ) . equals ( String . class ) ) { // From Optional to String if ( source == null ) return "" ; Optional < ? > opt = ( Optional ) source ; return opt . map ( o -> conversion . convert ( source , sourceType . getElementTypeDescriptor ( ) , targetType ) ) . orElse ( "" ) ; } return null ; } public Set < GenericConverter . ConvertiblePair > getConvertibleTypes ( ) { Set < ConvertiblePair > result = new HashSet <> ( ) ; result . add ( new ConvertiblePair ( Optional . class , String . class ) ) ; result . add ( new ConvertiblePair ( String . class , Optional . class ) ) ; return result ; } } ) ; return this ; }


Input: Registers a simple formatter . [CODESPLIT] public < T > Formatters register ( final Class < T > clazz , final SimpleFormatter < T > formatter ) { conversion . addFormatterForFieldType ( clazz , new org . springframework . format . Formatter < T > ( ) { public T parse ( String text , Locale locale ) throws java . text . ParseException { return formatter . parse ( text , locale ) ; } public String print ( T t , Locale locale ) { return formatter . print ( t , locale ) ; } public String toString ( ) { return formatter . toString ( ) ; } } ) ; return this ; }


Input: Registers an annotation - based formatter . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < A extends Annotation , T > Formatters register ( final Class < T > clazz , final AnnotationFormatter < A , T > formatter ) { final Class < ? extends Annotation > annotationType = ( Class < ? extends Annotation > ) GenericTypeResolver . resolveTypeArguments ( formatter . getClass ( ) , AnnotationFormatter . class ) [ 0 ] ; conversion . addConverter ( new ConditionalGenericConverter ( ) { public Set < GenericConverter . ConvertiblePair > getConvertibleTypes ( ) { Set < GenericConverter . ConvertiblePair > types = new HashSet <> ( ) ; types . add ( new GenericConverter . ConvertiblePair ( clazz , String . class ) ) ; return types ; } public boolean matches ( TypeDescriptor sourceType , TypeDescriptor targetType ) { return ( sourceType . getAnnotation ( annotationType ) != null ) ; } public Object convert ( Object source , TypeDescriptor sourceType , TypeDescriptor targetType ) { final A a = ( A ) sourceType . getAnnotation ( annotationType ) ; Locale locale = LocaleContextHolder . getLocale ( ) ; try { return formatter . print ( a , ( T ) source , locale ) ; } catch ( Exception ex ) { throw new ConversionFailedException ( sourceType , targetType , source , ex ) ; } } public String toString ( ) { return "@" + annotationType . getName ( ) + " " + clazz . getName ( ) + " -> " + String . class . getName ( ) + ": " + formatter ; } } ) ; conversion . addConverter ( new ConditionalGenericConverter ( ) { public Set < GenericConverter . ConvertiblePair > getConvertibleTypes ( ) { Set < GenericConverter . ConvertiblePair > types = new HashSet <> ( ) ; types . add ( new GenericConverter . ConvertiblePair ( String . class , clazz ) ) ; return types ; } public boolean matches ( TypeDescriptor sourceType , TypeDescriptor targetType ) { return ( targetType . getAnnotation ( annotationType ) != null ) ; } public Object convert ( Object source , TypeDescriptor sourceType , TypeDescriptor targetType ) { final A a = ( A ) targetType . getAnnotation ( annotationType ) ; Locale locale = LocaleContextHolder . getLocale ( ) ; try { return formatter . parse ( a , ( String ) source , locale ) ; } catch ( Exception ex ) { throw new ConversionFailedException ( sourceType , targetType , source , ex ) ; } } public String toString ( ) { return String . class . getName ( ) + " -> @" + annotationType . getName ( ) + " " + clazz . getName ( ) + ": " + formatter ; } } ) ; return this ; }


Input: Encodes the specified cookie into a Set - Cookie header value . [CODESPLIT] public String encode ( Cookie cookie ) { if ( cookie == null ) { throw new NullPointerException ( "cookie" ) ; } final String name = cookie . name ( ) ; final String value = cookie . value ( ) != null ? cookie . value ( ) : "" ; validateCookie ( name , value ) ; StringBuilder buf = new StringBuilder ( ) ; if ( cookie . wrap ( ) ) { addQuoted ( buf , name , value ) ; } else { add ( buf , name , value ) ; } if ( cookie . maxAge ( ) != Integer . MIN_VALUE ) { add ( buf , CookieHeaderNames . MAX_AGE , cookie . maxAge ( ) ) ; Date expires = cookie . maxAge ( ) <= 0 ? new Date ( 0 ) // Set expires to the Unix epoch : new Date ( cookie . maxAge ( ) * 1000L + System . currentTimeMillis ( ) ) ; add ( buf , CookieHeaderNames . EXPIRES , HttpHeaderDateFormat . get ( ) . format ( expires ) ) ; } if ( cookie . sameSite ( ) != null ) { add ( buf , CookieHeaderNames . SAMESITE , cookie . sameSite ( ) ) ; } if ( cookie . path ( ) != null ) { add ( buf , CookieHeaderNames . PATH , cookie . path ( ) ) ; } if ( cookie . domain ( ) != null ) { add ( buf , CookieHeaderNames . DOMAIN , cookie . domain ( ) ) ; } if ( cookie . isSecure ( ) ) { add ( buf , CookieHeaderNames . SECURE ) ; } if ( cookie . isHttpOnly ( ) ) { add ( buf , CookieHeaderNames . HTTPONLY ) ; } return stripTrailingSeparator ( buf ) ; }


Input: Batch encodes cookies into Set - Cookie header values . [CODESPLIT] public List < String > encode ( Cookie ... cookies ) { if ( cookies == null ) { throw new NullPointerException ( "cookies" ) ; } if ( cookies . length == 0 ) { return Collections . emptyList ( ) ; } List < String > encoded = new ArrayList < String > ( cookies . length ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encoded . add ( encode ( c ) ) ; } return encoded ; }


Input: Batch encodes cookies into Set - Cookie header values . [CODESPLIT] public List < String > encode ( Collection < ? extends Cookie > cookies ) { if ( cookies == null ) { throw new NullPointerException ( "cookies" ) ; } if ( cookies . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < String > encoded = new ArrayList < String > ( cookies . size ( ) ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encoded . add ( encode ( c ) ) ; } return encoded ; }


Input: Batch encodes cookies into Set - Cookie header values . [CODESPLIT] public List < String > encode ( Iterable < ? extends Cookie > cookies ) { if ( cookies == null ) { throw new NullPointerException ( "cookies" ) ; } if ( cookies . iterator ( ) . hasNext ( ) ) { return Collections . emptyList ( ) ; } List < String > encoded = new ArrayList < String > ( ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encoded . add ( encode ( c ) ) ; } return encoded ; }


Input: Decodes the specified Set - Cookie HTTP header value into a { @link Cookie } . [CODESPLIT] public Set < Cookie > decode ( String header ) { if ( header == null ) { throw new NullPointerException ( "header" ) ; } final int headerLen = header . length ( ) ; if ( headerLen == 0 ) { return Collections . emptySet ( ) ; } Set < Cookie > cookies = new TreeSet < Cookie > ( ) ; int i = 0 ; boolean rfc2965Style = false ; if ( header . regionMatches ( true , 0 , RFC2965_VERSION , 0 , RFC2965_VERSION . length ( ) ) ) { // RFC 2965 style cookie, move to after version value i = header . indexOf ( ' ' ) + 1 ; rfc2965Style = true ; } loop : for ( ; ; ) { // Skip spaces and separators. for ( ; ; ) { if ( i == headerLen ) { break loop ; } char c = header . charAt ( i ) ; if ( c == ' ' || c == ' ' || c == 0x0b || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' ) { i ++ ; continue ; } break ; } int nameBegin = i ; int nameEnd = i ; int valueBegin = - 1 ; int valueEnd = - 1 ; if ( i != headerLen ) { keyValLoop : for ( ; ; ) { char curChar = header . charAt ( i ) ; if ( curChar == ' ' ) { // NAME; (no value till ';') nameEnd = i ; valueBegin = valueEnd = - 1 ; break keyValLoop ; } else if ( curChar == ' ' ) { // NAME=VALUE nameEnd = i ; i ++ ; if ( i == headerLen ) { // NAME= (empty value, i.e. nothing after '=') valueBegin = valueEnd = 0 ; break keyValLoop ; } valueBegin = i ; // NAME=VALUE; int semiPos = header . indexOf ( ' ' , i ) ; valueEnd = i = semiPos > 0 ? semiPos : headerLen ; break keyValLoop ; } else { i ++ ; } if ( i == headerLen ) { // NAME (no value till the end of string) nameEnd = headerLen ; valueBegin = valueEnd = - 1 ; break ; } } } if ( rfc2965Style && ( header . regionMatches ( nameBegin , RFC2965_PATH , 0 , RFC2965_PATH . length ( ) ) || header . regionMatches ( nameBegin , RFC2965_DOMAIN , 0 , RFC2965_DOMAIN . length ( ) ) || header . regionMatches ( nameBegin , RFC2965_PORT , 0 , RFC2965_PORT . length ( ) ) ) ) { // skip obsolete RFC2965 fields continue ; } DefaultCookie cookie = initCookie ( header , nameBegin , nameEnd , valueBegin , valueEnd ) ; if ( cookie != null ) { cookies . add ( cookie ) ; } } return cookies ; }


Input: Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofStream ( Http . Request request , InputStream stream ) { return JavaRangeResult . ofStream ( stream , rangeHeader ( request ) , null , Optional . empty ( ) ) ; }


Input: Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofStream ( InputStream stream , long contentLength ) { return ofStream ( Http . Context . current ( ) . request ( ) , stream , contentLength ) ; }


Input: Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofPath ( Http . Request request , Path path ) { return ofPath ( request , path , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }


Input: Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofPath ( Http . Request request , Path path , FileMimeTypes fileMimeTypes ) { return JavaRangeResult . ofPath ( path , rangeHeader ( request ) , fileMimeTypes . forFileName ( path . toFile ( ) . getName ( ) ) ) ; }


Input: Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofPath ( Path path , String fileName ) { return ofPath ( Http . Context . current ( ) . request ( ) , path , fileName ) ; }


Input: Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofPath ( Http . Request request , Path path , String fileName , FileMimeTypes fileMimeTypes ) { return JavaRangeResult . ofPath ( path , rangeHeader ( request ) , fileName , fileMimeTypes . forFileName ( fileName ) ) ; }


Input: Returns the file as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofFile ( File file , String fileName ) { return ofFile ( Http . Context . current ( ) . request ( ) , file , fileName ) ; }


Input: Returns the file as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofFile ( Http . Request request , File file , String fileName ) { return ofFile ( request , file , fileName , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }


Input: Returns the file as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofFile ( Http . Request request , File file , String fileName , FileMimeTypes fileMimeTypes ) { return JavaRangeResult . ofFile ( file , rangeHeader ( request ) , fileName , fileMimeTypes . forFileName ( fileName ) ) ; }


Input: Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofSource ( Long entityLength , Source < ByteString , ? > source , String fileName , String contentType ) { return ofSource ( Http . Context . current ( ) . request ( ) , entityLength , source , fileName , contentType ) ; }


Input: Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofSource ( Http . Request request , Long entityLength , Source < ByteString , ? > source , String fileName , String contentType ) { return JavaRangeResult . ofSource ( entityLength , source , rangeHeader ( request ) , Optional . ofNullable ( fileName ) , Optional . ofNullable ( contentType ) ) ; }


Input: Select all nodes that are selected by this XPath expression . If multiple nodes match multiple nodes will be returned . Nodes will be returned in document - order [CODESPLIT] public static NodeList selectNodes ( String path , Object node ) { return selectNodes ( path , node , null ) ; }


Input: Converts a Java List to Scala Seq . [CODESPLIT] public static < T > scala . collection . immutable . Seq < T > toSeq ( java . util . List < T > list ) { return scala . collection . JavaConverters . asScalaBufferConverter ( list ) . asScala ( ) . toList ( ) ; }


Input: Converts a Java Array to Scala Seq . [CODESPLIT] public static < T > scala . collection . immutable . Seq < T > toSeq ( T [ ] array ) { return toSeq ( java . util . Arrays . asList ( array ) ) ; }


Input: Converts a Java varargs to Scala varargs . [CODESPLIT] @ SafeVarargs public static < T > scala . collection . immutable . Seq < T > varargs ( T ... array ) { return toSeq ( array ) ; }


Input: Acceptor for JSON WebSockets . [CODESPLIT] public static < In , Out > MappedWebSocketAcceptor < In , Out > json ( Class < In > in ) { return new MappedWebSocketAcceptor <> ( Scala . partialFunction ( message -> { try { if ( message instanceof Message . Binary ) { return F . Either . Left ( play . libs . Json . mapper ( ) . readValue ( ( ( Message . Binary ) message ) . data ( ) . iterator ( ) . asInputStream ( ) , in ) ) ; } else if ( message instanceof Message . Text ) { return F . Either . Left ( play . libs . Json . mapper ( ) . readValue ( ( ( Message . Text ) message ) . data ( ) , in ) ) ; } } catch ( Exception e ) { return F . Either . Right ( new Message . Close ( CloseCodes . Unacceptable ( ) , e . getMessage ( ) ) ) ; } throw Scala . noMatch ( ) ; } ) , outMessage -> { try { return new Message . Text ( play . libs . Json . mapper ( ) . writeValueAsString ( outMessage ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } ) ; }


Input: Helper to create handlers for WebSockets . [CODESPLIT] private static < In , Out > WebSocket acceptOrResult ( PartialFunction < Message , F . Either < In , Message > > inMapper , Function < Http . RequestHeader , CompletionStage < F . Either < Result , Flow < In , Out , ? > > > > f , Function < Out , Message > outMapper ) { return new WebSocket ( ) { @ Override public CompletionStage < F . Either < Result , Flow < Message , Message , ? > > > apply ( Http . RequestHeader request ) { return f . apply ( request ) . thenApply ( resultOrFlow -> { if ( resultOrFlow . left . isPresent ( ) ) { return F . Either . Left ( resultOrFlow . left . get ( ) ) ; } else { Flow < Message , Message , ? > flow = AkkaStreams . bypassWith ( Flow . < Message > create ( ) . collect ( inMapper ) , play . api . libs . streams . AkkaStreams . onlyFirstCanFinishMerge ( 2 ) , resultOrFlow . right . get ( ) . map ( outMapper :: apply ) ) ; return F . Either . Right ( flow ) ; } } ) ; } } ; }


Input: Returns whether a { @link Member } is accessible . [CODESPLIT] static boolean isAccessible ( final Member m ) { return m != null && Modifier . isPublic ( m . getModifiers ( ) ) && ! m . isSynthetic ( ) ; }


Input: XXX Default access superclass workaround . [CODESPLIT] static boolean setAccessibleWorkaround ( final AccessibleObject o ) { if ( o == null || o . isAccessible ( ) ) { return false ; } final Member m = ( Member ) o ; if ( ! o . isAccessible ( ) && Modifier . isPublic ( m . getModifiers ( ) ) && isPackageAccess ( m . getDeclaringClass ( ) . getModifiers ( ) ) ) { try { o . setAccessible ( true ) ; return true ; } catch ( final SecurityException e ) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false ; }


Input: Compares the relative fitness of two Constructors in terms of how well they match a set of runtime parameter types such that a list ordered by the results of the comparison would return the best match first ( least ) . [CODESPLIT] static int compareConstructorFit ( final Constructor < ? > left , final Constructor < ? > right , final Class < ? > [ ] actual ) { return compareParameterTypes ( Executable . of ( left ) , Executable . of ( right ) , actual ) ; }


Input: Compares the relative fitness of two Methods in terms of how well they match a set of runtime parameter types such that a list ordered by the results of the comparison would return the best match first ( least ) . [CODESPLIT] static int compareMethodFit ( final Method left , final Method right , final Class < ? > [ ] actual ) { return compareParameterTypes ( Executable . of ( left ) , Executable . of ( right ) , actual ) ; }


Input: Compares the relative fitness of two Executables in terms of how well they match a set of runtime parameter types such that a list ordered by the results of the comparison would return the best match first ( least ) . [CODESPLIT] private static int compareParameterTypes ( final Executable left , final Executable right , final Class < ? > [ ] actual ) { final float leftCost = getTotalTransformationCost ( actual , left ) ; final float rightCost = getTotalTransformationCost ( actual , right ) ; return leftCost < rightCost ? - 1 : rightCost < leftCost ? 1 : 0 ; }


Input: Gets the number of steps required to promote a primitive number to another type . [CODESPLIT] private static float getPrimitivePromotionCost ( final Class < ? > srcClass , final Class < ? > destClass ) { float cost = 0.0f ; Class < ? > cls = srcClass ; if ( ! cls . isPrimitive ( ) ) { // slight unwrapping penalty cost += 0.1f ; cls = ClassUtils . wrapperToPrimitive ( cls ) ; } for ( int i = 0 ; cls != destClass && i < ORDERED_PRIMITIVE_TYPES . length ; i ++ ) { if ( cls == ORDERED_PRIMITIVE_TYPES [ i ] ) { cost += 0.1f ; if ( i < ORDERED_PRIMITIVE_TYPES . length - 1 ) { cls = ORDERED_PRIMITIVE_TYPES [ i + 1 ] ; } } } return cost ; }


Input: Returns the sum of the object transformation cost for each class in the source argument list . [CODESPLIT] private static float getTotalTransformationCost ( final Class < ? > [ ] srcArgs , final Executable executable ) { final Class < ? > [ ] destArgs = executable . getParameterTypes ( ) ; final boolean isVarArgs = executable . isVarArgs ( ) ; // "source" and "destination" are the actual and declared args respectively. float totalCost = 0.0f ; final long normalArgsLen = isVarArgs ? destArgs . length - 1 : destArgs . length ; if ( srcArgs . length < normalArgsLen ) { return Float . MAX_VALUE ; } for ( int i = 0 ; i < normalArgsLen ; i ++ ) { totalCost += getObjectTransformationCost ( srcArgs [ i ] , destArgs [ i ] ) ; } if ( isVarArgs ) { // When isVarArgs is true, srcArgs and dstArgs may differ in length. // There are two special cases to consider: final boolean noVarArgsPassed = srcArgs . length < destArgs . length ; final boolean explicitArrayForVarags = srcArgs . length == destArgs . length && srcArgs [ srcArgs . length - 1 ] . isArray ( ) ; final float varArgsCost = 0.001f ; final Class < ? > destClass = destArgs [ destArgs . length - 1 ] . getComponentType ( ) ; if ( noVarArgsPassed ) { // When no varargs passed, the best match is the most generic matching type, not the most // specific. totalCost += getObjectTransformationCost ( destClass , Object . class ) + varArgsCost ; } else if ( explicitArrayForVarags ) { final Class < ? > sourceClass = srcArgs [ srcArgs . length - 1 ] . getComponentType ( ) ; totalCost += getObjectTransformationCost ( sourceClass , destClass ) + varArgsCost ; } else { // This is typical varargs case. for ( int i = destArgs . length - 1 ; i < srcArgs . length ; i ++ ) { final Class < ? > srcClass = srcArgs [ i ] ; totalCost += getObjectTransformationCost ( srcClass , destClass ) + varArgsCost ; } } } return totalCost ; }


Input:
Gets the number of steps required needed to turn the source class into the destination class . This represents the number of steps in the object hierarchy graph . [CODESPLIT] private static float getObjectTransformationCost ( Class < ? > srcClass , final Class < ? > destClass ) { if ( destClass . isPrimitive ( ) ) { return getPrimitivePromotionCost ( srcClass , destClass ) ; } float cost = 0.0f ; while ( srcClass != null && ! destClass . equals ( srcClass ) ) { if ( destClass . isInterface ( ) && ClassUtils . isAssignable ( srcClass , destClass ) ) { // slight penalty for interface match. // we still want an exact match to override an interface match, // but // an interface match should override anything where we have to // get a superclass. cost += 0.25f ; break ; } cost ++ ; srcClass = srcClass . getSuperclass ( ) ; } /*
     * If the destination class is null, we've traveled all the way up to
     * an Object match. We'll penalize this by adding 1.5 to the cost.
     */ if ( srcClass == null ) { cost += 1.5f ; } return cost ; }


Input: #explicit - messages - api [CODESPLIT] private MessagesApi explicitMessagesApi ( ) { return new play . i18n . MessagesApi ( new play . api . i18n . DefaultMessagesApi ( Collections . singletonMap ( Lang . defaultLang ( ) . code ( ) , Collections . singletonMap ( "foo" , "bar" ) ) , new play . api . i18n . DefaultLangs ( ) . asJava ( ) ) ) ; }


Input: Get the message at the given key . [CODESPLIT] public String at ( String key , Object ... args ) { return messagesApi . get ( lang , key , args ) ; }


Input: Get the message at the first defined key . [CODESPLIT] public String at ( List < String > keys , Object ... args ) { return messagesApi . get ( lang , keys , args ) ; }


Input: Create a pooled database with the given configuration . [CODESPLIT] public static Database createFrom ( String name , String driver , String url , Map < String , ? extends Object > config ) { ImmutableMap . Builder < String , Object > dbConfig = new ImmutableMap . Builder < String , Object > ( ) ; dbConfig . put ( "driver" , driver ) ; dbConfig . put ( "url" , url ) ; dbConfig . putAll ( config ) ; return new DefaultDatabase ( name , dbConfig . build ( ) ) ; }


Input: Create a pooled database with the given configuration . [CODESPLIT] public static Database createFrom ( String name , String driver , String url ) { return createFrom ( name , driver , url , ImmutableMap . < String , Object > of ( ) ) ; }


Input: Create a pooled database named default with the given configuration . [CODESPLIT] public static Database createFrom ( String driver , String url , Map < String , ? extends Object > config ) { return createFrom ( "default" , driver , url , config ) ; }


Input: Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name , String url , Map < String , ? extends Object > config ) { return createFrom ( name , "org.h2.Driver" , url , config ) ; }


Input: Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name , Map < String , String > urlOptions , Map < String , ? extends Object > config ) { StringBuilder urlExtra = new StringBuilder ( ) ; for ( Map . Entry < String , String > option : urlOptions . entrySet ( ) ) { urlExtra . append ( ' ' ) . append ( option . getKey ( ) ) . append ( ' ' ) . append ( option . getValue ( ) ) ; } String url = "jdbc:h2:mem:" + name + urlExtra ; return inMemory ( name , url , config ) ; }


Input: Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name , Map < String , ? extends Object > config ) { return inMemory ( name , "jdbc:h2:mem:" + name , config ) ; }


Input: Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name ) { return inMemory ( name , ImmutableMap . < String , Object > of ( ) ) ; }


Input: Create an in - memory H2 database with name default and with extra configuration provided by the given entries . [CODESPLIT] public static Database inMemoryWith ( String k1 , Object v1 ) { return inMemory ( ImmutableMap . of ( k1 , v1 ) ) ; }


Input: Create an in - memory H2 database with name default and with extra configuration provided by the given entries . [CODESPLIT] public static Database inMemoryWith ( String k1 , Object v1 , String k2 , Object v2 , String k3 , Object v3 ) { return inMemory ( ImmutableMap . of ( k1 , v1 , k2 , v2 , k3 , v3 ) ) ; }


Input: Helper method to create a new <code > BeanMap< / code > . For finer control over the generated instance use a new instance of <code > BeanMap . Generator< / code > instead of this static method . [CODESPLIT] public static BeanMap create ( Object bean ) { Generator gen = new Generator ( ) ; gen . setBean ( bean ) ; return gen . create ( ) ; }


Input: TODO : optimize [CODESPLIT] public Set entrySet ( ) { HashMap copy = new HashMap ( ) ; for ( Iterator it = keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Object key = it . next ( ) ; copy . put ( key , get ( key ) ) ; } return Collections . unmodifiableMap ( copy ) . entrySet ( ) ; }


Input: Create a new ParallelSorter object for a set of arrays . You may sort the arrays multiple times via the same ParallelSorter object . [CODESPLIT] public static ParallelSorter create ( Object [ ] arrays ) { Generator gen = new Generator ( ) ; gen . setArrays ( arrays ) ; return gen . create ( ) ; }


Input: Sort the arrays using the quicksort algorithm . [CODESPLIT] public void quickSort ( int index , int lo , int hi , Comparator cmp ) { chooseComparer ( index , cmp ) ; super . quickSort ( lo , hi - 1 ) ; }


Input: Sort the arrays using an in - place merge sort . [CODESPLIT] public void mergeSort ( int index , int lo , int hi , Comparator cmp ) { chooseComparer ( index , cmp ) ; super . mergeSort ( lo , hi - 1 ) ; }


Input: TODO : support constructor indices ( <init > ) [CODESPLIT] private void emitIndexBySignature ( List methods ) { CodeEmitter e = begin_method ( Constants . ACC_PUBLIC , SIGNATURE_GET_INDEX , null ) ; List signatures = CollectionUtils . transform ( methods , new Transformer ( ) { public Object transform ( Object obj ) { return ReflectUtils . getSignature ( ( Method ) obj ) . toString ( ) ; } } ) ; e . load_arg ( 0 ) ; e . invoke_virtual ( Constants . TYPE_OBJECT , TO_STRING ) ; signatureSwitchHelper ( e , signatures ) ; e . end_method ( ) ; }


Input: TODO [CODESPLIT] private void emitIndexByClassArray ( List methods ) { CodeEmitter e = begin_method ( Constants . ACC_PUBLIC , METHOD_GET_INDEX , null ) ; if ( methods . size ( ) > TOO_MANY_METHODS ) { // hack for big classes List signatures = CollectionUtils . transform ( methods , new Transformer ( ) { public Object transform ( Object obj ) { String s = ReflectUtils . getSignature ( ( Method ) obj ) . toString ( ) ; return s . substring ( 0 , s . lastIndexOf ( ' ' ) + 1 ) ; } } ) ; e . load_args ( ) ; e . invoke_static ( FAST_CLASS , GET_SIGNATURE_WITHOUT_RETURN_TYPE ) ; signatureSwitchHelper ( e , signatures ) ; } else { e . load_args ( ) ; List info = CollectionUtils . transform ( methods , MethodInfoTransformer . getInstance ( ) ) ; EmitUtils . method_switch ( e , info , new GetIndexCallback ( e , info ) ) ; } e . end_method ( ) ; }


Input: Helper method to create an interface mixin . For finer control over the generated instance use a new instance of <code > Mixin< / code > instead of this static method . TODO [CODESPLIT] public static Mixin create ( Object [ ] delegates ) { Generator gen = new Generator ( ) ; gen . setDelegates ( delegates ) ; return gen . create ( ) ; }


Input: Helper method to create an interface mixin . For finer control over the generated instance use a new instance of <code > Mixin< / code > instead of this static method . TODO [CODESPLIT] public static Mixin create ( Class [ ] interfaces , Object [ ] delegates ) { Generator gen = new Generator ( ) ; gen . setClasses ( interfaces ) ; gen . setDelegates ( delegates ) ; return gen . create ( ) ; }


Input: Helper method to create a bean mixin . For finer control over the generated instance use a new instance of <code > Mixin< / code > instead of this static method . TODO [CODESPLIT] public static Mixin createBean ( ClassLoader loader , Object [ ] beans ) { Generator gen = new Generator ( ) ; gen . setStyle ( STYLE_BEANS ) ; gen . setDelegates ( beans ) ; gen . setClassLoader ( loader ) ; return gen . create ( ) ; }


Input: } [CODESPLIT] private static Route route ( Object [ ] delegates ) { Object key = ClassesKey . create ( delegates ) ; Route route = ( Route ) ROUTE_CACHE . get ( key ) ; if ( route == null ) { ROUTE_CACHE . put ( key , route = new Route ( delegates ) ) ; } return route ; }


Input: For internal use by { [CODESPLIT] public static MethodProxy create ( Class c1 , Class c2 , String desc , String name1 , String name2 ) { MethodProxy proxy = new MethodProxy ( ) ; proxy . sig1 = new Signature ( name1 , desc ) ; proxy . sig2 = new Signature ( name2 , desc ) ; proxy . createInfo = new CreateInfo ( c1 , c2 ) ; return proxy ; }


Input: Return the <code > MethodProxy< / code > used when intercepting the method matching the given signature . [CODESPLIT] public static MethodProxy find ( Class type , Signature sig ) { try { Method m = type . getDeclaredMethod ( MethodInterceptorGenerator . FIND_PROXY_NAME , MethodInterceptorGenerator . FIND_PROXY_TYPES ) ; return ( MethodProxy ) m . invoke ( null , new Object [ ] { sig } ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( "Class " + type + " does not use a MethodInterceptor" ) ; } catch ( IllegalAccessException e ) { throw new CodeGenerationException ( e ) ; } catch ( InvocationTargetException e ) { throw new CodeGenerationException ( e ) ; } }


Input: Invoke the original method on a different object of the same type . [CODESPLIT] public Object invoke ( Object obj , Object [ ] args ) throws Throwable { try { init ( ) ; FastClassInfo fci = fastClassInfo ; return fci . f1 . invoke ( fci . i1 , obj , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } catch ( IllegalArgumentException e ) { if ( fastClassInfo . i1 < 0 ) throw new IllegalArgumentException ( "Protected method: " + sig1 ) ; throw e ; } }


Input: Invoke the original ( super ) method on the specified object . [CODESPLIT] public Object invokeSuper ( Object obj , Object [ ] args ) throws Throwable { try { init ( ) ; FastClassInfo fci = fastClassInfo ; return fci . f2 . invoke ( fci . i2 , obj , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } }


Input: Casts from one primitive numeric type to another [CODESPLIT] public void cast_numeric ( Type from , Type to ) { if ( from != to ) { if ( from == Type . DOUBLE_TYPE ) { if ( to == Type . FLOAT_TYPE ) { mv . visitInsn ( Constants . D2F ) ; } else if ( to == Type . LONG_TYPE ) { mv . visitInsn ( Constants . D2L ) ; } else { mv . visitInsn ( Constants . D2I ) ; cast_numeric ( Type . INT_TYPE , to ) ; } } else if ( from == Type . FLOAT_TYPE ) { if ( to == Type . DOUBLE_TYPE ) { mv . visitInsn ( Constants . F2D ) ; } else if ( to == Type . LONG_TYPE ) { mv . visitInsn ( Constants . F2L ) ; } else { mv . visitInsn ( Constants . F2I ) ; cast_numeric ( Type . INT_TYPE , to ) ; } } else if ( from == Type . LONG_TYPE ) { if ( to == Type . DOUBLE_TYPE ) { mv . visitInsn ( Constants . L2D ) ; } else if ( to == Type . FLOAT_TYPE ) { mv . visitInsn ( Constants . L2F ) ; } else { mv . visitInsn ( Constants . L2I ) ; cast_numeric ( Type . INT_TYPE , to ) ; } } else { if ( to == Type . BYTE_TYPE ) { mv . visitInsn ( Constants . I2B ) ; } else if ( to == Type . CHAR_TYPE ) { mv . visitInsn ( Constants . I2C ) ; } else if ( to == Type . DOUBLE_TYPE ) { mv . visitInsn ( Constants . I2D ) ; } else if ( to == Type . FLOAT_TYPE ) { mv . visitInsn ( Constants . I2F ) ; } else if ( to == Type . LONG_TYPE ) { mv . visitInsn ( Constants . I2L ) ; } else if ( to == Type . SHORT_TYPE ) { mv . visitInsn ( Constants . I2S ) ; } } } }


Input: Pushes the specified argument of the current method onto the stack . [CODESPLIT] public void load_arg ( int index ) { load_local ( state . argumentTypes [ index ] , state . localOffset + skipArgs ( index ) ) ; }


Input: zero - based ( see load_this ) [CODESPLIT] public void load_args ( int fromArg , int count ) { int pos = state . localOffset + skipArgs ( fromArg ) ; for ( int i = 0 ; i < count ; i ++ ) { Type t = state . argumentTypes [ fromArg + i ] ; load_local ( t , pos ) ; pos += t . getSize ( ) ; } }


Input: package - protected for EmitUtils try to fix [CODESPLIT] void emit_field ( int opcode , Type ctype , String name , Type ftype ) { mv . visitFieldInsn ( opcode , ctype . getInternalName ( ) , name , ftype . getDescriptor ( ) ) ; }


Input: If the argument is a primitive class replaces the primitive value on the top of the stack with the wrapped ( Object ) equivalent . For example char - > Character . If the class is Void a null is pushed onto the stack instead . [CODESPLIT] public void box ( Type type ) { if ( TypeUtils . isPrimitive ( type ) ) { if ( type == Type . VOID_TYPE ) { aconst_null ( ) ; } else { Type boxed = TypeUtils . getBoxedType ( type ) ; new_instance ( boxed ) ; if ( type . getSize ( ) == 2 ) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o dup_x2 ( ) ; dup_x2 ( ) ; pop ( ) ; } else { // p -> po -> opo -> oop -> o dup_x1 ( ) ; swap ( ) ; } invoke_constructor ( boxed , new Signature ( Constants . CONSTRUCTOR_NAME , Type . VOID_TYPE , new Type [ ] { type } ) ) ; } } }


Input: If the argument is a primitive class replaces the object on the top of the stack with the unwrapped ( primitive ) equivalent . For example Character - > char . [CODESPLIT] public void unbox ( Type type ) { Type t = Constants . TYPE_NUMBER ; Signature sig = null ; switch ( type . getSort ( ) ) { case Type . VOID : return ; case Type . CHAR : t = Constants . TYPE_CHARACTER ; sig = CHAR_VALUE ; break ; case Type . BOOLEAN : t = Constants . TYPE_BOOLEAN ; sig = BOOLEAN_VALUE ; break ; case Type . DOUBLE : sig = DOUBLE_VALUE ; break ; case Type . FLOAT : sig = FLOAT_VALUE ; break ; case Type . LONG : sig = LONG_VALUE ; break ; case Type . INT : case Type . SHORT : case Type . BYTE : sig = INT_VALUE ; } if ( sig == null ) { checkcast ( type ) ; } else { checkcast ( t ) ; invoke_virtual ( t , sig ) ; } }


Input:
Allocates and fills an Object [] array with the arguments to the current method . Primitive values are inserted as their boxed ( Object ) equivalents . [CODESPLIT] public void create_arg_array ( ) { /* generates:
           Object[] args = new Object[]{ arg1, new Integer(arg2) };
         */ push ( state . argumentTypes . length ) ; newarray ( ) ; for ( int i = 0 ; i < state . argumentTypes . length ; i ++ ) { dup ( ) ; push ( i ) ; load_arg ( i ) ; box ( state . argumentTypes [ i ] ) ; aastore ( ) ; } }


Input: Pushes a zero onto the stack if the argument is a primitive class or a null otherwise . [CODESPLIT] public void zero_or_null ( Type type ) { if ( TypeUtils . isPrimitive ( type ) ) { switch ( type . getSort ( ) ) { case Type . DOUBLE : push ( 0d ) ; break ; case Type . LONG : push ( 0L ) ; break ; case Type . FLOAT : push ( 0f ) ; break ; case Type . VOID : aconst_null ( ) ; default : push ( 0 ) ; } } else { aconst_null ( ) ; } }


Input: Unboxes the object on the top of the stack . If the object is null the unboxed primitive value becomes zero . [CODESPLIT] public void unbox_or_zero ( Type type ) { if ( TypeUtils . isPrimitive ( type ) ) { if ( type != Type . VOID_TYPE ) { Label nonNull = make_label ( ) ; Label end = make_label ( ) ; dup ( ) ; ifnonnull ( nonNull ) ; pop ( ) ; zero_or_null ( type ) ; goTo ( end ) ; mark ( nonNull ) ; unbox ( type ) ; mark ( end ) ; } } else { checkcast ( type ) ; } }


Input: Process an array on the stack . Assumes the top item on the stack is an array of the specified type . For each element in the array puts the element on the stack and triggers the callback . [CODESPLIT] public static void process_array ( CodeEmitter e , Type type , ProcessArrayCallback callback ) { Type componentType = TypeUtils . getComponentType ( type ) ; Local array = e . make_local ( ) ; Local loopvar = e . make_local ( Type . INT_TYPE ) ; Label loopbody = e . make_label ( ) ; Label checkloop = e . make_label ( ) ; e . store_local ( array ) ; e . push ( 0 ) ; e . store_local ( loopvar ) ; e . goTo ( checkloop ) ; e . mark ( loopbody ) ; e . load_local ( array ) ; e . load_local ( loopvar ) ; e . array_load ( componentType ) ; callback . processElement ( componentType ) ; e . iinc ( loopvar , 1 ) ; e . mark ( checkloop ) ; e . load_local ( loopvar ) ; e . load_local ( array ) ; e . arraylength ( ) ; e . if_icmp ( e . LT , loopbody ) ; }


Input: Branches to the specified label if the top two items on the stack are not equal . The items must both be of the specified class . Equality is determined by comparing primitive values directly and by invoking the <code > equals< / code > method for Objects . Arrays are recursively processed in the same manner . [CODESPLIT] public static void not_equals ( final CodeEmitter e , Type type , final Label notEquals , final CustomizerRegistry registry ) { ( new ProcessArrayCallback ( ) { public void processElement ( Type type ) { not_equals_helper ( e , type , notEquals , registry , this ) ; } } ) . processElement ( type ) ; }


Input: If both objects on the top of the stack are non - null does nothing . If one is null or both are null both are popped off and execution branches to the respective label . [CODESPLIT] private static void nullcmp ( CodeEmitter e , Label oneNull , Label bothNull ) { e . dup2 ( ) ; Label nonNull = e . make_label ( ) ; Label oneNullHelper = e . make_label ( ) ; Label end = e . make_label ( ) ; e . ifnonnull ( nonNull ) ; e . ifnonnull ( oneNullHelper ) ; e . pop2 ( ) ; e . goTo ( bothNull ) ; e . mark ( nonNull ) ; e . ifnull ( oneNullHelper ) ; e . goTo ( end ) ; e . mark ( oneNullHelper ) ; e . pop2 ( ) ; e . goTo ( oneNull ) ; e . mark ( end ) ; }


Input: / * generates : } catch ( RuntimeException e ) { throw e ; } catch ( Error e ) { throw e ; } catch ( <DeclaredException > e ) { throw e ; } catch ( Throwable e ) { throw new <Wrapper > ( e ) ; } [CODESPLIT] public static void wrap_undeclared_throwable ( CodeEmitter e , Block handler , Type [ ] exceptions , Type wrapper ) { Set set = ( exceptions == null ) ? Collections . EMPTY_SET : new HashSet ( Arrays . asList ( exceptions ) ) ; if ( set . contains ( Constants . TYPE_THROWABLE ) ) return ; boolean needThrow = exceptions != null ; if ( ! set . contains ( Constants . TYPE_RUNTIME_EXCEPTION ) ) { e . catch_exception ( handler , Constants . TYPE_RUNTIME_EXCEPTION ) ; needThrow = true ; } if ( ! set . contains ( Constants . TYPE_ERROR ) ) { e . catch_exception ( handler , Constants . TYPE_ERROR ) ; needThrow = true ; } if ( exceptions != null ) { for ( int i = 0 ; i < exceptions . length ; i ++ ) { e . catch_exception ( handler , exceptions [ i ] ) ; } } if ( needThrow ) { e . athrow ( ) ; } // e -> eo -> oeo -> ooe -> o e . catch_exception ( handler , Constants . TYPE_THROWABLE ) ; e . new_instance ( wrapper ) ; e . dup_x1 ( ) ; e . swap ( ) ; e . invoke_constructor ( wrapper , CSTRUCT_THROWABLE ) ; e . athrow ( ) ; }


Input: Finds all bridge methods that are being called with invokespecial & returns them . [CODESPLIT] public Map /*<Signature, Signature>*/ resolveAll ( ) { Map resolved = new HashMap ( ) ; for ( Iterator entryIter = declToBridge . entrySet ( ) . iterator ( ) ; entryIter . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entryIter . next ( ) ; Class owner = ( Class ) entry . getKey ( ) ; Set bridges = ( Set ) entry . getValue ( ) ; try { InputStream is = classLoader . getResourceAsStream ( owner . getName ( ) . replace ( ' ' , ' ' ) + ".class" ) ; if ( is == null ) { return resolved ; } try { new ClassReader ( is ) . accept ( new BridgedFinder ( bridges , resolved ) , ClassReader . SKIP_FRAMES | ClassReader . SKIP_DEBUG ) ; } finally { is . close ( ) ; } } catch ( IOException ignored ) { } } return resolved ; }


Input: Set the class which the generated class will extend . As a convenience if the supplied superclass is actually an interface <code > setInterfaces< / code > will be called with the appropriate argument instead . A non - interface argument must not be declared as final and must have an accessible constructor . [CODESPLIT] public void setSuperclass ( Class superclass ) { if ( superclass != null && superclass . isInterface ( ) ) { setInterfaces ( new Class [ ] { superclass } ) ; } else if ( superclass != null && superclass . equals ( Object . class ) ) { // affects choice of ClassLoader this . superclass = null ; } else { this . superclass = superclass ; } }


Input: Set the array of callbacks to use . Ignored if you use { [CODESPLIT] public void setCallbacks ( Callback [ ] callbacks ) { if ( callbacks != null && callbacks . length == 0 ) { throw new IllegalArgumentException ( "Array cannot be empty" ) ; } this . callbacks = callbacks ; }


Input: Set the array of callback types to use . This may be used instead of { [CODESPLIT] public void setCallbackTypes ( Class [ ] callbackTypes ) { if ( callbackTypes != null && callbackTypes . length == 0 ) { throw new IllegalArgumentException ( "Array cannot be empty" ) ; } this . callbackTypes = CallbackInfo . determineTypes ( callbackTypes ) ; }


Input: Generate a new class if necessary and uses the specified callbacks ( if any ) to create a new object instance . Uses the constructor of the superclass matching the <code > argumentTypes< / code > parameter with the given arguments . [CODESPLIT] public Object create ( Class [ ] argumentTypes , Object [ ] arguments ) { classOnly = false ; if ( argumentTypes == null || arguments == null || argumentTypes . length != arguments . length ) { throw new IllegalArgumentException ( "Arguments must be non-null and of equal length" ) ; } this . argumentTypes = argumentTypes ; this . arguments = arguments ; return createHelper ( ) ; }


Input: Finds all of the methods that will be extended by an Enhancer - generated class using the specified superclass and interfaces . This can be useful in building a list of Callback objects . The methods are added to the end of the given list . Due to the subclassing nature of the classes generated by Enhancer the methods are guaranteed to be non - static non - final and non - private . Each method signature will only occur once even if it occurs in multiple classes . [CODESPLIT] public static void getMethods ( Class superclass , Class [ ] interfaces , List methods ) { getMethods ( superclass , interfaces , methods , null , null ) ; }


Input: Filter the list of constructors from the superclass . The constructors which remain will be included in the generated class . The default implementation is to filter out all private constructors but subclasses may extend Enhancer to override this behavior . [CODESPLIT] protected void filterConstructors ( Class sc , List constructors ) { CollectionUtils . filter ( constructors , new VisibilityPredicate ( sc , true ) ) ; if ( constructors . size ( ) == 0 ) throw new IllegalArgumentException ( "No visible constructors in " + sc ) ; }


Input: Determine if a class was generated using <code > Enhancer< / code > . [CODESPLIT] public static boolean isEnhanced ( Class type ) { try { getCallbacksSetter ( type , SET_THREAD_CALLBACKS_NAME ) ; return true ; } catch ( NoSuchMethodException e ) { return false ; } }


Input: Instantiates a proxy instance and assigns callback values . Implementation detail : java . lang . reflect instances are not cached so this method should not be used on a hot path . This method is used when { @link #setUseCache ( boolean ) } is set to { @code false } . [CODESPLIT] private Object createUsingReflection ( Class type ) { setThreadCallbacks ( type , callbacks ) ; try { if ( argumentTypes != null ) { return ReflectUtils . newInstance ( type , argumentTypes , arguments ) ; } else { return ReflectUtils . newInstance ( type ) ; } } finally { // clear thread callbacks to allow them to be gc'd setThreadCallbacks ( type , null ) ; } }


Input: Helper method to create an intercepted object . For finer control over the generated instance use a new instance of <code > Enhancer< / code > instead of this static method . [CODESPLIT] public static Object create ( Class type , Callback callback ) { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( type ) ; e . setCallback ( callback ) ; return e . create ( ) ; }


Input: Helper method to create an intercepted object . For finer control over the generated instance use a new instance of <code > Enhancer< / code > instead of this static method . [CODESPLIT] public static Object create ( Class superclass , Class interfaces [ ] , Callback callback ) { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( superclass ) ; e . setInterfaces ( interfaces ) ; e . setCallback ( callback ) ; return e . create ( ) ; }


Input: Helper method to create an intercepted object . For finer control over the generated instance use a new instance of <code > Enhancer< / code > instead of this static method . [CODESPLIT] public static Object create ( Class superclass , Class [ ] interfaces , CallbackFilter filter , Callback [ ] callbacks ) { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( superclass ) ; e . setInterfaces ( interfaces ) ; e . setCallbackFilter ( filter ) ; e . setCallbacks ( callbacks ) ; return e . create ( ) ; }


Input: Set the class which the generated class will extend . The class must not be declared as final and must have a non - private no - argument constructor . [CODESPLIT] public void setSuperclass ( Class superclass ) { if ( superclass != null && superclass . equals ( Object . class ) ) { superclass = null ; } this . superclass = superclass ; }


Input: to avoid JVM hashcode implementation incompatibilities [CODESPLIT] private void getField ( String [ ] names ) throws Exception { final CodeEmitter e = begin_method ( Constants . ACC_PUBLIC , PROVIDER_GET , null ) ; e . load_this ( ) ; e . load_arg ( 0 ) ; EmitUtils . string_switch ( e , names , Constants . SWITCH_STYLE_HASH , new ObjectSwitchCallback ( ) { public void processCase ( Object key , Label end ) { Type type = ( Type ) fields . get ( key ) ; e . getfield ( ( String ) key ) ; e . box ( type ) ; e . return_value ( ) ; } public void processDefault ( ) { e . throw_exception ( ILLEGAL_ARGUMENT_EXCEPTION , "Unknown field name" ) ; } } ) ; e . end_method ( ) ; }


Input: Add a method signature to the interface . The method modifiers are ignored since interface methods are by definition abstract and public . [CODESPLIT] public void add ( Method method ) { add ( ReflectUtils . getSignature ( method ) , ReflectUtils . getExceptionTypes ( method ) ) ; }


Input: Add all the public methods in the specified class . Methods from superclasses are included except for methods declared in the base Object class ( e . g . <code > getClass< / code > <code > equals< / code > <code > hashCode< / code > ) . [CODESPLIT] public void add ( Class clazz ) { Method [ ] methods = clazz . getMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method m = methods [ i ] ; if ( ! m . getDeclaringClass ( ) . getName ( ) . equals ( "java.lang.Object" ) ) { add ( m ) ; } } }


Input: If bit 31 is set then this method results in an infinite loop . [CODESPLIT] public int cardinality ( ) { int w = value ; int c = 0 ; while ( w != 0 ) { c += T [ w & 255 ] ; w >>= 8 ; } return c ; }


Input: Override the default naming policy . [CODESPLIT] public void setNamingPolicy ( NamingPolicy namingPolicy ) { if ( namingPolicy == null ) namingPolicy = DefaultNamingPolicy . INSTANCE ; this . namingPolicy = namingPolicy ; }


Input: Set the strategy to use to create the bytecode from this generator . By default an instance of { [CODESPLIT] public void setStrategy ( GeneratorStrategy strategy ) { if ( strategy == null ) strategy = DefaultGeneratorStrategy . INSTANCE ; this . strategy = strategy ; }


Input: Loads entry to the cache . If entry is missing put { [CODESPLIT] protected V createEntry ( final K key , KK cacheKey , Object v ) { FutureTask < V > task ; boolean creator = false ; if ( v != null ) { // Another thread is already loading an instance task = ( FutureTask < V > ) v ; } else { task = new FutureTask < V > ( new Callable < V > ( ) { public V call ( ) throws Exception { return loader . apply ( key ) ; } } ) ; Object prevTask = map . putIfAbsent ( cacheKey , task ) ; if ( prevTask == null ) { // creator does the load creator = true ; task . run ( ) ; } else if ( prevTask instanceof FutureTask ) { task = ( FutureTask < V > ) prevTask ; } else { return ( V ) prevTask ; } } V result ; try { result = task . get ( ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( "Interrupted while loading cache item" , e ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( ( RuntimeException ) cause ) ; } throw new IllegalStateException ( "Unable to load cache item" , cause ) ; } if ( creator ) { map . put ( cacheKey , result ) ; } return result ; }


Input: used by MethodInterceptorGenerated generated code [CODESPLIT] public static Method [ ] findMethods ( String [ ] namesAndDescriptors , Method [ ] methods ) { Map map = new HashMap ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method method = methods [ i ] ; map . put ( method . getName ( ) + Type . getMethodDescriptor ( method ) , method ) ; } Method [ ] result = new Method [ namesAndDescriptors . length / 2 ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = ( Method ) map . get ( namesAndDescriptors [ i * 2 ] + namesAndDescriptors [ i * 2 + 1 ] ) ; if ( result [ i ] == null ) { // TODO: error? } } return result ; }


Input: Resolves subpath in safer way . For some reason if child starts with a separator it gets resolved as a full path ignoring the base . This method acts different . [CODESPLIT] public static Path resolve ( final Path base , String child ) { if ( StringUtil . startsWithChar ( child , File . separatorChar ) ) { child = child . substring ( 1 ) ; } return base . resolve ( child ) ; }


Input: Reads path content . [CODESPLIT] public static String readString ( final Path path ) throws IOException { try ( BufferedReader reader = Files . newBufferedReader ( path , StandardCharsets . UTF_8 ) ) { StringWriter writer = new StringWriter ( ) ; // flush & close not needed for StringWriter-instance StreamUtil . copy ( reader , writer ) ; return writer . toString ( ) ; } }


Input: Sets request host name . [CODESPLIT] public HttpRequest host ( final String host ) { this . host = host ; if ( headers . contains ( HEADER_HOST ) ) { headerOverwrite ( HEADER_HOST , host ) ; } return this ; }


Input: Sets the destination ( method host port ... ) at once . [CODESPLIT] public HttpRequest set ( String destination ) { destination = destination . trim ( ) ; // http method, optional int ndx = destination . indexOf ( ' ' ) ; if ( ndx != - 1 ) { String method = destination . substring ( 0 , ndx ) . toUpperCase ( ) ; try { HttpMethod httpMethod = HttpMethod . valueOf ( method ) ; this . method = httpMethod . name ( ) ; destination = destination . substring ( ndx + 1 ) ; } catch ( IllegalArgumentException ignore ) { // unknown http method } } // protocol ndx = destination . indexOf ( "://" ) ; if ( ndx != - 1 ) { protocol = destination . substring ( 0 , ndx ) ; destination = destination . substring ( ndx + 3 ) ; } // host ndx = destination . indexOf ( ' ' ) ; if ( ndx == - 1 ) { ndx = destination . length ( ) ; } if ( ndx != 0 ) { String hostToSet = destination . substring ( 0 , ndx ) ; destination = destination . substring ( ndx ) ; // port ndx = hostToSet . indexOf ( ' ' ) ; if ( ndx == - 1 ) { port = Defaults . DEFAULT_PORT ; } else { port = Integer . parseInt ( hostToSet . substring ( ndx + 1 ) ) ; hostToSet = hostToSet . substring ( 0 , ndx ) ; } host ( hostToSet ) ; } // path + query path ( destination ) ; return this ; }


Input: Generic request builder usually used when method is a variable . Otherwise use one of the other static request builder methods . [CODESPLIT] public static HttpRequest create ( final String method , final String destination ) { return new HttpRequest ( ) . method ( method . toUpperCase ( ) ) . set ( destination ) ; }


Input: Builds a CONNECT request . [CODESPLIT] public static HttpRequest connect ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . CONNECT ) . set ( destination ) ; }


Input: Builds a GET request . [CODESPLIT] public static HttpRequest get ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . GET ) . set ( destination ) ; }


Input: Builds a POST request . [CODESPLIT] public static HttpRequest post ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . POST ) . set ( destination ) ; }


Input: Builds a PUT request . [CODESPLIT] public static HttpRequest put ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . PUT ) . set ( destination ) ; }


Input: Builds a PATCH request . [CODESPLIT] public static HttpRequest patch ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . PATCH ) . set ( destination ) ; }


Input: Builds a DELETE request . [CODESPLIT] public static HttpRequest delete ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . DELETE ) . set ( destination ) ; }


Input: Builds a HEAD request . [CODESPLIT] public static HttpRequest head ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . HEAD ) . set ( destination ) ; }


Input: Builds a TRACE request . [CODESPLIT] public static HttpRequest trace ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . TRACE ) . set ( destination ) ; }


Input: Builds an OPTIONS request . [CODESPLIT] public static HttpRequest options ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . OPTIONS ) . set ( destination ) ; }


Input: Sets request path . Query string is allowed . Adds a slash if path doesn t start with one . Query will be stripped out from the path . Previous query is discarded . [CODESPLIT] public HttpRequest path ( String path ) { // this must be the only place that sets the path if ( ! path . startsWith ( StringPool . SLASH ) ) { path = StringPool . SLASH + path ; } int ndx = path . indexOf ( ' ' ) ; if ( ndx != - 1 ) { String queryString = path . substring ( ndx + 1 ) ; path = path . substring ( 0 , ndx ) ; query = HttpUtil . parseQuery ( queryString , true ) ; } else { query = HttpMultiMap . newCaseInsensitiveMap ( ) ; } this . path = path ; return this ; }


Input: Sets cookies to the request . [CODESPLIT] public HttpRequest cookies ( final Cookie ... cookies ) { if ( cookies . length == 0 ) { return this ; } StringBuilder cookieString = new StringBuilder ( ) ; boolean first = true ; for ( Cookie cookie : cookies ) { Integer maxAge = cookie . getMaxAge ( ) ; if ( maxAge != null && maxAge . intValue ( ) == 0 ) { continue ; } if ( ! first ) { cookieString . append ( "; " ) ; } first = false ; cookieString . append ( cookie . getName ( ) ) ; cookieString . append ( ' ' ) ; cookieString . append ( cookie . getValue ( ) ) ; } headerOverwrite ( "cookie" , cookieString . toString ( ) ) ; return this ; }


Input: Adds query parameter . [CODESPLIT] public HttpRequest query ( final String name , final String value ) { query . add ( name , value ) ; return this ; }


Input: Adds many query parameters at once . Although it accepts objects each value will be converted to string . [CODESPLIT] public HttpRequest query ( final String name1 , final Object value1 , final Object ... parameters ) { query ( name1 , value1 == null ? null : value1 . toString ( ) ) ; for ( int i = 0 ; i < parameters . length ; i += 2 ) { String name = parameters [ i ] . toString ( ) ; String value = parameters [ i + 1 ] . toString ( ) ; query . add ( name , value ) ; } return this ; }


Input: Adds all parameters from the provided map . [CODESPLIT] public HttpRequest query ( final Map < String , String > queryMap ) { for ( Map . Entry < String , String > entry : queryMap . entrySet ( ) ) { query . add ( entry . getKey ( ) , entry . getValue ( ) ) ; } return this ; }


Input: Sets query from provided query string . Previous query values are discarded . [CODESPLIT] public HttpRequest queryString ( final String queryString , final boolean decode ) { this . query = HttpUtil . parseQuery ( queryString , decode ) ; return this ; }


Input: Generates query string . All values are URL encoded . [CODESPLIT] public String queryString ( ) { if ( query == null ) { return StringPool . EMPTY ; } return HttpUtil . buildQuery ( query , queryEncoding ) ; }


Input: Returns full URL path . Simply concatenates { [CODESPLIT] public String url ( ) { StringBuilder url = new StringBuilder ( ) ; url . append ( hostUrl ( ) ) ; if ( path != null ) { url . append ( path ) ; } String queryString = queryString ( ) ; if ( StringUtil . isNotBlank ( queryString ) ) { url . append ( ' ' ) ; url . append ( queryString ) ; } return url . toString ( ) ; }


Input: Returns just host url without path and query . [CODESPLIT] public String hostUrl ( ) { StringBand url = new StringBand ( 8 ) ; if ( protocol != null ) { url . append ( protocol ) ; url . append ( "://" ) ; } if ( host != null ) { url . append ( host ) ; } if ( port != Defaults . DEFAULT_PORT ) { url . append ( ' ' ) ; url . append ( port ) ; } return url . toString ( ) ; }


Input: Enables basic authentication by adding required header . [CODESPLIT] public HttpRequest basicAuthentication ( final String username , final String password ) { if ( username != null && password != null ) { String data = username . concat ( StringPool . COLON ) . concat ( password ) ; String base64 = Base64 . encodeToString ( data ) ; headerOverwrite ( HEADER_AUTHORIZATION , "Basic " + base64 ) ; } return this ; }


Input: Sets Host header from current host and port . [CODESPLIT] public HttpRequest setHostHeader ( ) { String hostPort = this . host ; if ( port != Defaults . DEFAULT_PORT ) { hostPort += StringPool . COLON + port ; } headerOverwrite ( HEADER_HOST , hostPort ) ; return this ; }


Input: Opens a new { [CODESPLIT] public HttpRequest open ( final HttpConnectionProvider httpConnectionProvider ) { if ( this . httpConnection != null ) { throw new HttpException ( "Connection already opened" ) ; } try { this . httpConnectionProvider = httpConnectionProvider ; this . httpConnection = httpConnectionProvider . createHttpConnection ( this ) ; } catch ( IOException ioex ) { throw new HttpException ( "Can't connect to: " + url ( ) , ioex ) ; } return this ; }


Input: Assignees provided { [CODESPLIT] public HttpRequest open ( final HttpConnection httpConnection ) { if ( this . httpConnection != null ) { throw new HttpException ( "Connection already opened" ) ; } this . httpConnection = httpConnection ; this . httpConnectionProvider = null ; return this ; }


Input: Continues using the same keep - alive connection . Don t use any variant of <code > open () < / code > when continuing the communication! First it checks if Connection header exist in the response and if it is equal to Keep - Alive value . Then it checks the Keep - Alive headers max parameter . If its value is positive then the existing { @link jodd . http . HttpConnection } from the request will be reused . If max value is 1 connection will be sent with Connection : Close header indicating its the last request . When new connection is created the same { @link jodd . http . HttpConnectionProvider } that was used for creating initial connection is used for opening the new connection . [CODESPLIT] public HttpRequest keepAlive ( final HttpResponse httpResponse , final boolean doContinue ) { boolean keepAlive = httpResponse . isConnectionPersistent ( ) ; if ( keepAlive ) { HttpConnection previousConnection = httpResponse . getHttpRequest ( ) . httpConnection ; if ( previousConnection != null ) { // keep using the connection! this . httpConnection = previousConnection ; this . httpConnectionProvider = httpResponse . getHttpRequest ( ) . connectionProvider ( ) ; } //keepAlive = true; (already set) } else { // close previous connection httpResponse . close ( ) ; // force keep-alive on new request keepAlive = true ; } // if we don't want to continue with this persistent session, mark this connection as closed if ( ! doContinue ) { keepAlive = false ; } connectionKeepAlive ( keepAlive ) ; // if connection is not opened, open it using previous connection provider if ( httpConnection == null ) { open ( httpResponse . getHttpRequest ( ) . connectionProvider ( ) ) ; } return this ; }


Input: { [CODESPLIT] public HttpResponse send ( ) { if ( ! followRedirects ) { return _send ( ) ; } int redirects = this . maxRedirects ; while ( redirects > 0 ) { redirects -- ; final HttpResponse httpResponse = _send ( ) ; final int statusCode = httpResponse . statusCode ( ) ; if ( HttpStatus . isRedirect ( statusCode ) ) { _reset ( ) ; set ( httpResponse . location ( ) ) ; continue ; } return httpResponse ; } throw new HttpException ( "Max number of redirects exceeded: " + this . maxRedirects ) ; }