@ConfigurableContext(nocache=true) public class RestContext extends BeanContext
Modifier and Type | Class and Description |
---|---|
static class |
RestContext.Null
Represents a null value for the
Rest.context() annotation. |
Modifier and Type | Field and Description |
---|---|
static String |
REST_allowBodyParam
Configuration property: Allow body URL parameter.
|
static String |
REST_allowedHeaderParams
Configuration property: Allowed header URL parameters.
|
static String |
REST_allowedMethodHeaders
Configuration property: Allowed method headers.
|
static String |
REST_allowedMethodParams
Configuration property: Allowed method URL parameters.
|
static String |
REST_allowHeaderParams
Deprecated.
|
static String |
REST_attrs
Deprecated.
|
static String |
REST_callHandler
Deprecated.
|
static String |
REST_callLogger
Configuration property: REST call logger.
|
static String |
REST_callLoggerConfig
Configuration property: REST call logging rules.
|
static String |
REST_children
Configuration property: Children.
|
static String |
REST_classpathResourceFinder
Configuration property: Classpath resource finder.
|
static String |
REST_clientVersionHeader
Configuration property: Client version header.
|
static String |
REST_consumes
Configuration property: Supported content media types.
|
static String |
REST_context
Configuration property: REST context class.
|
static String |
REST_converters
Configuration property: Class-level response converters.
|
static String |
REST_debug
Configuration property: Debug mode.
|
static String |
REST_debugOn
Configuration property: Debug mode on specified classes/methods.
|
static String |
REST_defaultCharset
Configuration property: Default character encoding.
|
static String |
REST_defaultRequestHeaders
Deprecated.
|
static String |
REST_defaultResponseHeaders
Deprecated.
|
static String |
REST_encoders
Configuration property: Compression encoders.
|
static String |
REST_guards
Configuration property: Class-level guards.
|
static String |
REST_infoProvider
Configuration property: REST info provider.
|
static String |
REST_logger
Deprecated.
|
static String |
REST_maxInput
Configuration property: The maximum allowed input size (in bytes) on HTTP requests.
|
static String |
REST_messages
Configuration property: Messages.
|
static String |
REST_mimeTypes
Configuration property: MIME types.
|
static String |
REST_paramResolvers
Configuration property: Java method parameter resolvers.
|
static String |
REST_parsers
Configuration property: Parsers.
|
static String |
REST_partParser
Configuration property: HTTP part parser.
|
static String |
REST_partSerializer
Configuration property: HTTP part serializer.
|
static String |
REST_path
Configuration property: Resource path.
|
static String |
REST_produces
Configuration property: Supported accept media types.
|
static String |
REST_properties
Configuration property: Properties.
|
static String |
REST_renderResponseStackTraces
Configuration property: Render response stack traces in responses.
|
static String |
REST_reqAttrs
Configuration property: Default request attributes.
|
static String |
REST_reqHeaders
Configuration property: Default request headers.
|
static String |
REST_resHeaders
Configuration property: Default response headers.
|
static String |
REST_resourceResolver
Configuration property: REST resource resolver.
|
static String |
REST_responseHandlers
Configuration property: Response handlers.
|
static String |
REST_roleGuard
Configuration property: Role guard.
|
static String |
REST_rolesDeclared
Configuration property: Declared roles.
|
static String |
REST_serializers
Configuration property: Serializers.
|
static String |
REST_staticFileResponseHeaders
Configuration property: Static file response headers.
|
static String |
REST_staticFiles
Configuration property: Static file mappings.
|
static String |
REST_uriAuthority
Configuration property: Resource URI authority path.
|
static String |
REST_uriContext
Configuration property: Resource URI context path.
|
static String |
REST_uriRelativity
Configuration property: URI resolution relativity.
|
static String |
REST_uriResolution
Configuration property: URI resolution.
|
static String |
REST_useClasspathResourceCaching
Configuration property: Use classpath resource caching.
|
static String |
REST_useStackTraceHashes
Deprecated.
|
static String |
REST_widgets
Deprecated.
|
BEAN_annotations, BEAN_beanClassVisibility, BEAN_beanConstructorVisibility, BEAN_beanDictionary, BEAN_beanDictionary_add, BEAN_beanDictionary_remove, BEAN_beanFieldVisibility, BEAN_beanFilters, BEAN_beanFilters_add, BEAN_beanFilters_remove, BEAN_beanMapPutReturnsOldValue, BEAN_beanMethodVisibility, BEAN_beansRequireDefaultConstructor, BEAN_beansRequireSerializable, BEAN_beansRequireSettersForGetters, BEAN_beansRequireSomeProperties, BEAN_bpi, BEAN_bpro, BEAN_bpwo, BEAN_bpx, BEAN_examples, BEAN_excludeProperties, BEAN_fluentSetters, BEAN_ignoreInvocationExceptionsOnGetters, BEAN_ignoreInvocationExceptionsOnSetters, BEAN_ignorePropertiesWithoutSetters, BEAN_ignoreTransientFields, BEAN_ignoreUnknownBeanProperties, BEAN_ignoreUnknownNullBeanProperties, BEAN_implClasses, BEAN_includeProperties, BEAN_notBeanClasses, BEAN_notBeanClasses_add, BEAN_notBeanClasses_remove, BEAN_notBeanPackages, BEAN_notBeanPackages_add, BEAN_notBeanPackages_remove, BEAN_pojoSwaps, BEAN_pojoSwaps_add, BEAN_pojoSwaps_remove, BEAN_propertyNamer, BEAN_sortProperties, BEAN_swaps, BEAN_swaps_add, BEAN_swaps_remove, BEAN_typePropertyName, BEAN_useEnumNames, BEAN_useInterfaceProxies, BEAN_useJavaBeanIntrospector, DEFAULT, DEFAULT_SORTED
CONTEXT_debug, CONTEXT_locale, CONTEXT_mediaType, CONTEXT_timeZone
Constructor and Description |
---|
RestContext(RestContextBuilder builder)
Constructor.
|
Modifier and Type | Method and Description |
---|---|
protected void |
checkForInitException()
Throws a
HttpException if an exception occurred in the constructor of this object. |
Throwable |
convertThrowable(Throwable t)
Method that can be subclassed to allow uncaught throwables to be treated as other types of throwables.
|
static RestContextBuilder |
create(Object resource)
Constructor.
|
protected RestCall |
createCall(HttpServletRequest req,
HttpServletResponse res)
Wraps an incoming servlet request/response pair into a single
RestCall object. |
RestRequest |
createRequest(RestCall call)
Creates a
RestRequest object based on the specified incoming HttpServletRequest object. |
RestResponse |
createResponse(RestCall call)
Creates a
RestResponse object based on the specified incoming HttpServletResponse object
and the request returned by createRequest(RestCall) . |
protected void |
destroy()
Called during servlet initialization to invoke all
HookEvent.DESTROY methods. |
void |
execute(HttpServletRequest r1,
HttpServletResponse r2)
The main service method.
|
protected RestMethodParam[] |
findParams(MethodInfo mi,
boolean isPreOrPost,
UrlPathPattern pathPattern)
Finds the
RestMethodParam instances to handle resolving objects on the calls to the specified Java method. |
protected void |
finishCall(RestCall call)
Called at the end of a request to invoke all
HookEvent.END_CALL methods. |
Set<String> |
getAllowedHeaderParams()
Allowed header URL parameters.
|
Set<String> |
getAllowedMethodHeaders()
Allowed method headers.
|
Set<String> |
getAllowedMethodParams()
Allowed method URL parameters.
|
RestCallLogger |
getCallLogger()
Returns the call logger to use for this resource.
|
RestCallLoggerConfig |
getCallLoggerConfig()
Returns the call logger config to use for this resource.
|
Map<String,RestContext> |
getChildResources()
Returns the child resources associated with this servlet.
|
<T> T |
getClasspathResource(Class<T> c,
MediaType mediaType,
String name,
Locale locale)
Reads the input stream from
getClasspathResource(String, Locale) and parses it into a POJO using the parser
matched by the specified media type. |
InputStream |
getClasspathResource(String name,
Locale locale)
Same as
Class.getResourceAsStream(String) except if it doesn't find the resource on this class, searches
up the parent hierarchy chain. |
String |
getClasspathResourceAsString(String name,
Locale locale)
Reads the input stream from
getClasspathResource(String, Locale) into a String. |
String |
getClientVersionHeader()
Returns the name of the client version header name used by this resource.
|
Config |
getConfig()
Returns the config file associated with this servlet.
|
List<MediaType> |
getConsumes()
Returns the explicit list of supported content types for this resource.
|
Enablement |
getDebug(Method method)
Returns the debug setting on this context for the specified method.
|
static Map<Class<?>,RestContext> |
getGlobalRegistry()
Returns a registry of all created
RestContext objects. |
RestInfoProvider |
getInfoProvider()
Returns the REST information provider used by this resource.
|
JsonSchemaGenerator |
getJsonSchemaGenerator()
Returns the JSON-Schema generator associated with this resource.
|
RestLogger |
getLogger()
Deprecated.
|
String |
getMediaTypeForName(String name)
Returns the media type for the specified file name.
|
Messages |
getMessages()
Returns the resource bundle used by this resource.
|
List<RestMethodContext> |
getMethodContexts()
Returns the REST Java methods defined in this resource.
|
List<MethodExecStats> |
getMethodExecStats()
Returns timing information on all method executions on this class.
|
protected MethodExecStats |
getMethodExecStats(Method m)
Returns the time statistics gatherer for the specified method.
|
String |
getMethodExecStatsReport()
Returns the timing information returned by
getMethodExecStats() in a readable format. |
RestContext |
getParentContext()
Returns the parent resource context (if this resource was initialized from a parent).
|
HttpPartParser |
getPartParser()
Returns the HTTP-part parser associated with this resource.
|
HttpPartSerializer |
getPartSerializer()
Returns the HTTP-part serializer associated with this resource.
|
String |
getPath()
Returns the path for this resource as defined by the
@Rest(path) annotation or
RestContextBuilder.path(String) method concatenated with those on all parent classes. |
List<MediaType> |
getProduces()
Returns the explicit list of supported accept types for this resource.
|
RestContextProperties |
getProperties()
Returns the class-level properties associated with this servlet.
|
OMap |
getReqAttrs()
Returns the default request attributes for this resource.
|
Map<String,Object> |
getReqHeaders()
Returns the default request headers for this resource.
|
RestRequest |
getRequest()
Returns the HTTP request object for the current request.
|
Map<String,Object> |
getResHeaders()
Returns the default response headers for this resource.
|
Object |
getResource()
Returns the resource object.
|
protected RestResourceResolver |
getResourceResolver()
Returns the resource resolver associated with this context.
|
RestResponse |
getResponse()
Returns the HTTP response object for the current request.
|
ResponseBeanMeta |
getResponseBeanMeta(Object o)
If the specified object is annotated with
Response , this returns the response metadata about that object. |
protected ResponseHandler[] |
getResponseHandlers()
Returns the response handlers associated with this resource.
|
RestServlet |
getRestServlet()
Returns the resource object as a
RestServlet . |
String |
getServletInitParameter(String name)
Returns the servlet init parameter returned by
ServletConfig.getInitParameter(String) . |
Map<String,Object> |
getSessionObjects(RestCall call)
Returns the session objects for the specified request.
|
StackTraceDatabase |
getStackTraceDb()
Gives access to the internal stack trace database.
|
int |
getStackTraceOccurrence(Throwable e)
Deprecated.
|
protected StaticFile |
getStaticFile(String pathInfo)
Resolve a static resource file.
|
RestContextStats |
getStats()
Gives access to the internal stack trace database.
|
String |
getUriAuthority()
Returns the authority path of the resource.
|
String |
getUriContext()
Returns the context path of the resource.
|
UriRelativity |
getUriRelativity()
Returns the setting on how relative URIs should be interpreted as relative to.
|
UriResolution |
getUriResolution()
Returns the setting on how relative URIs should be resolved.
|
VarResolver |
getVarResolver()
Returns the variable resolver for this servlet.
|
void |
handleError(RestCall call,
Throwable e)
Method for handling response errors.
|
void |
handleNotFound(RestCall call)
Handle the case where a matching method was not found.
|
void |
handleResponse(RestCall call)
The main method for serializing POJOs passed in through the
RestResponse.setOutput(Object) method or
returned by the Java method. |
boolean |
isAllowBodyParam()
Returns whether it's safe to pass the HTTP body as a
|
boolean |
isRenderResponseStackTraces()
Returns whether it's safe to render stack traces in HTTP responses.
|
boolean |
isStaticFile(String p)
Returns
|
protected void |
postCall(RestCall call)
Called during a request to invoke all
HookEvent.POST_CALL methods. |
RestContext |
postInit()
Called during servlet initialization to invoke all
HookEvent.POST_INIT methods. |
RestContext |
postInitChildFirst()
Called during servlet initialization to invoke all
HookEvent.POST_INIT_CHILD_FIRST methods. |
protected void |
preCall(RestCall call)
Called during a request to invoke all
HookEvent.PRE_CALL methods. |
protected void |
startCall(RestCall call)
Called at the start of a request to invoke all
HookEvent.START_CALL methods. |
OMap |
toMap()
Returns the properties defined on this bean context as a simple map for debugging purposes.
|
_class, builder, create, createBeanSession, createBeanSession, createDefaultBeanSessionArgs, createDefaultSessionArgs, createSession, createSession, createSession, dumpCacheStats, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getBeanClassVisibility, getBeanConstructorVisibility, getBeanDictionaryClasses, getBeanFieldVisibility, getBeanFilters, getBeanMeta, getBeanMethodVisibility, getBeanRegistry, getBeanToStringSerializer, getBeanTypePropertyName, getBpi, getBpi, getBpro, getBpro, getBpwo, getBpwo, getBpx, getBpx, getClassMeta, getClassMeta, getClassMetaForObject, getDeclaredAnnotations, getDeclaredAnnotations, getExamples, getImplClassConstructor, getImplClasses, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastDeclaredAnnotation, getLastDeclaredAnnotation, getNotBeanClasses, getNotBeanPackagesNames, getNotBeanPackagesPrefixes, getPropertyNamer, getSwaps, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasDeclaredAnnotation, hasDeclaredAnnotation, hasSameCache, isBean, isBeanMapPutReturnsOldValue, isBeansRequireDefaultConstructor, isBeansRequireSerializable, isBeansRequireSettersForGetters, isBeansRequireSomeProperties, isFluentSetters, isIgnoreInvocationExceptionsOnGetters, isIgnoreInvocationExceptionsOnSetters, isIgnorePropertiesWithoutSetters, isIgnoreTransientFields, isIgnoreUnknownBeanProperties, isIgnoreUnknownNullBeanProperties, isNotABean, isSortProperties, isUseEnumNames, isUseInterfaceProxies, isUseJavaBeanIntrospector, object, resolveClassMeta, string
equals, getArrayProperty, getArrayProperty, getBooleanProperty, getCdlProperty, getClassArrayProperty, getClassArrayProperty, getClassArrayProperty, getClassListProperty, getClassListProperty, getClassMapProperty, getClassMapProperty, getClassProperty, getClassSetProperty, getClassSetProperty, getDefaultLocale, getDefaultMediaType, getDefaultTimeZone, getInstanceArrayProperty, getInstanceArrayProperty, getInstanceArrayProperty, getInstanceProperty, getInstanceProperty, getInstanceProperty, getIntegerProperty, getListProperty, getListProperty, getLongProperty, getMapProperty, getProperty, getProperty, getPropertyKeys, getPropertyStore, getSetProperty, getSetProperty, getStringProperty, getStringPropertyWithNone, hashCode, identityCode, isDebug, toString
public static final String REST_allowBodyParam
REST_allowBodyParam
When enabled, the HTTP body content on PUT and POST requests can be passed in as text using the
For example:
?body=(name='John%20Smith',age=45)
public static final String REST_allowedHeaderParams
REST_allowedHeaderParams
When specified, allows headers such as
For example:
?Accept=text/json&Content-Type=text/json
public static final String REST_allowedMethodHeaders
REST_allowedMethodHeaders
A comma-delimited list of HTTP method names that are allowed to be passed as values in an
Allows you to override the actual HTTP method with a simulated method.
For example, if an HTTP Client API doesn't support
public static final String REST_allowedMethodParams
REST_allowedMethodParams
When specified, the HTTP method can be overridden by passing in a
For example:
/myservlet/myendpoint?method=OPTIONS
Useful in cases where you want to simulate a non-GET request in a browser by simply adding a parameter.
Also useful if you want to construct hyperlinks to non-GET REST endpoints such as links to
Note that per the HTTP specification, special care should
be taken when allowing non-safe (
@Deprecated public static final String REST_allowHeaderParams
REST_allowedHeaderParams
@Deprecated public static final String REST_callHandler
REST_context
and override methods.
public static final String REST_callLogger
REST_callLogger
RestCallLogger
RestCallLogger
>BasicRestCallLogger
Specifies the logger to use for logging of HTTP requests and responses.
BasicRestCallLogger
.
RestCallLogger
interface and not
explicitly overridden via this annotation.
RestServlet
and BasicRest
classes implement the RestCallLogger
interface with the same
that gets used if not overridden by this annotation.
public T(RestContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_callLoggerConfig
REST_callLoggerConfig
RestCallLoggerConfig
RestCallLoggerConfig.DEFAULT_NOOP
Specifies rules on how to handle logging of HTTP requests/responses.
public static final String REST_children
REST_children
RestChild
>Defines children of this resource.
A REST child resource is simply another servlet or object that is initialized as part of the ascendant resource and has a
servlet path directly under the ascendant resource object path.
The main advantage to defining servlets as REST children is that you do not need to define them in the
This can cut down on the number of entries that show up in the
Child resources must specify a value for @Rest(path)
that identifies the subpath of the child resource
relative to the ascendant path UNLESS you use the RestContextBuilder.child(String, Object)
method to register it.
Child resources can be nested arbitrarily deep using this technique (i.e. children can also have children).
A child resource will be initialized immediately after the ascendant servlet/resource is initialized.
The child resource receives the same servlet config as the ascendant servlet/resource.
This allows configuration information such as servlet initialization parameters to filter to child
resources.
As a rule, methods defined on the
For example, the
Therefore, the runtime behavior should be equivalent to deploying the child servlet in the
REST_resourceResolver
which
by default is BasicRestResourceResolver
which requires the class have one of the following
constructors:
public T(RestContextBuilder)
public T()
public static final String REST_classpathResourceFinder
REST_classpathResourceFinder
ResourceFinder
BasicResourceFinder
Used to retrieve localized files from the classpath.
Used by the following methods:
It also affects the behavior of the REST_staticFiles
property.
BasicResourceFinder
which provides basic support for finding localized
resources on the classpath and JVM working directory.
RecursiveResourceFinder
is another option that also recursively searches for resources
up the class-hierarchy.
ResourceFinder
interface and not
explicitly overridden via this annotation.
RestServlet
and BasicRest
classes implement the ResourceFinder
interface with the same
functionality as BasicResourceFinder
that gets used if not overridden by this annotation.
public T(RestContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_clientVersionHeader
REST_clientVersionHeader
Specifies the name of the header used to denote the client version on HTTP requests.
The client version is used to support backwards compatibility for breaking REST interface changes.
Used in conjunction with @RestMethod(clientVersion)
annotation.
public static final String REST_converters
REST_converters
RestConverter
|Class<RestConverter
>>
Associates one or more converters
with a resource class.
These converters get called immediately after execution of the REST method in the same order specified in the
annotation.
The object passed into this converter is the object returned from the Java method or passed into
the RestResponse.setOutput(Object)
method.
Can be used for performing post-processing on the response object before serialization.
When multiple converters are specified, they're executed in the order they're specified in the annotation (e.g. first the results will be traversed, then the resulting node will be searched/sorted).
Traversable
- Allows URL additional path info to address individual elements in a POJO tree.
Queryable
- Allows query/view/sort functions to be performed on POJOs.
Introspectable
- Allows Java public methods to be invoked on the returned POJOs.
public T(BeanContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_debug
REST_debug
Enablement
Enablement.FALSE
Enables the following:
public static final String REST_debugOn
REST_debugOn
Enables the following:
public static final String REST_defaultCharset
REST_defaultCharset
The default character encoding for the request and response if not specified on the request.
@Deprecated public static final String REST_attrs
REST_reqAttrs
@Deprecated public static final String REST_defaultRequestHeaders
REST_reqHeaders
@Deprecated public static final String REST_defaultResponseHeaders
REST_resHeaders
public static final String REST_encoders
REST_encoders
Encoder
|Class<Encoder
>>
These can be used to enable various kinds of compression (e.g.
public T(BeanContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_guards
REST_guards
RestGuard
|Class<RestGuard
>>
Associates one or more RestGuards
with all REST methods defined in this class.
These guards get called immediately before execution of any REST method in this class.
If multiple guards are specified, ALL guards must pass.
Note that this is different than matchers where only ONE matcher needs to pass.
public T(RestContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_infoProvider
REST_infoProvider
RestInfoProvider
RestInfoProvider
>BasicRestInfoProvider
Class used to retrieve title/description/swagger information about a resource.
BasicRestInfoProvider
.
RestInfoProvider
interface and not
explicitly overridden via this annotation.
RestServlet
and BasicRest
classes implement the RestInfoProvider
interface with the same
functionality as BasicRestInfoProvider
that gets used if not overridden by this annotation.
public T(RestContext)
public T()
public static T create (RestContext)
public static T create ()
@Deprecated public static final String REST_logger
REST_callLogger
public static final String REST_maxInput
REST_maxInput
Useful for alleviating DoS attacks by throwing an exception when too much input is received instead of resulting in out-of-memory errors which could affect system stability.
public static final String REST_messages
REST_messages
Tuple2
<Class,String>>Identifies the location of the resource bundle for this class if it's different from the class name.
By default, the resource bundle name is assumed to match the class name. For example, given the class
Resource bundles are searched using the following base name patterns:
This annotation is used to provide request-localized (based on
Request-localized messages are also available by passing either of the following parameter types into your Java method:
ResourceBundle
- Basic Java resource bundle.
Messages
- Extended resource bundle with several convenience methods.
public static final String REST_mimeTypes
REST_mimeTypes
Defines MIME-type file type mappings.
Used for specifying the content type on file resources retrieved through the following methods:
RestContext.resolveStaticFile(String)
RestRequest.getClasspathHttpResource(String,boolean,MediaType,boolean)
RestRequest.getClasspathHttpResource(String,boolean)
RestRequest.getClasspathHttpResource(String)
This list appends to the existing list provided by ExtendedMimetypesFileTypeMap
.
public static final String REST_paramResolvers
REST_paramResolvers
RestMethodParam
|Class<RestMethodParam
>>
By default, the Juneau framework will automatically Java method parameters of various types (e.g.
For example, if you want to pass in instances of
public T(BeanContext)
public T()
public static T create (RestContext)
public static T create ()
RestMethodParam
for the list of predefined parameter resolvers.
public static final String REST_parsers
REST_parsers
Parser
|Class<Parser
>>Adds class-level parsers to this resource.
Parsers are used to convert the body of HTTP requests into POJOs.
Any of the Juneau framework parsers can be used in this setting.
The parser selected is based on the request
BasicRestServlet
which comes
preconfigured with the following parsers:
public static final String REST_partParser
REST_partParser
HttpPartParser
|Class<HttpPartParser
>OpenApiParser
Specifies the HttpPartParser
to use for parsing headers, query/form parameters, and URI parts.
The default value is OpenApiParser
which allows for both plain-text and URL-Encoded-Object-Notation values.
If your parts contain text that can be confused with UON (e.g. SimplePartParser
which treats everything as plain text.
public static final String REST_partSerializer
REST_partSerializer
OpenApiSerializer
Specifies the HttpPartSerializer
to use for serializing headers, query/form parameters, and URI parts.
The default value is OpenApiSerializer
which serializes based on OpenAPI rules, but defaults to UON notation for beans and maps, and
plain text for everything else.
Other options include:
SimplePartSerializer
- Always serializes to plain text.
UonSerializer
- Always serializers to UON.
public static final String REST_path
REST_path
Identifies the URL subpath relative to the ascendant resource.
This setting is critical for the routing of HTTP requests from ascendant to child resources.
@Rest(children)
annotation.
public static final String REST_renderResponseStackTraces
REST_renderResponseStackTraces
Render stack traces in HTTP response bodies when errors occur.
handleError(RestCall, Throwable)
.
public static final String REST_reqAttrs
REST_reqAttrs
Specifies default values for request attributes if they're not already set on the request.
public static final String REST_reqHeaders
REST_reqHeaders
Specifies default values for request headers if they're not passed in through the request.
RestRequest.getHeader(String)
when the header is not present on the request.
Serializer
is picked.
public static final String REST_resHeaders
REST_resHeaders
Specifies default values for response headers if they're not set after the Java REST method is called.
RestResponse.setHeader(String, String)
programmatically in each of
the Java methods.
public static final String REST_resourceResolver
REST_resourceResolver
BasicRestResourceResolver
The resolver used for resolving instances of child resources.
Can be used to provide customized resolution of REST resource class instances (e.g. resources retrieve from Spring).
RestResourceResolver
interface and not
explicitly overridden via this annotation.
RestServlet
and BasicRest
classes implement the RestResourceResolver
interface with the same
functionality as BasicRestResourceResolver
that gets used if not overridden by this annotation.
public T(RestContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_responseHandlers
REST_responseHandlers
ResponseHandler
|Class<ResponseHandler
>>
Specifies a list of ResponseHandler
classes that know how to convert POJOs returned by REST methods or
set via RestResponse.setOutput(Object)
into appropriate HTTP responses.
By default, the following response handlers are provided out-of-the-box:
ReaderHandler
- Reader
objects.
InputStreamHandler
- InputStream
objects.
DefaultHandler
- All other POJOs.
public T(RestContext)
public T()
public static T create (RestContext)
public static T create ()
public static final String REST_rolesDeclared
REST_rolesDeclared
A comma-delimited list of all possible user roles.
Used in conjunction with RestContextBuilder.roleGuard(String)
is used with patterns.
public static final String REST_roleGuard
REST_roleGuard
An expression defining if a user with the specified roles are allowed to access methods on this class.
Rest.rolesDeclared()
or REST_rolesDeclared
.
public static final String REST_serializers
REST_serializers
Serializer
|Class<Serializer
>>Adds class-level serializers to this resource.
Serializer are used to convert POJOs to HTTP response bodies.
Any of the Juneau framework serializers can be used in this setting.
The serializer selected is based on the request
BasicRestServlet
which comes
preconfigured with the following serializers:
public static final String REST_staticFileResponseHeaders
REST_staticFileResponseHeaders
{'Cache-Control' : 'max-age=86400, public }
Used to customize the headers on responses returned for statically-served files.
Note that headers can also be specified per path-mapping via the @Rest(staticFiles)
annotation.
REST_staticFiles
for information about statically-served files.
public static final String REST_staticFiles
REST_staticFiles
StaticFileMapping
>Used to define paths and locations of statically-served files such as images or HTML documents from the classpath or file system.
The format of the value is one of the following:
An example where this class is used is in the Rest.staticFiles()
annotation:
In the example above, given a GET request to the following URL...
/myresource/htdocs/foobar.html
The location is interpreted as an absolute path if it starts with
In the example above, given a GET request to the following URL...
/myresource/htdocs/foobar.html
Response headers can be specified for served files by adding a 3rd section that consists of a Overview > juneau-marshall > JSON Details > Simplified JSON object.
The same path can map to multiple locations. Files are searched in the order
REST_classpathResourceFinder
for configuring how classpath resources are located and retrieved.
REST_mimeTypes
for configuring the media types based on file extension.
REST_staticFileResponseHeaders
for configuring response headers on statically served files.
REST_useClasspathResourceCaching
for configuring static file caching.
getClasspathResource(String,Locale)
for retrieving static files.
public static final String REST_produces
REST_produces
Overrides the media types inferred from the serializers that identify what media types can be produced by the resource.
An example where this might be useful if you have serializers registered that handle media types that you
don't want exposed in the Swagger documentation.
This affects the returned values from the following:
RestContext.getProduces()
RestRequest.getProduces()
RestInfoProvider.getSwagger(RestRequest)
- Affects produces field.
public static final String REST_properties
REST_properties
Shortcut to add properties to the bean contexts of all serializers and parsers on all methods in the class.
Any of the properties defined on RestContext
or any of the serializers and parsers can be specified.
Property values will be converted to the appropriate type.
public static final String REST_consumes
REST_consumes
Overrides the media types inferred from the parsers that identify what media types can be consumed by the resource.
An example where this might be useful if you have parsers registered that handle media types that you
don't want exposed in the Swagger documentation.
This affects the returned values from the following:
RestContext.getConsumes()
RestRequest.getConsumes()
RestInfoProvider.getSwagger(RestRequest)
- Affects consumes field.
public static final String REST_context
REST_context
RestContext
>RestContext
Allows you to extend the RestContext
class to modify how any of the methods are implemented.
The subclass must provide the following:
RestContextBuilder
.
public static final String REST_useClasspathResourceCaching
REST_useClasspathResourceCaching
When enabled, resources retrieved via getClasspathResource(String, Locale)
(and related
methods) will be cached in memory to speed subsequent lookups.
REST_staticFiles
for information about static files.
@Deprecated public static final String REST_useStackTraceHashes
Logging.useStackTraceHashing()
public static final String REST_uriAuthority
REST_uriAuthority
Overrides the authority path value for this resource and any child resources.
Affects the following methods:
If you do not specify the authority, it is automatically calculated via the following:
String scheme = request.getScheme();
public static final String REST_uriContext
REST_uriContext
Overrides the context path value for this resource and any child resources.
This setting is useful if you want to use
Affects the following methods:
RestRequest.getContextPath()
- Returns the overridden context path for the resource.
RestRequest.getServletPath()
- Includes the overridden context path for the resource.
public static final String REST_uriRelativity
REST_uriRelativity
Specifies how relative URIs should be interpreted by serializers.
See UriResolution
for possible values.
Affects the following methods:
public static final String REST_uriResolution
REST_uriResolution
Specifies how relative URIs should be interpreted by serializers.
See UriResolution
for possible values.
Affects the following methods:
@Deprecated public static final String REST_widgets
HtmlDocSerializer.HTMLDOC_widgets
public RestContext(RestContextBuilder builder) throws Exception
builder
- The servlet configuration object.Exception
- If any initialization problems were encountered.public static final Map<Class<?>,RestContext> getGlobalRegistry()
RestContext
objects.RestContext
objects.public static RestContextBuilder create(Object resource) throws ServletException
resource
- The resource annotated with ServletException
- Something bad happened.protected RestResourceResolver getResourceResolver()
The resource resolver is used for instantiating child resource classes.
protected MethodExecStats getMethodExecStats(Method m)
m
- The method to get statistics for.public VarResolver getVarResolver()
Variable resolvers are used to replace variables in property values. They can be nested arbitrarily deep. They can also return values that themselves contain other variables.
A typical usage pattern involves using variables inside the @HtmlDocConfig
annotation:
public Config getConfig()
The config file is identified via one of the following:
protected StaticFile getStaticFile(String pathInfo) throws NotFound, IOException
The location of static resources are defined via:
pathInfo
- The unencoded path info.NotFound
- Invalid path.IOException
- Thrown by underlying stream.public InputStream getClasspathResource(String name, Locale locale) throws IOException
Class.getResourceAsStream(String)
except if it doesn't find the resource on this class, searches
up the parent hierarchy chain.
If the resource cannot be found in the classpath, then an attempt is made to look in the JVM working directory.
If the
For example, if looking for the resource
name
- The resource name.locale
- Optional locale.
IOException
- Thrown by underlying stream.public String getClasspathResourceAsString(String name, Locale locale) throws IOException
getClasspathResource(String, Locale)
into a String.
name
- The resource name.locale
- Optional locale.
IOException
- If resource could not be found.public <T> T getClasspathResource(Class<T> c, MediaType mediaType, String name, Locale locale) throws IOException, ServletException
getClasspathResource(String, Locale)
and parses it into a POJO using the parser
matched by the specified media type.
Useful if you want to load predefined POJOs from JSON files in your classpath.
c
- The class type of the POJO to create.mediaType
- The media type of the data in the stream (e.g. name
- The resource name (e.g. "htdocs/styles.css").locale
- Optional locale.
IOException
- Thrown by underlying stream.ServletException
- If the media type was unknown or the input could not be parsed into a POJO.public String getPath()
@Rest(path)
annotation or
RestContextBuilder.path(String)
method concatenated with those on all parent classes.
If path is not specified, returns
@Deprecated public RestLogger getLogger()
getCallLogger()
public RestCallLogger getCallLogger()
public RestCallLoggerConfig getCallLoggerConfig()
public Messages getMessages()
public RestInfoProvider getInfoProvider()
public Object getResource()
This is the instance of the class annotated with the @Rest
annotation, usually
an instance of RestServlet
.
public RestServlet getRestServlet()
RestServlet
.RestServlet
, or RestServlet
.protected void checkForInitException() throws HttpException
HttpException
if an exception occurred in the constructor of this object.HttpException
- The initialization exception wrapped in a HttpException
.public RestContext getParentContext()
From this object, you can get access to the parent resource class itself using getResource()
or
getRestServlet()
public RestContextProperties getProperties()
Properties at the class level are defined via the following:
Map
is mutable.
init()
method.
RestContextProperties
.public String getServletInitParameter(String name)
ServletConfig.getInitParameter(String)
.name
- The init parameter name.public Map<String,RestContext> getChildResources()
@Rest(path)
annotation defined on the child resource.@Deprecated public int getStackTraceOccurrence(Throwable e)
e
- The exception to check.REST_useStackTraceHashes
setting is not enabled.public boolean isRenderResponseStackTraces()
public boolean isAllowBodyParam()
public Set<String> getAllowedHeaderParams()
public Set<String> getAllowedMethodHeaders()
public Set<String> getAllowedMethodParams()
public Enablement getDebug(Method method)
method
- The java method.public String getClientVersionHeader()
public HttpPartParser getPartParser()
public HttpPartSerializer getPartSerializer()
public JsonSchemaGenerator getJsonSchemaGenerator()
public List<MediaType> getProduces()
public List<MediaType> getConsumes()
public Map<String,Object> getReqHeaders()
public OMap getReqAttrs()
public Map<String,Object> getResHeaders()
protected ResponseHandler[] getResponseHandlers()
public String getUriAuthority()
public String getUriContext()
public UriRelativity getUriRelativity()
public UriResolution getUriResolution()
public String getMediaTypeForName(String name)
name
- The file name.public boolean isStaticFile(String p)
Static files are files pulled from the classpath and served up directly to the browser.
p
- The URL path remainder after the servlet match.public List<RestMethodContext> getMethodContexts()
These are the methods annotated with the @RestMethod
annotation.
public StackTraceDatabase getStackTraceDb()
public List<MethodExecStats> getMethodExecStats()
Timing information is maintained for any
public RestContextStats getStats()
public String getMethodExecStatsReport()
getMethodExecStats()
in a readable format.protected RestMethodParam[] findParams(MethodInfo mi, boolean isPreOrPost, UrlPathPattern pathPattern) throws ServletException
RestMethodParam
instances to handle resolving objects on the calls to the specified Java method.mi
- The Java method being called.isPreOrPost
- Whether this is a HookEvent.PRE_CALL
or HookEvent.POST_CALL
.pathPattern
- The path pattern to match against.ServletException
- If an annotation usage error was detected.protected RestCall createCall(HttpServletRequest req, HttpServletResponse res)
RestCall
object.
This is the first method called by execute(HttpServletRequest, HttpServletResponse)
.
req
- The rest request.res
- The rest response.public RestRequest createRequest(RestCall call) throws ServletException
RestRequest
object based on the specified incoming HttpServletRequest
object.
This method is called immediately after startCall(RestCall)
has been called.
call
- The current REST call.ServletException
- If any errors occur trying to interpret the request.public RestResponse createResponse(RestCall call) throws ServletException
RestResponse
object based on the specified incoming HttpServletResponse
object
and the request returned by createRequest(RestCall)
.call
- The current REST call.ServletException
- If any errors occur trying to interpret the request or response.public void execute(HttpServletRequest r1, HttpServletResponse r2) throws ServletException, IOException
Subclasses can optionally override this method if they want to tailor the behavior of requests.
r1
- The incoming HTTP servlet request object.r2
- The incoming HTTP servlet response object.ServletException
- General servlet exception.IOException
- Thrown by underlying stream.public void handleResponse(RestCall call) throws IOException, HttpException, NotImplemented
RestResponse.setOutput(Object)
method or
returned by the Java method.
Subclasses may override this method if they wish to modify the way the output is rendered or support other output formats.
The default implementation simply iterates through the response handlers on this resource
looking for the first one whose ResponseHandler.handle(RestRequest,RestResponse)
method returns
call
- The HTTP call.IOException
- Thrown by underlying stream.HttpException
- Non-200 response.NotImplemented
- No registered response handlers could handle the call.public Throwable convertThrowable(Throwable t)
The default implementation looks at the throwable class name to determine whether it can be converted to another type:
Unauthorized
.
NotFound
.
t
- The thrown object.public void handleNotFound(RestCall call) throws Exception
Subclasses can override this method to provide a 2nd-chance for specifying a response. The default implementation will simply throw an exception with an appropriate message.
call
- The HTTP call.Exception
- Any exception can be thrown.public void handleError(RestCall call, Throwable e) throws IOException
Subclasses can override this method to provide their own custom error response handling.
call
- The rest call.e
- The exception that occurred.IOException
- Can be thrown if a problem occurred trying to write to the output stream.public Map<String,Object> getSessionObjects(RestCall call)
The default implementation simply returns a single map containing
call
- The current REST call.protected void startCall(RestCall call)
HookEvent.START_CALL
methods.call
- The current request.protected void preCall(RestCall call) throws HttpException
HookEvent.PRE_CALL
methods.call
- The current request.HttpException
- If thrown from call methods.protected void postCall(RestCall call) throws HttpException
HookEvent.POST_CALL
methods.call
- The current request.HttpException
- If thrown from call methods.protected void finishCall(RestCall call)
HookEvent.END_CALL
methods.
This is the very last method called in execute(HttpServletRequest, HttpServletResponse)
.
call
- The current request.public RestContext postInit() throws ServletException
HookEvent.POST_INIT
methods.ServletException
- Error occurred.public RestContext postInitChildFirst() throws ServletException
HookEvent.POST_INIT_CHILD_FIRST
methods.ServletException
- Error occurred.protected void destroy()
HookEvent.DESTROY
methods.public RestRequest getRequest()
public RestResponse getResponse()
public ResponseBeanMeta getResponseBeanMeta(Object o)
Response
, this returns the response metadata about that object.o
- The object to check.Response
.public OMap toMap()
Context
toMap
in class BeanContext
Copyright © 2016–2020 The Apache Software Foundation. All rights reserved.