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());
                })));
  }

Using the given splitter flow, allow messages to bypass a flow.

<p>If the splitter flow produces Left, they will be fed into the flow. If it produces Right,
they will bypass the flow.

@param <In> the In type parameter for Flow
@param <FlowIn> the FlowIn type parameter for the left branch in Either.
@param <Out> the Out type parameter for Flow.
@param flow the original flow.
@param splitter the splitter function.
@param mergeStrategy the merge strategy (onlyFirstCanFinishMerge, ignoreAfterFinish,
ignoreAfterCancellation)
@return the flow with a bypass.

Using the given splitter flow allow messages to bypass a flow .


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();
  }

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 ( ) ; }

Create a flow that is handled by an actor.

Messages can be sent downstream by sending them to the actor passed into the props function.
This actor meets the contract of the actor returned by {@link
akka.stream.javadsl.Source#actorRef}.

The props function should return the props for an actor to handle the flow. This actor will
be created using the passed in {@link akka.actor.ActorRefFactory}. Each message received will
be sent to the actor - there is no back pressure, if the actor is unable to process the
messages, they will queue up in the actors mailbox. The upstream can be cancelled by the actor
terminating itself.

@param <In> the In type parameter for a Flow
@param <Out> the Out type parameter for a Flow
@param props A function that creates the props for actor to handle the flow.
@param bufferSize The maximum number of elements to buffer.
@param overflowStrategy The strategy for how to handle a buffer overflow.
@param factory The Actor Factory used to create the actor to handle the flow - for example, an
ActorSystem.
@param mat The materializer to materialize the flow.
@return the flow itself.

Create a flow that is handled by an actor .


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);
  }

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 ) ; }

Convert the error arguments.

@param arguments The arguments to convert.
@return The converted arguments.


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);
  }

public
Form
<
T
>
fill
(
T
value
)
{
if
(
value
==
)
{
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
)
;
}

Populates this form with an existing value, used for edit forms.

@param value existing value of type T used to fill this form
@return a copy of this form filled with the new data

Populates this form with an existing value used for edit forms .


public List<ValidationError> globalErrors() {
    return Collections.unmodifiableList(
        errors.stream().filter(error -> error.key().isEmpty()).collect(Collectors.toList()));
  }

public List < ValidationError > globalErrors ( ) { return Collections . unmodifiableList ( errors . stream ( ) . filter ( error -> error . key ( ) . isEmpty ( ) ) . collect ( Collectors . toList ( ) ) ) ; }

Retrieve all global errors - errors without a key.

@return All global errors.

Retrieve all global errors - errors without a key .


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);
  }

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 ) ; }

Returns the form errors serialized as Json using the given Lang.

@param lang the language to use.
@return the JSON node containing the errors.

Returns the form errors serialized as Json using the given Lang .


public Optional<Object> value(String key) {
    return super.value().map(v -> v.getData().get(asNormalKey(key)));
  }

public Optional < Object > value ( String key ) { return super . value ( ) . map ( v -> v . getData ( ) . get ( asNormalKey ( key ) ) ) ; }

Gets the concrete value

@param key the string key.
@return the value


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));
  }

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 ) ) ; }

Fills the form with existing data.

@param value the map of values to fill in the form.
@return the modified form.


public <T> T parse(String text, Class<T> clazz) {
    return conversion.convert(text, clazz);
  }

public < T > T parse ( String text , Class < T > clazz ) { return conversion . convert ( text , clazz ) ; }

Parses this string as instance of the given class.

@param text the text to parse
@param clazz class representing the required type
@param <T> the type to parse out of the text
@return the parsed value

Parses this string as instance of the given class .


@SuppressWarnings("unchecked")
  public <T> T parse(Field field, String text) {
    return (T) conversion.convert(text, new TypeDescriptor(field));
  }

@ SuppressWarnings ( "unchecked" ) public < T > T parse ( Field field , String text ) { return ( T ) conversion . convert ( text , new TypeDescriptor ( field ) ) ; }

Parses this string as instance of a specific field

@param field the related field (custom formatters are extracted from this field annotation)
@param text the text to parse
@param <T> the type to parse out of the text
@return the parsed value


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();
    }
  }

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 ( ) ; } }

Computes the display string for any value.

@param t the value to print
@param <T> the type to print
@return the formatted string

Computes the display string for any value .


public <T> String print(Field field, T t) {
    return print(new TypeDescriptor(field), t);
  }

public < T > String print ( Field field , T t ) { return print ( new TypeDescriptor ( field ) , t ) ; }

Computes the display string for any value, for a specific field.

@param field the related field - custom formatters are extracted from this field annotation
@param t the value to print
@param <T> the type to print
@return the formatted string

Computes the display string for any value for a specific field .


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();
    }
  }

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 ( ) ; } }

Computes the display string for any value, for a specific type.

@param desc the field descriptor - custom formatters are extracted from this descriptor.
@param t the value to print
@param <T> the type to print
@return the formatted string

Computes the display string for any value for a specific type .


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;
  }

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
==
)
return
""
;
Optional
<
>
opt
=
(
Optional
)
source
;
return
opt
.
map
(
o
->
conversion
.
convert
(
source
,
sourceType
.
getElementTypeDescriptor
(
)
,
targetType
)
)
.
orElse
(
""
)
;
}
return
;
}
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
;
}

Converter for String -> Optional and Optional -> String

Converter for String - > Optional and Optional - > String


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;
  }

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 ; }

Registers a simple formatter.

@param clazz class handled by this formatter
@param <T> the type that this formatter will parse and print
@param formatter the formatter to register
@return the modified Formatters object.


@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;
  }

@
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
)
!=
)
;
}
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
)
!=
)
;
}
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
;
}

Registers an annotation-based formatter.

@param clazz class handled by this formatter
@param formatter the formatter to register
@param <A> the annotation type
@param <T> the type that will be parsed or printed
@return the modified Formatters object.

Registers an annotation - based formatter .


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);
  }

