private boolean doRead(SelectionKey key, Iterator<SelectionKey> i) throws InterruptedException, IOException {
		WebSocketImpl conn = (WebSocketImpl) key.attachment();
		ByteBuffer buf = takeBuffer();
		if(conn.getChannel() == null){
			key.cancel();

			handleIOException( key, conn, new IOException() );
			return false;
		}
		try {
			if( SocketChannelIOHelper.read( buf, conn, conn.getChannel() ) ) {
				if( buf.hasRemaining() ) {
					conn.inQueue.put( buf );
					queue( conn );
					i.remove();
					if( conn.getChannel() instanceof WrappedByteChannel && ( (WrappedByteChannel) conn.getChannel() ).isNeedRead() ) {
						iqueue.add( conn );
					}
				} else {
					pushBuffer(buf);
				}
			} else {
				pushBuffer( buf );
			}
		} catch ( IOException e ) {
			pushBuffer( buf );
			throw e;
		}
		return true;
	}

private boolean doRead ( SelectionKey key , Iterator < SelectionKey > i ) throws InterruptedException , IOException { WebSocketImpl conn = ( WebSocketImpl ) key . attachment ( ) ; ByteBuffer buf = takeBuffer ( ) ; if ( conn . getChannel ( ) == null ) { key . cancel ( ) ; handleIOException ( key , conn , new IOException ( ) ) ; return false ; } try { if ( SocketChannelIOHelper . read ( buf , conn , conn . getChannel ( ) ) ) { if ( buf . hasRemaining ( ) ) { conn . inQueue . put ( buf ) ; queue ( conn ) ; i . remove ( ) ; if ( conn . getChannel ( ) instanceof WrappedByteChannel && ( ( WrappedByteChannel ) conn . getChannel ( ) ) . isNeedRead ( ) ) { iqueue . add ( conn ) ; } } else { pushBuffer ( buf ) ; } } else { pushBuffer ( buf ) ; } } catch ( IOException e ) { pushBuffer ( buf ) ; throw e ; } return true ; }

Execute a read operation
@param key the selectionkey to read off
@param i the iterator for the selection keys
@return true, if the read was successful, or false if there was an error
@throws InterruptedException thrown by taking a buffer
@throws IOException if an error happened during read


private void doWrite(SelectionKey key) throws IOException {
		WebSocketImpl conn = (WebSocketImpl) key.attachment();
		if( SocketChannelIOHelper.batch( conn, conn.getChannel() ) ) {
			if( key.isValid() ) {
				key.interestOps(SelectionKey.OP_READ);
			}
		}
	}

private void doWrite ( SelectionKey key ) throws IOException { WebSocketImpl conn = ( WebSocketImpl ) key . attachment ( ) ; if ( SocketChannelIOHelper . batch ( conn , conn . getChannel ( ) ) ) { if ( key . isValid ( ) ) { key . interestOps ( SelectionKey . OP_READ ) ; } } }

Execute a write operation
@param key the selectionkey to write on
@throws IOException if an error happened during batch


private boolean doSetupSelectorAndServerThread() {
		selectorthread.setName( "WebSocketSelector-" + selectorthread.getId() );
		try {
			server = ServerSocketChannel.open();
			server.configureBlocking( false );
			ServerSocket socket = server.socket();
			socket.setReceiveBufferSize( WebSocketImpl.RCVBUF );
			socket.setReuseAddress( isReuseAddr() );
			socket.bind( address );
			selector = Selector.open();
			server.register( selector, server.validOps() );
			startConnectionLostTimer();
			for( WebSocketWorker ex : decoders ){
				ex.start();
			}
			onStart();
		} catch ( IOException ex ) {
			handleFatal( null, ex );
			return false;
		}
		return true;
	}

private boolean doSetupSelectorAndServerThread ( ) { selectorthread . setName ( "WebSocketSelector-" + selectorthread . getId ( ) ) ; try { server = ServerSocketChannel . open ( ) ; server . configureBlocking ( false ) ; ServerSocket socket = server . socket ( ) ; socket . setReceiveBufferSize ( WebSocketImpl . RCVBUF ) ; socket . setReuseAddress ( isReuseAddr ( ) ) ; socket . bind ( address ) ; selector = Selector . open ( ) ; server . register ( selector , server . validOps ( ) ) ; startConnectionLostTimer ( ) ; for ( WebSocketWorker ex : decoders ) { ex . start ( ) ; } onStart ( ) ; } catch ( IOException ex ) { handleFatal ( null , ex ) ; return false ; } return true ; }

Setup the selector thread as well as basic server settings
@return true, if everything was successful, false if some error happened


private boolean doEnsureSingleThread() {
		synchronized ( this ) {
			if( selectorthread != null )
				throw new IllegalStateException( getClass().getName() + " can only be started once." );
			selectorthread = Thread.currentThread();
			if( isclosed.get() ) {
				return false;
			}
		}
		return true;
	}

private
boolean
doEnsureSingleThread
(
)
{
synchronized
(
this
)
{
if
(
selectorthread
!=
)
throw
new
IllegalStateException
(
getClass
(
)
.
getName
(
)
+
" can only be started once."
)
;
selectorthread
=
Thread
.
currentThread
(
)
;
if
(
isclosed
.
get
(
)
)
{
return
false
;
}
}
return
true
;
}

The websocket server can only be started once
@return true, if the server can be started, false if already a thread is running


private void doServerShutdown() {
		stopConnectionLostTimer();
		if( decoders != null ) {
			for( WebSocketWorker w : decoders ) {
				w.interrupt();
			}
		}
		if( selector != null ) {
			try {
				selector.close();
			} catch ( IOException e ) {
				log.error( "IOException during selector.close", e );
				onError( null, e );
			}
		}
		if( server != null ) {
			try {
				server.close();
			} catch ( IOException e ) {
				log.error( "IOException during server.close", e );
				onError( null, e );
			}
		}
	}

private
void
doServerShutdown
(
)
{
stopConnectionLostTimer
(
)
;
if
(
decoders
!=
)
{
for
(
WebSocketWorker
w
:
decoders
)
{
w
.
interrupt
(
)
;
}
}
if
(
selector
!=
)
{
try
{
selector
.
close
(
)
;
}
catch
(
IOException
e
)
{
log
.
error
(
"IOException during selector.close"
,
e
)
;
onError
(
,
e
)
;
}
}
if
(
server
!=
)
{
try
{
server
.
close
(
)
;
}
catch
(
IOException
e
)
{
log
.
error
(
"IOException during server.close"
,
e
)
;
onError
(
,
e
)
;
}
}
}


private Socket getSocket( WebSocket conn ) {
		WebSocketImpl impl = (WebSocketImpl) conn;
		return ( (SocketChannel) impl.getSelectionKey().channel() ).socket();
	}

private Socket getSocket ( WebSocket conn ) { WebSocketImpl impl = ( WebSocketImpl ) conn ; return ( ( SocketChannel ) impl . getSelectionKey ( ) . channel ( ) ) . socket ( ) ; }

Getter to return the socket used by this specific connection
@param conn The specific connection
@return The socket used by this connection


public void broadcast(byte[] data, Collection<WebSocket> clients) {
		if (data == null || clients == null) {
			throw new IllegalArgumentException();
		}
		broadcast(ByteBuffer.wrap(data), clients);
	}

public void broadcast ( byte [ ] data , Collection < WebSocket > clients ) { if ( data == null || clients == null ) { throw new IllegalArgumentException ( ) ; } broadcast ( ByteBuffer . wrap ( data ) , clients ) ; }

Send a byte array to a specific collection of websocket connections
@param data the data to send to the endpoints
@param clients a collection of endpoints to whom the text has to be send


public void broadcast(String text, Collection<WebSocket> clients) {
		if (text == null || clients == null) {
			throw new IllegalArgumentException();
		}
		doBroadcast(text, clients);
	}

public void broadcast ( String text , Collection < WebSocket > clients ) { if ( text == null || clients == null ) { throw new IllegalArgumentException ( ) ; } doBroadcast ( text , clients ) ; }

Send a text to a specific collection of websocket connections
@param text the text to send to the endpoints
@param clients a collection of endpoints to whom the text has to be send


private void doBroadcast(Object data, Collection<WebSocket> clients) {
		String sData = null;
		if (data instanceof String) {
			sData = (String)data;
		}
		ByteBuffer bData = null;
		if (data instanceof ByteBuffer) {
			bData = (ByteBuffer)data;
		}
		if (sData == null && bData == null) {
			return;
		}
		Map<Draft, List<Framedata>> draftFrames = new HashMap<Draft, List<Framedata>>();
		for( WebSocket client : clients ) {
			if( client != null ) {
				Draft draft = client.getDraft();
				fillFrames(draft, draftFrames, sData, bData);
				try {
					client.sendFrame( draftFrames.get( draft ) );
				} catch ( WebsocketNotConnectedException e ) {
					//Ignore this exception in this case
				}
			}
		}
	}

private
void
doBroadcast
(
Object
data
,
Collection
<
WebSocket
>
clients
)
{
String
sData
=
;
if
(
data
instanceof
String
)
{
sData
=
(
String
)
data
;
}
ByteBuffer
bData
=
;
if
(
data
instanceof
ByteBuffer
)
{
bData
=
(
ByteBuffer
)
data
;
}
if
(
sData
==
&&
bData
==
)
{
return
;
}
Map
<
Draft
,
List
<
Framedata
>
>
draftFrames
=
new
HashMap
<
Draft
,
List
<
Framedata
>
>
(
)
;
for
(
WebSocket
client
:
clients
)
{
if
(
client
!=
)
{
Draft
draft
=
client
.
getDraft
(
)
;
fillFrames
(
draft
,
draftFrames
,
sData
,
bData
)
;
try
{
client
.
sendFrame
(
draftFrames
.
get
(
draft
)
)
;
}
catch
(
WebsocketNotConnectedException
e
)
{
//Ignore this exception in this case
}
}
}
}

Private method to cache all the frames to improve memory footprint and conversion time
@param data the data to broadcast
@param clients the clients to send the message to


private void fillFrames(Draft draft, Map<Draft, List<Framedata>> draftFrames, String sData, ByteBuffer bData) {
		if( !draftFrames.containsKey( draft ) ) {
			List<Framedata> frames = null;
			if (sData != null) {
				frames = draft.createFrames( sData, false );
			}
			if (bData != null) {
				frames = draft.createFrames( bData, false );
			}
			if (frames != null) {
				draftFrames.put(draft, frames);
			}
		}
	}

private void fillFrames ( Draft draft , Map < Draft , List < Framedata > > draftFrames , String sData , ByteBuffer bData ) { if ( ! draftFrames . containsKey ( draft ) ) { List < Framedata > frames = null ; if ( sData != null ) { frames = draft . createFrames ( sData , false ) ; } if ( bData != null ) { frames = draft . createFrames ( bData , false ) ; } if ( frames != null ) { draftFrames . put ( draft , frames ) ; } } }

Fills the draftFrames with new data for the broadcast
@param draft The draft to use
@param draftFrames The list of frames per draft to fill
@param sData the string data, can be null
@param bData the bytebuffer data, can be null


