public interface Context extends ExecControl, Registry
Handler
invocation.
It provides:
request
and response
next()
and insert(ratpack.handling.Handler...)
family of methods)
A context is also a Registry
of objects.
Arbitrary objects can be "pushed" into the context for use by downstream handlers.
There are some significant contextual objects that drive key infrastructure.
For example, error handling is based on informing the contextual ServerErrorHandler
of exceptions.
The error handling strategy for an application can be changed by pushing a new implementation of this interface into the context that is used downstream.
See insert(Handler...)
for more on how to do this.
There is also a set of default objects that are made available via the Ratpack infrastructure:
LaunchConfig
FileSystemBinding
that is the application LaunchConfig.getBaseDir()
MimeTypes
implementationServerErrorHandler
ClientErrorHandler
FileRenderer
BindAddress
PublicAddress
Redirector
Modifier and Type | Method and Description |
---|---|
void |
addInterceptor(ExecInterceptor execInterceptor,
Action<? super Execution> continuation)
Adds an interceptor that wraps the rest of the current execution segment and all future segments of this execution.
|
<T> Iterable<? extends T> |
all(TypeToken<T> type,
Predicate<? super T> predicate)
Returns all of the objects whose declared type is assignment compatible with the given type and who satisfy the given predicate.
|
<T> Promise<T> |
blocking(Callable<T> blockingOperation)
Executes a blocking operation, returning a promise for its result.
|
void |
byContent(Action<? super ByContentSpec> action)
Respond to the request based on the requested content type (i.e.
|
void |
byMethod(Action<? super ByMethodSpec> action)
Respond to the request based on the request method.
|
void |
clientError(int statusCode)
Forwards the error to the
ClientErrorHandler in this service. |
<T> boolean |
each(TypeToken<T> type,
Predicate<? super T> predicate,
Action<? super T> action)
Calls the given action with each object whose declared type is assignment compatible with the given type and who satisfies the given predicate.
|
void |
error(Throwable throwable)
Forwards the exception to the
ServerErrorHandler in this service. |
Path |
file(String path)
Gets the file relative to the contextual
FileSystemBinding . |
<T> T |
first(TypeToken<T> type,
Predicate<? super T> predicate)
Returns the first object whose declared type is assignment compatible with the given type and who satisfies the given predicate.
|
void |
fork(Action<? super Execution> action)
Forks a new execution, detached from the current.
|
void |
fork(Action<? super Execution> action,
Action<? super Throwable> onError) |
void |
fork(Action<? super Execution> action,
Action<? super Throwable> onError,
Action<? super Execution> onComplete) |
<O> O |
get(Class<O> type)
Provides an object of the specified type, or throws an exception if no object of that type is available.
|
<O> O |
get(TypeToken<O> type)
Provides an object of the specified type, or throws an exception if no object of that type is available.
|
<O> Iterable<? extends O> |
getAll(Class<O> type)
Returns all of the objects whose declared type is assignment compatible with the given type.
|
<O> Iterable<? extends O> |
getAll(TypeToken<O> type)
Returns all of the objects whose declared type is assignment compatible with the given type.
|
PathTokens |
getAllPathTokens()
The contextual path tokens of the current
PathBinding . |
BindAddress |
getBindAddress()
The address that this request was received on.
|
Context |
getContext()
Returns this.
|
ExecController |
getController() |
DirectChannelAccess |
getDirectChannelAccess()
Provides direct access to the backing Netty channel.
|
Execution |
getExecution()
The execution of handling this request.
|
LaunchConfig |
getLaunchConfig() |
PathTokens |
getPathTokens()
The contextual path tokens of the current
PathBinding . |
Request |
getRequest()
The HTTP request.
|
Response |
getResponse()
The HTTP response.
|
void |
insert(Handler... handlers)
Inserts some handlers into the pipeline, then delegates to the first.
|
void |
insert(Registry registry,
Handler... handlers)
Inserts some handlers into the pipeline to execute with the given registry, then delegates to the first.
|
void |
lastModified(Date date,
Runnable runnable)
Convenience method for handling last-modified based HTTP caching.
|
<O> O |
maybeGet(Class<O> type)
Does the same thing as
Registry.get(Class) , except returns null instead of throwing an exception. |
<O> O |
maybeGet(TypeToken<O> type)
Does the same thing as
Registry.get(Class) , except returns null instead of throwing an exception. |
void |
next()
Delegate handling to the next handler in line.
|
void |
next(Registry registry)
Invokes the next handler, after adding the given registry.
|
void |
onClose(Action<? super RequestOutcome> onClose)
Registers a callback to be notified when the request for this context is “closed” (i.e.
|
<T> T |
parse(Class<T> type)
Parse the request into the given type, using no options (or more specifically an instance of
NullParseOpts as the options). |
<T,O> T |
parse(Class<T> type,
O options)
Constructs a
Parse from the given args and delegates to parse(Parse) . |
<T,O> T |
parse(Parse<T,O> parse)
Parses the request body into an object.
|
<T> T |
parse(TypeToken<T> type)
Parse the request into the given type, using no options (or more specifically an instance of
NullParseOpts as the options). |
<T,O> T |
parse(TypeToken<T> type,
O options)
Constructs a
Parse from the given args and delegates to parse(Parse) . |
<T> Promise<T> |
promise(Action<? super Fulfiller<T>> action)
Creates a promise of a value that will made available asynchronously.
|
void |
redirect(int code,
String location)
Sends a redirect response location URL and status code (which should be in the 3xx range).
|
void |
redirect(String location)
Sends a temporary redirect response (i.e.
|
void |
render(Object object)
Render the given object, using the rendering framework.
|
<T> void |
stream(org.reactivestreams.Publisher<T> publisher,
org.reactivestreams.Subscriber<? super T> subscriber)
Process streams of data asynchronously with non-blocking back pressure.
|
Context getContext()
Execution getExecution()
getExecution
in interface ExecControl
LaunchConfig getLaunchConfig()
Request getRequest()
Response getResponse()
@NonBlocking void next()
The request and response of this object should not be accessed after this method is called.
@NonBlocking void next(Registry registry)
The given registry is appended to the existing. This means that it can shadow objects previously available.
import ratpack.handling.Handler; import ratpack.handling.Handlers; import ratpack.handling.Chain; import ratpack.handling.ChainAction; import ratpack.handling.Context; import ratpack.launch.HandlerFactory; import ratpack.launch.LaunchConfig; import ratpack.launch.LaunchConfigBuilder; import ratpack.func.Factory; import static ratpack.registry.Registries.just; public interface SomeThing {} public class SomeThingImpl implements SomeThing {} public class UpstreamHandler implements Handler { public void handle(Context context) { context.next(just(SomeThing.class, new SomeThingImpl())); } } public class DownstreamHandler implements Handler { public void handle(Context context) { SomeThing someThing = context.get(SomeThing.class); // instance provided upstream assert someThing instanceof SomeThingImpl; // … } } LaunchConfigBuilder.baseDir(new File("base")).build(new HandlerFactory() { public Handler create(LaunchConfig launchConfig) { return Handlers.chain(launchConfig, new ChainAction() { protected void execute() { handler(new UpstreamHandler()); handler(new DownstreamHandler()); } }); } });
registry
- The registry to make available for subsequent handlers.@NonBlocking void insert(Handler... handlers)
The request and response of this object should not be accessed after this method is called.
handlers
- The handlers to insert.@NonBlocking void insert(Registry registry, Handler... handlers)
The given registry is only applicable to the inserted handlers.
Almost always, the registry should be a super set of the current registry.
handlers
- The handlers to insertregistry
- The registry for the inserted handlers@NonBlocking void byMethod(Action<? super ByMethodSpec> action) throws Exception
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.handling.ByMethodSpec; import ratpack.func.Action; import ratpack.test.UnitTest; import ratpack.test.handling.HandlingResult; import ratpack.test.handling.RequestFixture; public class Example { public static class MultiMethodHandler implements Handler { public void handle(final Context context) throws Exception { final String message = "hello!"; context.byMethod(new Action<ByMethodSpec>() { public void execute(ByMethodSpec spec) { spec.get(new Handler() { public void handle(Context context) { context.render(message + " from GET request"); } }). post(new Handler() { public void handle(Context context) { context.render(message + " from POST request"); } }); } }); } } public static void main(String[] args) { Handler handler = new MultiMethodHandler(); HandlingResult result = UnitTest.handle(handler, new Action<RequestFixture>() { public void execute(RequestFixture fixture) { fixture.method("get"); } }); assert result.rendered(String.class).equals("hello! from GET request"); result = UnitTest.handle(handler, new Action<RequestFixture>() { public void execute(RequestFixture fixture) { fixture.method("post"); } }); assert result.rendered(String.class).equals("hello! from POST request"); } }
Only the last added handler for a method will be used. Adding a subsequent handler for the same method will replace the previous.
If no handler has been registered for the actual request method, a 405
will be issued by clientError(int)
.
If the handler only needs to respond to one HTTP method it can be more convenient to use Chain.get(Handler)
and friends.
action
- the specification of how to handle the request based on the request methodException
- any thrown by actionvoid byContent(Action<? super ByContentSpec> action) throws Exception
This is useful when a given handler can provide content of more than one type (i.e. content negotiation).
The handler to use will be selected based on parsing the "Accepts" header, respecting quality weighting and wildcard matching. The order that types are specified is significant for wildcard matching. The earliest registered type that matches the wildcard will be used.
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.handling.ByContentSpec; import ratpack.func.Action; import ratpack.test.UnitTest; import ratpack.test.handling.HandlingResult; import ratpack.test.handling.RequestFixture; public class Example { public static class ContentNegotiatingHandler implements Handler { public void handle(final Context context) throws Exception { final String message = "hello!"; context.byContent(new Action<ByContentSpec>() { public void execute(ByContentSpec spec) { spec.json(new Handler() { public void handle(Context context) { context.render("{\"msg\": \"" + message + "\"}"); } }). html(new Handler() { public void handle(Context context) { context.render("<p>" + message + "</p>"); } }); } }); } } public static void main(String[] args) { Handler handler = new ContentNegotiatingHandler(); HandlingResult result = UnitTest.handle(handler, new Action<RequestFixture>() { public void execute(RequestFixture fixture) { fixture.header("Accept", "application/json"); } }); assert result.rendered(String.class).equals("{\"msg\": \"hello!\"}"); assert result.getHeaders().get("Content-Type").equals("application/json"); result = UnitTest.handle(handler, new Action<RequestFixture>() { public void execute(RequestFixture fixture) { fixture.header("Accept", "text/plain; q=1.0, text/html; q=0.8, application/json; q=0.7"); } }); assert result.rendered(String.class).equals("<p>hello!</p>"); assert result.getHeaders().get("content-type").equals("text/html;charset=UTF-8"); } }If there is no type registered, or if the client does not accept any of the given types, a
406
will be issued with clientError(int)
.
Only the last specified handler for a type will be used. That is, adding a subsequent handler for the same type will replace the previous.
action
- the specification of how to handle the request based on the clients preference of content typeException
- any thrown by action@NonBlocking void error(Throwable throwable)
ServerErrorHandler
in this service.
The default configuration of Ratpack includes a ServerErrorHandler
in all contexts.
A NotInRegistryException
will only be thrown if a very custom service setup is being used.
throwable
- The exception that occurredNotInRegistryException
- if no ServerErrorHandler
can be found in the service<T> Promise<T> blocking(Callable<T> blockingOperation)
This method executes asynchronously, in that it does not invoke the operation
before returning the promise.
When the returned promise is subscribed to (i.e. its SuccessPromise.then(Action)
method is called),
the given operation
will be submitted to a thread pool that is different to the request handling thread pool.
Therefore, if the returned promise is never subscribed to, the operation
will never be initiated.
The promise returned by this method, has the same default error handling strategy as those returned by ExecControl.promise(ratpack.func.Action)
.
import ratpack.handling.*; import ratpack.func.Action; import java.util.concurrent.Callable; public class BlockingJavaHandler implements Handler { void handle(final Context context) { context.blocking(new Callable<String>() { public String call() { // perform some kind of blocking IO in here, such as accessing a database return "hello world!"; } }).then(new Action<String>() { public void execute(String result) { context.render(result); } }); } } public class BlockingGroovyHandler implements Handler { void handle(final Context context) { context.blocking { "hello world!" } then { String result -> context.render(result) } } } // Test (Groovy) … import static ratpack.test.http.TestHttpClients.testHttpClient import static ratpack.groovy.test.embed.EmbeddedApplications.embeddedApp def app = embeddedApp { handlers { get("java", new BlockingJavaHandler()) get("groovy", new BlockingGroovyHandler()) } } def client = testHttpClient(app) assert client.getText("java") == "hello world!" assert client.getText("groovy") == "hello world!" app.close()
blocking
in interface ExecControl
T
- The type of result object that the operation producesblockingOperation
- The operation to perform<T> Promise<T> promise(Action<? super Fulfiller<T>> action)
The action
given to this method receives a Fulfiller
, which can be used to fulfill the promise at any time in the future.
The action
is not required to fulfill the promise during the execution of the execute()
method (i.e. it can be asynchronous).
The action
MUST call one of the fulfillment methods.
Otherwise, the promise will go unfulfilled.
There is no time limit or timeout on fulfillment.
The promise returned has a default error handling strategy of forwarding exceptions to error(Throwable)
of this context.
To use a different error strategy, supply it to the Promise.onError(Action)
method.
The promise will always be fulfilled on a thread managed by Ratpack.
import ratpack.handling.*; import ratpack.exec.Fulfiller; import ratpack.func.Action; public class PromiseUsingJavaHandler implements Handler { public void handle(final Context context) { context.promise(new Action<Fulfiller<String>>() { public void execute(final Fulfiller<String> fulfiller) { new Thread(new Runnable() { public void run() { fulfiller.success("hello world!"); } }).start(); } }).then(new Action<String>() { public void execute(String string) { context.render(string); } }); } } class PromiseUsingGroovyHandler implements Handler { void handle(Context context) { context.promise { Fulfiller<String> fulfiller -> Thread.start { fulfiller.success("hello world!") } } then { String string -> context.render(string) } } } // Test (Groovy) … import static ratpack.test.http.TestHttpClients.testHttpClient import static ratpack.groovy.test.embed.EmbeddedApplications.embeddedApp def app = embeddedApp { handlers { get("java", new PromiseUsingJavaHandler()) get("groovy", new PromiseUsingGroovyHandler()) } } def client = testHttpClient(app) assert client.getText("java") == "hello world!" assert client.getText("groovy") == "hello world!" app.close()
promise
in interface ExecControl
T
- the type of value promisedaction
- an action that invokes an asynchronous API, forwarding the result to the given fulfiller.Fulfiller
,
Fulfillment
void fork(Action<? super Execution> action)
This can be used to launch a one time background job during request processing. The forked execution does not inherit anything from the current execution.
Forked executions MUST NOT write to the response or participate in the handler pipeline at all.
That is, they should not call methods like next()
or insert(Handler...)
.
When using forking to process work in parallel, use promise(ratpack.func.Action)
to continue request handling when the parallel work is done.
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.func.Action; import ratpack.func.Actions; import ratpack.exec.Execution; import ratpack.exec.Fulfiller; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import ratpack.test.UnitTest; import ratpack.test.handling.HandlingResult; import ratpack.test.handling.RequestFixture; public class Example { public static class ForkingHandler implements Handler { public void handle(final Context context) { final int numJobs = 3; final Integer failOnIteration = context.getPathTokens().asInt("failOn"); context.promise(new Action<Fulfiller<Integer>>() { private final AtomicInteger counter = new AtomicInteger(); private final AtomicReference<Throwable> error = new AtomicReference<>(); private void completeJob(Fulfiller<Integer> fulfiller) { if (counter.incrementAndGet() == numJobs) { Throwable throwable = error.get(); if (throwable == null) { fulfiller.success(numJobs); } else { fulfiller.error(throwable); } } } public void execute(final Fulfiller<Integer> fulfiller) { for (int i = 0; i < numJobs; ++i) { final int iteration = i; context.fork(new Action<Execution>() { public void execute(Execution execution) throws Exception { if (failOnIteration != null && failOnIteration.intValue() == iteration) { throw new Exception("bang!"); } else { completeJob(fulfiller); } } }, new Action<Throwable>() { public void execute(Throwable throwable) { error.compareAndSet(null, throwable); // just take the first error completeJob(fulfiller); } }); } } }).then(new Action<Integer>() { public void execute(Integer integer) { context.render(integer.toString()); } }); } } public static void main(String[] args) { HandlingResult result = UnitTest.handle(new ForkingHandler(), Actions.noop()); assert result.rendered(String.class).equals("3"); result = UnitTest.handle(new ForkingHandler(), new Action<RequestFixture>() { public void execute(RequestFixture fixture) { fixture.pathBinding(Collections.singletonMap("failOn", "2")); } }); assert result.getException().getMessage().equals("bang!"); } }
fork
in interface ExecControl
action
- the initial execution segmentExecController getController()
getController
in interface ExecControl
void addInterceptor(ExecInterceptor execInterceptor, Action<? super Execution> continuation) throws Exception
ExecControl
The given action is executed immediately (i.e. as opposed to being queued to be executed as the next execution segment). Any code executed after a call to this method in the same execution segment WILL NOT be intercepted. Therefore, it is advisable to not execute any code after calling this method in a given execution segment.
See ExecInterceptor
for example use of an interceptor.
addInterceptor
in interface ExecControl
execInterceptor
- the execution interceptor to addcontinuation
- the rest of the code to be executedException
- any thrown by continuation
ExecInterceptor
void fork(Action<? super Execution> action, Action<? super Throwable> onError)
fork
in interface ExecControl
void fork(Action<? super Execution> action, Action<? super Throwable> onError, Action<? super Execution> onComplete)
fork
in interface ExecControl
<T> void stream(org.reactivestreams.Publisher<T> publisher, org.reactivestreams.Subscriber<? super T> subscriber)
ExecControl
This method allows the processing of elements (onNext) or termination signals (onError, onComplete) to happen outside of the execution stack of the Publisher. In other words these "events" are executed asynchronously, on a Ratpack managed thread, without blocking the Publisher.
stream
in interface ExecControl
T
- the type of streamed elementspublisher
- the provider of a potentially unbounded number of sequenced elements, publishing them according to the demand
received from its Subscriber(s)subscriber
- a component that accepts a sequenced stream of elements provided by a Publisher@NonBlocking void clientError(int statusCode) throws NotInRegistryException
ClientErrorHandler
in this service.
The default configuration of Ratpack includes a ClientErrorHandler
in all contexts.
A NotInRegistryException
will only be thrown if a very custom service setup is being used.statusCode
- The 4xx range status code that indicates the error typeNotInRegistryException
- if no ClientErrorHandler
can be found in the service@NonBlocking void render(Object object) throws NoSuchRendererException
The first Renderer
, that is able to render the given object will be delegated to.
If the given argument is null
, this method will have the same effect as clientError(404)
.
If no renderer can be found for the given type, a NoSuchRendererException
will be given to error(Throwable)
.
If a renderer throws an exception during its execution it will be wrapped in a RendererException
and given to error(Throwable)
.
Ratpack has built in support for rendering the following types:
Path
(see FileRenderer
)CharSequence
(see CharSequenceRenderer
)
See Renderer
for more on how to contribute to the rendering framework.
object
- The object to renderNoSuchRendererException
- if no suitable renderer can be foundvoid redirect(String location) throws NotInRegistryException
location
- the redirect location URLNotInRegistryException
- if there is no Redirector
in the current service but one is provided by defaultvoid redirect(int code, String location) throws NotInRegistryException
code
- The status code of the redirectlocation
- the redirect location URLNotInRegistryException
- if there is no Redirector
in the current service but one is provided by default@NonBlocking void lastModified(Date date, Runnable runnable)
The given date is the "last modified" value of the response. If the client sent an "If-Modified-Since" header that is of equal or greater value than date, a 304 will be returned to the client. Otherwise, the given runnable will be executed (it should send a response) and the "Last-Modified" header will be set by this method.
date
- The effective last modified date of the responserunnable
- The response sending action if the response needs to be sent<T> T parse(Class<T> type) throws NoSuchParserException, ParserException
NullParseOpts
as the options).
The code sample is functionally identical to the sample given for the parse(Parse)
variant…
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.form.Form; public class FormHandler implements Handler { public void handle(Context context) { Form form = context.parse(Form.class); context.render(form.get("someFormParam")); } }
That is, it is a convenient form of parse(Parse.of(T))
.
T
- the type to parse totype
- the type to parse toNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsing<T> T parse(TypeToken<T> type) throws NoSuchParserException, ParserException
NullParseOpts
as the options).
The code sample is functionally identical to the sample given for the parse(Parse)
variant…
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.form.Form; import com.google.common.reflect.TypeToken; public class FormHandler implements Handler { public void handle(Context context) { Form form = context.parse(new TypeToken<Form>() {}); context.render(form.get("someFormParam")); } }
That is, it is a convenient form of parse(Parse.of(T))
.
T
- the type to parse totype
- the type to parse toNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsing<T,O> T parse(Class<T> type, O options) throws NoSuchParserException, ParserException
Parse
from the given args and delegates to parse(Parse)
.T
- The type to parse toO
- The type of the parse optstype
- The type to parse tooptions
- The parse optionsNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsing<T,O> T parse(TypeToken<T> type, O options) throws NoSuchParserException, ParserException
Parse
from the given args and delegates to parse(Parse)
.T
- The type to parse toO
- The type of the parse optstype
- The type to parse tooptions
- The parse optionsNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsing<T,O> T parse(Parse<T,O> parse) throws NoSuchParserException, ParserException
How to parse the request is determined by the given Parse
object.
Parser resolution happens as follows:
parsers
are retrieved from the context registry (i.e. getAll(Parser.class)
);getAll()
) for compatibility with the current request content type and options type;Parser.parse(Context, ratpack.http.TypedData, Parse)
method is called;null
the next parser will be tried, if it returns a value it will be returned by this method;NoSuchParserException
will be thrown.A parser is compatible if all of the following hold true:
Parser.getContentType()
is exactly equal to getRequest().getBody().getContentType().getType()
parse
object is an instanceof
its Parser.getOptsType()
()}Parser.parse(Context, ratpack.http.TypedData, Parse)
method returns a non null value.
If the request has no declared content type, text/plain
will be assumed.
Ratpack core provides implicit no opt parsers
for the following types and content types:
Form
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.form.Form; import ratpack.parse.Parse; import ratpack.parse.NullParseOpts; public class FormHandler implements Handler { public void handle(Context context) { Form form = context.parse(Parse.of(Form.class)); context.render(form.get("someFormParam")); } }
T
- The type of object the request is parsed intoO
- the type of the parse options objectparse
- The specification of how to parse the requestNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsingparse(Class)
,
parse(Class, Object)
,
Parser
DirectChannelAccess getDirectChannelAccess()
General only useful for low level extensions. Avoid if possible.
BindAddress getBindAddress()
PathTokens getPathTokens() throws NotInRegistryException
PathBinding
.
Shorthand for get(PathBinding.class).getPathTokens()
.
PathBinding
.NotInRegistryException
- if there is no PathBinding
in the current servicePathTokens getAllPathTokens() throws NotInRegistryException
PathBinding
.
Shorthand for get(PathBinding.class).getAllPathTokens()
.
PathBinding
.NotInRegistryException
- if there is no PathBinding
in the current servicevoid onClose(Action<? super RequestOutcome> onClose)
onClose
- A notification callbackPath file(String path) throws NotInRegistryException
FileSystemBinding
.
Shorthand for get(FileSystemBinding.class).file(path)
.
The default configuration of Ratpack includes a FileSystemBinding
in all contexts.
A NotInRegistryException
will only be thrown if a very custom service setup is being used.
path
- The path to pass to the FileSystemBinding.file(String)
method.FileSystemBinding
NotInRegistryException
- if there is no FileSystemBinding
in the current service<O> O get(Class<O> type) throws NotInRegistryException
get
in interface Registry
O
- The type of the object to providetype
- The type of the object to provideNotInRegistryException
- If no object of this type can be returned@Nullable <O> O maybeGet(Class<O> type)
Registry.get(Class)
, except returns null instead of throwing an exception.<O> Iterable<? extends O> getAll(Class<O> type)
<O> O get(TypeToken<O> type) throws NotInRegistryException
get
in interface Registry
O
- The type of the object to providetype
- The type of the object to provideNotInRegistryException
- If no object of this type can be returned@Nullable <O> O maybeGet(TypeToken<O> type)
Registry.get(Class)
, except returns null instead of throwing an exception.<O> Iterable<? extends O> getAll(TypeToken<O> type)
@Nullable <T> T first(TypeToken<T> type, Predicate<? super T> predicate)
first
in interface Registry
T
- the type of the object to search fortype
- the type of object to search forpredicate
- a predicate to check objects against<T> Iterable<? extends T> all(TypeToken<T> type, Predicate<? super T> predicate)
<T> boolean each(TypeToken<T> type, Predicate<? super T> predicate, Action<? super T> action) throws Exception
each
in interface Registry
T
- the type of object to search fortype
- the type of object to search forpredicate
- a predicate to check objects againstaction
- an action to call with each matching objectException
- any thrown by action