public
String
encode
(
Cookie
cookie
)
{
if
(
cookie
==
)
{
throw
new
NullPointerException
(
"cookie"
)
;
}
final
String
name
=
cookie
.
name
(
)
;
final
String
value
=
cookie
.
value
(
)
!=
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
(
)
!=
)
{
add
(
buf
,
CookieHeaderNames
.
SAMESITE
,
cookie
.
sameSite
(
)
)
;
}
if
(
cookie
.
path
(
)
!=
)
{
add
(
buf
,
CookieHeaderNames
.
PATH
,
cookie
.
path
(
)
)
;
}
if
(
cookie
.
domain
(
)
!=
)
{
add
(
buf
,
CookieHeaderNames
.
DOMAIN
,
cookie
.
domain
(
)
)
;
}
if
(
cookie
.
isSecure
(
)
)
{
add
(
buf
,
CookieHeaderNames
.
SECURE
)
;
}
if
(
cookie
.
isHttpOnly
(
)
)
{
add
(
buf
,
CookieHeaderNames
.
HTTPONLY
)
;
}
return
stripTrailingSeparator
(
buf
)
;
}

Encodes the specified cookie into a Set-Cookie header value.

@param cookie the cookie
@return a single Set-Cookie header value

Encodes the specified cookie into a Set - Cookie header value .


public static NodeList selectNodes(String path, Object node) {
    return selectNodes(path, node, null);
  }

public static NodeList selectNodes ( String path , Object node ) { return selectNodes ( path , node , null ) ; }

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,

@param path the xpath expression
@param node the starting node
@return result of evaluating the xpath expression against node

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


public static <T> scala.collection.immutable.Seq<T> toSeq(java.util.List<T> list) {
        return scala.collection.JavaConverters.asScalaBufferConverter(list).asScala().toList();
    }

public static < T > scala . collection . immutable . Seq < T > toSeq ( java . util . List < T > list ) { return scala . collection . JavaConverters . asScalaBufferConverter ( list ) . asScala ( ) . toList ( ) ; }

Converts a Java List to Scala Seq.

@param list    the java list.
@return the converted Seq.
@param <T> the element type.


public static <T> scala.collection.immutable.Seq<T> toSeq(T[] array) {
        return toSeq(java.util.Arrays.asList(array));
    }

public static < T > scala . collection . immutable . Seq < T > toSeq ( T [ ] array ) { return toSeq ( java . util . Arrays . asList ( array ) ) ; }

Converts a Java Array to Scala Seq.

@param array    the java array.
@return the converted Seq.
@param <T> the element type.


@SafeVarargs
    public static <T> scala.collection.immutable.Seq<T> varargs(T... array) {
        return toSeq(array);
    }

@ SafeVarargs public static < T > scala . collection . immutable . Seq < T > varargs ( T ... array ) { return toSeq ( array ) ; }

Converts a Java varargs to Scala varargs.

@param array    the java array.
@return the Scala varargs
@param <T> the element type.

Converts a Java varargs to Scala varargs .


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);
          }
        });
  }

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 ) ; } } ) ; }

Acceptor for JSON WebSockets.

@param in The class of the incoming messages, used to decode them from the JSON.
@param <In> The websocket's input type (what it receives from clients)
@param <Out> The websocket's output type (what it writes to clients)
@return The WebSocket acceptor.


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);
                  }
                });
      }
    };
  }

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 ) ; } } ) ; } } ; }

Helper to create handlers for WebSockets.

@param inMapper Function to map input messages. If it produces left, the message will be passed
to the WebSocket flow, if it produces right, the message will be sent back out to the
client - this can be used to send errors directly to the client.
@param f The function to handle the WebSocket.
@param outMapper Function to map output messages.
@return The WebSocket handler.

Helper to create handlers for WebSockets .


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;
  }

XXX Default access superclass workaround.

<p>When a {@code public} class has a default access superclass with {@code public} members,
these members are accessible. Calling them from compiled code works fine. Unfortunately, on
some JVMs, using reflection to invoke these members seems to (wrongly) prevent access even when
the modifier is {@code public}. Calling {@code setAccessible(true)} solves the problem but will
only work from sufficiently privileged code. Better workarounds would be gratefully accepted.

@param o the AccessibleObject to set as accessible
@return a boolean indicating whether the accessibility of the object was set to true.

XXX Default access superclass workaround .


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;
  }

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
;
}

Gets the number of steps required to promote a primitive number to another type.

@param srcClass the (primitive) source class
@param destClass the (primitive) destination class
@return The cost of promoting the primitive

Gets the number of steps required to promote a primitive number to another type .


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;
  }

Returns the sum of the object transformation cost for each class in the source argument list.

@param srcArgs The source arguments
@param executable The executable to calculate transformation costs for
@return The total transformation cost

Returns the sum of the object transformation cost for each class in the source argument list .


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;
  }

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.

@param srcClass The source class
@param destClass The destination class
@return The cost of transforming an object

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 .


public String at(String key, Object... args) {
    return messagesApi.get(lang, key, args);
  }

public String at ( String key , Object ... args ) { return messagesApi . get ( lang , key , args ) ; }

Get the message at the given key.

<p>Uses `java.text.MessageFormat` internally to format the message.

@param key the message key
@param args the message arguments
@return the formatted message or a default rendering if the key wasn't defined


public String at(List<String> keys, Object... args) {
    return messagesApi.get(lang, keys, args);
  }

public String at ( List < String > keys , Object ... args ) { return messagesApi . get ( lang , keys , args ) ; }

Get the message at the first defined key.

<p>Uses `java.text.MessageFormat` internally to format the message.

@param keys the messages keys
@param args the message arguments
@return the formatted message or a default rendering if the key wasn't defined

Get the message at the first defined key .


public static Database createFrom(
      String driver, String url, Map<String, ? extends Object> config) {
    return createFrom("default", driver, url, config);
  }

public static Database createFrom ( String driver , String url , Map < String , ? extends Object > config ) { return createFrom ( "default" , driver , url , config ) ; }

Create a pooled database named "default" with the given configuration.

@param driver the database driver class
@param url the database url
@param config a map of extra database configuration
@return a configured database