public static int transferByteBuffer( ByteBuffer source, ByteBuffer dest ) {
		if( source == null || dest == null ) {
			throw new IllegalArgumentException();
		}
		int fremain = source.remaining();
		int toremain = dest.remaining();
		if( fremain > toremain ) {
			int limit = Math.min( fremain, toremain );
			source.limit( limit );
			dest.put( source );
			return limit;
		} else {
			dest.put( source );
			return fremain;
		}
	}

public static int transferByteBuffer ( ByteBuffer source , ByteBuffer dest ) { if ( source == null || dest == null ) { throw new IllegalArgumentException ( ) ; } int fremain = source . remaining ( ) ; int toremain = dest . remaining ( ) ; if ( fremain > toremain ) { int limit = Math . min ( fremain , toremain ) ; source . limit ( limit ) ; dest . put ( source ) ; return limit ; } else { dest . put ( source ) ; return fremain ; } }

Transfer from one ByteBuffer to another ByteBuffer

@param source the ByteBuffer to copy from
@param dest   the ByteBuffer to copy to
@return the number of transferred bytes


public JPAApi start() {
    jpaConfig
        .persistenceUnits()
        .forEach(
            persistenceUnit ->
                emfs.put(
                    persistenceUnit.name,
                    Persistence.createEntityManagerFactory(persistenceUnit.unitName)));
    return this;
  }

public JPAApi start ( ) { jpaConfig . persistenceUnits ( ) . forEach ( persistenceUnit -> emfs . put ( persistenceUnit . name , Persistence . createEntityManagerFactory ( persistenceUnit . unitName ) ) ) ; return this ; }

Initialise JPA entity manager factories.

Initialise JPA entity manager factories .


public EntityManager em(String name) {
    EntityManagerFactory emf = emfs.get(name);
    if (emf == null) {
      return null;
    }
    return emf.createEntityManager();
  }

public EntityManager em ( String name ) { EntityManagerFactory emf = emfs . get ( name ) ; if ( emf == null ) { return null ; } return emf . createEntityManager ( ) ; }

Get a newly created EntityManager for the specified persistence unit name.

@param name The persistence unit name

Get a newly created EntityManager for the specified persistence unit name .


public void withTransaction(Consumer<EntityManager> block) {
    withTransaction(
        em -> {
          block.accept(em);
          return null;
        });
  }

public void withTransaction ( Consumer < EntityManager > block ) { withTransaction ( em -> { block . accept ( em ) ; return null ; } ) ; }

Run a block of code with a newly created EntityManager for the default Persistence Unit.

@param block Block of code to execute

Run a block of code with a newly created EntityManager for the default Persistence Unit .


private static Seq<Object> convertArgsToScalaBuffer(final Object... args) {
    return scala.collection.JavaConverters.asScalaBufferConverter(wrapArgsToListIfNeeded(args))
        .asScala()
        .toList();
  }

private static Seq < Object > convertArgsToScalaBuffer ( final Object ... args ) { return scala . collection . JavaConverters . asScalaBufferConverter ( wrapArgsToListIfNeeded ( args ) ) . asScala ( ) . toList ( ) ; }

Converts the varargs to a scala buffer, takes care of wrapping varargs into a intermediate list
if necessary

@param args the message arguments
@return scala type for message processing

Converts the varargs to a scala buffer takes care of wrapping varargs into a intermediate list if necessary


@SafeVarargs
  private static <T> List<T> wrapArgsToListIfNeeded(final T... args) {
    List<T> out;
    if (args != null && args.length == 1 && args[0] instanceof List) {
      out = (List<T>) args[0];
    } else {
      out = Arrays.asList(args);
    }
    return out;
  }

@ SafeVarargs private static < T > List < T > wrapArgsToListIfNeeded ( final T ... args ) { List < T > out ; if ( args != null && args . length == 1 && args [ 0 ] instanceof List ) { out = ( List < T > ) args [ 0 ] ; } else { out = Arrays . asList ( args ) ; } return out ; }

Wraps arguments passed into a list if necessary.

<p>Returns the first value as is if it is the only argument and a subtype of `java.util.List`
Otherwise, it calls Arrays.asList on args

@param args arguments as a List

Wraps arguments passed into a list if necessary .


public String get(play.api.i18n.Lang lang, String key, Object... args) {
    Seq<Object> scalaArgs = convertArgsToScalaBuffer(args);
    return messages.apply(key, scalaArgs, lang);
  }

public String get ( play . api . i18n . Lang lang , String key , Object ... args ) { Seq < Object > scalaArgs = convertArgsToScalaBuffer ( args ) ; return messages . apply ( key , scalaArgs , lang ) ; }

Translates a message.

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

@param lang the message lang
@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 get(play.api.i18n.Lang lang, List<String> keys, Object... args) {
    Buffer<String> keyArgs = scala.collection.JavaConverters.asScalaBufferConverter(keys).asScala();
    Seq<Object> scalaArgs = convertArgsToScalaBuffer(args);
    return messages.apply(keyArgs.toSeq(), scalaArgs, lang);
  }

public String get ( play . api . i18n . Lang lang , List < String > keys , Object ... args ) { Buffer < String > keyArgs = scala . collection . JavaConverters . asScalaBufferConverter ( keys ) . asScala ( ) ; Seq < Object > scalaArgs = convertArgsToScalaBuffer ( args ) ; return messages . apply ( keyArgs . toSeq ( ) , scalaArgs , lang ) ; }

Translates the first defined message.

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

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


public Boolean isDefinedAt(play.api.i18n.Lang lang, String key) {
    return messages.isDefinedAt(key, lang);
  }

public Boolean isDefinedAt ( play . api . i18n . Lang lang , String key ) { return messages . isDefinedAt ( key , lang ) ; }

Check if a message key is defined.

@param lang the message lang
@param key the message key
@return a Boolean


public Messages preferred(Collection<Lang> candidates) {
    Seq<Lang> cs = Scala.asScala(candidates);
    play.api.i18n.Messages msgs = messages.preferred((Seq) cs);
    return new MessagesImpl(new Lang(msgs.lang()), this);
  }

public Messages preferred ( Collection < Lang > candidates ) { Seq < Lang > cs = Scala . asScala ( candidates ) ; play . api . i18n . Messages msgs = messages . preferred ( ( Seq ) cs ) ; return new MessagesImpl ( new Lang ( msgs . lang ( ) ) , this ) ; }

Get a messages context appropriate for the given candidates.

<p>Will select a language from the candidates, based on the languages available, and fallback
to the default language if none of the candidates are available.

@param candidates the candidate languages
@return the most appropriate Messages instance given the candidate languages

Get a messages context appropriate for the given candidates .


public Messages preferred(Http.RequestHeader request) {
    play.api.i18n.Messages msgs = messages.preferred(request);
    return new MessagesImpl(new Lang(msgs.lang()), this);
  }

public Messages preferred ( Http . RequestHeader request ) { play . api . i18n . Messages msgs = messages . preferred ( request ) ; return new MessagesImpl ( new Lang ( msgs . lang ( ) ) , this ) ; }

Get a messages context appropriate for the given request.

<p>Will select a language from the request, based on the languages available, and fallback to
the default language if none of the candidates are available.

@param request the incoming request
@return the preferred messages context for the request

Get a messages context appropriate for the given request .


public Result setLang(Result result, Lang lang) {
    return messages.setLang(result.asScala(), lang).asJava();
  }

public Result setLang ( Result result , Lang lang ) { return messages . setLang ( result . asScala ( ) , lang ) . asJava ( ) ; }

Given a Result and a Lang, return a new Result with the lang cookie set to the given Lang.

@param result the result where the lang will be set.
@param lang the lang to set on the result
@return a new result with the lang.

Given a Result and a Lang return a new Result with the lang cookie set to the given Lang .


public final Self bindings(GuiceableModule... modules) {
    return newBuilder(delegate.bindings(Scala.varargs(modules)));
  }

public final Self bindings ( GuiceableModule ... modules ) { return newBuilder ( delegate . bindings ( Scala . varargs ( modules ) ) ) ; }

Add bindings from guiceable modules.

@param modules the set of modules to bind
@return a copy of this builder configured with those modules


public final Self bindings(play.api.inject.Module... modules) {
    return bindings(Guiceable.modules(modules));
  }

public final Self bindings ( play . api . inject . Module ... modules ) { return bindings ( Guiceable . modules ( modules ) ) ; }

Add bindings from Play modules.

@param modules the set of Guice modules whose bindings to apply
@return a copy of this builder configured with the provided bindings


public final Self bindings(play.api.inject.Binding<?>... bindings) {
    return bindings(Guiceable.bindings(bindings));
  }

public final Self bindings ( play . api . inject . Binding < ? > ... bindings ) { return bindings ( Guiceable . bindings ( bindings ) ) ; }

Add Play bindings.

@param bindings the set of play bindings to apply
@return a copy of this builder configured with the provided bindings


public final Self overrides(GuiceableModule... modules) {
    return newBuilder(delegate.overrides(Scala.varargs(modules)));
  }

public final Self overrides ( GuiceableModule ... modules ) { return newBuilder ( delegate . overrides ( Scala . varargs ( modules ) ) ) ; }

Override bindings using guiceable modules.

@param modules the set of Guice modules whose bindings override some previously configured ones
@return a copy of this builder re-configured with the provided bindings

Override bindings using guiceable modules .


public final Self overrides(play.api.inject.Module... modules) {
    return overrides(Guiceable.modules(modules));
  }

public final Self overrides ( play . api . inject . Module ... modules ) { return overrides ( Guiceable . modules ( modules ) ) ; }

Override bindings using Play modules.

@param modules the set of Play modules whose bindings override some previously configured ones
@return a copy of this builder re-configured with the provided bindings


public final Self overrides(play.api.inject.Binding<?>... bindings) {
    return overrides(Guiceable.bindings(bindings));
  }

public final Self overrides ( play . api . inject . Binding < ? > ... bindings ) { return overrides ( Guiceable . bindings ( bindings ) ) ; }

Override bindings using Play bindings.

@param bindings a set of Play bindings that override some previously configured ones
@return a copy of this builder re-configured with the provided bindings


public final Self disable(Class<?>... moduleClasses) {
    return newBuilder(delegate.disable(Scala.toSeq(moduleClasses)));
  }

public final Self disable ( Class < ? > ... moduleClasses ) { return newBuilder ( delegate . disable ( Scala . toSeq ( moduleClasses ) ) ) ; }

Disable modules by class.

@param moduleClasses the module classes whose bindings should be disabled
@return a copy of this builder configured to ignore the provided module classes


@Deprecated // TODO: When you remove this method make call(Request) below abstract
  public CompletionStage<Result> call(Context ctx) {
    return call(
        ctx.args != null && !ctx.args.isEmpty()
            ? ctx.request().addAttr(CTX_ARGS, ctx.args)
            : ctx.request());
  }

Executes this action with the given HTTP context and returns the result.