Create a pooled database named default with the given configuration .


public static ParallelSorter create(Object[] arrays) {
        Generator gen = new Generator();
        gen.setArrays(arrays);
        return gen.create();
    }

public static ParallelSorter create ( Object [ ] arrays ) { Generator gen = new Generator ( ) ; gen . setArrays ( arrays ) ; return gen . create ( ) ; }

Create a new ParallelSorter object for a set of arrays. You may
sort the arrays multiple times via the same ParallelSorter object.
@param arrays An array of arrays to sort. The arrays may be a mix
of primitive and non-primitive types, but should all be the same
length.
@param loader ClassLoader for generated class, uses "current" if null

Create a new ParallelSorter object for a set of arrays . You may sort the arrays multiple times via the same ParallelSorter object .


public void quickSort(int index, int lo, int hi, Comparator cmp) {
        chooseComparer(index, cmp);
        super.quickSort(lo, hi - 1);
    }

public void quickSort ( int index , int lo , int hi , Comparator cmp ) { chooseComparer ( index , cmp ) ; super . quickSort ( lo , hi - 1 ) ; }

Sort the arrays using the quicksort algorithm.
@param index array (column) to sort by
@param lo starting array index (row), inclusive
@param hi ending array index (row), exclusive
@param cmp Comparator to use if the specified column is non-primitive

Sort the arrays using the quicksort algorithm .


public void mergeSort(int index, int lo, int hi, Comparator cmp) {
        chooseComparer(index, cmp);
        super.mergeSort(lo, hi - 1);
    }

public void mergeSort ( int index , int lo , int hi , Comparator cmp ) { chooseComparer ( index , cmp ) ; super . mergeSort ( lo , hi - 1 ) ; }

Sort the arrays using an in-place merge sort.
@param index array (column) to sort by
@param lo starting array index (row), inclusive
@param hi ending array index (row), exclusive
@param cmp Comparator to use if the specified column is non-primitive

Sort the arrays using an in - place merge sort .


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;
        }
    }

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
;
}
}

Invoke the original method, on a different object of the same type.
@param obj the compatible object; recursion will result if you use the object passed as the first
argument to the MethodInterceptor (usually not what you want)
@param args the arguments passed to the intercepted method; you may substitute a different
argument array as long as the types are compatible
@see MethodInterceptor#intercept
@throws Throwable the bare exceptions thrown by the called method are passed through
without wrapping in an InvocationTargetException

Invoke the original method on a different object of the same type .


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);
                }
            }
        }
    }

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 ) ; } } } }

Casts from one primitive numeric type to another


public void load_arg(int index) {
        load_local(state.argumentTypes[index],
                   state.localOffset + skipArgs(index));
    }

public void load_arg ( int index ) { load_local ( state . argumentTypes [ index ] , state . localOffset + skipArgs ( index ) ) ; }

Pushes the specified argument of the current method onto the stack.
@param index the zero-based index into the argument list

Pushes the specified argument of the current method onto the stack .


void emit_field(int opcode, Type ctype, String name, Type ftype) {
        mv.visitFieldInsn(opcode,
                          ctype.getInternalName(),
                          name,
                          ftype.getDescriptor());
    }

void emit_field ( int opcode , Type ctype , String name , Type ftype ) { mv . visitFieldInsn ( opcode , ctype . getInternalName ( ) , name , ftype . getDescriptor ( ) ) ; }

package-protected for EmitUtils, try to fix

package - protected for EmitUtils try to fix


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();
        }
    }

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 ( ) ; } }

Pushes a zero onto the stack if the argument is a primitive class, or a null otherwise.

Pushes a zero onto the stack if the argument is a primitive class or a null otherwise .


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);
        }
    }

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 ) ; } }

Unboxes the object on the top of the stack. If the object is null, the
unboxed primitive value becomes zero.

Unboxes the object on the top of the stack . If the object is null the unboxed primitive value becomes zero .


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);
    }

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 ) ; }

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.
@param type the type of the array (type.isArray() must be true)
@param callback the callback triggered for each element

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 .


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);
    }

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 ) ; }

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.
@param oneNull label to branch to if only one of the objects is null
@param bothNull label to branch to if both of the objects are null

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 .


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;
    }

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
==
)
{
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
;
}

Finds all bridge methods that are being called with invokespecial &
returns them.

Finds all bridge methods that are being called with invokespecial & returns them .


public static void getMethods(Class superclass, Class[] interfaces, List methods)
    {
        getMethods(superclass, interfaces, methods, null, null);
    }

public static void getMethods ( Class superclass , Class [ ] interfaces , List methods ) { getMethods ( superclass , interfaces , methods , null , null ) ; }

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.
@param superclass the class that will be extended, or null
@param interfaces the list of interfaces that will be implemented, or null
@param methods the list into which to copy the applicable methods

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 .


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);
    }

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
)
;
}

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.
@param sc the superclass
@param constructors the list of all declared constructors from the superclass
@throws IllegalArgumentException if there are no non-private constructors

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 .


public void setSuperclass(Class superclass) {
        if (superclass != null && superclass.equals(Object.class)) {
            superclass = null;
        }
        this.superclass = superclass;
    }

public void setSuperclass ( Class superclass ) { if ( superclass != null && superclass . equals ( Object . class ) ) { superclass = null ; } this . superclass = superclass ; }

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.
@param superclass class to extend, or null to extend Object

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 .


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();
    }

private
void
getField
(
String
[
]
names
)
throws
Exception
{
final
CodeEmitter
e
=
begin_method
(
Constants
.
ACC_PUBLIC
,
PROVIDER_GET
,
)
;
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
(
)
;
}

to avoid JVM hashcode implementation incompatibilities


public void add(Method method) {
        add(ReflectUtils.getSignature(method),
            ReflectUtils.getExceptionTypes(method));
    }

public void add ( Method method ) { add ( ReflectUtils . getSignature ( method ) , ReflectUtils . getExceptionTypes ( method ) ) ; }

Add a method signature to the interface. The method modifiers are ignored,
since interface methods are by definition abstract and public.
@param method the method to add to the interface

Add a method signature to the interface . The method modifiers are ignored since interface methods are by definition abstract and public .


public int cardinality() {
        int w = value;
        int c = 0;
        while (w != 0) {
            c += T[w & 255];
            w >>= 8;
        }
        return c;
    }

public int cardinality ( ) { int w = value ; int c = 0 ; while ( w != 0 ) { c += T [ w & 255 ] ; w >>= 8 ; } return c ; }

If bit 31 is set then this method results in an infinite loop.

@return the number of bits set to true in this TinyBitSet.

If bit 31 is set then this method results in an infinite loop .


public void setNamingPolicy(NamingPolicy namingPolicy) {
        if (namingPolicy == null)
            namingPolicy = DefaultNamingPolicy.INSTANCE;
        this.namingPolicy = namingPolicy;
    }

public void setNamingPolicy ( NamingPolicy namingPolicy ) { if ( namingPolicy == null ) namingPolicy = DefaultNamingPolicy . INSTANCE ; this . namingPolicy = namingPolicy ; }

Override the default naming policy.
@see DefaultNamingPolicy
@param namingPolicy the custom policy, or null to use the default


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;
    }

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
]
==
)
{
// TODO: error?
}
}
return
result
;
}

used by MethodInterceptorGenerated generated code


public static Path resolve(final Path base, String child) {
		if (StringUtil.startsWithChar(child, File.separatorChar)) {
			child = child.substring(1);
		}
		return base.resolve(child);
	}

public static Path resolve ( final Path base , String child ) { if ( StringUtil . startsWithChar ( child , File . separatorChar ) ) { child = child . substring ( 1 ) ; } return base . resolve ( child ) ; }

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.

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 .


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();
		}
	}


public HttpRequest host(final String host) {
		this.host = host;
		if (headers.contains(HEADER_HOST)) {
			headerOverwrite(HEADER_HOST, host);
		}
		return this;
	}

public HttpRequest host ( final String host ) { this . host = host ; if ( headers . contains ( HEADER_HOST ) ) { headerOverwrite ( HEADER_HOST , host ) ; } return this ; }


public static HttpRequest create(final String method, final String destination) {
		return new HttpRequest()
				.method(method.toUpperCase())
				.set(destination);
	}

public static HttpRequest create ( final String method , final String destination ) { return new HttpRequest ( ) . method ( method . toUpperCase ( ) ) . set ( destination ) ; }

Generic request builder, usually used when method is a variable.
Otherwise, use one of the other static request builder methods.

Generic request builder usually used when method is a variable . Otherwise use one of the other static request builder methods .


public static HttpRequest connect(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.CONNECT)
				.set(destination);
	}

public static HttpRequest connect ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . CONNECT ) . set ( destination ) ; }


public static HttpRequest get(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.GET)
				.set(destination);
	}

public static HttpRequest get ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . GET ) . set ( destination ) ; }


public static HttpRequest post(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.POST)
				.set(destination);
	}

public static HttpRequest post ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . POST ) . set ( destination ) ; }


public static HttpRequest put(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.PUT)
				.set(destination);
	}

public static HttpRequest put ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . PUT ) . set ( destination ) ; }


public static HttpRequest patch(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.PATCH)
				.set(destination);
	}

public static HttpRequest patch ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . PATCH ) . set ( destination ) ; }


public static HttpRequest delete(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.DELETE)
				.set(destination);
	}

public static HttpRequest delete ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . DELETE ) . set ( destination ) ; }


public static HttpRequest head(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.HEAD)
				.set(destination);
	}

public static HttpRequest head ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . HEAD ) . set ( destination ) ; }


public static HttpRequest trace(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.TRACE)
				.set(destination);
	}

public static HttpRequest trace ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . TRACE ) . set ( destination ) ; }


public static HttpRequest options(final String destination) {
		return new HttpRequest()
				.method(HttpMethod.OPTIONS)
				.set(destination);
	}

public static HttpRequest options ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . OPTIONS ) . set ( destination ) ; }


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;
	}

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.
@see #query()

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 .


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;
	}

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
!=
&&
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
;
}


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;
	}

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 ; }

Adds many query parameters at once. Although it accepts objects,
each value will be converted to string.

Adds many query parameters at once . Although it accepts objects each value will be converted to string .


public HttpRequest query(final Map<String, String> queryMap) {
		for (Map.Entry<String, String> entry : queryMap.entrySet()) {
			query.add(entry.getKey(), entry.getValue());
		}
		return this;
	}

public HttpRequest query ( final Map < String , String > queryMap ) { for ( Map . Entry < String , String > entry : queryMap . entrySet ( ) ) { query . add ( entry . getKey ( ) , entry . getValue ( ) ) ; } return this ; }

Adds all parameters from the provided map.

Adds all parameters from the provided map .


public HttpRequest queryString(final String queryString, final boolean decode) {
		this.query = HttpUtil.parseQuery(queryString, decode);
		return this;
	}

public HttpRequest queryString ( final String queryString , final boolean decode ) { this . query = HttpUtil . parseQuery ( queryString , decode ) ; return this ; }

Sets query from provided query string. Previous query values
are discarded.

Sets query from provided query string . Previous query values are discarded .


public String queryString() {
		if (query == null) {
			return StringPool.EMPTY;
		}
		return HttpUtil.buildQuery(query, queryEncoding);
	}

public String queryString ( ) { if ( query == null ) { return StringPool . EMPTY ; } return HttpUtil . buildQuery ( query , queryEncoding ) ; }

Generates query string. All values are URL encoded.

Generates query string . All values are URL encoded .


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();
	}

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 ( ) ; }

Returns just host url, without path and query.

Returns just host url without path and query .


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;
	}

public
HttpRequest
basicAuthentication
(
final
String
username
,
final
String
password
)
{
if
(
username
!=
&&
password
!=
)
{
String
data
=
username
.
concat
(
StringPool
.
COLON
)
.
concat
(
password
)
;
String
base64
=
Base64
.
encodeToString
(
data
)
;
headerOverwrite
(
HEADER_AUTHORIZATION
,
"Basic "
+
base64
)
;
}
return
this
;
}