@param ctx the http context in which to execute this action
@return a promise to the action's result
@deprecated Since 2.7.0. Use {@link #call(Request)} instead. Please see the
migration guide for more details.

Executes this action with the given HTTP context and returns the result .


public CompletionStage<Result> call(
      Request req) { // TODO: Make this method abstract after removing call(Context)
    return Context.safeCurrent()
        .map(
            threadLocalCtx -> {
              // A previous action did explicitly set a context onto the thread local (via
              // Http.Context.current.set(...))
              // Let's use that context so the user doesn't loose data he/she set onto that ctx
              // (args,...)
              Context newCtx = threadLocalCtx.withRequest(req.removeAttr(CTX_ARGS));
              Context.setCurrent(newCtx);
              return call(newCtx);
            })
        .orElseGet(
            () -> {
              // A previous action did not set a context explicitly, we simply create a new one to
              // pass on the request
              Context ctx = new Context(req.removeAttr(CTX_ARGS), contextComponents);
              ctx.args = req.attrs().getOptional(CTX_ARGS).orElse(new HashMap<>());
              return call(ctx);
            });
  }

Executes this action with the given HTTP request and returns the result.

@param req the http request with which to execute this action
@return a promise to the action's result

Executes this action with the given HTTP request and returns the result .


public Optional<File> getExistingFile(String relativePath) {
    return OptionConverters.toJava(env.getExistingFile(relativePath));
  }

public Optional < File > getExistingFile ( String relativePath ) { return OptionConverters . toJava ( env . getExistingFile ( relativePath ) ) ; }

Retrieves a file relative to the application root path. This method returns an Optional, using
empty if the file was not found.

@param relativePath relative path of the file to fetch
@return an existing file

Retrieves a file relative to the application root path . This method returns an Optional using empty if the file was not found .


public <A extends Annotation> Binding<T> in(final Class<A> scope) {
    return underlying.in(scope).asJava();
  }

public < A extends Annotation > Binding < T > in ( final Class < A > scope ) { return underlying . in ( scope ) . asJava ( ) ; }


public static <A, B> Tuple<A, B> Tuple(A a, B b) {
    return new Tuple<A, B>(a, b);
  }

public static < A , B > Tuple < A , B > Tuple ( A a , B b ) { return new Tuple < A , B > ( a , b ) ; }

Constructs a tuple of A,B

@param a The a value
@param b The b value
@param <A> a's type
@param <B> b's type
@return The tuple


public static <A, B, C, D, E> Tuple5<A, B, C, D, E> Tuple5(A a, B b, C c, D d, E e) {
    return new Tuple5<A, B, C, D, E>(a, b, c, d, e);
  }

public static < A , B , C , D , E > Tuple5 < A , B , C , D , E > Tuple5 ( A a , B b , C c , D d , E e ) { return new Tuple5 < A , B , C , D , E > ( a , b , c , d , e ) ; }

Constructs a tuple of A,B,C,D,E

@param a The a value
@param b The b value
@param c The c value
@param d The d value
@param e The e value
@param <A> a's type
@param <B> b's type
@param <C> c's type
@param <D> d's type
@param <E> e's type
@return The tuple


private static Executor toExecutor(ExecutionContext ec) {
    ExecutionContext prepared = ec.prepare();
    if (prepared instanceof Executor) {
      return (Executor) prepared;
    } else {
      return prepared::execute;
    }
  }

private static Executor toExecutor ( ExecutionContext ec ) { ExecutionContext prepared = ec . prepare ( ) ; if ( prepared instanceof Executor ) { return ( Executor ) prepared ; } else { return prepared :: execute ; } }

Converts the execution context to an executor, preparing it first.

@param ec the execution context.
@return the Java Executor.

Converts the execution context to an executor preparing it first .


public static JPAConfig of(String name, String unitName) {
    return new DefaultJPAConfig(new JPAConfig.PersistenceUnit(name, unitName));
  }

public static JPAConfig of ( String name , String unitName ) { return new DefaultJPAConfig ( new JPAConfig . PersistenceUnit ( name , unitName ) ) ; }

Create a default JPA configuration with the given name and unit name.

@param name the name for the entity manager factory
@param unitName the persistence unit name as used in `persistence.xml`
@return a default JPA configuration

Create a default JPA configuration with the given name and unit name .


public static JPAConfig of(String n1, String u1, String n2, String u2) {
    return new DefaultJPAConfig(
        new JPAConfig.PersistenceUnit(n1, u1), new JPAConfig.PersistenceUnit(n2, u2));
  }

public static JPAConfig of ( String n1 , String u1 , String n2 , String u2 ) { return new DefaultJPAConfig ( new JPAConfig . PersistenceUnit ( n1 , u1 ) , new JPAConfig . PersistenceUnit ( n2 , u2 ) ) ; }

Create a default JPA configuration with the given names and unit names.

@param n1 Name of the first entity manager factory
@param u1 Name of the first unit
@param n2 Name of the second entity manager factory
@param u2 Name of the second unit
@return a default JPA configuration with the provided persistence units.

Create a default JPA configuration with the given names and unit names .


public static JPAConfig from(Map<String, String> map) {
    ImmutableSet.Builder<JPAConfig.PersistenceUnit> persistenceUnits =
        new ImmutableSet.Builder<JPAConfig.PersistenceUnit>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
      persistenceUnits.add(new JPAConfig.PersistenceUnit(entry.getKey(), entry.getValue()));
    }
    return new DefaultJPAConfig(persistenceUnits.build());
  }