Enables basic authentication by adding required header.

Enables basic authentication by adding required header .


public HttpRequest setHostHeader() {
		String hostPort = this.host;

		if (port != Defaults.DEFAULT_PORT) {
			hostPort += StringPool.COLON + port;
		}

		headerOverwrite(HEADER_HOST, hostPort);
		return this;
	}

public HttpRequest setHostHeader ( ) { String hostPort = this . host ; if ( port != Defaults . DEFAULT_PORT ) { hostPort += StringPool . COLON + port ; } headerOverwrite ( HEADER_HOST , hostPort ) ; return this ; }

Sets 'Host' header from current host and port.

Sets Host header from current host and port .


@Override
	protected Buffer buffer(final boolean fullRequest) {
		// INITIALIZATION

		// host port

		if (header(HEADER_HOST) == null) {
			setHostHeader();
		}

		// form

		Buffer formBuffer = formBuffer();

		// query string

		String queryString = queryString();

		// user-agent

		if (header("User-Agent") == null) {
			header("User-Agent", Defaults.userAgent);
		}

		// POST method requires Content-Type to be set

		if (method.equals("POST") && (contentLength() == null)) {
			contentLength(0);
		}

		// BUILD OUT

		Buffer request = new Buffer();

		request.append(method)
			.append(SPACE)
			.append(path);

		if (query != null && !query.isEmpty()) {
			request.append('?');
			request.append(queryString);
		}

		request.append(SPACE)
			.append(httpVersion)
			.append(CRLF);

		populateHeaderAndBody(request, formBuffer, fullRequest);

		return request;
	}


public <R> R sendAndReceive(final Function<HttpResponse, R> responseHandler) {
		return responseHandler.apply(send());
	}

public < R > R sendAndReceive ( final Function < HttpResponse , R > responseHandler ) { return responseHandler . apply ( send ( ) ) ; }


static Handler removeRange(final Handler firstHandler, final Label start, final Label end) {
    if (firstHandler == null) {
      return null;
    } else {
      firstHandler.nextHandler = removeRange(firstHandler.nextHandler, start, end);
    }
    int handlerStart = firstHandler.startPc.bytecodeOffset;
    int handlerEnd = firstHandler.endPc.bytecodeOffset;
    int rangeStart = start.bytecodeOffset;
    int rangeEnd = end == null ? Integer.MAX_VALUE : end.bytecodeOffset;
    // Return early if [handlerStart,handlerEnd[ and [rangeStart,rangeEnd[ don't intersect.
    if (rangeStart >= handlerEnd || rangeEnd <= handlerStart) {
      return firstHandler;
    }
    if (rangeStart <= handlerStart) {
      if (rangeEnd >= handlerEnd) {
        // If [handlerStart,handlerEnd[ is included in [rangeStart,rangeEnd[, remove firstHandler.
        return firstHandler.nextHandler;
      } else {
        // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [rangeEnd,handlerEnd[
        return new Handler(firstHandler, end, firstHandler.endPc);
      }
    } else if (rangeEnd >= handlerEnd) {
      // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [handlerStart,rangeStart[
      return new Handler(firstHandler, firstHandler.startPc, start);
    } else {
      // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ =
      //     [handlerStart,rangeStart[ + [rangeEnd,handerEnd[
      firstHandler.nextHandler = new Handler(firstHandler, end, firstHandler.endPc);
      return new Handler(firstHandler, firstHandler.startPc, start);
    }
  }

Removes the range between start and end from the Handler list that begins with the given
element.

@param firstHandler the beginning of a Handler list. May be {@literal null}.
@param start the start of the range to be removed.
@param end the end of the range to be removed. Maybe {@literal null}.
@return the exception handler list with the start-end range removed.

Removes the range between start and end from the Handler list that begins with the given element .


static int getExceptionTableLength(final Handler firstHandler) {
    int length = 0;
    Handler handler = firstHandler;
    while (handler != null) {
      length++;
      handler = handler.nextHandler;
    }
    return length;
  }

static int getExceptionTableLength ( final Handler firstHandler ) { int length = 0 ; Handler handler = firstHandler ; while ( handler != null ) { length ++ ; handler = handler . nextHandler ; } return length ; }

Returns the number of elements of the Handler list that begins with the given element.

@param firstHandler the beginning of a Handler list. May be {@literal null}.
@return the number of elements of the Handler list that begins with 'handler'.

Returns the number of elements of the Handler list that begins with the given element .


protected void collectActionInterceptors() {
		final Collection<? extends ActionInterceptor> interceptorValues = interceptorsManager.getAllInterceptors();
		interceptors = new ArrayList<>();
		interceptors.addAll(interceptorValues);
		interceptors.sort(Comparator.comparing(a -> a.getClass().getSimpleName()));
	}

protected void collectActionInterceptors ( ) { final Collection < ? extends ActionInterceptor > interceptorValues = interceptorsManager . getAllInterceptors ( ) ; interceptors = new ArrayList <> ( ) ; interceptors . addAll ( interceptorValues ) ; interceptors . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }


protected void collectActionFilters() {
		final Collection<? extends ActionFilter> filterValues = filtersManager.getAllFilters();
		filters = new ArrayList<>();
		filters.addAll(filterValues);
		filters.sort(Comparator.comparing(a -> a.getClass().getSimpleName()));
	}

protected void collectActionFilters ( ) { final Collection < ? extends ActionFilter > filterValues = filtersManager . getAllFilters ( ) ; filters = new ArrayList <> ( ) ; filters . addAll ( filterValues ) ; filters . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }


protected void collectActionResults() {
		final Collection<ActionResult> resultsValues = resultsManager.getAllActionResults();
		results = new ArrayList<>();
		results.addAll(resultsValues);
		results.sort(Comparator.comparing(a -> a.getClass().getSimpleName()));
	}

protected void collectActionResults ( ) { final Collection < ActionResult > resultsValues = resultsManager . getAllActionResults ( ) ; results = new ArrayList <> ( ) ; results . addAll ( resultsValues ) ; results . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }


protected void collectActionRuntimes() {
		actions = actionsManager.getAllActionRuntimes();
		actions.sort(Comparator.comparing(ActionRuntime::getActionPath));
	}

protected void collectActionRuntimes ( ) { actions = actionsManager . getAllActionRuntimes ( ) ; actions . sort ( Comparator . comparing ( ActionRuntime :: getActionPath ) ) ; }

Collects all action runtime configurations.

Collects all action runtime configurations .


@SuppressWarnings({"unchecked"})
	protected void setSimpleProperty(final BeanProperty bp, final Object value) {
		Setter setter = bp.getSetter(isDeclared);

		// try: setter
		if (setter != null) {
			invokeSetter(setter, bp, value);
			return;
		}

		// try: put("property", value)
		if (bp.isMap()) {
			((Map) bp.bean).put(bp.name, value);
			return;
		}
		if (isSilent) {
			return;
		}
		throw new BeanException("Simple property not found: " + bp.name, bp);
	}

@
SuppressWarnings
(
{
"unchecked"
}
)
protected
void
setSimpleProperty
(
final
BeanProperty
bp
,
final
Object
value
)
{
Setter
setter
=
bp
.
getSetter
(
isDeclared
)
;
// try: setter
if
(
setter
!=
)
{
invokeSetter
(
setter
,
bp
,
value
)
;
return
;
}
// try: put("property", value)
if
(
bp
.
isMap
(
)
)
{
(
(
Map
)
bp
.
bean
)
.
put
(
bp
.
name
,
value
)
;
return
;
}
if
(
isSilent
)
{
return
;
}
throw
new
BeanException
(
"Simple property not found: "
+
bp
.
name
,
bp
)
;
}


@Override
	public <T> T getProperty(final Object bean, final String name) {
		BeanProperty beanProperty = new BeanProperty(this, bean, name);
		if (!isSilent) {
			resolveNestedProperties(beanProperty);
			return (T) getIndexProperty(beanProperty);
		}
		else {
			try {
				resolveNestedProperties(beanProperty);
				return (T) getIndexProperty(beanProperty);
			}
			catch (Exception ignore) {
				return null;
			}
		}
	}

@ Override public < T > T getProperty ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! isSilent ) { resolveNestedProperties ( beanProperty ) ; return ( T ) getIndexProperty ( beanProperty ) ; } else { try { resolveNestedProperties ( beanProperty ) ; return ( T ) getIndexProperty ( beanProperty ) ; } catch ( Exception ignore ) { return null ; } } }


@Override
	public String extractThisReference(final String propertyName) {
		int ndx = StringUtil.indexOfChars(propertyName, INDEX_CHARS);
		if (ndx == -1) {
			return propertyName;
		}
		return propertyName.substring(0, ndx);
	}

@ Override public String extractThisReference ( final String propertyName ) { int ndx = StringUtil . indexOfChars ( propertyName , INDEX_CHARS ) ; if ( ndx == - 1 ) { return propertyName ; } return propertyName . substring ( 0 , ndx ) ; }

Extract the first name of this reference.

Extract the first name of this reference .


@Override
	public PrintWriter getWriter() {
		if (writer == null) {
			writer = new FastCharArrayWriter();
			printWriter = new PrintWriter(writer);
		}
		return printWriter;
	}

@ Override public PrintWriter getWriter ( ) { if ( writer == null ) { writer = new FastCharArrayWriter ( ) ; printWriter = new PrintWriter ( writer ) ; } return printWriter ; }

Returns buffered writer. Buffer will be created if not already used.

Returns buffered writer . Buffer will be created if not already used .


public void setObjectReference(final String name, final Object object) {
		if (objectRefs == null) {
			objectRefs = new HashMap<>();
		}
		objectRefs.put(name, object);
	}

public void setObjectReference ( final String name , final Object object ) { if ( objectRefs == null ) { objectRefs = new HashMap <> ( ) ; } objectRefs . put ( name , object ) ; }


public Object getObjectReference(final String name) {
		if (objectRefs == null) {
			return null;
		}
		return objectRefs.get(name);
	}

public Object getObjectReference ( final String name ) { if ( objectRefs == null ) { return null ; } return objectRefs . get ( name ) ; }


public Object lookupObject(final String ref) {
		Object value = getObjectReference(ref);
		if (value == null) {
			throw new DbSqlBuilderException("Invalid object reference: " + ref);
		}
		return value;
	}

public
Object
lookupObject
(
final
String
ref
)
{
Object
value
=
getObjectReference
(
ref
)
;
if
(
value
==
)
{
throw
new
DbSqlBuilderException
(
"Invalid object reference: "
+
ref
)
;
}
return
value
;
}

Lookups for object reference and throws an exception if reference doesn't exist.

Lookups for object reference and throws an exception if reference doesn t exist .


public DbEntityDescriptor getTableDescriptor(final String tableRef) {
		if (tableRefs == null) {
			return null;
		}
		TableRefData t = tableRefs.get(tableRef);
		return t == null ? null : t.desc;
	}

public DbEntityDescriptor getTableDescriptor ( final String tableRef ) { if ( tableRefs == null ) { return null ; } TableRefData t = tableRefs . get ( tableRef ) ; return t == null ? null : t . desc ; }

Returns entity descriptor for provided table reference.

Returns entity descriptor for provided table reference .


public DbEntityDescriptor findTableDescriptorByColumnRef(final String columnRef) {
		for (Map.Entry<String, TableRefData> entry : tableRefs.entrySet()) {
			DbEntityDescriptor ded = entry.getValue().desc;

			if (ded.findByPropertyName(columnRef) != null) {
				return ded;
			}
		}
		return null;
	}

public DbEntityDescriptor findTableDescriptorByColumnRef ( final String columnRef ) { for ( Map . Entry < String , TableRefData > entry : tableRefs . entrySet ( ) ) { DbEntityDescriptor ded = entry . getValue ( ) . desc ; if ( ded . findByPropertyName ( columnRef ) != null ) { return ded ; } } return null ; }