public static JPAConfig from ( Map < String , String > map ) { ImmutableSet . Builder < JPAConfig . PersistenceUnit > persistenceUnits = new ImmutableSet . Builder < JPAConfig . PersistenceUnit > ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { persistenceUnits . add ( new JPAConfig . PersistenceUnit ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return new DefaultJPAConfig ( persistenceUnits . build ( ) ) ; }

Create a default JPA configuration from a map of names to unit names.

@param map Map of entity manager factory names to unit names
@return a JPAConfig configured with the provided mapping

Create a default JPA configuration from a map of names to unit names .


public static Flow<String, ByteString, NotUsed> string(String callbackName) {
    return Flow.of(String.class)
        .map(
            str -> {
              return ByteString.fromString("'" + StringEscapeUtils.escapeEcmaScript(str) + "'");
            })
        .via(flow(callbackName));
  }

public static Flow < String , ByteString , NotUsed > string ( String callbackName ) { return Flow . of ( String . class ) . map ( str -> { return ByteString . fromString ( "'" + StringEscapeUtils . escapeEcmaScript ( str ) + "'" ) ; } ) . via ( flow ( callbackName ) ) ; }

Produces a Flow of escaped ByteString from a series of String elements. Calls out to Comet.flow
internally.

@param callbackName the javascript callback method.
@return a flow of ByteString elements.

Produces a Flow of escaped ByteString from a series of String elements . Calls out to Comet . flow internally .


public static Flow<JsonNode, ByteString, NotUsed> json(String callbackName) {
    return Flow.of(JsonNode.class)
        .map(
            json -> {
              return ByteString.fromString(Json.stringify(json));
            })
        .via(flow(callbackName));
  }

public static Flow < JsonNode , ByteString , NotUsed > json ( String callbackName ) { return Flow . of ( JsonNode . class ) . map ( json -> { return ByteString . fromString ( Json . stringify ( json ) ) ; } ) . via ( flow ( callbackName ) ) ; }

Produces a flow of ByteString using `Json.stringify` from a Flow of JsonNode. Calls out to
Comet.flow internally.

@param callbackName the javascript callback method.
@return a flow of ByteString elements.

Produces a flow of ByteString using Json . stringify from a Flow of JsonNode . Calls out to Comet . flow internally .


public <T extends ConstraintValidator<?, ?>>
      MappedConstraintValidatorFactory addConstraintValidator(Class<T> key, T constraintValidator) {
    validators.put(key, () -> constraintValidator);
    return this;
  }

public < T extends ConstraintValidator < ? , ? > > MappedConstraintValidatorFactory addConstraintValidator ( Class < T > key , T constraintValidator ) { validators . put ( key , ( ) -> constraintValidator ) ; return this ; }

Adds validator as a singleton.

@param key the constraint validator type
@param constraintValidator the constraint validator instance
@param <T> the type of constraint validator implementation
@return {@link MappedConstraintValidatorFactory} with the given constraint validator added.


private <T extends ConstraintValidator<?, ?>> T newInstance(Class<T> key) {
    try {
      return key.getDeclaredConstructor().newInstance();
    } catch (InstantiationException
        | RuntimeException
        | IllegalAccessException
        | NoSuchMethodException
        | InvocationTargetException ex) {
      throw new RuntimeException(ex);
    }
  }

private < T extends ConstraintValidator < ? , ? > > T newInstance ( Class < T > key ) { try { return key . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( InstantiationException | RuntimeException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex ) { throw new RuntimeException ( ex ) ; } }


public static Method getMatchingAccessibleMethod(
      final Class<?> cls, final String methodName, final Class<?>... parameterTypes) {
    try {
      final Method method = cls.getMethod(methodName, parameterTypes);
      MemberUtils.setAccessibleWorkaround(method);
      return method;
    } catch (final NoSuchMethodException e) { // NOPMD - Swallow the exception
    }
    // search through all methods
    Method bestMatch = null;
    final Method[] methods = cls.getMethods();
    for (final Method method : methods) {
      // compare name and parameters
      if (method.getName().equals(methodName)
          && MemberUtils.isMatchingMethod(method, parameterTypes)) {
        // get accessible version of method
        final Method accessibleMethod = getAccessibleMethod(method);
        if (accessibleMethod != null
            && (bestMatch == null
                || MemberUtils.compareMethodFit(accessibleMethod, bestMatch, parameterTypes) < 0)) {
          bestMatch = accessibleMethod;
        }
      }
    }
    if (bestMatch != null) {
      MemberUtils.setAccessibleWorkaround(bestMatch);
    }

    if (bestMatch != null
        && bestMatch.isVarArgs()
        && bestMatch.getParameterTypes().length > 0
        && parameterTypes.length > 0) {
      final Class<?>[] methodParameterTypes = bestMatch.getParameterTypes();
      final Class<?> methodParameterComponentType =
          methodParameterTypes[methodParameterTypes.length - 1].getComponentType();
      final String methodParameterComponentTypeName =
          ClassUtils.primitiveToWrapper(methodParameterComponentType).getName();
      final String parameterTypeName = parameterTypes[parameterTypes.length - 1].getName();
      final String parameterTypeSuperClassName =
          parameterTypes[parameterTypes.length - 1].getSuperclass().getName();

      if (!methodParameterComponentTypeName.equals(parameterTypeName)
          && !methodParameterComponentTypeName.equals(parameterTypeSuperClassName)) {
        return null;
      }
    }

    return bestMatch;
  }

public
static
Method
getMatchingAccessibleMethod
(
final
Class
<
>
cls
,
final
String
methodName
,
final
Class
<
>
...
parameterTypes
)
{
try
{
final
Method
method
=
cls
.
getMethod
(
methodName
,
parameterTypes
)
;
MemberUtils
.
setAccessibleWorkaround
(
method
)
;
return
method
;
}
catch
(
final
NoSuchMethodException
e
)
{
// NOPMD - Swallow the exception
}
// search through all methods
Method
bestMatch
=
;
final
Method
[
]
methods
=
cls
.
getMethods
(
)
;
for
(
final
Method
method
:
methods
)
{
// compare name and parameters
if
(
method
.
getName
(
)
.
equals
(
methodName
)
&&
MemberUtils
.
isMatchingMethod
(
method
,
parameterTypes
)
)
{
// get accessible version of method
final
Method
accessibleMethod
=
getAccessibleMethod
(
method
)
;
if
(
accessibleMethod
!=
&&
(
bestMatch
==
||
MemberUtils
.
compareMethodFit
(
accessibleMethod
,
bestMatch
,
parameterTypes
)
<
0
)
)
{
bestMatch
=
accessibleMethod
;
}
}
}
if
(
bestMatch
!=
)
{
MemberUtils
.
setAccessibleWorkaround
(
bestMatch
)
;
}
if
(
bestMatch
!=
&&
bestMatch
.
isVarArgs
(
)
&&
bestMatch
.
getParameterTypes
(
)
.
length
>
0
&&
parameterTypes
.
length
>
0
)
{
final
Class
<
>
[
]
methodParameterTypes
=
bestMatch
.
getParameterTypes
(
)
;
final
Class
<
>
methodParameterComponentType
=
methodParameterTypes
[
methodParameterTypes
.
length
1
]
.
getComponentType
(
)
;
final
String
methodParameterComponentTypeName
=
ClassUtils
.
primitiveToWrapper
(
methodParameterComponentType
)
.
getName
(
)
;
final
String
parameterTypeName
=
parameterTypes
[
parameterTypes
.
length
1
]
.
getName
(
)
;
final
String
parameterTypeSuperClassName
=
parameterTypes
[
parameterTypes
.
length
1
]
.
getSuperclass
(
)
.
getName
(
)
;
if
(
!
methodParameterComponentTypeName
.
equals
(
parameterTypeName
)
&&
!
methodParameterComponentTypeName
.
equals
(
parameterTypeSuperClassName
)
)
{
return
;
}
}
return
bestMatch
;
}

Finds an accessible method that matches the given name and has compatible parameters.
Compatible parameters mean that every method parameter is assignable from the given parameters.
In other words, it finds a method with the given name that will take the parameters given.

<p>This method can match primitive parameter by passing in wrapper classes. For example, a
{@code Boolean} will match a primitive {@code boolean} parameter.

@param cls find method in this class
@param methodName find method with this name
@param parameterTypes find method with most compatible parameters
@return The accessible method

Finds an accessible method that matches the given name and has compatible parameters . Compatible parameters mean that every method parameter is assignable from the given parameters . In other words it finds a method with the given name that will take the parameters given .


@Override
  public CompletionStage<Result> onClientError(
      RequestHeader request, int statusCode, String message) {
    if (statusCode == 400) {
      return onBadRequest(request, message);
    } else if (statusCode == 403) {
      return onForbidden(request, message);
    } else if (statusCode == 404) {
      return onNotFound(request, message);
    } else if (statusCode >= 400 && statusCode < 500) {
      return onOtherClientError(request, statusCode, message);
    } else {
      throw new IllegalArgumentException(
          "onClientError invoked with non client error status code " + statusCode + ": " + message);
    }
  }

Invoked when a client error occurs, that is, an error in the 4xx series.

<p>The base implementation calls onBadRequest, onForbidden, onNotFound, or onOtherClientError
depending on the HTTP status code.

@param request The request that caused the client error.
@param statusCode The error status code. Must be greater or equal to 400, and less than 500.
@param message The error message.
@return a CompletionStage containing the Result.

Invoked when a client error occurs that is an error in the 4xx series .


protected CompletionStage<Result> onBadRequest(RequestHeader request, String message) {
    return CompletableFuture.completedFuture(
        Results.badRequest(
            views.html.defaultpages.badRequest.render(
                request.method(), request.uri(), message, request.asScala())));
  }

protected CompletionStage < Result > onBadRequest ( RequestHeader request , String message ) { return CompletableFuture . completedFuture ( Results . badRequest ( views . html . defaultpages . badRequest . render ( request . method ( ) , request . uri ( ) , message , request . asScala ( ) ) ) ) ; }

Invoked when a client makes a bad request.

<p>Returns Results.badRequest (400) with the included template from {@code
views.html.defaultpages.badRequest} as the content.

@param request The request that was bad.
@param message The error message.
@return a CompletionStage containing the Result.

Invoked when a client makes a bad request .


protected CompletionStage<Result> onForbidden(RequestHeader request, String message) {
    return CompletableFuture.completedFuture(
        Results.forbidden(views.html.defaultpages.unauthorized.render(request.asScala())));
  }

protected CompletionStage < Result > onForbidden ( RequestHeader request , String message ) { return CompletableFuture . completedFuture ( Results . forbidden ( views . html . defaultpages . unauthorized . render ( request . asScala ( ) ) ) ) ; }

Invoked when a client makes a request that was forbidden.

<p>Returns Results.forbidden (401) with the included template from {@code
views.html.defaultpages.unauthorized} as the content.

@param request The forbidden request.
@param message The error message.
@return a CompletionStage containing the Result.

Invoked when a client makes a request that was forbidden .


protected CompletionStage<Result> onNotFound(RequestHeader request, String message) {
    if (environment.isProd()) {
      return CompletableFuture.completedFuture(
          Results.notFound(
              views.html.defaultpages.notFound.render(
                  request.method(), request.uri(), request.asScala())));
    } else {
      return CompletableFuture.completedFuture(
          Results.notFound(
              views.html.defaultpages.devNotFound.render(
                  request.method(), request.uri(), Some.apply(routes.get()), request.asScala())));
    }
  }

protected CompletionStage < Result > onNotFound ( RequestHeader request , String message ) { if ( environment . isProd ( ) ) { return CompletableFuture . completedFuture ( Results . notFound ( views . html . defaultpages . notFound . render ( request . method ( ) , request . uri ( ) , request . asScala ( ) ) ) ) ; } else { return CompletableFuture . completedFuture ( Results . notFound ( views . html . defaultpages . devNotFound . render ( request . method ( ) , request . uri ( ) , Some . apply ( routes . get ( ) ) , request . asScala ( ) ) ) ) ; } }

Invoked when a handler or resource is not found.

If the environment's mode is production, then returns Results.notFound (404) with the
included template from `views.html.defaultpages.notFound` as the content.

Otherwise, Results.notFound (404) is rendered with {@code
views.html.defaultpages.devNotFound} template.

@param request The request that no handler was found to handle.
@param message A message, which is not used by the default implementation.
@return a CompletionStage containing the Result.

Invoked when a handler or resource is not found .


@Override
  public CompletionStage<Result> onServerError(RequestHeader request, Throwable exception) {
    try {
      UsefulException usefulException = throwableToUsefulException(exception);

      logServerError(request, usefulException);

      switch (environment.mode()) {
        case PROD:
          return onProdServerError(request, usefulException);
        default:
          return onDevServerError(request, usefulException);
      }
    } catch (Exception e) {
      logger.error("Error while handling error", e);
      return CompletableFuture.completedFuture(Results.internalServerError());
    }
  }

@
Override
public
CompletionStage
<
Result
>
onServerError
(
RequestHeader
request
,
Throwable
exception
)
{
try
{
UsefulException
usefulException
=
throwableToUsefulException
(
exception
)
;
logServerError
(
request
,
usefulException
)
;
switch
(
environment
.
mode
(
)
)
{
case
PROD
:
return
onProdServerError
(
request
,
usefulException
)
;
default
:
return
onDevServerError
(
request
,
usefulException
)
;
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"Error while handling error"
,
e
)
;
return
CompletableFuture
.
completedFuture
(
Results
.
internalServerError
(
)
)
;
}
}

Invoked when a server error occurs.

<p>By default, the implementation of this method delegates to [[onProdServerError()]] when in
prod mode, and [[onDevServerError()]] in dev mode. It is recommended, if you want Play's debug
info on the error page in dev mode, that you override [[onProdServerError()]] instead of this
method.

@param request The request that triggered the server error.
@param exception The server error.
@return a CompletionStage containing the Result.


protected void logServerError(RequestHeader request, UsefulException usefulException) {
    logger.error(
        String.format(
            "\n\n! @%s - Internal server error, for (%s) [%s] ->\n",
            usefulException.id, request.method(), request.uri()),
        usefulException);
  }

Responsible for logging server errors.

The base implementation uses a SLF4J Logger. If a special annotation is desired for internal
server errors, you may want to use SLF4J directly with the Marker API to distinguish server
errors from application errors.

This can also be overridden to add additional logging information, eg. the id of the
authenticated user.

@param request The request that triggered the server error.
@param usefulException The server error.


protected final UsefulException throwableToUsefulException(final Throwable throwable) {
    return HttpErrorHandlerExceptions.throwableToUsefulException(
        sourceMapper.sourceMapper(), environment.isProd(), throwable);
  }

protected final UsefulException throwableToUsefulException ( final Throwable throwable ) { return HttpErrorHandlerExceptions . throwableToUsefulException ( sourceMapper . sourceMapper ( ) , environment . isProd ( ) , throwable ) ; }

Convert the given exception to an exception that Play can report more information about.

<p>This will generate an id for the exception, and in dev mode, will load the source code for
the code that threw the exception, making it possible to report on the location that the
exception was thrown from.

Convert the given exception to an exception that Play can report more information about .


protected CompletionStage<Result> onDevServerError(
      RequestHeader request, UsefulException exception) {
    return CompletableFuture.completedFuture(
        Results.internalServerError(
            views.html.defaultpages.devError.render(playEditor, exception, request.asScala())));
  }

protected CompletionStage < Result > onDevServerError ( RequestHeader request , UsefulException exception ) { return CompletableFuture . completedFuture ( Results . internalServerError ( views . html . defaultpages . devError . render ( playEditor , exception , request . asScala ( ) ) ) ) ; }

Invoked in dev mode when a server error occurs. Note that this method is where the URL set by
play.editor is used.

<p>The base implementation returns {@code Results.internalServerError} with the content of
{@code views.html.defaultpages.devError}.

@param request The request that triggered the error.
@param exception The exception.
@return a CompletionStage containing the Result.

Invoked in dev mode when a server error occurs . Note that this method is where the URL set by play . editor is used .


protected CompletionStage<Result> onProdServerError(
      RequestHeader request, UsefulException exception) {
    return CompletableFuture.completedFuture(
        Results.internalServerError(
            views.html.defaultpages.error.render(exception, request.asScala())));
  }

protected CompletionStage < Result > onProdServerError ( RequestHeader request , UsefulException exception ) { return CompletableFuture . completedFuture ( Results . internalServerError ( views . html . defaultpages . error . render ( exception , request . asScala ( ) ) ) ) ; }

Invoked in prod mode when a server error occurs.

The base implementation returns {@code Results.internalServerError} with the content of
{@code views.html.defaultpages.error} template.

Override this rather than [[onServerError()]] if you don't want to change Play's debug
output when logging errors in dev mode.

@param request The request that triggered the error.
@param exception The exception.
@return a CompletionStage containing the Result.

Invoked in prod mode when a server error occurs .


public static BuildDocHandler fromResources(File[] files, String[] baseDirs) throws IOException {
    assert (files.length == baseDirs.length);

    FileRepository[] repositories = new FileRepository[files.length];
    List<JarFile> jarFiles = new ArrayList<>();

    for (int i = 0; i < files.length; i++) {
      File file = files[i];
      String baseDir = baseDirs[i];

      if (file.isDirectory()) {
        repositories[i] = new FilesystemRepository(file);
      } else {
        // Assume it's a jar file
        JarFile jarFile = new JarFile(file);
        jarFiles.add(jarFile);
        repositories[i] = new JarRepository(jarFile, Option.apply(baseDir));
      }
    }

    return new DocumentationHandler(
        new AggregateFileRepository(repositories),
        () -> {
          for (JarFile jarFile : jarFiles) {
            jarFile.close();
          }
        });
  }

public
static
BuildDocHandler
fromResources
(
File
[
]
files
,
String
[
]
baseDirs
)
throws
IOException
{
assert
(
files
.
length
==
baseDirs
.
length
)
;
FileRepository
[
]
repositories
=
new
FileRepository
[
files
.
length
]
;
List
<
JarFile
>
jarFiles
=
new
ArrayList
<>
(
)
;
for
(
int
i
=
0
;
i
<
files
.
length
;
i
++
)
{
File
file
=
files
[
i
]
;
String
baseDir
=
baseDirs
[
i
]
;
if
(
file
.
isDirectory
(
)
)
{
repositories
[
i
]
=
new
FilesystemRepository
(
file
)
;
}
else
{
// Assume it's a jar file
JarFile
jarFile
=
new
JarFile
(
file
)
;
jarFiles
.
add
(
jarFile
)
;
repositories
[
i
]
=
new
JarRepository
(
jarFile
,
Option
.
apply
(
baseDir
)
)
;
}
}
return
new
DocumentationHandler
(
new
AggregateFileRepository
(
repositories
)
,
(
)
->
{
for
(
JarFile
jarFile
:
jarFiles
)
{
jarFile
.
close
(
)
;
}
}
)
;
}

Create a BuildDocHandler that serves documentation from the given files, which could either be
directories or jar files. The baseDir array must be the same length as the files array, and the
corresponding entry in there for jar files is used as a base directory to use resources from in
the jar.

@param files The directories or jar files to serve documentation from.
@param baseDirs The base directories for the jar files. Entries may be null.
@return a BuildDocHandler.

Create a BuildDocHandler that serves documentation from the given files which could either be directories or jar files . The baseDir array must be the same length as the files array and the corresponding entry in there for jar files is used as a base directory to use resources from in the jar .


public static BuildDocHandler fromDirectory(File directory) {
    FileRepository repo = new FilesystemRepository(directory);
    return new DocumentationHandler(repo);
  }

public static BuildDocHandler fromDirectory ( File directory ) { FileRepository repo = new FilesystemRepository ( directory ) ; return new DocumentationHandler ( repo ) ; }

Create an BuildDocHandler that serves documentation from a given directory by wrapping a
FilesystemRepository.

@param directory The directory to serve the documentation from.

Create an BuildDocHandler that serves documentation from a given directory by wrapping a FilesystemRepository .


public static BuildDocHandler fromDirectoryAndJar(File directory, JarFile jarFile, String base) {
    return fromDirectoryAndJar(directory, jarFile, base, false);
  }

public static BuildDocHandler fromDirectoryAndJar ( File directory , JarFile jarFile , String base ) { return fromDirectoryAndJar ( directory , jarFile , base , false ) ; }

Create an BuildDocHandler that serves the manual from a given directory by wrapping a
FilesystemRepository, and the API docs from a given JAR file by wrapping a JarRepository

@param directory The directory to serve the documentation from.
@param jarFile The JAR file to server the documentation from.
@param base The directory within the JAR file to serve the documentation from, or null if the
documentation should be served from the root of the JAR.

Create an BuildDocHandler that serves the manual from a given directory by wrapping a FilesystemRepository and the API docs from a given JAR file by wrapping a JarRepository


public static BuildDocHandler fromDirectoryAndJar(
      File directory, JarFile jarFile, String base, boolean fallbackToJar) {
    FileRepository fileRepo = new FilesystemRepository(directory);
    FileRepository jarRepo = new JarRepository(jarFile, Option.apply(base));
    FileRepository manualRepo;
    if (fallbackToJar) {
      manualRepo = new AggregateFileRepository(new FileRepository[] {fileRepo, jarRepo});
    } else {
      manualRepo = fileRepo;
    }

    return new DocumentationHandler(manualRepo, jarRepo);
  }

public static BuildDocHandler fromDirectoryAndJar ( File directory , JarFile jarFile , String base , boolean fallbackToJar ) { FileRepository fileRepo = new FilesystemRepository ( directory ) ; FileRepository jarRepo = new JarRepository ( jarFile , Option . apply ( base ) ) ; FileRepository manualRepo ; if ( fallbackToJar ) { manualRepo = new AggregateFileRepository ( new FileRepository [ ] { fileRepo , jarRepo } ) ; } else { manualRepo = fileRepo ; } return new DocumentationHandler ( manualRepo , jarRepo ) ; }

Create an BuildDocHandler that serves the manual from a given directory by wrapping a
FilesystemRepository, and the API docs from a given JAR file by wrapping a JarRepository.

@param directory The directory to serve the documentation from.
@param jarFile The JAR file to server the documentation from.
@param base The directory within the JAR file to serve the documentation from, or null if the
documentation should be served from the root of the JAR.
@param fallbackToJar Whether the doc handler should fall back to the jar repo for docs.

Create an BuildDocHandler that serves the manual from a given directory by wrapping a FilesystemRepository and the API docs from a given JAR file by wrapping a JarRepository .


public static BuildDocHandler fromJar(JarFile jarFile, String base) {
    FileRepository repo = new JarRepository(jarFile, Option.apply(base));
    return new DocumentationHandler(repo);
  }

public static BuildDocHandler fromJar ( JarFile jarFile , String base ) { FileRepository repo = new JarRepository ( jarFile , Option . apply ( base ) ) ; return new DocumentationHandler ( repo ) ; }

Create an BuildDocHandler that serves documentation from a given JAR file by wrapping a
JarRepository.

@param jarFile The JAR file to server the documentation from.
@param base The directory within the JAR file to serve the documentation from, or null if the
documentation should be served from the root of the JAR.

Create an BuildDocHandler that serves documentation from a given JAR file by wrapping a JarRepository .


public CompletionStage<ByteString> consumeData(Materializer mat) {
    return dataStream().runFold(ByteString.empty(), ByteString::concat, mat);
  }

public CompletionStage < ByteString > consumeData ( Materializer mat ) { return dataStream ( ) . runFold ( ByteString . empty ( ) , ByteString :: concat , mat ) ; }

Consumes the data.

<p>This method should be used carefully, since if the source represents an ephemeral stream,
then the entity may not be usable after this method is invoked.

@param mat the application's materializer.
@return a CompletionStage holding the data


public static final HttpEntity fromContent(Content content, String charset) {
    String body;
    if (content instanceof Xml) {
      // See https://github.com/playframework/playframework/issues/2770
      body = content.body().trim();
    } else {
      body = content.body();
    }
    return new Strict(
        ByteString.fromString(body, charset),
        Optional.of(content.contentType() + "; charset=" + charset));
  }

Create an entity from the given content.

@param content The content.
@param charset The charset.
@return the HTTP entity.

Create an entity from the given content .


public static final HttpEntity fromString(String content, String charset) {
    return new Strict(
        ByteString.fromString(content, charset), Optional.of("text/plain; charset=" + charset));
  }

public
static
final
HttpEntity
fromString
(
String
content
,
String
charset
)
{
return
new
Strict
(
ByteString
.
fromString
(
content
,
charset
)
,
Optional
.
of
(
"text/plain; charset="
+
charset
)
)
;
}

Create an entity from the given String.

@param content The content.
@param charset The charset.
@return the HTTP entity.

Create an entity from the given String .


public static final HttpEntity chunked(Source<ByteString, ?> data, Optional<String> contentType) {
    return new Chunked(data.map(HttpChunk.Chunk::new), contentType);
  }

public static final HttpEntity chunked ( Source < ByteString , ? > data , Optional < String > contentType ) { return new Chunked ( data . map ( HttpChunk . Chunk :: new ) , contentType ) ; }

Convert the given source of ByteStrings to a chunked entity.

@param data The source.
@param contentType The optional content type.
@return The ByteStrings.

Convert the given source of ByteStrings to a chunked entity .


public static Result status(int status, JsonNode content) {
    return status(status, content, JsonEncoding.UTF8);
  }

public static Result status ( int status , JsonNode content ) { return status ( status , content , JsonEncoding . UTF8 ) ; }

Generates a simple result with json content and UTF8 encoding.

@param status the HTTP status for this result e.g. 200 (OK), 404 (NOT_FOUND)
@param content the result's body content as a play-json object
@return the result

Generates a simple result with json content and UTF8 encoding .


public static Result status(int status, JsonNode content, JsonEncoding encoding) {
    if (content == null) {
      throw new NullPointerException("Null content");
    }
    return status(status).sendJson(content, encoding);
  }

public
static
Result
status
(
int
status
,
JsonNode
content
,
JsonEncoding
encoding
)
{
if
(
content
==
)
{
throw
new
NullPointerException
(
"Null content"
)
;
}
return
status
(
status
)
.
sendJson
(
content
,
encoding
)
;
}

Generates a simple result with json content.

@param status the HTTP status for this result e.g. 200 (OK), 404 (NOT_FOUND)
@param content the result's body content, as a play-json object
@param encoding the encoding into which the json should be encoded
@return the result

Generates a simple result with json content .


public static Result status(int status, byte[] content) {
    if (content == null) {
      throw new NullPointerException("Null content");
    }
    return new Result(
        status, new HttpEntity.Strict(ByteString.fromArray(content), Optional.empty()));
  }

public
static
Result
status
(
int
status
,
byte
[
]
content
)
{
if
(
content
==
)
{
throw
new
NullPointerException
(
"Null content"
)
;
}
return
new
Result
(
status
,
new
HttpEntity
.
Strict
(
ByteString
.
fromArray
(
content
)
,
Optional
.
empty
(
)
)
)
;
}

Generates a simple result with byte-array content.

@param status the HTTP status for this result e.g. 200 (OK), 404 (NOT_FOUND)
@param content the result's body content, as a byte array
@return the result

Generates a simple result with byte - array content .


public static Result status(int status, InputStream content, long contentLength) {
    return status(status).sendInputStream(content, contentLength);
  }

public static Result status ( int status , InputStream content , long contentLength ) { return status ( status ) . sendInputStream ( content , contentLength ) ; }

Generates a chunked result.

@param status the HTTP status for this result e.g. 200 (OK), 404 (NOT_FOUND)
@param content the input stream containing data to chunk over
@param contentLength the length of the provided content in bytes.
@return the result


public static Result status(int status, File content) {
    return status(status, content, StaticFileMimeTypes.fileMimeTypes());
  }

public static Result status ( int status , File content ) { return status ( status , content , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }

Generates a result with file contents.

@param status the HTTP status for this result e.g. 200 (OK), 404 (NOT_FOUND)
@param content the file to send
@return the result


private User findById(Long id) {
    if (id > 3) return null;
    User user = new User();
    user.id = id;
    user.name = "User " + String.valueOf(id);
    return user;
  }

private
User
findById
(
Long
id
)
{
if
(
id
>
3
)
return
;
User
user
=
new
User
(
)
;
user
.
id
=
id
;
user
.
name
=
"User "
+
String
.
valueOf
(
id
)
;
return
user
;
}


public Lang preferred(Collection<Lang> candidates) {
    return new Lang(
        langs.preferred((scala.collection.immutable.Seq) Scala.asScala(candidates).toSeq()));
  }

public Lang preferred ( Collection < Lang > candidates ) { return new Lang ( langs . preferred ( ( scala . collection . immutable . Seq ) Scala . asScala ( candidates ) . toSeq ( ) ) ) ; }

Select a preferred language, given the list of candidates.

<p>Will select the preferred language, based on what languages are available, or return the
default language if none of the candidates are available.

@param candidates The candidate languages
@return The preferred language

Select a preferred language given the list of candidates .


public Call unique() {
    return new play.api.mvc.Call(method(), this.uniquify(this.url()), fragment());
  }

public Call unique ( ) { return new play . api . mvc . Call ( method ( ) , this . uniquify ( this . url ( ) ) , fragment ( ) ) ; }

Append a unique identifier to the URL.

@return a copy if this call with a unique identifier to this url


public Call withFragment(String fragment) {
    return new play.api.mvc.Call(method(), url(), fragment);
  }

public Call withFragment ( String fragment ) { return new play . api . mvc . Call ( method ( ) , url ( ) , fragment ) ; }

Returns a new Call with the given fragment.

@param fragment the URL fragment
@return a copy of this call that contains the fragment

Returns a new Call with the given fragment .


public String absoluteURL(Http.Request request) {
    return absoluteURL(request.secure(), request.host());
  }

public String absoluteURL ( Http . Request request ) { return absoluteURL ( request . secure ( ) , request . host ( ) ) ; }

Transform this call to an absolute URL.

@param request used to identify the host and protocol that should base this absolute URL
@return the absolute URL string

Transform this call to an absolute URL .


public String webSocketURL(Http.Request request) {
    return webSocketURL(request.secure(), request.host());
  }

public String webSocketURL ( Http . Request request ) { return webSocketURL ( request . secure ( ) , request . host ( ) ) ; }

Transform this call to an WebSocket URL.

@param request used as the base for forming the WS url
@return the websocket url string

Transform this call to an WebSocket URL .


AbstractFunction1<Connection, BoxedUnit> connectionFunction(final ConnectionRunnable block) {
    return new AbstractFunction1<Connection, BoxedUnit>() {
      public BoxedUnit apply(Connection connection) {
        try {
          block.run(connection);
          return BoxedUnit.UNIT;
        } catch (java.sql.SQLException e) {
          throw new RuntimeException("Connection runnable failed", e);
        }
      }
    };
  }

AbstractFunction1
<
Connection
,
BoxedUnit
>
connectionFunction
(
final
ConnectionRunnable
block
)
{
return
new
AbstractFunction1
<
Connection
,
BoxedUnit
>
(
)
{
public
BoxedUnit
apply
(
Connection
connection
)
{
try
{
block
.
run
(
connection
)
;
return
BoxedUnit
.
UNIT
;
}
catch
(
java
.
sql
.
SQLException
e
)
{
throw
new
RuntimeException
(
"Connection runnable failed"
,
e
)
;
}
}
}
;
}

Create a Scala function wrapper for ConnectionRunnable.

@param block a Java functional interface instance to wrap
@return a scala function that wraps the given block

Create a Scala function wrapper for ConnectionRunnable .


<A> AbstractFunction1<Connection, A> connectionFunction(final ConnectionCallable<A> block) {
    return new AbstractFunction1<Connection, A>() {
      public A apply(Connection connection) {
        try {
          return block.call(connection);
        } catch (java.sql.SQLException e) {
          throw new RuntimeException("Connection callable failed", e);
        }
      }
    };
  }

<
A
>
AbstractFunction1
<
Connection
,
A
>
connectionFunction
(
final
ConnectionCallable
<
A
>
block
)
{
return
new
AbstractFunction1
<
Connection
,
A
>
(
)
{
public
A
apply
(
Connection
connection
)
{
try
{
return
block
.
call
(
connection
)
;
}
catch
(
java
.
sql
.
SQLException
e
)
{
throw
new
RuntimeException
(
"Connection callable failed"
,
e
)
;
}
}
}
;
}

Create a Scala function wrapper for ConnectionCallable.

@param block a Java functional interface instance to wrap
@param <A> the provided block's return type
@return a scala function wrapping the given block

Create a Scala function wrapper for ConnectionCallable .


public static Server forRouter(Mode mode, int port, Function<BuiltInComponents, Router> block) {
    return new Builder().mode(mode).http(port).build(block);
  }

public static Server forRouter ( Mode mode , int port , Function < BuiltInComponents , Router > block ) { return new Builder ( ) . mode ( mode ) . http ( port ) . build ( block ) ; }

Create a server for the router returned by the given block.

@param block The block which creates a router.
@param mode The mode the server will run on.
@param port The port the server will run on.
@return The running server.

Create a server for the router returned by the given block .


public static JsonNode toJson(final Object data) {
    try {
      return mapper().valueToTree(data);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

public static JsonNode toJson ( final Object data ) { try { return mapper ( ) . valueToTree ( data ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }

Converts an object to JsonNode.

@param data Value to convert in Json.
@return the JSON node.


public static <A> A fromJson(JsonNode json, Class<A> clazz) {
    try {
      return mapper().treeToValue(json, clazz);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

public static < A > A fromJson ( JsonNode json , Class < A > clazz ) { try { return mapper ( ) . treeToValue ( json , clazz ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }

Converts a JsonNode to a Java value

@param <A> the type of the return value.
@param json Json value to convert.
@param clazz Expected Java value type.
@return the return value.


public static JsonNode parse(String src) {
    try {
      return mapper().readTree(src);
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

public static JsonNode parse ( String src ) { try { return mapper ( ) . readTree ( src ) ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } }

Parses a String representing a json, and return it as a JsonNode.

@param src the JSON string.
@return the JSON node.

Parses a String representing a json and return it as a JsonNode .


public static JsonNode parse(java.io.InputStream src) {
    try {
      return mapper().readTree(src);
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

public static JsonNode parse ( java . io . InputStream src ) { try { return mapper ( ) . readTree ( src ) ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } }

Parses a InputStream representing a json, and return it as a JsonNode.

@param src the JSON input stream.
@return the JSON node.

Parses a InputStream representing a json and return it as a JsonNode .


public static String relative(String startPath, String targetPath) {
    // If the start and target path's are the same then link to the current directory
    if (startPath.equals(targetPath)) {
      return CURRENT_DIR;
    }

    String[] start = toSegments(canonical(startPath));
    String[] target = toSegments(canonical(targetPath));

    // If start path has no trailing separator (a "file" path), then drop file segment
    if (!startPath.endsWith(SEPARATOR)) start = Arrays.copyOfRange(start, 0, start.length - 1);

    // If target path has no trailing separator, then drop file segment, but keep a reference to add
    // it later
    String targetFile = "";
    if (!targetPath.endsWith(SEPARATOR)) {
      targetFile = target[target.length - 1];
      target = Arrays.copyOfRange(target, 0, target.length - 1);
    }

    // Work out how much of the filepath is shared by start and path.
    String[] common = commonPrefix(start, target);
    String[] parents = toParentDirs(start.length - common.length);

    int relativeStartIdx = common.length;
    String[] relativeDirs = Arrays.copyOfRange(target, relativeStartIdx, target.length);
    String[] relativePath = Arrays.copyOf(parents, parents.length + relativeDirs.length);
    System.arraycopy(relativeDirs, 0, relativePath, parents.length, relativeDirs.length);

    // If this is not a sibling reference append a trailing / to path
    String trailingSep = "";
    if (relativePath.length > 0) trailingSep = SEPARATOR;

    return Arrays.stream(relativePath).collect(Collectors.joining(SEPARATOR))
        + trailingSep
        + targetFile;
  }

Create a path to targetPath that's relative to the given startPath.

Create a path to targetPath that s relative to the given startPath .


public static String canonical(String url) {
    String[] urlPath = toSegments(url);
    Stack<String> canonical = new Stack<>();
    for (String comp : urlPath) {
      if (comp.isEmpty() || comp.equals(CURRENT_DIR)) continue;
      if (!comp.equals(PARENT_DIR) || (!canonical.empty() && canonical.peek().equals(PARENT_DIR)))
        canonical.push(comp);
      else canonical.pop();
    }

    String prefixSep = url.startsWith(SEPARATOR) ? SEPARATOR : "";
    String trailingSep = url.endsWith(SEPARATOR) ? SEPARATOR : "";

    return prefixSep + canonical.stream().collect(Collectors.joining(SEPARATOR)) + trailingSep;
  }

public static String canonical ( String url ) { String [ ] urlPath = toSegments ( url ) ; Stack < String > canonical = new Stack <> ( ) ; for ( String comp : urlPath ) { if ( comp . isEmpty ( ) || comp . equals ( CURRENT_DIR ) ) continue ; if ( ! comp . equals ( PARENT_DIR ) || ( ! canonical . empty ( ) && canonical . peek ( ) . equals ( PARENT_DIR ) ) ) canonical . push ( comp ) ; else canonical . pop ( ) ; } String prefixSep = url . startsWith ( SEPARATOR ) ? SEPARATOR : "" ; String trailingSep = url . endsWith ( SEPARATOR ) ? SEPARATOR : "" ; return prefixSep + canonical . stream ( ) . collect ( Collectors . joining ( SEPARATOR ) ) + trailingSep ; }

Create a canonical path that does not contain parent directories, current directories, or
superfluous directory separators.

Create a canonical path that does not contain parent directories current directories or superfluous directory separators .


public static List<Tuple<String, List<Object>>> displayableConstraint(
      Set<ConstraintDescriptor<?>> constraints) {
    return constraints
        .parallelStream()
        .filter(c -> c.getAnnotation().annotationType().isAnnotationPresent(Display.class))
        .map(c -> displayableConstraint(c))
        .collect(Collectors.toList());
  }

public static List < Tuple < String , List < Object > > > displayableConstraint ( Set < ConstraintDescriptor < ? > > constraints ) { return constraints . parallelStream ( ) . filter ( c -> c . getAnnotation ( ) . annotationType ( ) . isAnnotationPresent ( Display . class ) ) . map ( c -> displayableConstraint ( c ) ) . collect ( Collectors . toList ( ) ) ; }

Converts a set of constraints to human-readable values. Does not guarantee the order of the
returned constraints.

<p>This method calls {@code displayableConstraint} under the hood.

@param constraints the set of constraint descriptors.
@return a list of pairs of tuples assembled from displayableConstraint.

Converts a set of constraints to human - readable values . Does not guarantee the order of the returned constraints .


public static Tuple<String, List<Object>> displayableConstraint(
      ConstraintDescriptor<?> constraint) {
    final Display displayAnnotation =
        constraint.getAnnotation().annotationType().getAnnotation(Display.class);
    return Tuple(
        displayAnnotation.name(),
        Collections.unmodifiableList(
            Stream.of(displayAnnotation.attributes())
                .map(attr -> constraint.getAttributes().get(attr))
                .collect(Collectors.toList())));
  }

public static Tuple < String , List < Object > > displayableConstraint ( ConstraintDescriptor < ? > constraint ) { final Display displayAnnotation = constraint . getAnnotation ( ) . annotationType ( ) . getAnnotation ( Display . class ) ; return Tuple ( displayAnnotation . name ( ) , Collections . unmodifiableList ( Stream . of ( displayAnnotation . attributes ( ) ) . map ( attr -> constraint . getAttributes ( ) . get ( attr ) ) . collect ( Collectors . toList ( ) ) ) ) ; }

Converts a constraint to a human-readable value.

@param constraint the constraint descriptor.
@return A tuple containing the constraint's display name and the constraint attributes.

Converts a constraint to a human - readable value .


@Override
  public <A> CompletionStage<A> timeout(
      final CompletionStage<A> stage, final long amount, final TimeUnit unit) {
    requireNonNull(stage, "Null stage");
    requireNonNull(unit, "Null unit");

    FiniteDuration duration = FiniteDuration.apply(amount, unit);
    return toJava(delegate.timeout(duration, Scala.asScalaWithFuture(() -> stage)));
  }

@
Override
public
<
A
>
CompletionStage
<
A
>
timeout
(
final
CompletionStage
<
A
>
stage
,
final
long
amount
,
final
TimeUnit
unit
)
{
requireNonNull
(
stage
,
"Null stage"
)
;
requireNonNull
(
unit
,
"Null unit"
)
;
FiniteDuration
duration
=
FiniteDuration
.
apply
(
amount
,
unit
)
;
return
toJava
(
delegate
.
timeout
(
duration
,
Scala
.
asScalaWithFuture
(
(
)
->
stage
)
)
)
;
}

Creates a CompletionStage that returns either the input stage, or a futures.

<p>Note that timeout is not the same as cancellation. Even in case of futures, the given
completion stage will still complete, even though that completed value is not returned.

@param stage the input completion stage that may time out.
@param amount The amount (expressed with the corresponding unit).
@param unit The time Unit.
@param <A> the completion's result type.
@return either the completed future, or a completion stage that failed with futures.

Creates a CompletionStage that returns either the input stage or a futures .


public static boolean isAssignable(
      Class<?>[] classArray, Class<?>[] toClassArray, boolean autoboxing) {
    if (arrayGetLength(classArray) != arrayGetLength(toClassArray)) {
      return false;
    }
    if (classArray == null) {
      classArray = EMPTY_CLASS_ARRAY;
    }
    if (toClassArray == null) {
      toClassArray = EMPTY_CLASS_ARRAY;
    }
    for (int i = 0; i < classArray.length; i++) {
      if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) {
        return false;
      }
    }
    return true;
  }

public static boolean isAssignable ( Class < ? > [ ] classArray , Class < ? > [ ] toClassArray , boolean autoboxing ) { if ( arrayGetLength ( classArray ) != arrayGetLength ( toClassArray ) ) { return false ; } if ( classArray == null ) { classArray = EMPTY_CLASS_ARRAY ; } if ( toClassArray == null ) { toClassArray = EMPTY_CLASS_ARRAY ; } for ( int i = 0 ; i < classArray . length ; i ++ ) { if ( isAssignable ( classArray [ i ] , toClassArray [ i ] , autoboxing ) == false ) { return false ; } } return true ; }

Checks if an array of Classes can be assigned to another array of Classes.

This method calls {@link #isAssignable(Class, Class) isAssignable} for each Class pair in
the input arrays. It can be used to check if a set of arguments (the first parameter) are
suitably compatible with a set of method parameter types (the second parameter).

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into
account widenings of primitive classes and {@code null}s.

Primitive widenings allow an int to be assigned to a {@code long}, {@code float} or {@code
double}. This method returns the correct result for these cases.

{@code Null} may be assigned to any reference type. This method will return {@code true} if
{@code null} is passed in and the toClass is non-primitive.

Specifically, this method tests whether the type represented by the specified {@code Class}
parameter can be converted to the type represented by this {@code Class} object via an identity
conversion widening primitive or widening reference conversion. See The Java Language Specification, sections
5.1.1, 5.1.2 and 5.1.4 for details.

@param classArray the array of Classes to check, may be {@code null}
@param toClassArray the array of Classes to try to assign into, may be {@code null}
@param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
@return {@code true} if assignment possible

Checks if an array of Classes can be assigned to another array of Classes .


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

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

Parses a CRON expression.

@param cron the CRON String
@return the next Date that satisfies the expression


public static long cronInterval(String cron, Date date) {
    try {
      return new CronExpression(cron).getNextInterval(date);
    } catch (Exception e) {
      throw new IllegalArgumentException("Invalid CRON pattern : " + cron, e);
    }
  }

public
static
long
cronInterval
(
String
cron
,
Date
date
)
{
try
{
return
new
CronExpression
(
cron
)
.
getNextInterval
(
date
)
;
}
catch
(
Exception
e
)
{
throw
new
IllegalArgumentException
(
"Invalid CRON pattern : "
+
cron
,
e
)
;
}
}

Compute the number of milliseconds between the next valid date and the one after.

@param cron the CRON String
@param date the date to start search
@return the number of milliseconds between the next valid date and the one after, with an
invalid interval between

Compute the number of milliseconds between the next valid date and the one after .


public static AhcWSClient create(
      AhcWSClientConfig config, AhcHttpCache cache, Materializer materializer) {
    final StandaloneAhcWSClient client = StandaloneAhcWSClient.create(config, cache, materializer);
    return new AhcWSClient(client, materializer);
  }

public static AhcWSClient create ( AhcWSClientConfig config , AhcHttpCache cache , Materializer materializer ) { final StandaloneAhcWSClient client = StandaloneAhcWSClient . create ( config , cache , materializer ) ; return new AhcWSClient ( client , materializer ) ; }

Creates WS client manually from configuration, internally creating a new instance of
AsyncHttpClient and managing its own thread pool.

This client is not managed as part of Play's lifecycle, and must be closed by calling
ws.close(), otherwise you will run into memory leaks.

@param config a config object, usually from AhcWSClientConfigFactory
@param cache if not null, provides HTTP caching.
@param materializer an Akka materializer
@return a new instance of AhcWSClient.

Creates WS client manually from configuration internally creating a new instance of AsyncHttpClient and managing its own thread pool .


public GuiceApplicationBuilder builder(ApplicationLoader.Context context) {
    return initialBuilder
        .in(context.environment())
        .loadConfig(context.initialConfig())
        .overrides(overrides(context));
  }

public GuiceApplicationBuilder builder ( ApplicationLoader . Context context ) { return initialBuilder . in ( context . environment ( ) ) . loadConfig ( context . initialConfig ( ) ) . overrides ( overrides ( context ) ) ; }

Construct a builder to use for loading the given context.

@param context the context the returned builder will load
@return the builder

Construct a builder to use for loading the given context .


public static Result TODO(Request request) {
    return status(NOT_IMPLEMENTED, views.html.defaultpages.todo.render(request.asScala()));
  }

public static Result TODO ( Request request ) { return status ( NOT_IMPLEMENTED , views . html . defaultpages . todo . render ( request . asScala ( ) ) ) ; }

Generates a 501 NOT_IMPLEMENTED simple result.

Generates a 501 NOT_IMPLEMENTED simple result .


@Deprecated
  public static void session(String key, String value) {
    session().put(key, value);
  }

@ Deprecated public static void session ( String key , String value ) { session ( ) . put ( key , value ) ; }

Puts a new value into the current session.

@param key the key to set into the session
@param value the value to set for key
@deprecated Deprecated as of 2.7.0. Use {@link Result} instead.

Puts a new value into the current session .


@Deprecated
  public static void flash(String key, String value) {
    flash().put(key, value);
  }

@ Deprecated public static void flash ( String key , String value ) { flash ( ) . put ( key , value ) ; }

Puts a new value into the flash scope.

@param key the key to put into the flash scope
@param value the value corresponding to key
@deprecated Deprecated as of 2.7.0. Use {@link Result} instead.


public <A extends Annotation> BindingKey<T> qualifiedWith(final A instance) {
    return underlying.qualifiedWith(instance).asJava();
  }

public < A extends Annotation > BindingKey < T > qualifiedWith ( final A instance ) { return underlying . qualifiedWith ( instance ) . asJava ( ) ; }

Qualify this binding key with the given instance of an annotation.

<p>This can be used to specify bindings with annotations that have particular values.

Qualify this binding key with the given instance of an annotation .


public <A extends Annotation> BindingKey<T> qualifiedWith(final Class<A> annotation) {
    return underlying.qualifiedWith(annotation).asJava();
  }

public < A extends Annotation > BindingKey < T > qualifiedWith ( final Class < A > annotation ) { return underlying . qualifiedWith ( annotation ) . asJava ( ) ; }

Qualify this binding key with the given annotation.

For example, you may have both a cached implementation, and a direct implementation of a
service. To differentiate between them, you may define a Cached annotation:

{@code
bindClass(Foo.class).qualifiedWith(Cached.class).to(FooCached.class),
bindClass(Foo.class).to(FooImpl.class)

...

class MyController {
{@literal @}Inject
MyController({@literal @}Cached Foo foo) {
...
}
...
}
}

In the above example, the controller will get the cached {@code Foo} service.

Qualify this binding key with the given annotation .


public Binding<T> to(final Class<? extends T> implementation) {
    return underlying.to(implementation).asJava();
  }

public Binding < T > to ( final Class < ? extends T > implementation ) { return underlying . to ( implementation ) . asJava ( ) ; }

Bind this binding key to the given implementation class.

<p>This class will be instantiated and injected by the injection framework.

Bind this binding key to the given implementation class .


public Binding<T> to(final Provider<? extends T> provider) {
    return underlying.to(provider).asJava();
  }

public Binding < T > to ( final Provider < ? extends T > provider ) { return underlying . to ( provider ) . asJava ( ) ; }

Bind this binding key to the given provider instance.

<p>This provider instance will be invoked to obtain the implementation for the key.

Bind this binding key to the given provider instance .


public <A extends T> Binding<T> to(final Supplier<A> instance) {
    return underlying.to(new FromJavaSupplier<>(instance)).asJava();
  }

public < A extends T > Binding < T > to ( final Supplier < A > instance ) { return underlying . to ( new FromJavaSupplier <> ( instance ) ) . asJava ( ) ; }

Bind this binding key to the given instance.

Bind this binding key to the given instance .


public Binding<T> to(final BindingKey<? extends T> key) {
    return underlying.to(key.asScala()).asJava();
  }

public Binding < T > to ( final BindingKey < ? extends T > key ) { return underlying . to ( key . asScala ( ) ) . asJava ( ) ; }

Bind this binding key to another binding key.

Bind this binding key to another binding key .


public <P extends Provider<? extends T>> Binding<T> toProvider(final Class<P> provider) {
    return underlying.toProvider(provider).asJava();
  }

public < P extends Provider < ? extends T > > Binding < T > toProvider ( final Class < P > provider ) { return underlying . toProvider ( provider ) . asJava ( ) ; }

Bind this binding key to the given provider class.

<p>The dependency injection framework will instantiate and inject this provider, and then
invoke its `get` method whenever an instance of the class is needed.

Bind this binding key to the given provider class .


public static List<Lang> availables(Application app) {
    play.api.i18n.Langs langs = app.injector().instanceOf(play.api.i18n.Langs.class);
    List<play.api.i18n.Lang> availableLangs = Scala.asJava(langs.availables());
    return availableLangs.stream().map(Lang::new).collect(toList());
  }

public static List < Lang > availables ( Application app ) { play . api . i18n . Langs langs = app . injector ( ) . instanceOf ( play . api . i18n . Langs . class ) ; List < play . api . i18n . Lang > availableLangs = Scala . asJava ( langs . availables ( ) ) ; return availableLangs . stream ( ) . map ( Lang :: new ) . collect ( toList ( ) ) ; }

Retrieve Lang availables from the application configuration.

@param app the current application.
@return the list of available Lang.

Retrieve Lang availables from the application configuration .


public static Lang preferred(Application app, List<Lang> availableLangs) {
    play.api.i18n.Langs langs = app.injector().instanceOf(play.api.i18n.Langs.class);
    Stream<Lang> stream = availableLangs.stream();
    List<play.api.i18n.Lang> langSeq =
        stream.map(l -> new play.api.i18n.Lang(l.toLocale())).collect(toList());
    return new Lang(langs.preferred(Scala.toSeq(langSeq)));
  }

public static Lang preferred ( Application app , List < Lang > availableLangs ) { play . api . i18n . Langs langs = app . injector ( ) . instanceOf ( play . api . i18n . Langs . class ) ; Stream < Lang > stream = availableLangs . stream ( ) ; List < play . api . i18n . Lang > langSeq = stream . map ( l -> new play . api . i18n . Lang ( l . toLocale ( ) ) ) . collect ( toList ( ) ) ; return new Lang ( langs . preferred ( Scala . toSeq ( langSeq ) ) ) ; }

Guess the preferred lang in the langs set passed as argument. The first Lang that matches an
available Lang wins, otherwise returns the first Lang available in this application.

@param app the currept application
@param availableLangs the set of langs from which to guess the preferred
@return the preferred lang.

Guess the preferred lang in the langs set passed as argument . The first Lang that matches an available Lang wins otherwise returns the first Lang available in this application .


public static play.api.db.evolutions.EvolutionsReader fromMap(
      Map<String, List<Evolution>> evolutions) {
    return new SimpleEvolutionsReader(evolutions);
  }

public static play . api . db . evolutions . EvolutionsReader fromMap ( Map < String , List < Evolution > > evolutions ) { return new SimpleEvolutionsReader ( evolutions ) ; }

Create an evolutions reader based on a simple map of database names to evolutions.

@param evolutions The map of database names to evolutions.
@return the evolutions reader.

Create an evolutions reader based on a simple map of database names to evolutions .


public static play.api.db.evolutions.EvolutionsReader forDefault(Evolution... evolutions) {
    Map<String, List<Evolution>> map = new HashMap<String, List<Evolution>>();
    map.put("default", Arrays.asList(evolutions));
    return fromMap(map);
  }

public static play . api . db . evolutions . EvolutionsReader forDefault ( Evolution ... evolutions ) { Map < String , List < Evolution > > map = new HashMap < String , List < Evolution > > ( ) ; map . put ( "default" , Arrays . asList ( evolutions ) ) ; return fromMap ( map ) ; }

Create an evolutions reader for the default database from a list of evolutions.

@param evolutions The list of evolutions.
@return the evolutions reader.

Create an evolutions reader for the default database from a list of evolutions .


public static void cleanupEvolutions(Database database, boolean autocommit, String schema) {
    DatabaseEvolutions evolutions = new DatabaseEvolutions(database.asScala(), schema);
    evolutions.evolve(evolutions.resetScripts(), autocommit);
  }

public static void cleanupEvolutions ( Database database , boolean autocommit , String schema ) { DatabaseEvolutions evolutions = new DatabaseEvolutions ( database . asScala ( ) , schema ) ; evolutions . evolve ( evolutions . resetScripts ( ) , autocommit ) ; }

Cleanup evolutions for the given database.

<p>This will run the down scripts for all the applied evolutions.

@param database The database to apply the evolutions to.
@param autocommit Whether autocommit should be used.
@param schema The schema where all the play evolution tables are saved in

Cleanup evolutions for the given database .


public GuiceApplicationBuilder withConfigLoader(Function<Environment, Config> load) {
    return newBuilder(
        delegate.loadConfig(
            func(
                (play.api.Environment env) ->
                    new play.api.Configuration(load.apply(new Environment(env))))));
  }

public GuiceApplicationBuilder withConfigLoader ( Function < Environment , Config > load ) { return newBuilder ( delegate . loadConfig ( func ( ( play . api . Environment env ) -> new play . api . Configuration ( load . apply ( new Environment ( env ) ) ) ) ) ) ; }

Set the initial configuration loader. Overrides the default or any previously configured
values.

@param load the configuration loader
@return the configured application builder

Set the initial configuration loader . Overrides the default or any previously configured values .


public GuiceApplicationBuilder withModuleLoader(
      BiFunction<Environment, Config, List<GuiceableModule>> loader) {
    return newBuilder(
        delegate.load(
            func(
                (play.api.Environment env, play.api.Configuration conf) ->
                    Scala.toSeq(loader.apply(new Environment(env), conf.underlying())))));
  }

public GuiceApplicationBuilder withModuleLoader ( BiFunction < Environment , Config , List < GuiceableModule > > loader ) { return newBuilder ( delegate . load ( func ( ( play . api . Environment env , play . api . Configuration conf ) -> Scala . toSeq ( loader . apply ( new Environment ( env ) , conf . underlying ( ) ) ) ) ) ) ; }

Set the module loader. Overrides the default or any previously configured values.

@param loader the configuration
@return the configured application builder

Set the module loader . Overrides the default or any previously configured values .


public GuiceApplicationBuilder load(GuiceableModule... modules) {
    return newBuilder(delegate.load(Scala.varargs(modules)));
  }

public GuiceApplicationBuilder load ( GuiceableModule ... modules ) { return newBuilder ( delegate . load ( Scala . varargs ( modules ) ) ) ; }

Override the module loader with the given guiceable modules.

@param modules the set of overriding modules
@return an application builder that incorporates the overrides

Override the module loader with the given guiceable modules .


public GuiceApplicationBuilder load(com.google.inject.Module... modules) {
    return load(Guiceable.modules(modules));
  }

public GuiceApplicationBuilder load ( com . google . inject . Module ... modules ) { return load ( Guiceable . modules ( modules ) ) ; }

Override the module loader with the given Guice modules.

@param modules the set of overriding modules
@return an application builder that incorporates the overrides

Override the module loader with the given Guice modules .


public GuiceApplicationBuilder load(play.api.inject.Module... modules) {
    return load(Guiceable.modules(modules));
  }

public GuiceApplicationBuilder load ( play . api . inject . Module ... modules ) { return load ( Guiceable . modules ( modules ) ) ; }

Override the module loader with the given Play modules.

@param modules the set of overriding modules
@return an application builder that incorporates the overrides

Override the module loader with the given Play modules .


public GuiceApplicationBuilder load(play.api.inject.Binding<?>... bindings) {
    return load(Guiceable.bindings(bindings));
  }

public GuiceApplicationBuilder load ( play . api . inject . Binding < ? > ... bindings ) { return load ( Guiceable . bindings ( bindings ) ) ; }

Override the module loader with the given Play bindings.

@param bindings the set of binding override
@return an application builder that incorporates the overrides

Override the module loader with the given Play bindings .


protected GuiceApplicationBuilder newBuilder(
      play.api.inject.guice.GuiceApplicationBuilder builder) {
    return new GuiceApplicationBuilder(builder);
  }

protected GuiceApplicationBuilder newBuilder ( play . api . inject . guice . GuiceApplicationBuilder builder ) { return new GuiceApplicationBuilder ( builder ) ; }

Implementation of Self creation for GuiceBuilder.

@return the application builder

Implementation of Self creation for GuiceBuilder .


public String encode(Cookie cookie) {
    if (cookie == null) {
      throw new NullPointerException("cookie");
    }
    StringBuilder buf = new StringBuilder();
    encode(buf, cookie);
    return stripTrailingSeparator(buf);
  }

public String encode ( Cookie cookie ) { if ( cookie == null ) { throw new NullPointerException ( "cookie" ) ; } StringBuilder buf = new StringBuilder ( ) ; encode ( buf , cookie ) ; return stripTrailingSeparator ( buf ) ; }

Encodes the specified cookie into a Cookie header value.

@param cookie specified the cookie
@return a Rfc6265 style Cookie header value

Encodes the specified cookie into a Cookie header value .


public EntityManager em() {
    Deque<EntityManager> ems = this.emStack(true);

    if (ems.isEmpty()) {
      Http.Context.safeCurrent()
          .map(
              ctx -> {
                throw new RuntimeException(
                    "No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional");
              })
          .orElseGet(
              () -> {
                throw new RuntimeException(
                    "No EntityManager bound to this thread. Try wrapping this call in JPAApi.withTransaction, or ensure that the HTTP context is setup on this thread.");
              });
    }

    return ems.peekFirst();
  }

Get the default EntityManager for this thread.

@throws RuntimeException if no EntityManager is bound to the current Http.Context or the
current Thread.
@return the EntityManager

Get the default EntityManager for this thread .


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

Get the EntityManager stack.

@param threadLocalFallback if true, fall back to a ThreadLocal queue of entity managers if no
HTTP.Context object is found.
@return the queue of entity managers.


void pushOrPopEm(EntityManager em, boolean threadLocalFallback) {
    Deque<EntityManager> ems = this.emStack(threadLocalFallback);
    if (em != null) {
      ems.push(em);
    } else {
      if (ems.isEmpty()) {
        throw new IllegalStateException("Tried to remove the EntityManager, but none was set.");
      }
      ems.pop();
    }
  }

Pushes or pops the EntityManager stack depending on the value of the em argument. If em is
null, then the current EntityManager is popped. If em is non-null, then em is pushed onto the
stack and becomes the current EntityManager.

@param em the entity manager to push, if null then will pop one off the stack.
@param threadLocalFallback if true, fall back to a ThreadLocal queue of entity managers if no
HTTP.Context object is found.

Pushes or pops the EntityManager stack depending on the value of the em argument . If em is null then the current EntityManager is popped . If em is non - null then em is pushed onto the stack and becomes the current EntityManager .


public static <In, FlowIn, Out> Flow<In, Out, ?> bypassWith(
      Function<In, F.Either<FlowIn, Out>> splitter, Flow<FlowIn, Out, ?> flow) {
    return bypassWith(
        Flow.<In>create().map(splitter::apply),
        play.api.libs.streams.AkkaStreams.onlyFirstCanFinishMerge(2),
        flow);
  }

public static < In , FlowIn , Out > Flow < In , Out , ? > bypassWith ( Function < In , F . Either < FlowIn , Out > > splitter , Flow < FlowIn , Out , ? > flow ) { return bypassWith ( Flow . < In > create ( ) . map ( splitter :: apply ) , play . api . libs . streams . AkkaStreams . onlyFirstCanFinishMerge ( 2 ) , flow ) ; }

Bypass the given flow using the given splitter function.

If the splitter function returns Left, they will go through the flow. If it returns Right,
they will bypass the flow.

Uses onlyFirstCanFinishMerge(2) by default.

@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 to use
@return the flow with a bypass.

Bypass the given flow using the given splitter function .