Finds entity descriptor of a table that contains provided column reference.

Finds entity descriptor of a table that contains provided column reference .


public String getTableAlias(final String tableRef) {
		if (tableRefs == null) {
			return null;
		}
		TableRefData t = tableRefs.get(tableRef);
		return t == null ? null : t.alias;
	}

public String getTableAlias ( final String tableRef ) { if ( tableRefs == null ) { return null ; } TableRefData t = tableRefs . get ( tableRef ) ; return t == null ? null : t . alias ; }

Returns table alias for provided table reference.

Returns table alias for provided table reference .


public void registerTableReference(final String tableReference, final DbEntityDescriptor ded, final String tableAlias) {
		if (tableRefs == null) {
			tableRefs = new HashMap<>();
		}
		TableRefData t = new TableRefData(ded, tableAlias);
		if (tableRefs.put(tableReference, t) != null) {
			throw new DbSqlBuilderException("Duplicated table reference: " + tableReference);
		}
	}

public
void
registerTableReference
(
final
String
tableReference
,
final
DbEntityDescriptor
ded
,
final
String
tableAlias
)
{
if
(
tableRefs
==
)
{
tableRefs
=
new
HashMap
<>
(
)
;
}
TableRefData
t
=
new
TableRefData
(
ded
,
tableAlias
)
;
if
(
tableRefs
.
put
(
tableReference
,
t
)
!=
)
{
throw
new
DbSqlBuilderException
(
"Duplicated table reference: "
+
tableReference
)
;
}
}

Registers table reference for provided entity.

Registers table reference for provided entity .


protected DbEntityDescriptor lookupTableRef(final String tableRef) {
		DbEntityDescriptor ded = getTableDescriptor(tableRef);
		if (ded == null) {
			throw new DbSqlBuilderException("Table reference not used in this query: " + tableRef);
		}
		return ded;
	}

Lookups for table reference and throws an exception if table reference not found.

Lookups for table reference and throws an exception if table reference not found .


public void registerHint(final String hint) {
		if (hints == null) {
			hints = new ArrayList<>(hintCount);
		}
		hints.add(hint);
	}

public void registerHint ( final String hint ) { if ( hints == null ) { hints = new ArrayList <> ( hintCount ) ; } hints . add ( hint ) ; }


@Override
	public final boolean serialize(final JsonContext jsonContext, final T value) {
		if (jsonContext.pushValue(value)) {
			// prevent circular dependencies
			return false;
		}

		serializeValue(jsonContext, value);

		jsonContext.popValue();

		return true;
	}

@
Override
public
final
boolean
serialize
(
final
JsonContext
jsonContext
,
final
T
value
)
{
if
(
jsonContext
.
pushValue
(
value
)
)
{
// prevent circular dependencies
return
false
;
}
serializeValue
(
jsonContext
,
value
)
;
jsonContext
.
popValue
(
)
;
return
true
;
}

Detects circular dependencies and pushes value as current
type context.

Detects circular dependencies and pushes value as current type context .


protected void injectAttributes(final HttpServletRequest servletRequest, final Targets targets) {
		final Enumeration<String> attributeNames = servletRequest.getAttributeNames();
		while (attributeNames.hasMoreElements()) {
			final String attrName = attributeNames.nextElement();

			targets.forEachTargetAndIn(this, (target, in) -> {
				final String name = in.matchedName(attrName);
				if (name != null) {
					final Object attrValue = servletRequest.getAttribute(attrName);
					target.writeValue(name, attrValue, true);
				}
			});
		}
	}

protected void injectAttributes ( final HttpServletRequest servletRequest , final Targets targets ) { final Enumeration < String > attributeNames = servletRequest . getAttributeNames ( ) ; while ( attributeNames . hasMoreElements ( ) ) { final String attrName = attributeNames . nextElement ( ) ; targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( attrName ) ; if ( name != null ) { final Object attrValue = servletRequest . getAttribute ( attrName ) ; target . writeValue ( name , attrValue , true ) ; } } ) ; } }


protected void injectParameters(final HttpServletRequest servletRequest, final Targets targets) {
		final boolean encode = encodeGetParams && servletRequest.getMethod().equals("GET");
		final Enumeration<String> paramNames = servletRequest.getParameterNames();

		while (paramNames.hasMoreElements()) {
			final String paramName = paramNames.nextElement();
			if (servletRequest.getAttribute(paramName) != null) {
				continue;
			}

			targets.forEachTargetAndIn(this, (target, in) -> {
				final String name = in.matchedName(paramName);
				if (name != null) {
					String[] paramValues = servletRequest.getParameterValues(paramName);

					paramValues = ServletUtil.prepareParameters(
						paramValues, treatEmptyParamsAsNull, ignoreEmptyRequestParams);

					if (paramValues != null) {
						if (encode) {
							for (int j = 0; j < paramValues.length; j++) {
								final String p = paramValues[j];
								if (p != null) {
									final String encoding = madvocEncoding.getEncoding();
									paramValues[j] = StringUtil.convertCharset(p, StringPool.ISO_8859_1, encoding);
								}
							}
						}
						final Object value = (paramValues.length != 1 ? paramValues : paramValues[0]);
						target.writeValue(name, value, true);
					}
				}
			});
		}
	}

protected void injectParameters ( final HttpServletRequest servletRequest , final Targets targets ) { final boolean encode = encodeGetParams && servletRequest . getMethod ( ) . equals ( "GET" ) ; final Enumeration < String > paramNames = servletRequest . getParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { final String paramName = paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( paramName ) ; if ( name != null ) { String [ ] paramValues = servletRequest . getParameterValues ( paramName ) ; paramValues = ServletUtil . prepareParameters ( paramValues , treatEmptyParamsAsNull , ignoreEmptyRequestParams ) ; if ( paramValues != null ) { if ( encode ) { for ( int j = 0 ; j < paramValues . length ; j ++ ) { final String p = paramValues [ j ] ; if ( p != null ) { final String encoding = madvocEncoding . getEncoding ( ) ; paramValues [ j ] = StringUtil . convertCharset ( p , StringPool . ISO_8859_1 , encoding ) ; } } } final Object value = ( paramValues . length != 1 ? paramValues : paramValues [ 0 ] ) ; target . writeValue ( name , value , true ) ; } } } ) ; } }


protected void injectUploadedFiles(final HttpServletRequest servletRequest, final Targets targets) {
		if (!(servletRequest instanceof MultipartRequestWrapper)) {
			return;
		}
		final MultipartRequestWrapper multipartRequest = (MultipartRequestWrapper) servletRequest;
		if (!multipartRequest.isMultipart()) {
			return;
		}
		final Enumeration<String> paramNames = multipartRequest.getFileParameterNames();
		while (paramNames.hasMoreElements()) {
			final String paramName = paramNames.nextElement();
			if (servletRequest.getAttribute(paramName) != null) {
				continue;
			}

			targets.forEachTargetAndIn(this, (target, in) -> {
				final String name = in.matchedName(paramName);
				if (name != null) {
					final FileUpload[] paramValues = multipartRequest.getFiles(paramName);

					if (ignoreInvalidUploadFiles) {
						for (int j = 0; j < paramValues.length; j++) {
							final FileUpload paramValue = paramValues[j];

							if ((!paramValue.isValid()) || (!paramValue.isUploaded())) {
								paramValues[j] = null;
							}
						}
					}

					final Object value = (paramValues.length == 1 ? paramValues[0] : paramValues);
					target.writeValue(name, value, true);
				}
			});
		}
	}

protected void injectUploadedFiles ( final HttpServletRequest servletRequest , final Targets targets ) { if ( ! ( servletRequest instanceof MultipartRequestWrapper ) ) { return ; } final MultipartRequestWrapper multipartRequest = ( MultipartRequestWrapper ) servletRequest ; if ( ! multipartRequest . isMultipart ( ) ) { return ; } final Enumeration < String > paramNames = multipartRequest . getFileParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { final String paramName = paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( paramName ) ; if ( name != null ) { final FileUpload [ ] paramValues = multipartRequest . getFiles ( paramName ) ; if ( ignoreInvalidUploadFiles ) { for ( int j = 0 ; j < paramValues . length ; j ++ ) { final FileUpload paramValue = paramValues [ j ] ; if ( ( ! paramValue . isValid ( ) ) || ( ! paramValue . isUploaded ( ) ) ) { paramValues [ j ] = null ; } } } final Object value = ( paramValues . length == 1 ? paramValues [ 0 ] : paramValues ) ; target . writeValue ( name , value , true ) ; } } ) ; } }

Inject uploaded files from multipart request parameters.

Inject uploaded files from multipart request parameters .


public String convertPropertyNameToColumnName(final String propertyName) {
		StringBuilder tableName = new StringBuilder(propertyName.length() * 2);

		if (splitCamelCase) {
			String convertedTableName = Format.fromCamelCase(propertyName, separatorChar);
			tableName.append(convertedTableName);
		} else {
			tableName.append(propertyName);
		}

		if (!changeCase) {
			return tableName.toString();
		}
		return uppercase ?
				toUppercase(tableName).toString() :
				toLowercase(tableName).toString();

	}

public String convertPropertyNameToColumnName ( final String propertyName ) { StringBuilder tableName = new StringBuilder ( propertyName . length ( ) * 2 ) ; if ( splitCamelCase ) { String convertedTableName = Format . fromCamelCase ( propertyName , separatorChar ) ; tableName . append ( convertedTableName ) ; } else { tableName . append ( propertyName ) ; } if ( ! changeCase ) { return tableName . toString ( ) ; } return uppercase ? toUppercase ( tableName ) . toString ( ) : toLowercase ( tableName ) . toString ( ) ; }


public String convertColumnNameToPropertyName(final String columnName) {
		StringBuilder propertyName = new StringBuilder(columnName.length());
		int len = columnName.length();

		if (splitCamelCase) {
			boolean toUpper = false;
			for (int i = 0; i < len; i++) {
				char c = columnName.charAt(i);
				if (c == separatorChar) {
					toUpper = true;
					continue;
				}
				if (toUpper) {
					propertyName.append(Character.toUpperCase(c));
					toUpper = false;
				} else {
					propertyName.append(Character.toLowerCase(c));
				}
			}
			return propertyName.toString();
		}
		return columnName;
	}

public String convertColumnNameToPropertyName ( final String columnName ) { StringBuilder propertyName = new StringBuilder ( columnName . length ( ) ) ; int len = columnName . length ( ) ; if ( splitCamelCase ) { boolean toUpper = false ; for ( int i = 0 ; i < len ; i ++ ) { char c = columnName . charAt ( i ) ; if ( c == separatorChar ) { toUpper = true ; continue ; } if ( toUpper ) { propertyName . append ( Character . toUpperCase ( c ) ) ; toUpper = false ; } else { propertyName . append ( Character . toLowerCase ( c ) ) ; } } return propertyName . toString ( ) ; } return columnName ; }


public String applyToColumnName(final String columnName) {
		String propertyName = convertColumnNameToPropertyName(columnName);

		return convertPropertyNameToColumnName(propertyName);
	}

public String applyToColumnName ( final String columnName ) { String propertyName = convertColumnNameToPropertyName ( columnName ) ; return convertPropertyNameToColumnName ( propertyName ) ; }

Applies column naming strategy to given column name hint.
Returns full column name.

Applies column naming strategy to given column name hint . Returns full column name .


public void storeValue(final PreparedStatement st, final int index, final Object value, final int dbSqlType) throws SQLException {
		T t = TypeConverterManager.get().convertType(value, sqlType);
		set(st, index, t, dbSqlType);
	}

public void storeValue ( final PreparedStatement st , final int index , final Object value , final int dbSqlType ) throws SQLException { T t = TypeConverterManager . get ( ) . convertType ( value , sqlType ) ; set ( st , index , t , dbSqlType ) ; }

Stores value in database. Value is casted to sql type.

Stores value in database . Value is casted to sql type .