blob: 482e95de007e635cfb43a0dacc3c6e73a4d30d48 [file] [log] [blame]
<!DOCTYPE HTML>
<!--
/***************************************************************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
***************************************************************************************************************************/
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="icon" type="image/png" href="http://www.apache.org/favicons/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="http://www.apache.org/favicons/favicon-194x194.png" sizes="194x194">
<link rel="icon" type="image/png" href="http://www.apache.org/favicons/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="http://www.apache.org/favicons/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="http://www.apache.org/favicons/favicon-16x16.png" sizes="16x16">
<link rel="shortcut icon" href="http://www.apache.org/favicons/favicon.ico">
<style type="text/css">
/* For viewing in file system and page designer */
@IMPORT url("../../../../juneau-core/java/src/main/javadoc/javadoc.css");
@IMPORT url("../../../../juneau-core/java/src/main/javadoc/resources/juneau-doc.css");
@IMPORT url("../../../../juneau-core/java/src/main/javadoc/resources/juneau-code.css");
body {
margin: 20px;
}
.spaced-list li { padding:5px; }
.footer .spaced-list ul { margin:0 }
</style>
<script type="text/javascript">
/* Replace all @code and @link tags. */
window.onload = function() {
document.body.innerHTML = document.body.innerHTML.replace(/\{\@code ([^\}]+)\}/g, '<code>$1<\/code>');
document.body.innerHTML = document.body.innerHTML.replace(/\{\@link (([^\}]+)\.)?([^\.\}]+)\}/g, '<code>$3<\/code>');
}
</script>
</head>
<body>
<p>Apache Juneau Overview</p>
<script type="text/javascript">
function toggle(x) {
var div = x.nextSibling;
while (div != null && div.nodeType != 1)
div = div.nextSibling;
if (div != null) {
var d = div.style.display;
if (d == 'block' || d == '') {
div.style.display = 'none';
x.className += " closed";
} else {
div.style.display = 'block';
x.className = x.className.replace(/(?:^|\s)closed(?!\S)/g , '' );
}
}
}
</script>
<ul class='spaced-list'>
<li>A universal toolkit for marshalling POJOs to a wide variety of content types using a common framework.
<li>A universal REST server API for creating Swagger-based self-documenting REST interfaces using POJOs, simply deployed as
one or more top-level servlets in any Servlet 3.1 or above container.
<li>A universal REST client API for interacting with Juneau or 3rd-party REST interfaces using POJOs and proxy interfaces.
<li>A sophisticated configuration file API.
<li>A REST microservice API that combines all the features above with a simple configurable Jetty server for
creating lightweight stand-alone REST interfaces that start up in milliseconds.
<li>Built on top of Servlet and Apache HttpClient APIs that allow you to use the newest HTTP/2 features
such as request/response multiplexing and server push.
</ul>
<a id='TOC'></a><h5 class='toc'>Table of Contents</h5>
<ol class='toc'>
<li><p><a class='doclink' href='#Intro'>Introduction</a></p>
<ol>
<li><p><a class='doclink' href='#Intro.Features'>Features</a></p>
<li><p><a class='doclink' href='#Intro.Components'>Components</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-marshall'><i>juneau-marshall</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-marshall.Serializers'>Serializers</a></p>
<li><p><a class='doclink' href='#juneau-marshall.Parsers'>Parsers</a></p>
<li><p><a class='doclink' href='#juneau-marshall.Groups'>SerializerGroups and ParserGroups</a></p>
<li><p><a class='doclink' href='#juneau-marshall.ObjectMap'>ObjectMap and ObjectList</a></p>
<li><p><a class='doclink' href='#juneau-marshall.ConfigurableProperties'>Configurable Properties</a></p>
<li><p><a class='doclink' href='#juneau-marshall.ContextsBuildersSessionsPropertyStores'>Contexts, Builders, Sessions, and PropertyStores</a></p>
<li><p><a class='doclink' href='#juneau-marshall.Transforms'>Transforms</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-marshall.PojoSwaps'>PojoSwaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.PerMediaTypePojoSwaps'>Per-media-type PojoSwaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.OneWayPojoSwaps'>One-way PojoSwaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.SwapAnnotation'>@Swap Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.TemplatedSwaps'>Templated Swaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.SwapMethods'>Swap Methods</a></p>
<li><p><a class='doclink' href='#juneau-marshall.SurrogateClasses'>Surrogate Classes</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanAnnotation'>@Bean Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanPropertyAnnotation'>@BeanProperty Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanConstructorAnnotation'>@BeanConstructor Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanIgnoreAnnotation'>@BeanIgnore Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.NamePropertyAnnotation'>@NameProperty Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.ParentPropertyAnnotation'>@ParentProperty Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.PojoBuilders'>POJO Builders</a></p>
<li><p><a class='doclink' href='#juneau-marshall.URIs'>URIs</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanFilters'>BeanFilters</a></p>
<li><p><a class='doclink' href='#juneau-marshall.InterfaceFilters'>Interface filters</a></p>
<li><p><a class='doclink' href='#juneau-marshall.StopClasses'>Stop Classes</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BypassSerialization'>Bypass Serialization using Readers and InputStreams</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-marshall.BeanDictionaries'>Bean Name and Dictionaries</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-marshall.BeanSubTypes'>Bean Subtypes</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-marshall.VirtualBeans'>Virtual Beans</a></p>
<li><p><a class='doclink' href='#juneau-marshall.ReadingContinuousStreams'>Reading Continuous Streams</a></p>
<li><p><a class='doclink' href='#juneau-marshall.JacksonComparison'>Comparison with Jackson</a></p>
<li><p><a class='doclink' href='#juneau-marshall.PojoCategories'>POJO Categories</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BestPractices'>Best Practices</a></p>
<li><p><a class='doclink' href='#juneau-marshall.AdditionalInfo'>Additional Information</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-marshall.AdditionalInfo.JSON'>JSON</a></p>
<li><p><a class='doclink' href='#juneau-marshall.AdditionalInfo.XML'>XML</a></p>
<li><p><a class='doclink' href='#juneau-marshall.AdditionalInfo.HTML'>HTML</a></p>
<li><p><a class='doclink' href='#juneau-marshall.AdditionalInfo.UON'>UON</a></p>
<li><p><a class='doclink' href='#juneau-marshall.AdditionalInfo.URLEncoding'>URL-Encoding</a></p>
</ol>
</ol>
<li><p><a class='doclink' href='#juneau-marshall-rdf'><i>juneau-marshall-rdf</i></a></p>
<li><p><a class='doclink' href='#juneau-dto'><i>juneau-dto</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-dto.HTML5'>HTML5</a></p>
<li><p><a class='doclink' href='#juneau-dto.Atom'>Atom</a></p>
<li><p><a class='doclink' href='#juneau-dto.Swagger'>Swagger</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-svl'><i>juneau-svl</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-svl.SimpleVarLanguage'>Simple Variable Language</a></p>
<li><p><a class='doclink' href='#juneau-svl.SvlVariables'>SVL Variables</a></p>
<li><p><a class='doclink' href='#juneau-svl.VarResolvers'>VarResolvers and VarResolverSessions</a></p>
<li><p><a class='doclink' href='#juneau-svl.OtherNotes'>Other Notes</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-config'><i>juneau-config</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-config.Overview'>Overview</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-config.SyntaxRules'>Syntax Rules</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-config.EntryTypes'>Entry Types</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-config.PrimitiveTypes'>Primitive Types</a></p>
<li><p><a class='doclink' href='#juneau-config.POJOs'>POJOs</a></p>
<li><p><a class='doclink' href='#juneau-config.Arrays'>Arrays</a></p>
<li><p><a class='doclink' href='#juneau-config.Collections'>Collections</a></p>
<li><p><a class='doclink' href='#juneau-config.BinaryData'>Binary Data</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-config.Variables'>Variables</a></p>
<li><p><a class='doclink' href='#juneau-config.EncodedEntries'>Encoded Entries</a></p>
<li><p><a class='doclink' href='#juneau-config.SectionMaps'>Section Maps</a></p>
<li><p><a class='doclink' href='#juneau-config.SectionBeans'>Section Beans</a></p>
<li><p><a class='doclink' href='#juneau-config.SectionInterfaces'>Section Interfaces</a></p>
<li><p><a class='doclink' href='#juneau-config.SettingValues'>Setting Values</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-config.CustomEntrySerialization'>Custom Entry Serialization</a></p>
<li><p><a class='doclink' href='#juneau-config.BulkSettingValues'>Setting Values in Bulk</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-config.Listeners'>Listeners</a></p>
<li><p><a class='doclink' href='#juneau-config.Serializing'>Serializing</a></p>
<li><p><a class='doclink' href='#juneau-config.ConfigStores'>Config Stores</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-config.ConfigMemoryStore'>ConfigMemoryStore</a></p>
<li><p><a class='doclink' href='#juneau-config.ConfigFileStore'>ConfigFileStore</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-config.ReadOnlyConfigs'>Read-only Configs</a></p>
<li><p><a class='doclink' href='#juneau-config.ClosingConfigs'>Closing Configs</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server'><i>juneau-rest-server</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.HelloWorldExample'>Hello World Example</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.ClassHierarchy'>Class Hierarchy</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Instantiation'>Instantiation</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.RestServlet'>RestServlet</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestServletDefault'>RestServletDefault</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Children'>Children</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RouterPages'>Router Pages</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.ResourceResolvers'>Resource Resolvers</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.LifecycleHooks'>Lifecycle Hooks</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.RestResource'>@RestResource</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.AnnotationInheritance'>Annotation Inheritance</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.RestContext'>RestContext</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestMethod'>@RestMethod</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.MethodParameters'>Java Method Parameters</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestRequest'>RestRequest</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestResponse'>RestResponse</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RequestBody'>RequestBody</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RequestHeaders'>RequestHeaders</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RequestQuery'>RequestQuery</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RequestFormData'>RequestFormData</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestMethodPath'>@RestMethod.path()</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RequestPathMatch'>RequestPathMatch</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.MethodReturnTypes'>Method Return Types</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.ReaderResource'>ReaderResource</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.StreamResource'>StreamResource</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Redirect'>Redirect</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestMethodMatchers'>@RestMethod.matchers()</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.Body'>@Body</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.HandlingFormPosts'>Handling Form Posts</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.HandlingMultiPartFormPosts'>Handling Multi-Part Form Posts</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.FormData'>@FormData</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Query'>@Query</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Header'>@Header</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Serializers'>Serializers</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Parsers'>Parsers</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Properties'>Properties</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Transforms'>Transforms</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Guards'>Guards</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Converters'>Converters</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Messages'>Messages</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Encoders'>Encoders</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.SvlVariables'>SVL Variables</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.ConfigurationFiles'>Configuration Files</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.StaticFiles'>Static files</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.ClientVersioning'>Client Versioning</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.OptionsPages'>OPTIONS pages</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.RestInfoProvider'>RestInfoProvider</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RestInfoProviderDefault'>RestInfoProviderDefault</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.HtmlDocAnnotation'>@HtmlDoc</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.Widgets'>Widgets</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.PredefinedWidgets'>Predefined Widgets</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.UiCustomization'>UI Customization</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.Stylesheets'>Stylesheets</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.DefaultHeaders'>Default Headers</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.LoggingAndErrorHandling'>Logging and Error Handling</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.HttpStatusCodes'>HTTP Status Codes</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.OverloadingHttpMethods'>Overloading HTTP Methods</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.BuiltInParameters'>Built-in Parameters</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.CustomSerializersAndParsers'>Custom Serializers and Parsers</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.UsingWithOsgi'>Using with OSGi</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RemoteableProxies'>Remoteable Proxies</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server.RemoteableProxiesClientSide'>Client Side</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RemoteableProxiesServerSide'>Server Side</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.RemoteableProxiesRemoteableAnnotation'>@Remoteable Annotation</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server.Injection'>Using with Spring and Injection frameworks</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.HTTP2'>Using HTTP/2 features</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.PredefinedLabelBeans'>Predefined Label Beans</a></p>
<li><p><a class='doclink' href='#juneau-rest-server.OtherNotes'>Other Notes</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-server-jaxrs'><i>juneau-rest-server-jaxrs</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-server-jaxrs.BaseProvider'>Juneau JAX-RS Provider</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-client'><i>juneau-rest-client</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-client.3rdPartyProxies'>Interface Proxies Against 3rd-party REST Interfaces</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.SSL'>SSL Support</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-client.SSLOpts'>SSLOpts Bean</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-client.Authentication'>Authentication</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-rest-client.BASIC'>BASIC Authentication</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.FORM'>FORM-based Authentication</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.OIDC'>OIDC Authentication</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-rest-client.ResponsePatterns'>Using Response Patterns</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.PipingOutput'>Piping Response Output</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.Debugging'>Debugging</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.Logging'>Logging</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.Interceptors'>Interceptors</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.Remoteable'>Remoteable Proxies</a></p>
<li><p><a class='doclink' href='#juneau-rest-client.Other'>Other Useful Methods</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-microservice-server'><i>juneau-microservice-server</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-microservice-server.Introduction'>Microservice Introduction</a></p>
<li><p><a class='doclink' href='#juneau-microservice-server.GettingStarted'>Getting Started</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-microservice-server.Installing'>Installing in Eclipse</a></p>
<li><p><a class='doclink' href='#juneau-microservice-server.Running'>Running in Eclipse</a></p>
<li><p><a class='doclink' href='#juneau-microservice-server.Building'>Building and Running from Command-Line</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-microservice-server.Manifest'>Manifest File</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-microservice-server.ManifestApi'>Manifest API</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-microservice-server.Config'>Config</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-microservice-server.ConfigApi'>Config API</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-microservice-server.ResourceClasses'>Resource Classes</a></p>
<li><p><a class='doclink' href='#juneau-microservice-server.PredefinedResourceClasses'>Predefined Resource Classes</a></p>
<li><p><a class='doclink' href='#juneau-microservice-server.RestMicroservice'>RestMicroservice</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-microservice-server.ExtendingRestMicroservice'>Extending RestMicroservice</a></p>
</ol>
</ol>
<li><p><a class='doclink' href='#juneau-examples-core'><i>juneau-examples-core</i></a></p>
<li><p><a class='doclink' href='#juneau-examples-rest'><i>juneau-examples-rest</i></a></p>
<ol>
<li><p><a class='doclink' href='#juneau-examples-rest.RootResources'>RootResources</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.HelloWorldResource'>HelloWorldResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.MethodExampleResource'>MethodExampleResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.UrlEncodedFormResource'>UrlEncodedFormResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.RequestEchoResource'>RequestEchoResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource'>AddressBookResource</a></p>
<ol>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.Classes'>Classes</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.Demo'>Demo</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.Traversable'>Traversable</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.Queryable'>Queryable</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.Introspectable'>Introspectable</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.RestClient'>ClientTest</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AddressBookResource.Browser'>Browser Tips</a></p>
</ol>
<li><p><a class='doclink' href='#juneau-examples-rest.SampleRemoteableServlet'>SampleRemoteableServlet</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.TempDirResource'>TempDirResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.AtomFeedResource'>AtomFeedResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.DockerRegistryResource'>DockerRegistryResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.TumblrParserResource'>TumblrParserResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.PhotosResource'>PhotosResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.JsonSchemaResource'>JsonSchemaResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.SqlQueryResource'>SqlQueryResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.ConfigResource'>ConfigResource</a></p>
<li><p><a class='doclink' href='#juneau-examples-rest.LogsResource'>LogsResource</a></p>
</ol>
<li><p><a class='doclink' href='#Security'>Security Best-Practices</a></p>
<li><p><a class='doclink' href='#ReleaseNotes'>Release Notes</a></p>
</ol>
<!-- =============================================================================================================== -->
<a id="Intro"></a>
<h2 class='topic' onclick='toggle(this)'>1 - Introduction</h2>
<div class='topic'>
<p>
Juneau is a single cohesive framework consisting of the following parts:
</p>
<ul class='spaced-list'>
<li>A universal toolkit for marshalling POJOs to a wide variety of content types using a common framework.
<li>A universal REST server API for creating Swagger-based self-documenting REST interfaces using POJOs, simply
deployed as one or more top-level servlets in any Servlet 3.1 or above container.
<li>A universal REST client API for interacting with Juneau or 3rd-party REST interfaces using POJOs and proxy
interfaces.
<li>A sophisticated configuration file API.
<li>A REST microservice API that combines all the features above with a simple configurable Jetty server for
creating lightweight stand-alone REST interfaces that start up in milliseconds.
<li>Built on top of Servlet and Apache HttpClient APIs that allow you to use the newest HTTP/2 features
such as request/response multiplexing and server push.
</ul>
<p>
Questions via email to <a class='doclink' href='mailto:dev@juneau.apache.org?Subject=Apache%20Juneau%20question'>dev@juneau.apache.org</a> are always welcome.
</p>
<p>
Juneau is packed with features that may not be obvious at first.
Users are encouraged to ask for code reviews by providing links to specific source files such as through GitHub.
Not only can we help you with feedback, but it helps us understand usage patterns to further improve the product.
</p>
<h5 class='topic'>History</h5>
<p>
Juneau started off as a popular internal IBM toolkit called Juno.
Originally used for serializing POJOs to and from JSON, it later expanded in scope to include a variety of
content types, and then later REST servlet, client, and microservice APIs.
It's use grew to more than 50 projects and was one of the most popular community source projects within IBM.
</p>
<p>
In June of 2016, the code was donated to the Apache Foundation under the project <l>Apache Juneau</l> where it
has continued to evolve to where it is today.
</p>
<!-- =========================================================================================================== -->
<a id="Intro.Features"></a>
<h3 class='topic' onclick='toggle(this)'>1.1 - Features</h3>
<div class='topic'>
<ul class='spaced-list'>
<li>
KISS is our mantra! No auto-wiring. No code generation. No dependency injection (but still compatible with).
Just add it to your classpath and use it. Extremely simple unit testing!
<li>
Extensive and extensible support for a large variety of POJOs, including structured data (beans) and
unstructured data (<code>Maps</code> and <code>Collections</code>).
<li>
Sophisticated configurable serializers and parsers.
<br>For example, the JSON serializers and parsers can handle strict or lax syntax, comments,
concatenated strings, etc...
<li>Tiny - ~1MB
<li>Exhaustively tested
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="Intro.Components"></a>
<h3 class='topic' onclick='toggle(this)'>1.2 - Components</h3>
<div class='topic'>
<p>
We've strived to keep prerequisites to an absolute minimum in order to make adoption as easy as possible.
</p>
<p>
The library consists of the following artifacts found in the Maven group <code>"org.apache.juneau"</code>:
</p>
<table class='styled' style='min-width:800px;width:50%'>
<tr>
<th>Category</th><th>Maven Artifacts</th><th>Description</th><th>Prerequisites</th>
</tr>
<tr class='dark bb'>
<td rowspan="5" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-core</td>
<td class='code'><a class='doclink' href='#juneau-marshall'>juneau-marshall</a></td>
<td>Serializers and parsers for:
<ul style='margin:0px 10px;'>
<li>JSON
<li>XML
<li>HTML
<li>UON
<li>URL-Encoding
<li>MessagePack
<li>SOAP/XML
<li>CSV
<li>BSON (coming soon)
<li>YAML (coming soon)
<li>Protobuf (coming soon)
</ul>
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
</ul>
</td>
</tr>
<tr class='dark bb'>
<td class='code'><a class='doclink' href='#juneau-marshall-rdf'>juneau-marshall-rdf</a></td>
<td>
Serializers and parsers for:
<ul style='margin:0px 10px;'>
<li>RDF/XML
<li>RDF/XML-Abbrev
<li>N-Triple
<li>Turtle
<li>N3
</ul>
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Apache Jena 2.7.1
</ul>
</td>
</tr>
<tr class='dark bb'>
<td class='code'><a class='doclink' href='#juneau-dto'>juneau-dto</a></td>
<td>
Data Transfer Objects for:
<ul style='margin:0px 10px;'>
<li>HTML5
<li>Atom
<li>Cognos
<li>JSON-Schema
<li>Swagger 2.0
</ul>
</td>
<td><ul style='margin:0px 10px;'><li>Java 6</li></ul></td>
</tr>
<tr class='dark bb'>
<td class='code'><a class='doclink' href='#juneau-svl'>juneau-svl</a></td>
<td>
Simple Variable Language API
</td>
<td><ul style='margin:0px 10px;'><li>Java 6</li></ul></td>
</tr>
<tr class='dark bb'>
<td class='code'><a class='doclink' href='#juneau-config'>juneau-config</a></td>
<td>
Configuration file API
</td>
<td><ul style='margin:0px 10px;'><li>Java 6</li></ul></td>
</tr>
<tr class='light bb'>
<td rowspan="3" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-rest</td>
<td class='code'><a class='doclink' href='#juneau-rest-server'>juneau-rest-server</a></td>
<td>
REST Servlet API
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Servlet 3.1
</ul>
</td>
</tr>
<tr class='light bb'>
<td class='code'><a class='doclink' href='#juneau-rest-server-jaxrs'>juneau-rest-server-jaxrs</a></td>
<td>
Optional JAX-RS support
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>JAX-RS 2.0
</ul>
</td>
</tr>
<tr class='light bb'>
<td class='code'><a class='doclink' href='#juneau-rest-client'>juneau-rest-client</a></td>
<td>
REST Client API
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Apache HttpClient 4.5.3
</ul>
</td>
</tr>
<tr class='dark bb'>
<td rowspan="1" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-microservice</td>
<td class='code'><a class='doclink' href='#juneau-microservice-server'>juneau-microservice-server</a></td>
<td>
REST Microservice Server API
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 8
<li>Eclipse Jetty 9.4.3
</ul>
</td>
</tr>
<tr class='light bb'>
<td rowspan="2" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-examples</td>
<td class='code'><a class='doclink' href='#juneau-examples-core'>juneau-examples-core</a></td>
<td>
Core code examples
</td>
<td></td>
</tr>
<tr class='light bb'>
<td class='code'><a class='doclink' href='#juneau-examples-rest'>juneau-examples-rest</a></td>
<td>
REST code examples
</td>
<td></td>
</tr>
<tr class='dark bb'>
<td rowspan="1" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-all</td>
<td class='code'><code>juneau-all</code></td>
<td>
Combination of the following:
<ul style='margin:0px 10px;'>
<li>juneau-marshall
<li>juneau-dto
<li>juneau-svl
<li>juneau-config
<li>juneau-rest-server
<li>juneau-rest-client
</ul>
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Servlet 3.1
<li>Apache HttpClient 4.5.3
</ul>
</td>
</tr>
</table>
<p>
Each component are also packaged as stand-alone OSGi modules.
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-marshall"></a>
<h2 class='topic' onclick='toggle(this)'>2 - juneau-marshall</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-marshall<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-marshall-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.marshall_7.0.0.jar
</p>
<p>
The <code>juneau-marshall</code> artifact contains the API for defining serializers and parsers, and
marshalling support for JSON, XML, HTML, URL-Encoding, UON and others.
</p>
<p>
It also defines many convenience utility classes used throughout the framework.
</p>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.Serializers"></a>
<h3 class='topic' onclick='toggle(this)'>2.1 - Serializers</h3>
<div class='topic'>
<p>
One of the goals of Juneau was to make serialization as simple as possible.
In a single line of code, you should be able to serialize and parse most POJOs.
Despite this simplicity, Juneau provides lots of extensibility and configuration properties for tailoring how
POJOs are serialized and parsed.
</p>
<p>
The built-in serializers in Juneau are fast, efficient, and highly configurable.
They work by serializing POJOs directly to streams instead of using intermediate Document Object Model
objects.
</p>
<p>
In most cases, you can serialize objects in one line of code by using one of the default serializers:
</p>
<p class='bcode'>
<jc>// A simple bean</jc>
<jk>public class</jk> Person {
<jk>public</jk> String <jf>name</jf> = <js>"John Smith"</js>;
<jk>public int</jk> <jf>age</jf> = 21;
}
<jc>// Serialize to JSON, XML, or HTML</jc>
Person p = <jk>new</jk> Person();
<jc>// Produces:
// "{name:'John Smith',age:21}"</jc>
String json = JsonSerializer.<jsf>DEFAULT</jsf>.serialize(p);
<jc>// Produces:
// &lt;object&gt;
// &lt;name&gt;John Smith&lt;/name&gt;
// &lt;age&gt;21&lt;/age&gt;
// &lt;/object&gt;</jc>
String xml = XmlSerializer.<jsf>DEFAULT</jsf>.serialize(p);
<jc>// Produces:
// &lt;table&gt;
// &lt;tr&gt;&lt;th&gt;key&lt;/th&gt;&lt;th&gt;value&lt;/th&gt;&lt;/tr&gt;
// &lt;tr&gt;&lt;td&gt;name&lt;/td&gt;&lt;td&gt;John Smith&lt;/td&gt;&lt;/tr&gt;
// &lt;tr&gt;&lt;td&gt;age&lt;/td&gt;&lt;td&gt;21&lt;/td&gt;&lt;/tr&gt;
// &lt;/table&gt;</jc>
String html = HtmlSerializer.<jsf>DEFAULT</jsf>.serialize(p);
<jc>// Produces:
// "(name='John Smith',age=21)"</jc>
String uon = UonSerializer.<jsf>DEFAULT</jsf>.serialize(p);
<jc>// Produces:
// "name='John+Smith'&amp;age=21"</jc>
String urlencoding = UrlEncodingSerializer.<jsf>DEFAULT</jsf>.serialize(p);
<jc>// Produces:
// 82 A4 6E 61 6D 65 AA 4A 6F 68 6E 20 53 6D 69 74 68 A3 61 67 65 15 </jc>
<jk>byte</jk>[] b = MsgPackSerializer.<jsf>DEFAULT</jsf>.serialize(p);
</p>
<p>
In addition to the default serializers, customized serializers can be created using various built-in options:
</p>
<p class='bcode'>
<jc>// Use one of the default serializers to serialize a POJO</jc>
String json = JsonSerializer.<jsf>DEFAULT</jsf>.serialize(someObject);
<jc>// Create a custom serializer for lax syntax using single quote characters</jc>
JsonSerializer serializer = JsonSerializer.<jsm>create</jsm>().simple().sq().build();
<jc>// Clone an existing serializer and modify it to use single-quotes</jc>
JsonSerializer serializer = JsonSerializer.<jsf>DEFAULT</jsf>.builder().sq().build();
<jc>// Serialize a POJO to JSON</jc>
String json = serializer.serialize(someObject);
</p>
<p>
Default serialization support is provided for Java primitives, <code>Maps</code>, <code>Collections</code>,
beans, and arrays.
<br>Extensible support for other data types such as <code>Calendars</code>, <code>Dates</code>,
<code>Iterators</code> is available through the use of POJO swaps (described later).
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.Parsers"></a>
<h3 class='topic' onclick='toggle(this)'>2.2 - Parsers</h3>
<div class='topic'>
<p>
Parsers work by parsing input directly into POJOs instead of having to create intermediate Document Object
Models.
This allows them to parse input with minimal object creation.
</p>
<p>
Like the serializers, you can often parse objects in one line of code by using one of the default parsers:
</p>
<p class='bcode'>
<jc>// Use one of the predefined parsers.</jc>
Parser parser = JsonParser.<jsf>DEFAULT</jsf>;
<jc>// Parse a JSON object as a bean.</jc>
String json = <js>"{name:'John Smith',age:21}"</js>;
Person p = parser.parse(json, Person.<jk>class</jk>);
<jc>// Or parse it into a generic Map.</jc>
Map m1 = parser.parse(json, Map.<jk>class</jk>);
<jc>// Parse a JSON string.</jc>
json = <js>"'foobar'"</js>;
String s2 = parser.parse(json, String.<jk>class</jk>);
<jc>// Parse a JSON number as a Long or Float.</jc>
json = <js>"123"</js>;
Long l3 = parser.parse(json, Long.<jk>class</jk>);
Float f3 = parser.parse(json, Float.<jk>class</jk>);
<jc>// Parse a JSON object as a HashMap&lt;String,Person&gt;.</jc>
json = <js>"{a:{name:'John Smith',age:21},b:{name:'Joe Smith',age:42}}"</js>;
Map&lt;String,Person&gt; m4 = parser.parse(json, HashMap.<jk>class</jk>, String.<jk>class</jk>, Person.<jk>class</jk>)
<jc>// Parse a JSON object as a HashMap&lt;String,LinkedList&lt;Person&gt;&gt;.</jc>
json = <js>"{a:[{name:'John Smith',age:21},{name:'Joe Smith',age:42}]}"</js>;
Map&lt;String,List&lt;Person&gt;&gt; m5 = parser.parse(json, HashMap.<jk>class</jk>, String.<jk>class</jk>,
LinkedList.<jk>class</jk>, Person.<jk>class</jk>)
<jc>// Parse a JSON array of integers as a Collection of Integers or int[] array.</jc>
json = <js>"[1,2,3]"</js>;
List&lt;Integer&gt; l6 = parser.parse(json, LinkedList.<jk>class</jk>, Integer.<jk>class</jk>);
<jk>int</jk>[] i7 = parser.parse(json, <jk>int</jk>[].<jk>class</jk>);
</p>
<p>
The parsers can also be used to populating existing bean and collection objects:
</p>
<p class='bcode'>
<jc>// Use one of the predefined parsers.</jc>
Parser parser = JsonParser.<jsf>DEFAULT</jsf>;
<jc>// Populate the properties on an existing bean from a JSON object.</jc>
String json = <js>"{name:'John Smith',age:21}"</js>;
Person p = <jk>new</jk> Person();
parser.parseIntoBean(json, p);
<jc>// Populate an existing list from a JSON array of numbers.</jc>
json = <js>"[1,2,3]"</js>;
List&lt;Integer&gt; l2 = <jk>new</jk> LinkedList&lt;Integer&gt;();
parser.parseIntoCollection(json, l2, Integer.<jk>class</jk>);
<jc>// Populate an existing map from a JSON object containing beans.</jc>
json = <js>"{a:{name:'John Smith',age:21},b:{name:'Joe Smith',age:42}}"</js>;
Map&lt;String,Person&gt; m3 = <jk>new</jk> TreeMap&lt;String,Person&gt;();
parser.parseIntoMap(json, m3, String.<jk>class</jk>, Person.<jk>class</jk>);
</p>
<ul class='doctree'>
<li class='info'>
In the example above, we're parsing "lax" JSON (single quotes, unquoted attributes).
The JSON parser can handle any valid JSON syntax (such as quoted or unquoted attributes, single or double
quotes).
<br>It can also handle JSON fragments and embedded Javascript comments.
Many of the JSON examples provided will use lax syntax which is easier to read since we don't have to deal
with escapes.
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.Groups"></a>
<h3 class='topic' onclick='toggle(this)'>2.3 - SerializerGroups and ParserGroups</h3>
<div class='topic'>
<p>
Above the serializers and parsers are the {@link org.apache.juneau.serializer.SerializerGroup} and
{@link org.apache.juneau.parser.ParserGroup} classes.
These classes allow serializers and parsers to be retrieved by W3C-compliant HTTP <code>Accept</code>
and <code>Content-Type</code> values...
</p>
<p class='bcode'>
<jc>// Construct a new serializer group with configuration parameters that get applied to all serializers.</jc>
SerializerGroup sg = SerializerGroup.<jsm>create</jsm>()
.append(JsonSerializer.<jk>class</jk>, UrlEncodingSerializer.<jk>class</jk>);
.ws <jc>// or .useWhitespace(true)</jc>
.pojoSwaps(CalendarSwap.ISO8601DT.<jk>class</jk>)
.build();
<jc>// Find the appropriate serializer by Accept type and serialize our POJO to the specified writer.</jc>
sg.getSerializer(<js>"text/invalid, text/json;q=0.8, text/*;q:0.6, *\/*;q=0.0"</js>)
.serialize(myPersonObject, myWriter);
<jc>// Construct a new parser group with configuration parameters that get applied to all parsers.</jc>
ParserGroup pg = ParserGroup.<jsm>create</jsm>()
.append(JsonSerializer.<jk>class</jk>, UrlEncodingSerializer.<jk>class</jk>);
.pojoSwaps(CalendarSwap.ISO8601DT.<jk>class</jk>)
.build();
Person p = pg.getParser(<js>"text/json"</js>).parse(myReader, Person.<jk>class</jk>);
</p>
<p>
The REST servlet API builds upon the <code>SerializerGroup</code> and <code>ParserGroup</code> classes
to provide annotated REST servlets that automatically negotiate the HTTP media types and allow the developer
to work with requests and responses as POJOs.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.ObjectMap"></a>
<h3 class='topic' onclick='toggle(this)'>2.4 - ObjectMap and ObjectList</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.ObjectMap} and {@link org.apache.juneau.ObjectList} classes are generic Java
representations of JSON objects and arrays.
These classes can be used to create "unstructured" models for serialization (as opposed to "structured"
models consisting of beans).
If you want to quickly generate JSON/XML/HTML from generic maps/collections, or parse JSON/XML/HTML into
generic maps/collections, these classes work well.
</p>
<p>
These classes extend directly from the following JCF classes:
</p>
<ul class='doctree'>
<li class='jc'>
{@link java.util.LinkedHashMap java.util.LinkedHashMap}
<ul>
<li class='jc'>
{@link org.apache.juneau.ObjectMap org.apache.juneau.ObjectMap}
</ul>
</li>
<li class='jc'>
{@link java.util.LinkedList java.util.LinkedList}
<ul>
<li class='jc'>
{@link org.apache.juneau.ObjectMap org.apache.juneau.ObjectList}
</ul>
</li>
</ul>
<p>
The <l>ObjectMap</l> and <l>ObjectList</l> classes are very similar to the <l>JSONObject</l> and
<l>JSONArray</l> classes found in other libraries.
However, the names were chosen because the concepts of <l>Maps</l> and <l>Lists</l> are already familiar to
Java programmers, and these classes can be used with any of the serializers or parsers.
</p>
<p>
These object can be serialized in one of two ways:
</p>
<ol class='spaced-list'>
<li>
Using the provided {@link org.apache.juneau.ObjectMap#serializeTo(java.io.Writer)} or
{@link org.apache.juneau.ObjectList#serializeTo(java.io.Writer)} methods.
<li>
Passing them to one of the {@link org.apache.juneau.serializer.Serializer} serialize methods.
<li>
Simply calling the {@link org.apache.juneau.ObjectMap#toString()} or {@link org.apache.juneau.ObjectList#toString()}
methods which will serialize it as Simplified JSON.
</ol>
<p>
Any valid JSON can be parsed into an unstructured model consisting of generic
{@link org.apache.juneau.ObjectMap} and {@link org.apache.juneau.ObjectList} objects.
<br>
(In theory, any valid XML can also be parsed into an unstructured model, although this has not been
officially 'tested')
</p>
<p class='bcode'>
<jc>// Parse an arbitrary JSON document into an unstructered data model
// consisting of ObjectMaps, ObjectLists, and java primitive objects.</jc>
Parser parser = JsonParser.<jsf>DEFAULT</jsf>;
String json = <js>"{a:{name:'John Smith',age:21},b:{name:'Joe Smith',age:42}}"</js>;
ObjectMap m = parser.parse(json, ObjectMap.<jk>class</jk>);
<jc>// Use ObjectMap API to extract data from the unstructured model.</jc>
<jk>int</jk> johnSmithAge = m.getObjectMap(<js>"a"</js>).getInt(<js>"age"</js>);
<jc>// Convert it back into JSON.</jc>
json = JsonSerializer.<jsf>DEFAULT</jsf>.serialize(m);
<jc>// Or convert it to XML.</jc>
String xml = XmlSerializer.<jsf>DEFAULT</jsf>.serialize(m);
<jc>// Or just use toString().</jc>
json = m.toString();
</p>
<p>
The <code>ObjectMap</code> and <code>ObjectList</code> classes have many convenience features:
</p>
<p class='bcode'>
<jc>// Convert the map to a bean.</jc>
MyBean m = objectMap.cast(MyBean.<jk>class</jk>);
<jc>// Find entries by multiple keys.</jc>
MyBean m = objectMap.find(MyBean.<jk>class</jk>, <js>"key1"</js>, <js>"key2"</js>);
<jc>// Fluent-style appenders.</jc>
objectMap.append(<js>"key1"</js>, <js>"val1"</js>).append(<js>"key2"</js>, <js>"val2"</js>);
<jc>// REST-like functions for manipulating nodes in the data structure using URL-like notation.</jc>
objectMap.getAt(<js>"foo/bar/myBean"</js>, MyBean.<jk>class</jk>);
objectMap.putAt(<js>"foo/bar/myBean"</js>, MyBean.<jk>class</jk>);
objectMap.postAt(<js>"foo/bar/myListOfBeans"</js>, MyBean.<jk>class</jk>);
objectMap.deleteAt(<js>"foo/bar/myBean"</js>);
<jc>// Copy with inclusion or exclusion.</jc>
ObjectMap m2 = objectMap.include(<js>"key1"</js>, <js>"key2"</js>, <js>"key3"</js>);
ObjectMap m3 = objectMap.exclude(<js>"key1"</js>, <js>"key2"</js>, <js>"key3"</js>);
<jc>// Serialize using another serializer.</jc>
String xml = objectMap.serializeTo(XmlSerializer.<jsf>DEFAULT</jsf>);
<jc>// Nested maps.</jc>
objectMap.setInner(objectMapInner);
</p>
<ul class='doctree'>
<li class='info'>
As a general rule, if you do not specify a target type during parsing, or if the target type cannot be
determined through reflection, the parsers automatically generate <l>ObjectMaps</l> and <l>ObjectLists</l>.
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.ConfigurableProperties"></a>
<h3 class='topic' onclick='toggle(this)'>2.5 - Configurable Properties</h3>
<div class='topic'>
<p>
Serializers and parsers have a wide variety of configurable properties.
<br>They all extend from the {@link org.apache.juneau.BeanContextBuilder} class that allows you to easily construct
new instances from scratch or build upon existing instances.
<br>For example, the following code shows how to configure a JSON serializer:
</p>
<p class='bcode'>
WriterSerializer s = JsonSerializer
.<jsm>create</jsm>() <jc>// Create a JsonSerializerBuilder</jc>
.simple() <jc>// Simple mode</jc>
.ws() <jc>// Use whitespace</jc>
.sq() <jc>// Use single quotes </jc>
.build(); <jc>// Create a JsonSerializer</jc>
</p>
<p>
Configurable settings can also be set declaratively.
<br>The following produces the same serializer.
</p>
<p class='bcode'>
WriterSerializer s = JsonSerializer
.<jsm>create</jsm>()
.set(<jsf>JSON_simpleMode</jsf>, <jk>true</jk>)
.set(<jsf>SERIALIZER_useWhitespace</jsf>, <jk>true</jk>)
.set(<jsf>SERIALIZER_quoteChar</jsf>, <js>"'"</js>)
.build();
</p>
<p>
However, each of the serializers and parsers already contain reusable instances with common configurations.
<br>For example, JSON has the following predefined reusable serializers and parsers:
</p>
<ul class='doctree'>
<li class='jc'>
{@link org.apache.juneau.json.JsonSerializer}
<ul>
<li class='jf'>
{@link org.apache.juneau.json.JsonSerializer#DEFAULT DEFAULT}
<li class='jf'>
{@link org.apache.juneau.json.JsonSerializer#DEFAULT_LAX DEFAULT_LAX}
<li class='jf'>
{@link org.apache.juneau.json.JsonSerializer#DEFAULT_READABLE DEFAULT_READABLE}
<li class='jf'>
{@link org.apache.juneau.json.JsonSerializer#DEFAULT_LAX_READABLE DEFAULT_LAX_READABLE}
<li class='jf'>
{@link org.apache.juneau.json.JsonSerializer#DEFAULT_LAX_READABLE_SAFE DEFAULT_LAX_READABLE_SAFE}
</ul>
</li>
<li class='jc'>
{@link org.apache.juneau.json.JsonParser}
<ul>
<li class='jf'>
{@link org.apache.juneau.json.JsonParser#DEFAULT DEFAULT}
<li class='jf'>
{@link org.apache.juneau.json.JsonParser#DEFAULT_STRICT DEFAULT_STRICT}
</ul>
</li>
</ul>
<p>
These can be used directly, as follows:
</p>
<p class='bcode'>
<jc>// Serialize a POJO to LAX JSON.</jc>
String json = JsonSerializer.<jsf>DEFAULT_LAX</jsf>.serialize(myPojo);
</p>
<p>
For performance reasons, serializers and parsers are immutable.
However, they can be 'copied' and modified using the <code>builder()</code> method.
</p>
<p class='bcode'>
<jc>// Clone and customize an existing serializer.</jc>
WriterSerializer s = JsonSerializer.<jsf>DEFAULT_LAX</jsf>
.builder() <jc>// Create a new builder with copied settings.</jc>
.quoteChar(<js>'"'</js>) <jc>// Use a different quote character.</jc>
.build();
</p>
<h5 class='topic'>Additional Information</h5>
<p>
The following is a list of all configurable properties across all serializers and parsers.
</p>
<ul class='doctree'>
<li class='jc'>
{@link org.apache.juneau.BeanContext}
- Properties associated with handling beans on serializers and parsers.
<ul>
<li class='jc'>
{@link org.apache.juneau.serializer.Serializer}
- Configurable properties common to all serializers.
<ul>
<li class='jc'>
{@link org.apache.juneau.html.HtmlSerializer}
- Configurable properties on the HTML serializer.
<ul>
<li class='jc'>
{@link org.apache.juneau.html.HtmlDocSerializer}
- Configurable properties on the HTML document serializer.
</ul>
</li>
<li class='jic'>
{@link org.apache.juneau.jena.RdfCommon}
- Configurable properties common to the RDF serializers and parsers.
<ul>
<li class='jc'>
{@link org.apache.juneau.jena.RdfSerializer}
- Configurable properties on the RDF serializers.
</ul>
</li>
<li class='jc'>
{@link org.apache.juneau.json.JsonSerializer}
- Configurable properties on the JSON serializer.
<li class='jc'>
{@link org.apache.juneau.msgpack.MsgPackSerializer}
- Configurable properties on the MessagePack serializer.
<li class='jc'>
{@link org.apache.juneau.soap.SoapXmlSerializer}
- Configurable properties on the SOAP/XML serializer.
<li class='jc'>
{@link org.apache.juneau.uon.UonSerializer}
- Configurable properties on the URL-Encoding and UON serializers.
<li class='jc'>
{@link org.apache.juneau.xml.XmlSerializer}
- Configurable properties on the XML serializer.
</ul>
</li>
<li class='jc'>
{@link org.apache.juneau.parser.Parser}
- Configurable properties common to all parsers.
<ul>
<li class='jc'>
{@link org.apache.juneau.html.HtmlParser}
- Configurable properties on the HTML parser.
<li class='jic'>
{@link org.apache.juneau.jena.RdfCommon}
- Configurable properties common to the RDF serializers and parsers.
<ul>
<li class='jc'>
{@link org.apache.juneau.jena.RdfParser}
- Configurable properties on the RDF parsers.
</ul>
</li>
<li class='jc'>
{@link org.apache.juneau.json.JsonParser}
- Configurable properties on the JSON parser.
<li class='jc'>
{@link org.apache.juneau.msgpack.MsgPackParser}
- Configurable properties on the MessagePack parser.
<li class='jc'>
{@link org.apache.juneau.uon.UonParser}
- Configurable properties on the URL-Encoding and UON parsers.
<li class='jc'>
{@link org.apache.juneau.xml.XmlParser}
- Configurable properties on the XML parser.
</ul>
</li>
<li class='jc'>
{@link org.apache.juneau.rest.RestContext}
- Configurable properties on the REST servlet.
</li>
<li class='jc'>
{@link org.apache.juneau.rest.client.RestClient}
- Configurable properties on the REST client.
</li>
</ul>
</li>
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.ContextsBuildersSessionsPropertyStores"></a>
<h3 class='topic' onclick='toggle(this)'>2.6 - Contexts, Builders, Sessions, and PropertyStores</h3>
<div class='topic'>
<p>
All the serializers, parsers, and REST server/client classes use the following design pattern:
</p>
<ul class='spaced-list'>
<li>
<l>Context</l> - A thread-safe read-only object.
<br>Examples: <code>BeanContext</code>, <code>JsonSerializer</code>
<li>
<l>ContextBuilder</l> - A thread-safe builder for contexts.
<br>Examples: <code>BeanContextBuilder</code>, <code>JsonSerializerBuilder</code>
<li>
<l>Session</l> - A non-thread-safe single-use object with configuration combined from context and
runtime args such as locale/timezone and overridden properties.
<br>These are created by <code>Context</code> objects.
<br>Examples: <code>BeanSession</code>, <code>JsonSerializerSession</code>
<li>
<l>PropertyStore</l> - A thread-safe read-only set of configuration properties.
<br>Each <code>Context</code> contains one <code>PropertyStore</code>.
<li>
<l>PropertyStoreBuilder</l> - A thread-safe builder for <code>PropertyStore</code> objects.
<br>Each <code>ContextBuilder</code> contains one <code>PropertyStoreBuilder</code>.
</ul>
<p>
For example, the class hierarchy for <code>JsonSerializer</code> is:
</p>
<ul class='doctree'>
<li class='jc'><code>Object</code>
<ul>
<li class='jac'>{@link org.apache.juneau.Context}
<ul>
<li class='jc'>{@link org.apache.juneau.BeanContext}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.Serializer}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.WriterSerializer}
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonSerializer}
</ul>
</ul>
</ul>
</ul>
</ul>
</ul>
<p>
Each context object in the hierarchy define properties that can be stored in a <code>PropertyStore</code>
such as <jsf>SERIALIZER_useWhitespace</jsf> or <jsf>JSON_simpleMode</jsf>.
</p>
<p>
The class hierarchy for <code>JsonSerializerBuilder</code> is:
</p>
<ul class='doctree'>
<li class='jc'><code>Object</code>
<ul>
<li class='jac'>{@link org.apache.juneau.ContextBuilder}
<ul>
<li class='jc'>{@link org.apache.juneau.BeanContextBuilder}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.SerializerBuilder}
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonSerializerBuilder}
</ul>
</ul>
</ul>
</ul>
</ul>
<p>
The class hierarchy for <code>JsonSerializerSession</code> is:
</p>
<ul class='doctree'>
<li class='jc'><code>Object</code>
<ul>
<li class='jac'>{@link org.apache.juneau.Session}
<ul>
<li class='jc'>{@link org.apache.juneau.BeanSession}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.SerializerSession}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.WriterSerializerSession}
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonSerializerSession}
</ul>
</ul>
</ul>
</ul>
</ul>
</ul>
<p>
The general idea behind a {@link org.apache.juneau.PropertyStore} is to serve as a reusable configuration of an artifact
(such as a serializer) such that the artifact can be cached and reused if the property stores are 'equal'.
</p>
<p>
For example, two serializers of the same type created with the same configuration will always end up being
the same serializer:
</p>
<p class='bcode'>
<jc>// Two serializers created with identical configurations will always be the same copy.</jc>
WriterSerializer s1 = JsonSerializer.<jsm>create</jsm>().pojoSwaps(MySwap.<jk>class</jk>).simple().build();
WriterSerializer s2 = JsonSerializer.<jsm>create</jsm>().set(<jsf>JSON_simpleMode</jsf>, <jk>true</jk>).pojoSwaps(MySwap.<jk>class</jk>).build();
<jk>assert</jk>(s1 == s2);
</p>
<p>
This has the effect of significantly improving performance, especially if you're creating many
serializers and parsers.
</p>
<p>
The {@link org.apache.juneau.PropertyStoreBuilder} class is used to build up and instantiate immutable
<code>PropertyStore</code> objects.
</p>
<p>
In the example above, the property store being built looks like the following:
</p>
<p class='bcode'>
PropertyStore ps = PropertyStore
.<jsm>create</jsm>()
.set(<js>"BeanContext.pojoSwaps.lc"</js>, MySwap.<jk>class</jk>)
.set(<js>"JsonSerializer.simpleMode.b"</js>, <jk>true</jk>)
.build();
</p>
<p>
Property stores are immutable, comparable, and their hashcodes are calculated exactly one time.
That makes them particularly suited for use as hashmap keys, and thus for caching reusable serializers and parsers.
</p>
<p>
Refer to the {@link org.apache.juneau.PropertyStore} javadoc for a detailed explaination on how
property stores work.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.Transforms"></a>
<h3 class='topic' onclick='toggle(this)'>2.7 - Transforms</h3>
<div class='topic'>
<p>
By default, the Juneau framework can serialize and parse a wide variety of POJOs out-of-the-box.
<br>However, two special classes are provided tailor how certain Java objects are handled by the framework.
<br>These classes are:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.transform.BeanFilter} - Transforms that alter the way beans are handled.
<li class='jac'>{@link org.apache.juneau.transform.PojoSwap} - Transforms that swap non-serializable POJOs with
serializable POJOs during serialization (and optionally vis-versa during parsing).
<ul>
<li class='jc'>{@link org.apache.juneau.transform.StringSwap} - Convenience subclass for swaps that convert
objects to strings.
<li class='jc'>{@link org.apache.juneau.transform.MapSwap} - Convenience subclass for swaps that convert
objects to maps.
</ul>
</li>
</ul>
<p>
Transforms are added to serializers and parsers (and REST clients) using the following configuration properties:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.BeanContext#BEAN_beanFilters}
<li class='jm'>{@link org.apache.juneau.BeanContext#BEAN_pojoSwaps}
</ul>
<p>
Annotations are also provided for specifying transforms directly on classes and methods (all described in later sections):
</p>
<ul class='doctree'>
<li class='ja'>
{@link org.apache.juneau.annotation.Swap @Swap}
- Used to tailor how non-bean POJOs get interpreted by the framework.
<li class='ja'>
{@link org.apache.juneau.annotation.Bean @Bean}
- Used to tailor how beans get interpreted by the framework.
<li class='ja'>
{@link org.apache.juneau.annotation.BeanConstructor @BeanConstructor}
- Maps constructor arguments to property names on beans with read-only properties.
<li class='ja'>
{@link org.apache.juneau.annotation.BeanIgnore @BeanIgnore}
- Ignore classes, fields, and methods from being interpreted as bean or bean components.
<li class='ja'>
{@link org.apache.juneau.annotation.BeanProperty @BeanProperty}
- Used to tailor how bean properties get interpreted by the framework.
<li class='ja'>
{@link org.apache.juneau.annotation.NameProperty @NameProperty}
- Identifies a setter as a method for setting the name of a POJO as it's known by its parent object.
<li class='ja'>
{@link org.apache.juneau.annotation.ParentProperty @ParentProperty}
- Identifies a setter as a method for adding a parent reference to a child object.
<li class='ja'>
{@link org.apache.juneau.annotation.URI @URI}
- Used to identify a class or bean property as a URI.
</ul>
<!-- =================================================================================================== -->
<a id="juneau-marshall.PojoSwaps"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.1 - PojoSwaps</h4>
<div class='topic'>
<p>
{@link org.apache.juneau.transform.PojoSwap PojoSwaps} are a critical component of Juneau.
They allow the serializers and parsers to handle Java objects that wouldn't normally be serializable.
</p>
<p>
Swaps are, simply put, 'object swappers' that swap in serializable objects for
non-serializable ones during serialization, and vis-versa during parsing.
</p>
<p>
Some examples of non-serializable POJOs are <code>File</code>, <code>Reader</code>,
<code>Iterable</code>, etc...
These are classes that aren't beans and cannot be represented as simple maps, collections, or primitives.
</p>
<p>
In the following example, we introduce a <code>PojoSwap</code> that will swap in ISO8601 strings for
<code>Date</code> objects:
</p>
<p class='bcode'>
<jc>// Sample swap for converting Dates to ISO8601 strings.</jc>
<jk>public class</jk> MyDateSwap <jk>extends</jk> PojoSwap&lt;Date,String&gt; {
<jc>// ISO8601 formatter.</jc>
<jk>private</jk> DateFormat <jf>format</jf> = <jk>new</jk> SimpleDateFormat(<js>"yyyy-MM-dd'T'HH:mm:ssZ"</js>);
<jc>// Converts a Date object to an ISO8601 string.</jc>
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> String swap(BeanSession session, Date o) {
<jk>return</jk> <jf>format</jf>.format(o);
}
<jc>// Converts an ISO8601 string to a Date object.</jc>
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> Date unswap(BeanSession session, String o, ClassMeta hint) <jk>throws</jk> Exception {
<jk>return</jk> <jf>format</jf>.parse(o);
}
}
</p>
<p>
The swap can then be associated with serializers and parsers like so:
</p>
<p class='bcode'>
<jc>// Sample bean with a Date field.</jc>
<jk>public class</jk> MyBean {
<jk>public</jk> Date <jf>date</jf> = <jk>new</jk> Date(112, 2, 3, 4, 5, 6);
}
<jc>// Create a new JSON serializer, associate our date swap with it, and serialize a sample bean.</jc>
WriterSerializer s = JsonSerializer.<jsm>create</jsm>().simple().pojoSwaps(MyDateSwap.<jk>class</jk>).build();
String json = s.serialize(<jk>new</jk> MyBean()); <jc>// == "{date:'2012-03-03T04:05:06-0500'}"</jc>
<jc>// Create a JSON parser, associate our date swap with it, and reconstruct our bean (including the date).</jc>
ReaderParser p = JsonParser.<jsm>create</jsm>().pojoSwaps(MyDateSwap.<jk>class</jk>).build();
MyBean bean = p.parse(json, MyBean.<jk>class</jk>);
<jk>int</jk> day = bean.<jf>date</jf>.getDay(); <jc>// == 3</jc>
</p>
<p>
The {@link org.apache.juneau.BeanMap#get(Object)} and {@link org.apache.juneau.BeanMap#put(String,Object)}
methods will automatically convert to swapped values as the following example shows:
</p>
<p class='bcode'>
<jc>// Create a new bean context and add our swap.</jc>
BeanContext bc = BeanContext.<jsm>create</jsm>().pojoSwaps(MyDateSwap.<jk>class</jk>).build();
<jc>// Create a new bean.</jc>
MyBean myBean = <jk>new</jk> MyBean();
<jc>// Wrap it in a bean map.</jc>
BeanMap&lt;Bean&gt; beanMap = bc.forBean(myBean);
<jc>// Use the get() method to get the date field as an ISO8601 string.</jc>
String date = (String)beanMap.get(<js>"date"</js>); <jc>// == "2012-03-03T04:05:06-0500"</jc>
<jc>// Use the put() method to set the date field to an ISO8601 string.</jc>
beanMap.put(<js>"date"</js>, <js>"2013-01-01T12:30:00-0500"</js>); <jc>// Set it to a new value.</jc>
<jc>// Verify that the date changed on the original bean.</jc>
<jk>int</jk> year = myBean.<jf>date</jf>.getYear(); <jc>// == 113</jc>
</p>
<p>
Another example of a <code>PojoSwap</code> is one that converts <code><jk>byte</jk>[]</code> arrays to
BASE64-encoded strings:
</p>
<p class='bcode'>
<jk>public class</jk> ByteArrayBase64Swap <jk>extends</jk> StringSwap&lt;<jk>byte</jk>[]&gt; {
<ja>@Override</ja> <jc>/* StringSwap */</jc>
<jk>public</jk> String swap(<jk>byte</jk>[] b) <jk>throws</jk> Exception {
ByteArrayOutputStream baos = <jk>new</jk> ByteArrayOutputStream();
OutputStream b64os = MimeUtility.encode(baos, <js>"base64"</js>);
b64os.write(b);
b64os.close();
<jk>return new</jk> String(baos.toByteArray());
}
<ja>@Override</ja> <jc>/* StringSwap */</jc>
<jk>public byte</jk>[] unswap(String s, ClassMeta&lt;?&gt; hint) <jk>throws</jk> Exception {
<jk>byte</jk>[] b = s.getBytes();
ByteArrayInputStream bais = <jk>new</jk> ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, <js>"base64"</js>);
<jk>byte</jk>[] tmp = <jk>new byte</jk>[b.length];
<jk>int</jk> n = b64is.read(tmp);
<jk>byte</jk>[] res = <jk>new byte</jk>[n];
System.<jsm>arraycopy</jsm>(tmp, 0, res, 0, n);
<jk>return</jk> res;
}
}
</p>
<p>
The following example shows the BASE64 swap in use:
</p>
<p class='bcode'>
<jc>// Create a JSON serializer and register the BASE64 encoding swap with it.</jc>
WriterSerializer s = JsonSerializer.<jsm>create</jsm>().simple().pojoSwaps(ByteArrayBase64Swap.<jk>class</jk>).build();
ReaderParser p = JsonParser.<jsm>create</jsm>().pojoSwaps(ByteArrayBase64Swap.<jk>class</jk>).build();
<jk>byte</jk>[] bytes = {1,2,3};
String json = s.serialize(bytes); <jc>// Produces "'AQID'"</jc>
bytes = p.parse(json, <jk>byte</jk>[].<jk>class</jk>); <jc>// Reproduces {1,2,3}</jc>
<jk>byte</jk>[][] bytes2d = {{1,2,3},{4,5,6},<jk>null</jk>};
json = s.serialize(bytes2d); <jc>// Produces "['AQID','BAUG',null]"</jc>
bytes2d = p.parse(json, <jk>byte</jk>[][].<jk>class</jk>); <jc>// Reproduces {{1,2,3},{4,5,6},null}</jc>
</p>
<p>
Several <code>PojoSwaps</code> are already provided for common Java objects:
</p>
<ul class='doctree'>
<li class='jp'><jk>org.apache.juneau.transforms</jk>
<ul>
<li class='jc'>
{@link org.apache.juneau.transforms.ByteArrayBase64Swap}
<li class='jac'>
{@link org.apache.juneau.transforms.CalendarSwap}
<li class='jac'>
{@link org.apache.juneau.transforms.DateSwap}
<li class='jc'>
{@link org.apache.juneau.transforms.EnumerationSwap}
<li class='jc'>
{@link org.apache.juneau.transforms.IteratorSwap}
<li class='jc'>
{@link org.apache.juneau.transforms.ReaderSwap}
<li class='jc'>
{@link org.apache.juneau.transforms.XMLGregorianCalendarSwap}
</ul>
</li>
</ul>
<p>
In particular, the {@link org.apache.juneau.transforms.CalendarSwap} and
{@link org.apache.juneau.transforms.DateSwap} transforms provide a large number of customized swaps to
ISO, RFC, or localized strings.
</p>
<p>
Swaps have access to the session locale and timezone through the {@link org.apache.juneau.BeanSession#getLocale()} and
{@link org.apache.juneau.BeanSession#getTimeZone()} methods.
<br>This allows you to specify localized swap values when needed.
</p>
<p>
If using the REST server API, the locale and timezone are set based on the <code>Accept-Language</code> and
<code>Time-Zone</code> headers on the request.
</p>
<ul class='doctree'>
<li class='info'>
The 'swapped' class type must be a serializable type.
<br>See the definition for Category 4 objects in <a class='doclink' href='#juneau-marshall.PojoCategories'>POJO Categories</a>.
</ul>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.PerMediaTypePojoSwaps"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.2 - Per-media-type PojoSwaps</h4>
<div class='topic'>
<p>
Swaps can also be defined per-media-type.
</p>
<p>
The {@link org.apache.juneau.transform.PojoSwap#forMediaTypes()} method can be overridden to
provide a set of media types that the swap is invoked on.
<br>It's also possible to define multiple swaps against the same POJO as long as they're differentiated
by media type.
<br>When multiple swaps are defined, the best-match media type is used.
</p>
<p>
In the following example, we define 3 swaps against the same POJO.
One for JSON, one for XML, and one for all other types.
</p>
<p class='bcode'>
<jk>public class</jk> PojoSwapTest {
<jk>public static class</jk> MyPojo {}
<jk>public static class</jk> MyJsonSwap <jk>extends</jk> PojoSwap&lt;MyPojo,String&gt; {
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> MediaType[] forMediaTypes() {
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/json"</js>);
}
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> String swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
<jk>return</jk> <js>"It's JSON!"</js>;
}
}
<jk>public static class</jk> MyXmlSwap <jk>extends</jk> PojoSwap&lt;MyPojo,String&gt; {
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> MediaType[] forMediaTypes() {
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/xml"</js>);
}
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> String swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
<jk>return</jk> <js>"It's XML!"</js>;
}
}
<jk>public static class</jk> MyOtherSwap <jk>extends</jk> PojoSwap&lt;MyPojo,String&gt; {
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> MediaType[] forMediaTypes() {
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/*"</js>);
}
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> String swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
<jk>return</jk> <js>"It's something else!"</js>;
}
}
<ja>@Test</ja>
<jk>public void</jk> doTest() <jk>throws</jk> Exception {
SerializerGroup g = SerializerGroup.<jsm>create</jsm>()
.append(JsonSerializer.<jk>class</jk>, XmlSerializer.<jk>class</jk>, HtmlSerializer.<jk>class</jk>)
.sq()
.pojoSwaps(MyJsonSwap.<jk>class</jk>, MyXmlSwap.<jk>class</jk>, MyOtherSwap.<jk>class</jk>)
.build();
MyPojo myPojo = <jk>new</jk> MyPojo();
String json = g.getWriterSerializer(<js>"text/json"</js>).serialize(myPojo);
<jsm>assertEquals</jsm>(<js>"'It\\'s JSON!'"</js>, json);
String xml = g.getWriterSerializer(<js>"text/xml"</js>).serialize(myPojo);
<jsm>assertEquals</jsm>(<js>"&lt;string&gt;It's XML!&lt;/string&gt;"</js>, xml);
String html = g.getWriterSerializer(<js>"text/html"</js>).serialize(myPojo);
<jsm>assertEquals</jsm>(<js>"&lt;string&gt;It's something else!&lt;/string&gt;"</js>, html);
}
}
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.OneWayPojoSwaps"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.3 - One-way PojoSwaps</h4>
<div class='topic'>
<p>
In the previous sections, we defined two-way swaps, meaning swaps where the original objects could be
reconstructing during parsing.
<br>However, there are certain kinds of POJOs that we may want to support for serializing, but that are not
possible to reconstruct during parsing.
<br>For these, we can use one-way object swaps.
</p>
<p>
A one-way POJO swap is simply an object transform that only implements the {@code swap()} method.
<br>The {@code unswap()} method is simply left unimplemented.
</p>
<p>
An example of a one-way swaps would be one that allows {@code Iterators} to be serialized as JSON arrays.
<br>It can make sense to be able to render {@code Iterators} as arrays, but in general it's not possible to
reconstruct an {@code Iterator} during parsing.
</p>
<p class='bcode'>
<jk>public class</jk> IteratorSwap <jk>extends</jk> PojoSwap&lt;Iterator,List&gt; {
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> List swap(Iterator o) {
List l = <jk>new</jk> LinkedList();
<jk>while</jk> (o.hasNext())
l.add(o.next());
<jk>return</jk> l;
}
}
</p>
<p>
Here is an example of our one-way swap being used.
<br>Note that trying to parse the original object will cause a {@link org.apache.juneau.parser.ParseException}
to be thrown.
</p>
<p class='bcode'>
<jc>// Create a JSON serializer that can serialize Iterators.</jc>
WriterSerializer s = JsonSerializer.<jsm>create</jsm>().simple().pojoSwaps(IteratorSwap.<jk>class</jk>).build();
<jc>// Construct an iterator we want to serialize.</jc>
Iterator i = <jk>new</jk> ObjectList(1,2,3).iterator();
<jc>// Serialize our Iterator</jc>
String json = s.serialize(i); <jc>// Produces "[1,2,3]"</jc>
<jc>// Try to parse it.</jc>
ReaderParser p = JsonParser.<jsm>create</jsm>().pojoSwaps(IteratorSwap.<jk>class</jk>).build();
i = p.parse(s, Iterator.<jk>class</jk>); <jc>// Throws ParseException!!!</jc>
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.SwapAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.4 - @Swap Annotation</h4>
<div class='topic'>
<p>
{@link org.apache.juneau.annotation.Swap @Swap} can be used to associate a swap class using an
annotation.
<br>This is often cleaner than using the builder <code>pojoSwaps()</code> method since you can keep
your swap class near your POJO class.
</p>
<p class='bcode'>
<ja>@Swap</ja>(MyPojoSwap.<jk>class</jk>)
<jk>public class</jk> MyPojo {
...
}
<jc>// Sample swap for converting MyPojo classes to a simple string.</jc>
<jk>public class</jk> MyPojoSwap <jk>extends</jk> PojoSwap&lt;MyPojo,String&gt; {
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> String swap(BeanSession session, MyPojo o) {
<jk>return</jk> o.toSomeSerializableForm();
}
}
</p>
<p>
Multiple swaps can be associated with a POJO by using the {@link org.apache.juneau.annotation.Swaps @Swaps} annotation:
</p>
<p class='bcode'>
<ja>@Swaps</ja>(
{
<ja>@Swap</ja>(MyJsonSwap.<jk>class</jk>),
<ja>@Swap</ja>(MyXmlSwap.<jk>class</jk>),
<ja>@Swap</ja>(MyOtherSwap.<jk>class</jk>)
}
)
<jk>public class</jk> MyPojo {}
</p>
<p>
<code>Readers</code> get serialized directly to the output of a serializer.
Therefore it's possible to implement a swap that provides fully-customized output.
</p>
<p class='bcode'>
<jk>public class</jk> MyJsonSwap <jk>extends</jk> PojoSwap&lt;MyPojo,Reader&gt; {
<jk>public</jk> MediaType[] forMediaTypes() {
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/json"</js>);
}
<jk>public</jk> Reader swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
<jk>return new</jk> StringReader(<js>"{message:'Custom JSON!'}"</js>);
}
}
</p>
<p>
The <ja>@Swap</ja> annotation can also be used on getters and setters as well to apply a swap
to individual property values
</p>
<p class='bcode'>
<ja>@BeanProperty</ja>(swap=MyPojoSwap.<jk>class</jk>)
<jk>public</jk> MyPojo getMyPojo();
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.TemplatedSwaps"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.5 - Templated Swaps</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.Swap#template() @Swap.template()} annotation allows you to associate
arbitrary contextual strings with swaps.
<br>The primary purpose is for providing template names, such as for Apache FreeMarker, therefore
the name 'template'.
<br>However, the usage of the string is open-ended.
</p>
<p>
For example, you could pair a template string like so:
</p>
<p class='bcode'>
<ja>@Swap</ja>(impl=FreeMarkerSwap.<jk>class</jk>, template=<js>"MyPojo.div.ftl"</js>)
<jk>public class</jk> MyPojo {}
</p>
<p>
The implementation of the FreeMarker swap would look something like this:
</p>
<p class='bcode'>
<jc>// Our templated swap class.</jc>
<jk>public class</jk> FreeMarkerSwap <jk>extends</jk> PojoSwap&lt;Object,Reader&gt; {
<jk>public</jk> MediaType[] forMediaTypes() {
<jc>// Make sure this only applies to the HTML serializer.</jc>
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/html"</js>);
}
<jk>public</jk> Reader swap(BeanSession session, Object o, String template) <jk>throws</jk> Exception {
<jc>// Call some method that uses FreeMarker to convert 'o' to raw HTML using </jc>
<jc>// the 'MyPojo.div.ftl' template.</jc>
<jk>return</jk> getFreeMarkerReader(template, o);
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.SwapMethods"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.6 - Swap Methods</h4>
<div class='topic'>
<p>
Various methods can be defined on a class directly to affect how it gets serialized.
<br>This can often be simpler than using <code>PojoSwaps</code>.
</p>
<p>
Objects serialized as <code>Strings</code> can be parsed back into their original objects by
implementing one of the following methods on the class:
</p>
<ul class='spaced-list'>
<li>
<code><jk>public static</jk> T fromString(String)</code> method.
<br>Any of the following method names also work:
<ul>
<li><code>valueOf(String)</code>
<li><code>parse(String)</code>
<li><code>parseString(String)</code>
<li><code>forName(String)</code>
<li><code>forString(String)</code>
</ul>
<li>
<code><jk>public</jk> T(String)</code> constructor.
</ul>
<p>
Note that these methods cover conversion from several built-in Java types, meaning the parsers can
automatically construct these objects from strings:
</p>
<ul>
<li><code>fromString(String)</code> - {@link java.util.UUID}
<li><code>valueOf(String)</code> - {@link java.lang.Boolean}, {@link java.lang.Byte},
{@link java.lang.Double}, {@link java.lang.Float},
{@link java.lang.Integer}, {@link java.lang.Long}, {@link java.lang.Short}, {@link java.sql.Date},
{@link java.sql.Time}, {@link java.sql.Timestamp}
<li><code>parse(String)</code> - {@link java.text.DateFormat}, {@link java.text.MessageFormat},
{@link java.text.NumberFormat}, {@link java.util.Date}, {@link java.util.logging.Level}
<li><code>parseString(String)</code> - {@link javax.xml.bind.DatatypeConverter}
<li><code>forName(String)</code> - {@link java.lang.Class}
</ul>
<p>
If you want to force a bean-like class to be serialized as a string, you can use the
{@link org.apache.juneau.annotation.BeanIgnore @BeanIgnore} annotation on the class to force it to be
serialized to a string using the <code>toString()</code> method.
</p>
<p>
Serializing to other intermediate objects can be accomplished by defining a swap method directly on the
class:
</p>
<ul>
<li><code><jk>public</jk> X swap(BeanSession)</code> method, where <code>X</code> is any serializable
object.
</ul>
<p>
The <code>BeanSession</code> parameter allows you access to various information about the current
serialization session.
<br>For example, you could provide customized results based on the media type being produced
({@link org.apache.juneau.BeanSession#getMediaType()}).
</p>
<p>
The following example shows how an HTML5 form template object can be created that gets serialized as a
populated HTML5 {@link org.apache.juneau.dto.html5.Form} bean.
</p>
<p class='bcode'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
<jd>/**
* A simple HTML form template whose serialized form is an HTML5 Form object.
*/</jd>
<jk>public class</jk> FormTemplate {
<jk>private</jk> String <jf>action</jf>;
<jk>private int</jk> <jf>value1</jf>;
<jk>private boolean</jk> <jf>value2</jf>;
<jc>// Some constructor that initializes our fields. </jc>
<jk>public</jk> FormTemplate(String action, <jk>int</jk> value1, <jk>boolean</jk> value2) {
<jk>this</jk>.<jf>action</jf> = action;
<jk>this</jk>.<jf>value1</jf> = value1;
<jk>this</jk>.<jf>value2</jf> = value2;
}
<jc>// Special swap method that converts this template to a serializable bean</jc>
<jk>public</jk> Form swap(BeanSession session) {
<jk>return</jk> <jsm>form</jsm>(<jf>action</jf>,
<jsm>input</jsm>(<js>"text"</js>).name(<js>"v1"</js>).value(<jf>value1</jf>),
<jsm>input</jsm>(<js>"text"</js>).name(<js>"v2"</js>).value(<jf>value2</jf>)
);
}
}
</p>
<p>
Swapped objects can be converted back into their original form by the parsers by specifying one of the
following methods:
</p>
<ul>
<li><code><jk>public static</jk> T unswap(BeanSession, X)</code> method where <code>X</code> is the
swap class type.
<li><code><jk>public</jk> T(X)</code> constructor where <code>X</code> is the swap class type.
</ul>
<p>
The following shows how our form template class can be modified to allow the parsers to reconstruct our
original object:
</p>
<p class='bcode'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
<jd>/**
* A simple HTML form template whose serialized form is an HTML5 Form object.
* This time with parsing support.
*/</jd>
<ja>@Bean</ja>(beanDictionary=HtmlBeanDictionary.<jk>class</jk>)
<jk>public class</jk> FormTemplate {
<jk>private</jk> String <jf>action</jf>;
<jk>private int</jk> <jf>value1</jf>;
<jk>private boolean</jk> <jf>value2</jf>;
<jc>// Our 'unswap' constructor</jc>
<jk>public</jk> FormTemplate(Form f) {
<jk>this</jk>.<jf>action</jf> = f.getAttr(<js>"action"</js>);
<jk>this</jk>.<jf>value1</jf> = f.getChild(Input.<jk>class</jk>, 0)
.getAttr(<jk>int</jk>.<jk>class</jk>, <js>"value"</js>);
<jk>this</jk>.<jf>value2</jf> = f.getChild(Input.<jk>class</jk>, 1)
.getAttr(<jk>boolean</jk>.<jk>class</jk>, <js>"value"</js>);
}
<jk>public</jk> FormTemplate(String action, <jk>int</jk> value1, <jk>boolean</jk> value2) {
<jk>this</jk>.<jf>action</jf> = action;
<jk>this</jk>.<jf>value1</jf> = value1;
<jk>this</jk>.<jf>value2</jf> = value2;
}
<jk>public</jk> Form swap(BeanSession session) {
<jk>return</jk> <jsm>form</jsm>(<jf>action</jf>,
<jsm>input</jsm>(<js>"text"</js>).name(<js>"v1"</js>).value(<jf>value1</jf>),
<jsm>input</jsm>(<js>"text"</js>).name(<js>"v2"</js>).value(<jf>value2</jf>)
);
}
}
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.SurrogateClasses"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.7 - Surrogate Classes</h4>
<div class='topic'>
<p>
<p>
Surrogate classes are very similar in concept to <code>PojoSwaps</code> except they're simpler to define.
</p>
<p>
For example, let's say we want to be able to serialize the following class, but it's not serializable for
some reason (for example, there are no properties exposed):
<p class='bcode'>
<jc>// Not serializable because it's not a bean because it has no public properties.</jc>
<jk>public class</jk> MyNonSerializableClass {
<jk>protected</jk> String <jf>foo</jf>;
}
</p>
<p>
This could be solved with the following <code>PojoSwap</code>.
</p>
<p class='bcode'>
<jc>// A serializable bean with 1 property.</jc>
<jk>public class</jk> MySerializableSurrogate {
<jk>public</jk> String <jf>foo</jf>;
}
<jc>// A PojoSwap that swaps out our non-serializable object with our serializable object.</jc>
<jk>public class</jk> MySwap <jk>extends</jk> PojoSwap&lt;MyNonSerializableClass,MySerializableSurrogate&gt; {
<ja>@Override</ja> <jc>/* PojoSwap */</jc>
<jk>public</jk> MySerializableSurrogate swap(MyNonSerializableClass o) {
<jc>// Create some serializable class and manually copy the data into it.</jc>
MySerializableSurrogate s = <jk>new</jk> MySerializableSurrogate();
s.<jf>foo</jf> = o.<jf>foo</jf>;
<jk>return</jk> s;
}
}
</p>
<p>
However, the same can be accomplished by using a surrogate class that simply contains a constructor with
the non-serializable class as an argument:
</p>
<p class='bcode'>
<jk>public class</jk> MySerializableSurrogate {
<jk>public</jk> String <jf>foo</jf>;
<jc>// Constructor takes in our non-serializable object!</jc>
<jk>public</jk> MySerializableSurrogate(MyNonSerializableClass c) {
<jk>this</jk>.<jf>foo</jf> = c.<jf>foo</jf>;
}
}
</p>
<p>
The surrogate class is registered in the same way as a <code>PojoSwap</code>:
</p>
<p class='bcode'>
<jc>// Create a JSON serializer that can serialize Iterators.</jc>
WriterSerializer s = JsonSerializer.<jsm>create</jsm>().pojoSwaps(MySerializableSurrogate.<jk>class</jk>).build();
</p>
<p>
When the serializer encounters the non-serializable class, it will serialize an instance of the surrogate
instead.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jic'>{@link org.apache.juneau.transform.Surrogate}
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.BeanAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.8 - @Bean Annotation</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.Bean @Bean} annotation is used to tailor how beans are
interpreted by the framework.
</p>
<p>
Bean property inclusion and ordering on a bean class can be done using the
{@link org.apache.juneau.annotation.Bean#properties() @Bean.properties()} annotation.
</p>
<p class='bcode'>
<jc>// Address class with only street/city/state properties (in that order).</jc>
<jc>// All other properties are ignored.</jc>
<ja>@Bean</ja>(properties=<js>"street,city,state"</js>)
<jk>public class</jk> Address { ... }
</p>
<p>
Bean properties can be excluded using the {@link org.apache.juneau.annotation.Bean#excludeProperties() @Bean.excludeProperties()}
annotation.
</p>
<p class='bcode'>
<jc>// Address class with only street/city/state properties (in that order).</jc>
<jc>// All other properties are ignored.</jc>
<ja>@Bean</ja>(excludeProperties=<js>"city,state"</js>})
<jk>public class</jk> Address { ... }
</p>
<p>
Bean properties can be sorted alphabetically using {@link org.apache.juneau.annotation.Bean#sort() @Bean.sort()}
</p>
<p class='bcode'>
<jc>// Address class with only street/city/state properties (in that order).</jc>
<jc>// All other properties are ignored.</jc>
<ja>@Bean</ja>(sort=<jk>true</jk>)
<jk>public class</jk> MyBean { ... }
</p>
<p>
The {@link org.apache.juneau.annotation.Bean#propertyNamer() @Bean.propertyNamer()} annotation
is used to provide customized naming of properties.
</p>
<p>
Property namers are used to transform bean property names from standard form to some other form.
<br>For example, the {@link org.apache.juneau.PropertyNamerDLC} will convert property names to
dashed-lowercase, and these will be used as attribute names in JSON and element names in XML.
</p>
<p>
<p class='bcode'>
<jc>// Define a class with dashed-lowercase property names.</jc>
<ja>@Bean</ja>(propertyNamer=PropertyNamerDashedLC.<jk>class</jk>)
<jk>public class</jk> MyBean { ... }
</p>
<p>
The {@link org.apache.juneau.annotation.Bean#interfaceClass @Bean.interfaceClass()} annotation is used
to limit properties on beans to specific interface classes.
<br>When specified, only the list of properties defined on the interface class will be used during
serialization.
<br>Additional properties on subclasses will be ignored.
</p>
<p class='bcode'>
<jc>// Parent class</jc>
<ja>@Bean</ja>(interfaceClass=A.<jk>class</jk>)
<jk>public abstract class</jk> A {
<jk>public</jk> String <jf>f0</jf> = <js>"f0"</js>;
}
<jc>// Child class</jc>
<jk>public class</jk> A1 <jk>extends</jk> A {
<jk>public</jk> String <jf>f1</jf> = <js>"f1"</js>;
}
JsonSerializer s = JsonSerializer.<jsf>DEFAULT_LAX</jsf>;
A1 a1 = <jk>new</jk> A1();
String r = s.serialize(a1);
<jsm>assertEquals</jsm>(<js>"{f0:'f0'}"</js>, r); <jc>// Note f1 is not serialized.</jc>
</p>
<p>
Note that this annotation can be used on the parent class so that it filters to all child classes.
<br>Or can be set individually on the child classes.
</p>
<p>
The {@link org.apache.juneau.annotation.Bean#stopClass @Bean.stopClass()} annotation is another
way to limit which properties are serialized (except from the opposite direction).
<br>It's identical in purpose to the stop class specified by {@link java.beans.Introspector#getBeanInfo(Class, Class)}.
<br>Any properties in the stop class or in its base classes will be ignored during analysis.
</p>
<p>
For example, in the following class hierarchy, instances of <code>C3</code> will include property
<code>p3</code>, but not <code>p1</code> or <code>p2</code>.
</p>
<p class='bcode'>
<jk>public class</jk> C1 {
<jk>public int</jk> getP1();
}
<jk>public class</jk> C2 <jk>extends</jk> C1 {
<jk>public int</jk> getP2();
}
<ja>@Bean</ja>(stopClass=C2.<jk>class</jk>)
<jk>public class</jk> C3 <jk>extends</jk> C2 {
<jk>public int</jk> getP3();
}
</p>
<p>
The {@link org.apache.juneau.annotation.Bean#propertyFilter() @Bean.propertyFilter()} annotation
and {@link org.apache.juneau.transform.PropertyFilter} class can be used to perform interception
and inline handling of bean getter and setter calls.
</p>
<p class='bcode'>
<jc>// Register filter on bean class.</jc>
<ja>@Bean</ja>(propertyFilter=AddressPropertyFilter.<jk>class</jk>)
<jk>public class</jk> Address {
<jk>public</jk> String getTaxInfo() {...}
<jk>public void</jk> setTaxInfo(String s) {...}
}
<jc>// Property filter that strips out sensitive information in our bean.</jc>
<jk>public class</jk> AddressPropertyFilter <jk>extends</jk> PropertyFilter {
<ja>@Override</ja> <jc>/* PropertyFilter */</jc>
<jk>public</jk> Object readProperty(Object bean, String name, Object value) {
<jk>if</jk> (<js>"taxInfo"</js>.equals(name))
<jk>return</jk> <js>"redacted"</js>;
<jk>return</jk> value;
}
<ja>@Override</ja> <jc>/* PropertyFilter */</jc>
<jk>public</jk> Object writeProperty(Object bean, String name, Object value) {
AddressBook a = (Address)bean;
<jk>if</jk> (<js>"taxInfo"</js>.equals(name) &amp;&amp; <js>"redacted"</js>.equals(value))
<jk>return</jk> TaxInfoUtils.<jsm>lookUpByName</jsm>(a.getStreet(), a.getCity(), a.getState());
<jk>return</jk> value;
}
}
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.BeanPropertyAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.9 - @BeanProperty Annotation</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotation is used to tailor how
individual bean properties are interpreted by the framework.
</p>
<p>
The {@link org.apache.juneau.annotation.BeanProperty#name() @BeanProperty.name()} annotation
is used to override the name of the bean property.
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<ja>@BeanProperty</ja>(name=<js>"Bar"</js>)
<jk>public</jk> String getFoo() {...}
}
</p>
<p>
If the {@link org.apache.juneau.BeanContext#BEAN_beanFieldVisibility} setting on the bean context excludes this field
(e.g. the visibility is set to the default of PUBLIC, but the field is PROTECTED), this annotation
can be used to force the field to be identified as a property.
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<ja>@BeanProperty</ja>
<jk>protected</jk> String getFoo() {...}
}
</p>
<p>
The bean property named <js>"*"</js> is the designated "dynamic property" which allows for "extra" bean
properties not otherwise defined.
<br>This is similar in concept to the Jackson <ja>@JsonGetterAll</ja> and <ja>@JsonSetterAll</ja>
annotations, but generalized for all supported marshall languages.
<br>The primary purpose is for backwards compatibility in parsing newer streams with addition
information into older beans.
</p>
<p>
The following shows various ways of using dynamic bean properties.
</p>
<p class='bcode'>
<jc>// Option #1 - A simple public Map field.</jc>
<jc>// The field name can be anything.</jc>
<jk>public class</jk> BeanWithDynaField {
<ja>@BeanProperty</ja>(name=<js>"*"</js>)
<jk>public</jk> Map&lt;String,Object&gt; extraStuff = <jk>new</jk> LinkedHashMap&lt;String,Object&gt;();
}
<jc>// Option #2 - Getters and setters.</jc>
<jc>// Method names can be anything.</jc>
<jc>// Getter must return a Map with String keys.</jc>
<jc>// Setter must take in two arguments, a String and Object.</jc>
<jk>public class</jk> BeanWithDynaMethods {
<ja>@BeanProperty</ja>(name=<js>"*"</js>)
<jk>public</jk> Map&lt;String,Object&gt; getMyExtraStuff() {
...
}
<ja>@BeanProperty</ja>(name=<js>"*"</js>)
<jk>public void</jk> setAnExtraField(String name, Object value) {
...
}
}
<jc>// Option #3 - Getter only.</jc>
<jc>// Properties will be added through the getter.</jc>
<jk>public class</jk> BeanWithDynaGetterOnly {
<ja>@BeanProperty</ja>(name=<js>"*"</js>)
<jk>public</jk> Map&lt;String,Object&gt; getMyExtraStuff() {
...
}
}
</p>
<p>
Similar rules apply for value types and swaps.
<br>The property values optionally can be any serializable type or use swaps.
</p>
<p class='bcode'>
<jc>// A serializable type other than Object.</jc>
<jk>public class</jk> BeanWithDynaFieldWithListValues {
<ja>@BeanProperty</ja>(name=<js>"*"</js>)
<jk>public</jk> Map&lt;String,List&lt;String&gt;&gt; getMyExtraStuff() {
...
}
}
<jc>// A swapped value.</jc>
<jk>public class</jk> BeanWithDynaFieldWithSwappedValues {
<ja>@BeanProperty</ja>(name=<js>"*"</js>, swap=CalendarSwap.<jsf>ISO8601DTZ</jsf>.<jk>class</jk>)
<jk>public</jk> Map&lt;String,Calendar&gt; getMyExtraStuff() {
...
}
}
</p>
<ul class='doctree'>
<li class='info'>
Note that if you're not interested in these additional properties, you can also use the
{@link org.apache.juneau.BeanContext#BEAN_ignoreUnknownBeanProperties} setting to ignore values
that don't fit into existing properties.
</ul>
<p>
The {@link org.apache.juneau.annotation.BeanProperty#value() @BeanProperty.value()} annotation
is a synonym for {@link org.apache.juneau.annotation.BeanProperty#name() @BeanProperty.name()}.
<br>Use it in cases where you're only specifying a name so that you can shorten your annotation.
</p>
<p>
The following annotations are equivalent:
</p>
<p class='bcode'>
<ja>@BeanProperty</ja>(name=<js>"foo"</js>)
<ja>@BeanProperty</ja>(<js>"foo"</js>)
</p>
<p>
The {@link org.apache.juneau.annotation.BeanProperty#type() @BeanProperty.type()} annotation
is used to identify a specialized class type for a generalized property.
<br>Normally the type is inferred through reflection of the field type or getter return type.
<br>However, you'll want to specify this value if you're parsing beans where the bean property class
is an interface or abstract class to identify the bean type to instantiate.
<br>Otherwise, you may cause an {@link java.lang.InstantiationException} when trying to set these fields.
</p>
<p>
This property must denote a concrete class with a no-arg constructor.
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<jc>// Identify concrete type as a HashMap.</jc>
<ja>@BeanProperty</ja>(type=HashMap.<jk>class</jk>)
<jk>public</jk> Map <jf>p1</jf>;
</p>
<p>
The {@link org.apache.juneau.annotation.BeanProperty#params() @BeanProperty.params()} annotation
is for bean properties of type map or collection.
<br>It's used to identify the class types of the contents of the bean property object when
the general parameter types are interfaces or abstract classes.
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<jc>// This is a HashMap&lt;String,Integer&gt;.</jc>
<ja>@BeanProperty</ja>(type=HashMap.<jk>class</jk>, params={String.<jk>class</jk>,Integer.<jk>class</jk>})
<jk>public</jk> Map <jf>p1</jf>;
}
</p>
<p>
The {@link org.apache.juneau.annotation.BeanProperty#properties() @BeanProperty.properties()}
annotation is used to limit which child properties are rendered by the serializers.
<br>It can be used on any of the following bean property types:
</p>
<ul class='spaced-list'>
<li>Beans - Only render the specified properties of the bean.
<li>Maps - Only render the specified entries in the map.
<li>Bean/Map arrays - Same, but applied to each element in the array.
<li>Bean/Map collections - Same, but applied to each element in the collection.
</ul>
<p class='bcode'>
<jk>public class</jk> MyClass {
<jc>// Only render 'f1' when serializing this bean property.</jc>
<ja>@BeanProperty</ja>(properties={<js>"f1"</js>})
<jk>public</jk> MyChildClass x1 = <jk>new</jk> MyChildClass();
}
<jk>public class</jk> MyChildClass {
<jk>public int</jk> f1 = 1;
<jk>public int</jk> f2 = 2;
}
<jc>// Renders "{x1:{f1:1}}"</jc>
String json = JsonSerializer.<jsf>DEFAULT</jsf>.serialize(<jk>new</jk> MyClass());
</p>
<p>
The {@link org.apache.juneau.annotation.BeanProperty#format() @BeanProperty.format()}
annotation specifies a String format for converting a bean property value to a formatted string.
</p>
<p class='bcode'>
<jc>// Serialize a float as a string with 2 decimal places.</jc>
<ja>@BeanProperty</ja>(format=<js>"$%.2f"</js>)
<jk>public float</jk> <jf>price</jf>;
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.BeanConstructorAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.10 - @BeanConstructor Annotation</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.BeanConstructor @BeanConstructor} annotation is used to
map constructor arguments to property names on bean with read-only properties.
<br>Since method parameter names are lost during compilation, this annotation essentially redefines
them so that they are available at runtime.
</p>
<p>
The definition of a read-only bean is a bean with properties with only getters, like shown below:
</p>
<p class='bcode'>
<jc>// Our read-only bean.</jc>
<jk>public class</jk> Person {
<jk>private final</jk> String <jf>name</jf>;
<jk>private final int</jk> <jf>age</jf>;
<ja>@BeanConstructor</ja>(properties=<js>"name,age"</js>})
<jk>public</jk> Person(String name, <jk>int</jk> age) {
<jk>this</jk>.<jf>name</jf> = name;
<jk>this</jk>.<jf>age</jf> = age;
}
<jc>// Read only properties.</jc>
<jc>// Getters, but no setters.</jc>
<jk>public</jk> String getName() {
<jk>return</jk> <jf>name</jf>;
}
<jk>public int</jk> getAge() {
<jk>return</jk> <jf>age</jf>;
}
}
</p>
<p class='bcode'>
<jc>// Parsing into a read-only bean.</jc>
String json = <js>"{name:'John Smith',age:45}"</js>;
Person p = JsonParser.<jsf>DEFAULT</jsf>.parse(json);
String name = p.getName(); <jc>// "John Smith"</jc>
<jk>int</jk> age = p.getAge(); <jc>// 45</jc>
</p>
<p>
Beans can also be defined with a combination of read-only and read-write properties.
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.BeanIgnoreAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.11 - @BeanIgnore Annotation</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.BeanIgnore @BeanIgnore} annotation is used to
ignore classes, fields, and methods from being interpreted as beans or bean components.
</p>
<p>
When applied to classes, objects will be converted to strings even though they look like beans.
</p>
<p class='bcode'>
<jc>// Not really a bean! Use toString() instead!</jc>
<ja>@BeanIgnore</ja>
<jk>public class</jk> MyBean {...}
</p>
<p>
When applied to fields and getters/setters, they will be ignored as bean properties.
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<jc>// Not a bean property!</jc>
<ja>@BeanIgnore</ja>
<jk>public</jk> String <jf>foo</jf>;
<jc>// Not a bean property!</jc>
<ja>@BeanIgnore</ja>
<jk>public</jk> String getBar() {...}
}
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.NamePropertyAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.12 - @NameProperty Annotation</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.NameProperty @NameProperty} annotation is used to
identify a setter as a method for setting the name of a POJO as it's known by its parent object.
</p>
<p>
A commonly-used case is when you're parsing a JSON map containing beans where one of the bean
properties is the key used in the map.
</p>
<p class='bcode'>
<jc>// JSON</jc>
{
id1: {name: <js>'John Smith'</js>, sex:<js>'M'</js>},
id2: {name: <js>'Jane Doe'</js>, sex:<js>'F'</js>}
}
</p>
<p class='bcode'>
<jk>public class</jk> Person {
<ja>@NameProperty</ja>
<jk>public</jk> String <jf>id</jf>; <jc>// Value gets assigned from object key</jc>
<jk>public</jk> String <jf>name</jf>;
<jk>public char</jk> <jf>sex</jf>;
}
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.ParentPropertyAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.13 - @ParentProperty Annotation</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.annotation.ParentProperty @ParentProperty} annotation is used to
identify a setter as a method for adding a parent reference to a child object.
</p>
<p>
A commonly-used case is when you're parsing beans and a child bean has a reference to a parent bean.
</p>
<p class='bcode'>
<jk>public class</jk> AddressBook {
<jk>public</jk> List&lt;Person&gt; <jf>people</jf>;
}
<jk>public class</jk> Person {
<ja>@ParentProperty</ja>
<jk>public</jk> AddressBook <jf>addressBook</jf>; <jc>// A reference to the containing address book.</jc>
<jk>public</jk> String <jf>name</jf>;
<jk>public char</jk> <jf>sex</jf>;
}
</p>
<p>
Parsers will automatically set this field for you in the child beans.
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.PojoBuilders"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.14 - POJO Builders</h4>
<div class='topic'>
<p>
Juneau parsers can use builders to instantiate POJOs.
<br>This is useful in cases where you want to create beans with read-only properties.
<br>Note that while it's possible to do this using the {@link org.apache.juneau.annotation.BeanConstructor @BeanConstructor}
annotation, using builders can often be cleaner.
</p>
<p>
A typical builder usage is shown below:
</p>
<p class='bcode'>
MyBean b = MyBean.<jsm>create</jsm>().foo(<js>"foo"</js>).bar(123).build();
</p>
<p>
The code for such a builder is shown below:
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<jc>// Read-only properties.</jc>
<jk>public final</jk> String <jf>foo</jf>;
<jk>public final int</jk> <jf>bar</jf>;
<jc>// Private constructor.</jc>
<jk>private</jk> MyBean(MyBeanBuilder b) {
<jk>this</jk>.<jf>foo</jf> = b.foo;
<jk>this</jk>.<jf>bar</jf> = b.bar;
}
<jc>// Static method that creates a builder.</jc>
<jk>public static</jk> MyBeanBuilder <jsm>create</jsm>() {
<jk>return new</jk> MyBeanBuilder();
}
<jc>// Builder class.</jc>
<jk>public static class</jk> MyBeanBuilder {
<jk>private</jk> String <jf>foo</jf>;
<jk>private int</jk> <jf>bar</jf>;
<jc>// Method that creates the bean.</jc>
<jk>public</jk> MyBean build() {
<jk>return new</jk> MyBean(<jk>this</jk>);
}
<jc>// Bean property setters.</jc>
<ja>@BeanProperty</ja>
<jk>public</jk> MyBeanBuilder foo(String foo) {
<jk>this</jk>.<jf>foo</jf> = foo;
<jk>return this</jk>;
}
<ja>@BeanProperty</ja>
<jk>public</jk> MyBeanBuilder bar(<jk>int</jk> bar) {
<jk>this</jk>.<jf>bar</jf> = bar;
<jk>return this</jk>;
}
}
}
</p>
<p>
The POJO class can be any type including beans.
<br>Builders MUST be beans with one or more writable properties.
<br>The bean properties themselves do not need to be readable (i.e. getters are optional).
</p>
<p>
Builders require two parts:
</p>
<ol>
<li>A way to detect and instantiate a builder using reflection.
<li>A way to instantiate a POJO from a builder.
</ol>
<p>
The first can be accomplished through any of the following:
</p>
<ul class='spaced-list'>
<li>A static <code>create()</code> method on the POJO class that returns a builder instance.
<p class='bcode'>
<jk>public static</jk> MyBuilder <jsm>create</jsm>() {...}
</p>
<li>A public constructor on the POJO class that takes in a single parameter that implements the {@link org.apache.juneau.transform.Builder} interface.
<br>The builder class must have a public no-arg constructor.
<p class='bcode'>
<jk>public</jk> MyPojo(MyBuilder b) {...}
</p>
<li>A {@link org.apache.juneau.annotation.Builder @Builder} annotation on the POJO class.
<br>The builder class must have a public no-arg constructor.
<p class='bcode'>
<ja>@Builder</ja>(MyBuilder.<jk>class</jk>)
<jk>public class</jk> MyPojo {...}
</p>
</ul>
<p>
The second can be accomplished through any of the following:
</p>
<ul class='spaced-list'>
<li>The existence of a <code>build()</code> method on the builder class.
<p class='bcode'>
<jk>public</jk> MyPojo build() {...}
</p>
<li>The existence of a public constructor on the POJO class that takes in the builder instance.
<p class='bcode'>
<jk>public</jk> MyPojo(MyBuilder b) {...}
</p>
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.annotation.Builder}
<li class='jic'>{@link org.apache.juneau.transform.Builder}
</ul>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.URIs"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.15 - URIs</h4>
<div class='topic'>
<p>
Juneau serializers have sophisticated support for transforming relative URIs to absolute form.
</p>
<p>
The following example shows a bean containing URIs of various forms and how they end up serialized.
</p>
<p class='bcode'>
<jc>// Our bean with properties containing various kinds of URIs.</jc>
<jk>public class</jk> TestURIs {
<jk>public</jk> URI
<jf>f1a</jf> = URI.<jsm>create</jsm>(<js>"http://www.apache.org/f1a"</js>),
<jf>f1b</jf> = URI.<jsm>create</jsm>(<js>"/f1b"</js>),
<jf>f1c</jf> = URI.<jsm>create</jsm>(<js>"/f1c/x/y"</js>),
<jf>f1d</jf> = URI.<jsm>create</jsm>(<js>"f1d"</js>),
<jf>f1e</jf> = URI.<jsm>create</jsm>(<js>"f1e/x/y"</js>),
<jf>f1f</jf> = URI.<jsm>create</jsm>(<js>""</js>),
<jf>f2a</jf> = URI.<jsm>create</jsm>(<js>"context:/f2a/x"</js>),
<jf>f2b</jf> = URI.<jsm>create</jsm>(<js>"context:/f2b"</js>),
<jf>f2c</jf> = URI.<jsm>create</jsm>(<js>"context:/"</js>),
<jf>f2d</jf> = URI.<jsm>create</jsm>(<js>"context:/.."</js>),
<jf>f3a</jf> = URI.<jsm>create</jsm>(<js>"servlet:/f3a/x"</js>),
<jf>f3b</jf> = URI.<jsm>create</jsm>(<js>"servlet:/f3b"</js>),
<jf>f3c</jf> = URI.<jsm>create</jsm>(<js>"servlet:/"</js>),
<jf>f3d</jf> = URI.<jsm>create</jsm>(<js>"servlet:/.."</js>),
<jf>f4a</jf> = URI.<jsm>create</jsm>(<js>"request:/f4a/x"</js>),
<jf>f4b</jf> = URI.<jsm>create</jsm>(<js>"request:/f4b"</js>),
<jf>f4c</jf> = URI.<jsm>create</jsm>(<js>"request:/"</js>),
<jf>f4d</jf> = URI.<jsm>create</jsm>(<js>"request:/.."</js>),
<jf>f5 </jf> = <jk>null</jk>;
}
<jc>// Create a serializer.</jc>
WriterSerializer s = JsonSerializer
<jsm>create</jsm>()
.simple()
.uriContext(<js>"{authority:'http://foo.com:123',contextRoot:'/myContext',servletPath:'/myServlet',pathInfo:'/myPath'}"</js>)
.uriResolution(<jsf>ABSOLUTE</jsf>)
.uriRelativity(<jsf>RESOURCE</jsf>)
.build();
<jc>// Produces:</jc>
<jc>// {</jc>
<jc>// f1a:'http://www.apache.org/f1a',</jc>
<jc>// f1b:'http://foo.com:123/f1b',</jc>
<jc>// f1c:'http://foo.com:123/f1c/x/y',</jc>
<jc>// f1d:'http://foo.com:123/myContext/myServlet/f1d',</jc>
<jc>// f1e:'http://foo.com:123/myContext/myServlet/f1e/x/y',</jc>
<jc>// f1f:'http://foo.com:123/myContext/myServlet',</jc>
<jc>// f2a:'http://foo.com:123/myContext/f2a/x',</jc>
<jc>// f2b:'http://foo.com:123/myContext/f2b',</jc>
<jc>// f2c:'http://foo.com:123/myContext',</jc>
<jc>// f2d:'http://foo.com:123'</jc>
<jc>// f3a:'http://foo.com:123/myContext/myServlet/f3a/x',</jc>
<jc>// f3b:'http://foo.com:123/myContext/myServlet/f3b',</jc>
<jc>// f3c:'http://foo.com:123/myContext/myServlet',</jc>
<jc>// f3d:'http://foo.com:123/myContext',</jc>
<jc>// f4a:'http://foo.com:123/myContext/myServlet/myPath/f4a/x',</jc>
<jc>// f4b:'http://foo.com:123/myContext/myServlet/myPath/f4b',</jc>
<jc>// f4c:'http://foo.com:123/myContext/myServlet/myPath',</jc>
<jc>// f4d:'http://foo.com:123/myContext/myServlet',</jc>
<jc>// }</jc>
String json = s.serialize(<jk>new</jk> TestURIs());
</p>
<p>
URI resolution is controlled by the following settings:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.serializer.Serializer#SERIALIZER_uriContext}
<br>Setting that defines the URI contextual information used to resolve relative URIs.
<li class='jf'>{@link org.apache.juneau.serializer.Serializer#SERIALIZER_uriRelativity}
<br>Setting that defines how relative URIs should be interpreted.
<br>Possible values:
<ul>
<li class='jf'>{@link org.apache.juneau.UriRelativity#RESOURCE}
<br>Relative URIs should be considered relative to the servlet URI.
<br>(e.g. <js>"http://host:port/context-root/servlet-path"</js>).
<li class='jf'>{@link org.apache.juneau.UriRelativity#PATH_INFO}
<br>Relative URIs should be considered relative to the request URI.
<br>(e.g. <js>"http://host:port/context-root/servlet-path/path-info"</js>).
</ul>
<li class='jf'>{@link org.apache.juneau.serializer.Serializer#SERIALIZER_uriResolution}
<br>Setting that defines the final format of serialized URIs.
<br>Possible values:
<ul>
<li class='jf'>{@link org.apache.juneau.UriResolution#ABSOLUTE}
<br>Resolve to an absolute URL.
<br>(e.g. <js>"http://host:port/context-root/servlet-path/path-info"</js>).
<li class='jf'>{@link org.apache.juneau.UriResolution#ROOT_RELATIVE}
<br>Resolve to a root-relative URL.
<br>(e.g. <js>"/context-root/servlet-path/path-info"</js>).
<li class='jf'>{@link org.apache.juneau.UriResolution#NONE}
<br>Don't do any URL resolution.
</ul>
</ul>
<p>
Juneau automatically interprets any {@link java.net.URL} and {@link java.net.URI} objects as URIs and will
resolve them accordingly.
<br>The {@link org.apache.juneau.annotation.URI @URI} annotation can be used to extend that to other bean
properties and class types so that they also get interpreted as URIs.
<br>For example:
</p>
<p class='bcode'>
<jc>// Applied to a class whose toString() method returns a URI.</jc>
<ja>@URI</ja>
<jk>public class</jk> MyURI {
<ja>@Override</ja> <jc>/* Object */</jc>
<jk>public</jk> String toString() {
<jk>return</jk> <js>"http://localhost:9080/foo/bar"</js>;
}
}
<jc>// Applied to bean properties</jc>
<jk>public class</jk> MyBean {
<ja>@URI</ja>
<jk>public</jk> String <jf>beanUri</jf>;
<ja>@URI</ja>
<jk>public</jk> String getParentUri() {
...
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.BeanFilters"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.16 - BeanFilter Class</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.transform.BeanFilter} class is the programmatic equivalent to the
{@link org.apache.juneau.annotation.Bean @Bean} annotation.
</p>
<p>
In practice, it's usually simpler to use the {@link org.apache.juneau.annotation.Bean @Bean} and
{@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotations on your bean classes.
<br>However, bean filters make it possible to accomplish the same when you can't add annotations
to existing code.
</p>
<p>
Bean filters are defined through {@link org.apache.juneau.transform.BeanFilterBuilder BeanFilterBuilders}.
</p>
<p>
In the previous examples, we defined this bean annotation:
</p>
<p class='bcode'>
<ja>@Bean</ja>(properties=<js>"street,city,state"</js>)
<jk>public class</jk> Address { ... }
</p>
<p>
The programmatic equivalent would be:
</p>
<p class='bcode'>
<jk>public class</jk> AddressFilter <jk>extends</jk> BeanFilterBuilder&lt;Address&gt; {
<jc>// Must provide a no-arg constructor!</jc>
<jk>public</jk> AddressFilter() {
includeProperties(<js>"street,city,state"</js>); <jc>// The properties we want exposed.</jc>
}
}
</p>
<p>
Bean filters are added to serializers and parsers using the following:
</p>
<ul>
<li class='jf'>{@link org.apache.juneau.BeanContext#BEAN_beanFilters}
<li class='jm'>{@link org.apache.juneau.BeanContextBuilder#beanFilters(Object...)}
</ul>
<p>
For example:
</p>
<p class='bcode'>
<jc>// Create a new JSON serializer and associate a bean filter with it.</jc>
WriterSerializer s = JsonSerializer
.<jsm>create</jsm>()
.beanFilters(AddressFilter.<jk>class</jk>)
.build();
</p>
<p>
Note that if you use the annotation, you do NOT need to set anything on the serializers/parsers.
<br>The annotations will be detected and bean filters will automatically be created for them.
</p>
<p>
The {@link org.apache.juneau.BeanContextBuilder#beanFilters(Object...)} method also allows you to pass in interfaces.
<br>Any class that's not a subclass of {@link org.apache.juneau.transform.BeanFilterBuilder} get interpreted
as bean interface classes.
<br>These cause bean implementations of those interfaces to only expose the properties defined on the
interface.
</p>
<p class='bcode'>
<jc>// An interface with the 3 properties we want serialized.</jc>
<jk>public interface</jk> AddressInterface {
<jk>public</jk> String getStreet();
<jk>public</jk> String getCity();
<jk>public</jk> String getState();
}
<jc>// Our bean implementation.</jc>
<jk>public class</jk> Address <jk>implements</jk> AddressInterface {
<jk>public</jk> String getStreet() {...};
<jk>public</jk> String getCity() {...};
<jk>public</jk> String getState() {...};
<jk>public</jk> String getCountry() {...};
}
<jc>// Create a new JSON serializer that only exposes street,city,state on Address bean.</jc>
<jc>// The 'country' field will be ignored.</jc>
WriterSerializer s = JsonSerializer
.<jsm>create</jsm>()
.beanFilters(AddressInterface.<jk>class</jk>)
.build();
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.InterfaceFilters"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.17 - Interface Filters</h4>
<div class='topic'>
<p>
Occasionally, you may want to limit bean properties to only those defined on a parent class or interface.
<br>This is accomplished through interface filters.
</p>
<p>
Interface filters are defined through the following:
</p>
<ul>
<li class='jf'>{@link org.apache.juneau.BeanContext#BEAN_beanFilters}
<li class='ja'>{@link org.apache.juneau.annotation.Bean#interfaceClass() @Bean.interfaceClass()}
<li class='jm'>{@link org.apache.juneau.transform.BeanFilterBuilder#interfaceClass(Class)}
</ul>
<p>
For example, let's define the following interface and implementation:
</p>
<p class='bcode'>
<jc>// Interface</jc>
<jk>public class</jk> MyInterface {
<jk>public</jk> String getFoo();
}
<jc>// Implementation</jc>
<jk>public class</jk> MyInterfaceImpl <jk>implements</jk> MyInterface {
<jk>public</jk> String getFoo() {...}
<jk>public</jk> String getBar() {...}
}
</p>
<p>
Suppose we only want to render the properties defined on our interface, not the implementation.
<br>To do so, we can define the following bean filter:
</p>
<p class='bcode'>
<jc>// Define transform that limits properties to only those defined on MyClass</jc>
<jk>public class</jk> MyInterfaceFilter <jk>extends</jk> BeanFilter&lt;MyInterface&gt; {
<jk>public</jk> MyInterfaceFilter() {
interfaceClass(MyInterface.<jk>class</jk>);
}
}
</p>
<p>
When serialized, the serialized bean will only include properties defined on the interface.
</p>
<p class='bcode'>
WriterSerializer s = JsonSerializer
.<jsm>create</jsm>()
.simple()
.beanFilters(MyInterfaceFilter.<jk>class</jk>)
.build();
MyInterface o = <jk>new</jk> MyInterfaceImpl();
<jc>// Prints "{foo:'foo'}"</jc>
<jc>// bar is ignored because it's not on the interface</jc>
String json = s.serialize(o);
</p>
<p>
The {@link org.apache.juneau.BeanContextBuilder#beanFilters(Object...)} method will automatically interpret any
non-<code>BeanFilter</code> classes passed in as meaning interface classes.
<br>So in the previous example, the <code>BeanFilter</code> class could have been avoided altogether by just
passing in <code>MyInterface.<jk>class</jk></code> to the serializer, like so:
</p>
<p class='bcode'>
WriterSerializer s = JsonSerializer
.<jsm>create</jsm>()
.beanFilters(MyInterface.<jk>class</jk>) <jc>Shortcut!</jc>
.build();
</p>
<p>
The annotation equivalent is {@link org.apache.juneau.annotation.Bean#interfaceClass() Bean#interfaceClass()}.
</p>
<p class='bcode'>
<ja>@Bean</ja>(interfaceClass=MyInterface.<jk>class</jk>)
<jk>public class</jk> MyInterfaceImpl <jk>implements</jk> MyInterface {
<jk>public</jk> String getFoo() {...}
<jk>public</jk> String getBar() {...}
}
</p>
<p>
The annotation can be used in a couple of ways.
</p>
<p>
Using the annotation on an interface will be inherited by all children.
</p>
<p class='bcode'>
<ja>@Bean</ja>(interfaceClass=MyInterface.<jk>class</jk>)
<jk>public class</jk> MyInterface {
<jk>public</jk> String getFoo();
}
</p>
<p>
The annotation can be used on parent classes as well.
<br>Child beans will only serialize properties defined on the parent class.
<p class='bcode'>
<ja>@Bean</ja>(interfaceClass=MyAbstractClass.<jk>class</jk>)
<jk>public abstract class</jk> MyAbstractClass {
<jk>public</jk> String getFoo() {...};
}
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.StopClasses"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.18 - Stop Classes</h4>
<div class='topic'>
<p>
Whereas interface filters limit properties defined on child classes, stop filters
do the opposite and limit properties defined on parent classes.
</p>
<p>
Stop classes are defined through the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.annotation.Bean#stopClass() @Bean.stopClass()}
<li class='jf'>{@link org.apache.juneau.transform.BeanFilterBuilder#stopClass(Class)}
</ul>
<p>
Stop classes are identical in purpose to the stop class specified by {@link java.beans.Introspector#getBeanInfo(Class, Class)}.
<br>Any properties in the stop class or in its base classes will be ignored during serialization.
</p>
<p>
For example, in the following class hierarchy, instances of <code>C3</code> will include property <code>p3</code>,
but not <code>p1</code> or <code>p2</code>.
</p>
<p class='bcode'>
<jk>public class</jk> C1 {
<jk>public int</jk> getP1();
}
<jk>public class</jk> C2 <jk>extends</jk> C1 {
<jk>public int</jk> getP2();
}
<ja>@Bean</ja>(stopClass=C2.<jk>class</jk>)
<jk>public class</jk> C3 <jk>extends</jk> C2 {
<jk>public int</jk> getP3();
}
<jc>// Serializes property 'p3', but NOT 'p1' or 'p2'.</jc>
String json = JsonSerializer.<jsf>DEFAULT</jsf>.serialize(<jk>new</jk> C3());
</p>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.BypassSerialization"></a>
<h4 class='topic' onclick='toggle(this)'>2.7.19 - Bypass Serialization using Readers and InputStreams</h4>
<div class='topic'>
<p>
Juneau serializers treat instances of <code>Readers</code> and <code>InputStreams</code> special by
simply serializing their contents directly to the output stream or writer.
<br>This allows you to embed fully customized serializer output.
</p>
<p class='bcode'>
<jk>public class</jk> MyBean {
<jc>// A bean property that produces raw JSON.</jc>
<jk>public</jk> Reader f1 = <jk>new</jk> StringReader(<js>"{'foo':'bar'}"</js>);
}
<jc>// Produces "{f1:{'foo':'bar'}}"</jc>
String json = JsonSerializer.<jsf>DEFAULT_LAX</jsf>.toString(<jk>new</jk> MyBean());
</p>
<p>
Note that if you're serializing Readers and InputStreams, it's up to you to make sure you're producing
valid output (in this case JSON).
</p>
<p>
A more typical scenario where this is useful is by using swaps to convert POJOs to Readers whose
contents are determined via the {@link org.apache.juneau.BeanSession#getMediaType()} method.
<br>In the following example, we're customizing the JSON output for a particular bean type, but leaving
all other renditions as-is:
</p>
<p class='bcode'>
<ja>@Swap</ja>(MyBeanSwapSometimes.<jk>class</jk>)
<jk>public class</jk> MyBean {...}
<jc>// A swap that produces specialized output for JSON, but default serialization for</jc>
<jc>// all other media types.</jc>
<jk>public class</jk> MyBeanSwapSometimes <jk>extends</jk> PojoSwap&lt;MyBean,Object&gt; {
<jk>public</jk> Object swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
MediaType mt = session.getMediaType();
<jk>if</jk> (mt.hasSubType(<js>"json"</js>))
<jk>return new</jk> StringReader(<js>"{myPojo:'foobar'}"</js>); <jc>// Custom JSON output</jc>
<jk>return</jk> o; <jc>// Otherwise serialize it as a normal bean</jc>
}
}
</p>
<ul class='doctree'>
<li class='info'>
Due to the nature of the RDF serializers, Readers and InputStreams are serialized as literals,
not as RDF text.
This is due to the fact that the RDF serializers use a DOM for serialization, so we don't have
access to the underlying stream.
</ul>
</div>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.BeanDictionaries"></a>
<h3 class='topic' onclick='toggle(this)'>2.8 - Bean Names and Dictionaries</h3>
<div class='topic'>
<p>
While parsing into beans, Juneau attempts to determine the class types of bean properties through
reflection on the bean property getter or setter.
<br>Often this is insufficient if the property type is an interface or abstract class that cannot be
instantiated.
<br>This is where bean names and dictionaries come into play.
</p>
<p>
Bean names and dictionaries are used for identifying class types when they cannot be inferred through
reflection.
</p>
<p>
Bean classes are given names through the {@link org.apache.juneau.annotation.Bean#typeName() @Bean.typeName()}
annotation.
<br>These names are then added to the serialized output as virtual <js>"_type"</js> properties (or element
names in XML).
</p>
<p>
On the parsing side, these type names are resolved to classes through the use of bean dictionaries.
</p>
<p>
For example, if a bean property is of type <code>Object</code>, then the serializer will add
<js>"_type"</js> attributes so that the class can be determined during parsing.
</p>
<p class='bcode'>
<ja>@Bean</ja>(typeName=<js>"foo"</js>)
<jk>public class</jk> Foo {
<jc>// A bean property where the object types cannot be inferred since it's an Object[].</jc>
<ja>@BeanProperty</ja>(beanDictionary={Bar.<jk>class</jk>,Baz.<jk>class</jk>})
<jk>public</jk> Object[] x = <jk>new</jk> Object[]{<jk>new</jk> Bar(), <jk>new</jk> Baz()};
}
<ja>@Bean</ja>(typeName=<js>"bar"</js>)
<jk>public class</jk> Bar {}
<ja>@Bean</ja>(typeName=<js>"baz"</js>)
<jk>public class</jk> Baz {}
</p>
<p>
When serialized as JSON, <js>"_type"</js> attributes would be added when needed to infer the type during
parsing:
</p>
<p class='bcode'>
{
x: [
{_type:<js>'bar'</js>},
{_type:<js>'baz'</js>}
]
}
</p>
<p>
Type names can be represented slightly differently in different languages.
<br>For example, the dictionary name is used as element names when serialized to XML.
<br>This allows the <code>typeName</code> annotation to be used as a shortcut for defining element names for
beans.
</p>
<p>
When serialized as XML, the bean is rendered as:
</p>
<p class='bcode'>
<xt>&lt;foo&gt;</xt>
<xt>&lt;x&gt;</xt>
<xt>&lt;bar/&gt;</xt>
<xt>&lt;baz/&gt;</xt>
<xt>&lt;/x&gt;</xt>
<xt>&lt;/foo&gt;</xt>
</p>
<p>
Bean dictionaries are registered through the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.annotation.BeanProperty#beanDictionary() @BeanProperty.beanDictionary()}
- On individual bean properties through the annotation.
<li class='ja'>{@link org.apache.juneau.annotation.Bean#beanDictionary() @Bean.beanDictionary()}
- On all properties on a bean and all subclasses.
<li class='jf'>{@link org.apache.juneau.BeanContext#BEAN_beanDictionary}
- Configuration property on serializers and parsers.
<li class='jm'>{@link org.apache.juneau.BeanContextBuilder#beanDictionary(Object...)}
- Builder method on serializers and parsers.
</ul>
<p>
The bean dictionary setting can consist of any of the following types:
</p>
<ul>
<li>Any bean class that specifies a value for {@link org.apache.juneau.annotation.Bean#typeName() @Bean.typeName()}.
<li>Any subclass of {@link org.apache.juneau.BeanDictionaryList} containing a collection of bean classes with type name annotations.
<li>Any subclass of {@link org.apache.juneau.BeanDictionaryMap} containing a mapping of type names to classes without type name annotations.
<li>Any array or collection of the objects above.
</ul>
<p class='bcode'>
<jc>// Create a parser and tell it which classes to try to resolve.</jc>
ReaderParser p = JsonParser
.<jsm>create</jsm>()
.beanDictionary(Foo.<jk>class</jk>, Bar.<jk>class</jk>)
.build();
<jc>// Same, but use property.</jc>
ReaderParser p = JsonParser
.<jsm>create</jsm>()
.addTo(<jsf>BEAN_beanDictionary</jsf>, Foo.<jk>class</jk>)
.addTo(<jsf>BEAN_beanDictionary</jsf>, Bar.<jk>class</jk>)
.build();
<jc>// Use the predefined HTML5 bean dictionary which is a BeanDictionaryList.</jc>
ReaderParser p = HtmlParser
.<jsm>create</jsm>()
.beanDictionary(HtmlBeanDictionary.<jk>class</jk>)
.build();
</p>
<p>
The <js>"_type"</js> property name can be overridden through the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.annotation.Bean#typePropertyName() @Bean.typePropertyName()}
- On individual beans through the annotation.
<li class='jf'>{@link org.apache.juneau.BeanContext#BEAN_beanTypePropertyName}
- Configuration property on serializers and parsers.
<li class='jm'>{@link org.apache.juneau.BeanContextBuilder#beanTypePropertyName(String)}
- Builder method on serializers and parsers.
</ul>
<p>
When using the annotation, you'll typically want to define it on an interface class so that it can
be inherited by all subclasses.
</p>
<p class='bcode'>
<ja>@Bean</ja>(typePropertyName=<js>"mytype"</js>, beanDictionary={MyClass1.<jk>class</jk>,MyClass2.<jk>class</jk>})
<jk>public interface</jk> MyInterface {...}
<ja>@Bean</ja>(typeName=<js>"C1"</js>)
<jk>public class</jk> MyClass1 <jk>implements</jk> MyInterface {...}
<ja>@Bean</ja>(typeName=<js>"C2"</js>)
<jk>public class</jk> MyClass2 <jk>implements</jk> MyInterface {...}
MyInterface[] x = <jk>new</jk> MyInterface[]{ <jk>new</jk> MyClass1(), <jk>new</jk> MyClass2() };
<jc>// Produces "[{mytype:'C1',...},{mytype:'C2',...}]"</jc>
String json = JsonSerializer.<jsf>DEFAULT_LAX</jsf>.serialize(x);
</p>
<ul class='doctree'>
<li class='info'>
Type names do not need to be universally unique.
However, they must be unique within a dictionary.
<li class='info'>
The following reserved words cannot be used as type names:
<code>object, array, number, boolean, null</code>.
<li class='info'>
Serialized type names are DISABLED by default.
They must be enabled on the serializer using the
{@link org.apache.juneau.serializer.Serializer#SERIALIZER_addBeanTypeProperties}
configuration property.
</ul>
<!-- =================================================================================================== -->
<a id="juneau-marshall.BeanSubTypes"></a>
<h4 class='topic' onclick='toggle(this)'>2.8.1 - Bean Subtypes</h4>
<div class='topic'>
<p>
In addition to the bean type name support described above, simplified support is provided
for bean subtypes.
</p>
<p>
Bean subtypes are similar in concept to bean type names, except for the following differences:
</p>
<ul>
<li>You specify the list of possible subclasses through an annotation on a parent bean class.
<li>You do not need to register the subtype classes on the bean dictionary of the parser.
</ul>
<p>
In the following example, the abstract class has two subclasses:
</p>
<p class='bcode'>
<jc>// Abstract superclass</jc>
<ja>@Bean</ja>(
beanDictionary={A1.<jk>class</jk>, A2.<jk>class</jk>}
)
<jk>public abstract class</jk> A {
<jk>public</jk> String <jf>f0</jf> = <js>"f0"</js>;
}
<jc>// Subclass 1</jc>
<ja>@Bean</ja>(typeName=<js>"A1"</js>)
<jk>public class</jk> A1 <jk>extends</jk> A {
<jk>public</jk> String <jf>f1</jf>;
}
<jc>// Subclass 2</jc>
<ja>@Bean</ja>(typeName=<js>"A2"</js>)
<jk>public class</jk> A2 <jk>extends</jk> A {
<jk>public</jk> String <jf>f2</jf>;
}
</p>
<p>
When serialized, the subtype is serialized as a virtual <js>"_type"</js> property:
</p>
<p class='bcode'>
JsonSerializer s = JsonSerializer.<jsf>DEFAULT_LAX</jsf>;
A1 a1 = <jk>new</jk> A1();
a1.<jf>f1</jf> = <js>"f1"</js>;
String r = s.serialize(a1);
<jsm>assertEquals</jsm>(<js>"{_type:'A1',f1:'f1',f0:'f0'}"</js>, r);
</p>
<p>
The following shows what happens when parsing back into the original object.
</p>
<p class='bcode'>
JsonParser p = JsonParser.<jsf>DEFAULT</jsf>;
A a = p.parse(r, A.<jk>class</jk>);
<jsm>assertTrue</jsm>(a <jk>instanceof</jk> A1);
</p>
</div>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.VirtualBeans"></a>
<h3 class='topic' onclick='toggle(this)'>2.9 - Virtual Beans</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.BeanContext#BEAN_useInterfaceProxies} setting (enabled by default) allows
the Juneau parsers to parse content into virtual beans (bean interfaces without implementation classes).
</p>
<p>
For example, the following code creates an instance of the specified unimplemented interface:
</p>
<p class='bcode'>
<jc>// Our unimplemented interface</jc>
<jk>public interface</jk> Address {
String getStreet();
<jk>void</jk> setStreet(String x);
String getCity();
<jk>void</jk> setCity(String x);
StateEnum getState();
<jk>void</jk> setState(StateEnum x);
<jk>int</jk> getZip();
<jk>void</jk> setZip(<jk>int</jk> zip);
}
<jc>// Our code</jc>
Address address = JsonParser.<jsf>DEFAULT</jsf>.parse(
<js>"{street:'123 Main St', city:'Anywhere', state:'PR', zip:12345}"</js>,
Address.<jk>class</jk>
);
<jk>int</jk> zip = address.getZip();
address.setState(StateEnum.<jsf>NY</jsf>);
</p>
<p>
Getter and setter values can be any <a class='doclink' href='#juneau-marshall.PojoCategories'>parsable</a> values, even other virtual beans.
</p>
<p>
Under-the-covers, a virtual bean is simply a proxy interface on top of an existing <code>BeanMap</code>
instance. From a programmatic point-of-view, they're indistinguishable from real beans, and can be
manipulated and serialized like any other bean.
</p>
<p>
Virtual beans can also be created programmatically using the <code>BeanContext</code> class:
</p>
<p class='bcode'>
Address address = BeanContext.<jsf>DEFAULT</jsf>.createSession().newBean(Address.<jk>class</jk>);
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.ReadingContinuousStreams"></a>
<h3 class='topic' onclick='toggle(this)'>2.10 - Reading Continuous Streams</h3>
<div class='topic'>
<p>
The following parsers can be configured to read continous streams of objects from the same input stream:
</p>
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonParser}
<li class='jc'>{@link org.apache.juneau.uon.UonParser}
<li class='jc'>{@link org.apache.juneau.msgpack.MsgPackParser}
</ul>
<p>
The {@link org.apache.juneau.json.JsonParser} and {@link org.apache.juneau.uon.UonParser}
classes can read continous streams by using the {@link org.apache.juneau.parser.Parser#PARSER_unbuffered}
setting.
<br>This prevents the parsers from using an internal buffer that would read past the end of the currently
parsed POJO.
</p>
<h5 class='figure'>Examples:</h5>
<p class='bcode'>
<jc>// If you're calling parse on the same input multiple times, use a session instead of the parser directly.</jc>
ReaderParserSession p = JsonParser.<jsm>create</jsm>().unbuffered().build().createSession();
Object x;
Reader r;
r = new StringReader(<js>"{foo:'bar'}{baz:'qux'}"</js>);
x = p.parse(r, ObjectMap.<jk>class</jk>); <jc>// {foo:'bar'}</jc>
x = p.parse(r, ObjectMap.<jk>class</jk>); <jc>// {baz:'qux'}</jc>
r = reader(<js>"[123][456]"</js>);
x = p.parse(r, <jk>int</jk>[].<jk>class</jk>); <jc>// [123]</jc>
x = p.parse(r, <jk>int</jk>[].<jk>class</jk>); <jc>// [456]</jc>
</p>
<p>
Note that this isn't perfect in all cases since you can't combine two JSON numbers into a single
reader (e.g. <code>"123" + "456" = "123456"</code>).
</p>
<p>
For obvious reasons, do not use the following properties when reading continuous streams:
</p>
<ul>
<li class='jf'>{@link org.apache.juneau.json.JsonParser#JSON_validateEnd}
<li class='jf'>{@link org.apache.juneau.uon.UonParser#UON_validateEnd}
<li class='jf'>{@link org.apache.juneau.parser.Parser#PARSER_autoCloseStreams}
</ul>
<p>
The {@link org.apache.juneau.msgpack.MsgPackParser} class doesn't use any internal buffering to begin with, so it can be used with
continuous streams without any special properties.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.JacksonComparison"></a>
<h3 class='topic' onclick='toggle(this)'>2.11 - Comparison with Jackson</h3>
<div class='topic'>
<p>
Juneau was developed independently from Jackson, but shares many of the same features and capabilities.
Whereas Jackson was created to work primarily with JSON, Juneau was created to work for multiple languages.
Therefore, the terminology and annotations in Juneau are similar, but language-agnostic.
</p>
<p>
The following charts describe equivalent features between the two libraries:
</p>
<h5 class='topic'>Annotations</h5>
<table class='styled' style='min-width:800px;width:50%'>
<tr><th>Jackson</th><th>Juneau</th></tr>
<tr>
<td>
<ja>@JsonGetter</ja>
<br><ja>@JsonSetter</ja>
</td>
<td>
{@link org.apache.juneau.annotation.BeanProperty @BeanProperty}
</td>
</tr>
<tr>
<td>
<ja>@JsonAnyGetter</ja>
<br><ja>@JsonAnySetter</ja>
</td>
<td>
{@link org.apache.juneau.annotation.BeanProperty#name() @BeanProperty(name="*")}
</td>
</tr>
<tr>
<td>
<ja>@JsonIgnore</ja>
<br><ja>@JsonIgnoreType</ja>
</td>
<td>
{@link org.apache.juneau.annotation.BeanIgnore @BeanIgnore}
</td>
</tr>
<tr>
<td><code><ja>@JsonIgnoreProperties</ja>({...})</code></td>
<td>
{@link org.apache.juneau.annotation.Bean#excludeProperties @Bean(excludeProperties="...")}
</td>
</tr>
<tr>
<td><code><ja>@JsonAutoDetect</ja>(fieldVisibility=...)</code></td>
<td>
No equivalent annotation, but can be controlled via:
<br>{@link org.apache.juneau.BeanContext#BEAN_beanFieldVisibility}
<br>{@link org.apache.juneau.BeanContext#BEAN_beanMethodVisibility}
<br>Future annotation support planned.
</td>
</tr>
<tr>
<td>
<ja>@JsonCreator</ja>
<br><ja>@JsonProperty</ja>
</td>
<td>
{@link org.apache.juneau.annotation.BeanConstructor @BeanConstructor}
</td>
</tr>
<tr>
<td><ja>@JacksonInject</ja></td>
<td>
No equivalent.
<br>Future support planned.
</td>
</tr>
<tr>
<td>
<ja>@JsonSerialize</ja>
<br><ja>@JsonDeserialize</ja>
</td>
<td>
Juneau uses swaps to convert non-serializable object to serializable forms:
<br>{@link org.apache.juneau.annotation.Swap @Swap}
</td>
</tr>
<tr>
<td><ja>@JsonInclude</ja></td>
<td>
No equivalent annotation, but can be controlled via various settings:
<br>{@link org.apache.juneau.BeanContext}
<br>{@link org.apache.juneau.serializer.Serializer}
<br>Future annotation support planned.
</td>
</tr>
<tr>
<td><ja>@JsonPropertyOrder</ja></td>
<td>
{@link org.apache.juneau.annotation.Bean#properties @Bean(properties="...")}
<br>{@link org.apache.juneau.annotation.Bean#sort @Bean(sort=x)}
</td>
</tr>
<tr>
<td>
<ja>@JsonValue</ja>
<br><ja>@JsonRawValue</ja>
</td>
<td>
Can be replicated using swaps with <code>Reader</code> swapped values.
</td>
</tr>
</table>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.PojoCategories"></a>
<h3 class='topic' onclick='toggle(this)'>2.12 - POJO Categories</h3>
<div class='topic'>
<p>
The following chart shows POJOs categorized into groups and whether they can be serialized or parsed:
</p>
<table class='styled' style='border-collapse: collapse;min-width:800px;width:50%'>
<tr><th>Group</th><th>Description</th><th>Examples</th><th>Can<br>serialize?</th><th>Can<br>parse?</th></tr>
<tr class='dark bb' style='background-color:lightyellow;'>
<td style='text-align:center'>1</td>
<td><b>Java primitives and primitive objects</b></td>
<td>
<ul class='normal'>
<li>{@code String}
<li>{@code Integer}
<li>{@code Float}
<li>{@code Boolean}
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
</tr>
<tr class='dark bb' style='background-color:lightyellow'>
<td style='text-align:center'>2</td>
<td><b>Java Collections Framework objects and Java arrays</b></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>2a</td>
<td>
<b>With standard keys/values</b>
<br>Map keys are group [1, 4a, 6a] objects.
<br>Map, Collection, and array values are group [1, 2, 3ac, 4a, 6a] objects.
</td>
<td>
<ul class='normal'>
<li><code>HashSet&lt;String,Integer&gt;</code>
<li><code>TreeMap&lt;Integer,Bean&gt;</code>
<li><code>List&lt;<jk>int</jk>[][]&gt;</code>
<li><code>Bean[]</code>
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>2b</td>
<td>
<b>With non-standard keys/values</b>
<br>Map keys are group [2, 3, 4b, 5, 6b, 7] objects.
<br>Map, Collection, and array values are group [3b, 4b, 5, 6b, 7] objects.
</td>
<td>
<ul class='normal'>
<li><code>HashSet&lt;Bean,Integer&gt;</code>
<li><code>TreeMap&lt;Integer,Reader&gt;</code>
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
<tr class='dark bb' style='background-color:lightyellow'>
<td style='text-align:center'>3</td>
<td><b>Java Beans</b></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>3a</td>
<td>
<b>With standard properties</b>
<br>These are beans that have one or more properties defined by public getter
or public fields.
<br>Properties can also be defined as final read-only fields and passed in as constructor args.
<br>Property values are group [1, 2, 3ac, 4a, 6a] objects.
</td>
<td>&nbsp;</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>3b</td>
<td>
<b>With non-standard properties or not true beans</b>
<br>These include true beans that have one or more properties defined by getter
and setter methods or properties, but property types include group [3b, 4b, 5, 6b, 7] objects.
<br>This also includes classes that look like beans but aren't true beans.
For example, classes that have getters but not setters, or classes without no-arg constructors.
</td>
<td>&nbsp;</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>3c</td>
<td>
<b>Virtual beans</b>
<br>These are unimplemented bean interfaces with properties of type [1, 2, 3ac, 4a, 6a] objects.
<br>Parsers will automatically create interface proxies on top of BeanMap instances.
</td>
<td>&nbsp;</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>3d</td>
<td>
<b>Read-only beans without setters</b>
<br>The same as 3a, but without property setters or constructor args.
</td>
<td>&nbsp;</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
<tr class='dark bb' style='background-color:lightyellow'>
<td style='text-align:center'>4</td>
<td>
<b>Swapped objects</b>
<br>These are objects that are not directly serializable, but have
{@link org.apache.juneau.transform.PojoSwap PojoSwaps} associated with them.
The purpose of a POJO swap is to convert an object to another object that is easier to serialize
and parse.
For example, the {@link org.apache.juneau.transforms.DateSwap.ISO8601DT} class can be used to
serialize {@link java.util.Date} objects to ISO8601 strings, and parse them back into
{@link java.util.Date} objects.
</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>4a</td>
<td>
<b>2-way swapped to group [1, 2a, 3ac] objects</b>
<br>For example, a swap that converts a {@code Date} to a {@code String}.
</td>
<td>
<ul class='normal'>
<li><code>java.util.Date</code>
<li><code>java.util.GregorianCalendar</code>
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
</tr>
<tr class='light bb'>
<td style='text-align:center'>4b</td>
<td>
<b>1-way swapped to group [1, 2, 3] objects</b>
<br>For example, a swap that converts an {@code Iterator} to a {@code List}.
This would be one way, since you cannot reconstruct an {@code Iterator}.
</td>
<td>
<ul class='normal'>
<li><code>java.util.Iterator</code>
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
<tr class='dark bb' style='background-color:lightyellow'>
<td style='text-align:center'>5</td>
<td>
<b>Readers and InputStreams</b>
<br>Contents are serialized directly to the output stream or writer.
<br>Typically used for low-level language-specific replacement of POJOs using per-Media-Type
POJO swaps.
</td>
<td>
<ul class='normal'>
<li>{@code FileInputStream}
<li>{@code StringReader}
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
<tr class='dark bb' style='background-color:lightyellow'>
<td style='text-align:center'>6</td>
<td>
<b>Non-serializable objects with standard methods for converting to a serializable form</b><br>
</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr class='light bb' style='background-color:lightyellow'>
<td style='text-align:center'>6a</td>
<td>
Classes with a method that converts it to a serializable form:
<ul>
<li><code><jk>public</jk> X swap(BeanSession);</code> where <code>X</code> is in groups
[1, 2a, 3ac].
<li><code><jk>public</jk> String toString();</code> where the string is any meaningful data.
</ul>
And a method that converts it back into the original object:
<ul>
<li><code><jk>public static</jk> T fromString(String);</code>
<li><code><jk>public static</jk> T valueOf(String);</code>
<li><code><jk>public static</jk> T parse(String);</code>
<li><code><jk>public static</jk> T parseString(String);</code>
<li><code><jk>public static</jk> T forName(String);</code>
<li><code><jk>public static</jk> T forString(String);</code>
<li><code><jk>public</jk> T(X);</code> where <code>X</code> is in groups [1, 2a, 3ac].
<li><code><jk>public static</jk> T unswap(BeanSession,X);</code> where <code>X</code> is in
groups [1, 2a, 3ac].
</ul>
</td>
<td>
<ul class='normal'>
<li><code>java.lang.Class</code>
<li><code>java.sql.Time</code>
<li><code>java.sql.Timestamp</code>
<li><code>java.text.MessageFormat</code>
<li><code>java.text.NumberFormat</code>
<li><code>java.util.Date</code>
<li><code>java.util.UUID</code>
<li><code>java.util.logging.Level</code>
<li><code>javax.xml.bind.DatatypeConverter</code>
</ul>
</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
</tr>
<tr class='light bb' style='background-color:lightyellow'>
<td style='text-align:center'>6b</td>
<td>
Classes that only have a method to convert to a serializable form:
<ul>
<li><code><jk>public</jk> X swap(BeanSession);</code> where <code>X</code> is in groups
[1, 2, 3].
<li><code><jk>public</jk> String toString();</code> where the string is any meaningful data.
</ul>
</td>
<td>&nbsp;</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
<tr class='dark' style='background-color:lightyellow'>
<td style='text-align:center'>7</td>
<td>
<b>All other objects</b>
<br>Anything that doesn't fall into one of the groups above are simply converted to {@code Strings}
using the {@code toString()} method.
</td>
<td>&nbsp;</td>
<td style='background-color:lightgreen;text-align:center'><b>yes</b></td>
<td style='background-color:salmon;text-align:center'><b>no</b></td>
</tr>
</table>
<ul class='doctree'>
<li class='info'>
Serializers are designed to work on tree-shaped POJO models.
These are models where there are no referential loops (e.g. leaves with references to nodes, or nodes
in one branch referencing nodes in another branch).
There is a serializer setting {@code detectRecursions} to look for and handle these kinds of loops
(by setting these references to <jk>null</jk>), but it is not enabled by default since it introduces
a moderate performance penalty.
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.BestPractices"></a>
<h3 class='topic' onclick='toggle(this)'>2.13 - Best Practices</h3>
<div class='topic'>
<ol class='spaced-list'>
<li>
Reuse instances of serializers and parsers whenever possible.
<br>They are designed to be thread safe and maintain internal caches of bean metadata to increase performance.
<li>
The {@link org.apache.juneau.serializer.Serializer#SERIALIZER_detectRecursions SERIALIZER_detectRecursions}
option on the {@link org.apache.juneau.serializer.Serializer} class can cause a performance penalty of
around 20%.
Therefore, it's recommended that this option be used only when necessary.
<li>
In general, JSON serialization and parsing is about 20% faster than XML.
JSON is also more compact than XML.
MessagePack is fastest and most compact of all.
<li>
The RDF parsers are SLOW.
RDF simply isn't efficient with node traversal, so creating tree structures out of RDF models
is highly inefficient.
<li>
The {@link org.apache.juneau.parser.Parser} methods that take in {@link org.apache.juneau.ClassMeta}
parameters are slightly faster than methods that
take in {@link java.lang.Class} or {@link java.lang.Object} parameters, since the latter methods involve
hash lookups to resolve to {@link org.apache.juneau.ClassMeta} parameters.
</ol>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-marshall.AdditionalInfo"></a>
<h3 class='topic' onclick='toggle(this)'>2.14 - Additional Information</h3>
<div class='topic'>
<p>
Extensive javadocs exist for individual language support.
Refer to these docs for language-specific information.
</p>
<!-- =================================================================================================== -->
<a id="juneau-marshall.AdditionalInfo.JSON"></a>
<h4 class='topic' onclick='toggle(this)'>2.13.1 - JSON</h4>
<div class='topic'>
<h5 class='toc'>Additional Information - org.apache.juneau.json</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#Overview'>JSON support overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#OverviewExample'>Example</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#JsonSerializer'>JsonSerializer class</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#BeanAnnotations'>@Bean and @BeanProperty annotations</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#Collections'>Collections</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#JsonSchemaSupport'>JSON-Schema support</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#Recursion'> Non-tree models and recursion detection</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#SerializerConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#SerializerOtherNotes'>Other notes</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#JsonParser'>JsonParser class</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#GenericParsing'>Parsing into generic POJO models</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#ParserConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/json/package-summary.html#ParserOtherNotes'>Other notes</a></p>
</ol>
</ol>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.AdditionalInfo.XML"></a>
<h4 class='topic' onclick='toggle(this)'>2.13.2 - XML</h4>
<div class='topic'>
<h5 class='toc'>Additional Information - org.apache.juneau.xml</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#Overview'>XML support overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#OverviewExample'>XML support overview - example</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlSerializer'>XmlSerializer class</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#Methodology'>XML support methodology</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlAnnotation'>@Xml annotations</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlName'>@Bean.typeName()</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlChildName'>@Xml.childName()</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlFormat'>@Xml.format()</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#Namespaces'>Namespaces</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#AutoDetectNamespaces'>Auto-detection of namespaces</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#BeanAnnotations'>@Bean and @BeanProperty annotations</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#Collections'>Collections</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlSchemaSupport'>XML-Schema support</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#Recursion'> Non-tree models and recursion detection</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#SerializerConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#SerializerOtherNotes'>Other notes</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#XmlParser'>XmlParser class</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#GenericParsing'>Parsing into generic POJO models</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#ParserConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/xml/package-summary.html#ParserOtherNotes'>Other notes</a></p>
</ol>
</ol>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.AdditionalInfo.HTML"></a>
<h4 class='topic' onclick='toggle(this)'>2.13.3 - HTML</h4>
<div class='topic'>
<h5 class='toc'>Additional Information - org.apache.juneau.html</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/html/package-summary.html#HtmlSerializer'>HTML serialization support</a></p>
<li><p><a class='doclink' href='org/apache/juneau/html/package-summary.html#HtmlParser'>HTML parsing support</a></p>
</ol>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.AdditionalInfo.UON"></a>
<h4 class='topic' onclick='toggle(this)'>2.13.4 - UON</h4>
<div class='topic'>
<h5 class='toc'>Additional Information - org.apache.juneau.uon</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#Overview'>UON support overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#OverviewExample'>Example</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#UrlEncodingSerializer'>UrlEncodingSerializer and UonSerializer classes</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#BeanAnnotations'>@Bean and @BeanProperty annotations</a></p>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#Collections'>Collections</a></p>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#Recursion'> Non-tree models and recursion detection</a></p>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#SerializerConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#SerializerOtherNotes'>Other notes</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#UrlEncodingParser'>UrlEncodingParser and UonParser classes</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#GenericParsing'>Parsing into generic POJO models</a></p>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#ParserConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/uon/package-summary.html#ParserOtherNotes'>Other notes</a></p>
</ol>
</ol>
</div>
<!-- =================================================================================================== -->
<a id="juneau-marshall.AdditionalInfo.URLEncoding"></a>
<h4 class='topic' onclick='toggle(this)'>2.13.5 - URL-Encoding</h4>
<div class='topic'>
<h5 class='toc'>Additional Information - org.apache.juneau.urlencoding</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#Overview'>URL encoding support overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#OverviewExample'>Example</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#UrlEncodingSerializer'>UrlEncodingSerializer and UonSerializer classes</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#BeanAnnotations'>@Bean and @BeanProperty annotations</a></p>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#Collections'>Collections</a></p>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#Recursion'> Non-tree models and recursion detection</a></p>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#SerializerConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#SerializerOtherNotes'>Other notes</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#UrlEncodingParser'>UrlEncodingParser and UonParser classes</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#GenericParsing'>Parsing into generic POJO models</a></p>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#ParserConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#ParserOtherNotes'>Other notes</a></p>
</ol>
</ol>
</div>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-marshall-rdf"></a>
<h2 class='topic' onclick='toggle(this)'>3 - juneau-marshall-rdf</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-marshall-rdf<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-marshall-rdf-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.marshall.rdf_7.0.0.jar
</p>
<p>
The <code>juneau-marshall-rdf</code> library provides additional serializers and parsers for RDF.
These rely on the Apache Jena library to provide support for the following languages:
</p>
<ul>
<li>RDF/XML
<li>RDF/XML-Abbrev
<li>N-Triple
<li>Turtle
<li>N3
</ul>
<p>
The serializers and parsers work identically to those in <code>juneau-marshall</code>, but are
packaged separately so that you don't need to pull in the Jena dependency unless you need it.
</p>
<p class='bcode'>
<jc>// A simple bean</jc>
<jk>public class</jk> Person {
<jk>public</jk> String name = <js>"John Smith"</js>;
<jk>public int</jk> age = 21;
}
<jc>// Serialize a bean to JSON, XML, or HTML</jc>
Person p = <jk>new</jk> Person();
<jc>// Produces:
// &lt;rdf:RDF
// xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
// xmlns:jp="http://www.apache.org/juneaubp/"
// xmlns:j="http://www.apache.org/juneau/"&gt;
// &lt;rdf:Description&gt;
// &lt;jp:name&gt;John Smith&lt;/jp:name&gt;
// &lt;jp:age&gt;21&lt;/jp:age&gt;
// &lt;/rdf:Description&gt;
// &lt;/rdf:RDF&gt;</jc>
String rdfXml = RdfSerializer.<jsf>DEFAULT_XMLABBREV</jsf>.serialize(p);
<jc>// Produces:
// @prefix jp: &lt;http://www.apache.org/juneaubp/&gt; .
// @prefix j: &lt;http://www.apache.org/juneau/&gt; .
// [] jp:age "21" ;
// jp:name "John Smith" .</jc>
String rdfN3 = RdfSerializer.<jsf>DEFAULT_N3</jsf>.serialize(p);
<jc>// Produces:
// _:A3bf53c85X3aX157cf407e2dX3aXX2dX7ffd &lt;http://www.apache.org/juneaubp/name&gt; "John Smith" .
// _:A3bf53c85X3aX157cf407e2dX3aXX2dX7ffd &lt;http://www.apache.org/juneaubp/age&gt; "21" .</jc>
String rdfNTriple = RdfSerializer.<jsf>DEFAULT_NTRIPLE</jsf>.serialize(p);
</p>
<h5 class='toc'>Additional Information - org.apache.juneau.jena</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#RdfOverview'>RDF support overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#RdfOverviewExample'>Example</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#RdfSerializer'>RdfSerializer class</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#Namespaces'>Namespaces</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#UriProperties'>URI properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#BeanAnnotations'>@Bean and @BeanProperty annotations</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#Collections'>Collections</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#RootProperty'>Root property</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#TypedLiterals'>Typed literals</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#Recursion'>Non-tree models and recursion detection</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#SerializerConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#SerializerOtherNotes'>Other notes</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#RdfParser'>RdfParser class</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#GenericParsing'>Parsing into generic POJO models</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#ParserConfigurableProperties'>Configurable properties</a></p>
<li><p><a class='doclink' href='org/apache/juneau/jena/package-summary.html#ParserOtherNotes'>Other notes</a></p>
</ol>
</ol>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-dto"></a>
<h2 class='topic' onclick='toggle(this)'>4 - juneau-dto</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-dto<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-dto-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.dto_7.0.0.jar
</p>
<p>
The <code>juneau-dto</code> library contains several predefined POJOs for generating commonly-used document types.
This section describes support for these POJOs.
</p>
<!-- ======================================================================================================= -->
<a id="juneau-dto.HTML5"></a>
<h3 class='topic' onclick='toggle(this)'>4.1 - HTML5</h3>
<div class='topic'>
<p>
The Juneau HTML5 DTOs are simply beans with fluent-style setters that allow you to quickly construct HTML
fragments as Java objects. These object can then be serialized to HTML using one of the existing HTML
serializers, or to other languages such as JSON using the JSON serializers.
</p>
<p>
The {@link org.apache.juneau.dto.html5.HtmlBuilder} class is a utility class with predefined static methods
that allow you to easily construct DTO instances in a minimal amount of code.
</p>
<p>
The following examples show how to create HTML tables.
</p>
<table class='styled' style='width:auto'>
<tr>
<th>Java code</th>
<th>HTML</th>
</tr>
<tr>
<td class='code'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
Object mytable =
<jsm>table</jsm>(
<jsm>tr</jsm>(
<jsm>th</jsm>(<js>"c1"</js>),
<jsm>th</jsm>(<js>"c2"</js>)
),
<jsm>tr</jsm>(
<jsm>td</jsm>(<js>"v1"</js>),
<jsm>td</jsm>(<js>"v2"</js>)
)
);
String html = HtmlSerializer.<jsf>DEFAULT</jsf>.serialize(mytable);
</td>
<td class='code'><xt>
&lt;table&gt;
&lt;tr&gt;
&lt;th&gt;<xv>c1</xv>&lt;/th&gt;
&lt;th&gt;<xv>c2</xv>&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;<xv>v1</xv>&lt;/td&gt;
&lt;td&gt;<xv>v2</xv>&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
</xt></td>
</tr>
<tr>
<td class='code'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
Object mydiv =
<jsm>div</jsm>().align(<js>"center"</js>).onmouseover(<js>"alert(\"boo!\");"</js>)
.children(
<jsm>p</jsm>(<js>"Juneau supports "</js>, <jsm>b</jsm>(<jsm>i</jsm>(<js>"mixed"</js>)), <js>" content!"</js>)
);
String html = HtmlSerializer.<jsf>DEFAULT</jsf>.serialize(mydiv);
</td>
<td class='code'><xt>
&lt;div <xa>align</xa>=<xs>'center'</xs> <xa>onmouseover</xa>=<xs>'alert("boo!");'</xs>&gt;
&lt;p&gt;<xv>Juneau supports </xv>&lt;b&gt;&lt;i&gt;<xv>mixed</xv>&lt;/i&gt;&lt;/b&gt; <xv>content!</xv>&lt;/p&gt;
&lt;/table&gt;
</xt></td>
</tr>
<tr>
<td class='code'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
Object myform =
<jsm>form</jsm>().action(<js>"/submit"</js>).method(<js>"POST"</js>)
.children(
<js>"Position (1-10000): "</js>, <jsm>input</jsm>(<js>"number"</js>).name(<js>"pos"</js>).value(1), <jsm>br</jsm>(),
<js>"Limit (1-10000): "</js>, <jsm>input</jsm>(<js>"number"</js>).name(<js>"limit"</js>).value(100), <jsm>br</jsm>(),
<jsm>button</jsm>(<js>"submit"</js>, <js>"Submit"</js>),
<jsm>button</jsm>(<js>"reset"</js>, <js>"Reset"</js>)
);
String html = HtmlSerializer.<jsf>DEFAULT</jsf>.serialize(myform);
</td>
<td class='code'><xt>
&lt;form <xa>action</xa>=<xs>'/submit'</xs> <xa>method</xa>=<xs>'POST'</xs>&gt;
<xv>Position (1-10000):</xv> &lt;input <xa>name</xa>=<xs>'pos'</xs> <xa>type</xa>=<xs>'number'</xs>
<xa>value</xa>=<xs>'1'</xs>/&gt;&lt;br/&gt;
<xv>Limit (1-10000):</xv> &lt;input <xa>name</xa>=<xs>'pos'</xs> <xa>type</xa>=<xs>'number'</xs>
<xa>value</xa>=<xs>'100'</xs>/&gt;&lt;br/&gt;
&lt;button <xa>type</xa>=<xs>'submit'</xs>&gt;<xv>Submit</xv>&lt;/button&gt;
&lt;button <xa>type</xa>=<xs>'reset'</xs>&gt;<xv>Reset</xv>&lt;/button&gt;
&lt;/form&gt;
</xt></td>
</tr>
</table>
<p>
Using the HTML5 DTOs, you should be able to construct any valid HTML5 from full document bodies
to any possible fragments.
</p>
<p>
The {@link org.apache.juneau.html.HtmlParser} class can be used convert these HTML documents back
into POJOs.
</p>
<p>
Other serializers and parsers (e.g. {@link org.apache.juneau.json.JsonSerializer}) can be used to
represent these POJOs in languages other than HTML.
</p>
<h5 class='toc'>Additional Information - org.apache.juneau.dto.html5</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/dto/html5/package-summary.html#Overview'>Overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/dto/html5/package-summary.html#Serialize'>Generating HTML5</a></p>
<li><p><a class='doclink' href='org/apache/juneau/dto/html5/package-summary.html#Parse'>Parsing HTML5</a></p>
<li><p><a class='doclink' href='org/apache/juneau/dto/html5/package-summary.html#Templates'>HTML5 Templates</a></p>
</ol>
</ol>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-dto.Atom"></a>
<h3 class='topic' onclick='toggle(this)'>4.2 - Atom</h3>
<div class='topic'>
<p>
The Juneau ATOM feed DTOs are simply beans with fluent-style setters.
<br>The following code shows a feed being created programmatically using the
{@link org.apache.juneau.dto.atom.AtomBuilder} class.
</p>
<p class='bcode'>
<jk>import static</jk> org.apache.juneau.dto.atom.AtomBuilder.*;
Feed feed =
<jsm>feed</jsm>(<js>"tag:juneau.apache.org"</js>, <js>"Juneau ATOM specification"</js>, <js>"2016-01-02T03:04:05Z"</js>)
.subtitle(<jsm>text</jsm>(<js>"html"</js>).text(<js>"Describes &lt;em&gt;stuff&lt;/em&gt; about Juneau"</js>))
.links(
<jsm>link</jsm>(<js>"alternate"</js>, <js>"text/html"</js>, <js>"http://juneau.apache.org"</js>).hreflang(<js>"en"</js>),
<jsm>link</jsm>(<js>"self"</js>, <js>"application/atom+xml"</js>, <js>"http://juneau.apache.org/feed.atom"</js>)
)
.rights(<js>"Copyright (c) ..."</js>)
.generator(
<jsm>generator</jsm>(<js>"Juneau"</js>).uri(<js>"http://juneau.apache.org/"</js>).version(<js>"1.0"</js>)
)
.entries(
<jsm>entry</jsm>(<js>"tag:juneau.sample.com,2013:1.2345"</js>, <js>"Juneau ATOM specification snapshot"</js>, <js>"2016-01-02T03:04:05Z"</js>)
.links(
<jsm>link</jsm><js>"alternate"</js>, <js>"text/html"</js>, <js>"http://juneau.apache.org/juneau.atom"</js>),
<jsm>link</jsm>(<js>"enclosure"</js>, <js>"audio/mpeg"</js>, <js>"http://juneau.apache.org/audio/juneau_podcast.mp3"</js>).length(1337)
)
.published(<js>"2016-01-02T03:04:05Z"</js>)
.authors(
<jsm>person</jsm>(<js>"Jane Smith"</js>).uri(<js>"http://juneau.apache.org/"</js>).email(<js>"janesmith@apache.org"</js>)
)
.contributors(
<jsm>person</jsm>(<js>"John Smith"</js>)
)
.content(
<jsm>content</jsm>(<js>"xhtml"</js>)
.lang(<js>"en"</js>)
.base(<js>"http://www.apache.org/"</js>)
.text(<js>"&lt;div&gt;&lt;p&gt;&lt;i&gt;[Update: Juneau supports ATOM.]&lt;/i&gt;&lt;/p&gt;&lt;/div&gt;"</js>)
)
);
</p>
<p>
To serialize this to ATOM, use the {@link org.apache.juneau.xml.XmlSerializer} class:
</p>
<h5 class='figure'>Example with no namespaces</h5>
<p class='bcode'>
<jc>// Create a serializer with readable output, no namespaces yet.</jc>
XmlSerializer s = XmlSerializer.<jsm>create</jsm>().sq().ws().build();
<jc>// Serialize to ATOM/XML</jc>
String atomXml = s.serialize(feed);
</p>
<h5 class='figure'>Results</h5>
<p class='bcode'>
<xt>&lt;feed&gt;</xt>
<xt>&lt;id&gt;</xt>
tag:juneau.apache.org
<xt>&lt;/id&gt;</xt>
<xt>&lt;link</xt> <xa>href</xa>=<xs>'http://juneau.apache.org/'</xs> <xa>rel</xa>=<xs>'alternate'</xs>
<xa>type</xa>=<xs>'text/html'</xs> <xa>hreflang</xa>=<xs>'en'</xs>/<xt>&gt;</xt>
<xt>&lt;link</xt> <xa>href</xa>=<xs>'http://juneau.apache.org/feed.atom'</xs> <xa>rel</xa>=<xs>'self'</xs>
<xa>type</xa>=<xs>'application/atom+xml'</xs>/<xt>&gt;</xt>
<xt>&lt;rights&gt;</xt>
Copyright (c) ...
<xt>&lt;/rights&gt;</xt>
<xt>&lt;title</xt> <xa>type</xa>=<xs>'text'</xs>&gt;</xt>
Juneau ATOM specification
<xt>&lt;/title&gt;</xt>
<xt>&lt;updated&gt;</xt>2016-01-02T03:04:05Z<xt>&lt;/updated&gt;</xt>
<xt>&lt;generator</xt> <xa>uri</xa>=<xs>'http://juneau.apache.org/'</xs> <xa>version</xa>=<xs>'1.0'</xs><xt>&gt;</xt>
Juneau
<xt>&lt;/generator&gt;</xt>
<xt>&lt;subtitle</xt> <xa>type</xa>=<xs>'html'</xs><xt>&gt;</xt>
Describes &lt;em&gt;stuff&lt;/em&gt; about Juneau
<xt>&lt;/subtitle&gt;</xt>
<xt>&lt;entry&gt;</xt>
<xt>&lt;author&gt;</xt>
<xt>&lt;name&gt;</xt>Jane Smith<xt>&lt;/name&gt;</xt>
<xt>&lt;uri&gt;</xt>http://juneau.apache.org/<xt>&lt;/uri&gt;</xt>
<xt>&lt;email&gt;</xt>janesmith@apache.org<xt>&lt;/email&gt;</xt>
<xt>&lt;/author&gt;</xt>
<xt>&lt;contributor&gt;</xt>
<xt>&lt;name&gt;</xt>John Smith<xt>&lt;/name&gt;</xt>
<xt>&lt;/contributor&gt;</xt>
<xt>&lt;id&gt;</xt>
tag:juneau.apache.org
<xt>&lt;/id&gt;</xt>
<xt>&lt;link</xt> <xa>href</xa>=<xs>'http://juneau.apache.org/juneau.atom'</xs>
<xa>rel</xa>=<xs>'alternate'</xs> <xa>type</xa>=<xs>'text/html'</xs>/<xt>&gt;</xt>
<xt>&lt;link</xt> <xa>href</xa>=<xs>'http://juneau.apache.org/audio/juneau_podcast.mp3'</xs>
<xa>rel</xa>=<xs>'enclosure'</xs> <xa>type</xa>=<xs>'audio/mpeg'</xs> <xa>length</xa>=<xs>'12345'</xs>/<xt>&gt;</xt>
<xt>&lt;title&gt;</xt>
Juneau ATOM specification snapshot
<xt>&lt;/title&gt;</xt>
<xt>&lt;updated&gt;</xt>2016-01-02T03:04:05Z<xt>&lt;/updated&gt;</xt>
<xt>&lt;content</xt> <xa>base</xa>=<xs>'http://www.apache.org/'</xs> <xa>lang</xa>=<xs>'en'</xs>
<xa>type</xa>=<xs>'xhtml'</xs><xt>&gt;</xt>
<xt>&lt;div</xt> <xa>xmlns</xa>=<xs>"http://www.w3.org/1999/xhtml"</xs>
<xt>&gt;&lt;p&gt;&lt;i&gt;</xt>[Update: Juneau supports ATOM.]<xt>&lt;/i&gt;&lt;/p&gt;&lt;/div&gt;</xt>
<xt>&lt;/content&gt;</xt>
<xt>&lt;published&gt;</xt>2016-01-02T03:04:05Z<xt>&lt;/published&gt;</xt>
<xt>&lt;/entry&gt;</xt>
<xt>&lt;/feed&gt;</xt>
</p>
<p>
The {@link org.apache.juneau.xml.XmlParser} class can be used convert these Atom documents back into POJOs.
</p>
<p>
Other serializers and parsers (e.g. {@link org.apache.juneau.json.JsonSerializer}) can be used to
represent these POJOs in languages other than XML.
</p>
<h5 class='toc'>Additional Information - org.apache.juneau.dto.atom</h5>
<ol class='toc'>
<li><p><a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#Overview'>Overview</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#Serialize'>Serializing ATOM feeds</a></p>
<ol>
<li><p><a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#AtomJson'>ATOM/JSON</a></p>
<li><p><a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#AtomRdfXml'>ATOM/RDF/XML</a></p>
<li><p><a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#AtomHtml'>ATOM/HTML</a></p>
</ol>
<li><p><a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#Parse'>Parsing ATOM feeds</a></p>
</ol>
</ol>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-dto.Swagger"></a>
<h3 class='topic' onclick='toggle(this)'>4.3 - Swagger</h3>
<div class='topic'>
<p>
The Juneau Swagger DTOs are simply beans with fluent-style setters that allow you to quickly construct
Swagger documents as Java objects.
These object can then be serialized to JSON using one of the existing JSON serializers, or to other
languages such as XML or HTML using the other serializers.
</p>
<p>
The {@link org.apache.juneau.dto.swagger.SwaggerBuilder} class is a utility class with predefined static
methods that allow you to easily construct DTO instances in a minimal amount of code.
</p>
<p>
The following is an example Swagger document from the
<a href="http://petstore.swagger.io/">Swagger website</a>.
</p>
<p class='bcode'>
{
<jf>"swagger"</jf>: <js>"2.0"</js>,
<jf>"info"</jf>: {
<jf>"title"</jf>: <js>"Swagger Petstore"</js>,
<jf>"description"</jf>: <js>"This is a sample server Petstore server."</js>,
<jf>"version"</jf>: <js>"1.0.0"</js>,
<jf>"termsOfService"</jf>: <js>"http://swagger.io/terms/"</js>,
<jf>"contact"</jf>: {
<jf>"email"</jf>: <js>"apiteam@swagger.io"</js>
},
<jf>"license"</jf>: {
<jf>"name"</jf>: <js>"Apache 2.0"</js>,
<jf>"url"</jf>: <js>"http://www.apache.org/licenses/LICENSE-2.0.html"</js>
}
},
<jf>"host"</jf>: <js>"petstore.swagger.io"</js>,
<jf>"basePath"</jf>: <js>"/v2"</js>,
<jf>"tags"</jf>: [
{
<jf>"name"</jf>: <js>"pet"</js>,
<jf>"description"</jf>: <js>"Everything about your Pets"</js>,
<jf>"externalDocs"</jf>: {
<jf>"description"</jf>: <js>"Find out more"</js>,
<jf>"url"</jf>: <js>"http://swagger.io"</js>
}
}
],
<jf>"schemes"</jf>: [
<js>"http"</js>
],
<jf>"paths"</jf>: {
<jf>"/pet"</jf>: {
<jf>"post"</jf>: {
<jf>"tags"</jf>: [
<js>"pet"</js>
],
<jf>"summary"</jf>: <js>"Add a new pet to the store"</js>,
<jf>"description"</jf>: <js>""</js>,
<jf>"operationId"</jf>: <js>"addPet"</js>,
<jf>"consumes"</jf>: [
<js>"application/json"</js>,
<js>"text/xml"</js>
],
<jf>"produces"</jf>: [
<js>"application/json"</js>,
<js>"text/xml"</js>
],
<jf>"parameters"</jf>: [
{
<jf>"in"</jf>: <js>"body"</js>,
<jf>"name"</jf>: <js>"body"</js>,
<jf>"description"</jf>: <js>"Pet object that needs to be added to the store"</js>,
<jf>"required"</jf>: <jk>true</jk>
}
],
<jf>"responses"</jf>: {
<jf>"405"</jf>: {
<jf>"description"</jf>: <js>"Invalid input"</js>
}
}
}
}
},
}
</p>
<p>
This document can be generated by the following Java code:
</p>
<p class='bcode'>
<jk>static import</jk> org.apache.juneau.dto.swagger.SwaggerBuilder.*;
Swagger swagger = <jsm>swagger</jsm>()
.swagger(<js>"2.0"</js>)
.info(
<jsm>info</jsm>(<js>"Swagger Petstore"</js>, <js>"1.0.0"</js>)
.description(<js>"This is a sample server Petstore server."</js>)
.termsOfService(<js>"http://swagger.io/terms/"</js>)
.contact(
<jsm>contact</jsm>().email(<js>"apiteam@swagger.io"</js>)
)
.license(
<jsm>license</jsm>(<js>"Apache 2.0"</js>).url(<js>"http://www.apache.org/licenses/LICENSE-2.0.html"</js>)
)
)
.host(<js>"petstore.swagger.io"</js>)
.basePath(<js>"/v2"</js>)
.tags(
<jsm>tag</jsm>(<js>"pet"</js>).description(<js>"Everything about your Pets"</js>)
.externalDocs(
<jsm>externalDocumentation</jsm>(<js>"http://swagger.io"</js>, <js>"http://swagger.io"</js>)
)
)
.schemes(<js>"http"</js>)
.path(<js>"/pet"</js>, <js>"post"</js>,
<jsm>operation</jsm>()
.tags(<js>"pet"</js>)
.summary(<js>"Add a new pet to the store"</js>)
.description(<js>""</js>)
.operationId(<js>"addPet"</js>)
.consumes(MediaType.<jsf>JSON</jsf>, MediaType.<jsf>XML</jsf>)
.produces(MediaType.<jsf>JSON</jsf>, MediaType.<jsf>XML</jsf>)
.parameters(
<jsm>parameterInfo</jsm>(<js>"body"</js>, <js>"body"</js>)
.description(<js>"Pet object that needs to be added to the store"</js>)
.required(<jk>true</jk>)
)
.response(405, <jsm>responseInfo</jsm>(<js>"Invalid input"</js>))
);
<jc>// Serialize using JSON serializer.</jc>
String swaggerJson = JsonSerializer.<jsf>DEFAULT_READABLE</jsf>.serialize(swagger);
<jc>// Or just use toString().</jc>
String swaggerJson = swagger.toString();
</p>
<p>
Methods that take in beans and collections of beans can also take in JSON representations
of those objects.
</p>
<p class='bcode'>
<jc>// Pass in a JSON object representation of an Info object.</jc>
swagger.info(<js>"{title:'Swagger Petstore',...}"</js>);
</p>
<p>
Properties can also be accessed via the {@link org.apache.juneau.dto.swagger.SwaggerElement#get(String,Class)}
and {@link org.apache.juneau.dto.swagger.SwaggerElement#set(String,Object)} methods.
<br>These methods can also be used to set and retrieve non-Swagger attributes such as
<js>"$ref"</js> (which is not a part of the Swagger spec, but is part of the JSON Schema spec).
</p>
<p class='bcode'>
<jc>// Set a non-standard attribute.</jc>
swagger.set(<js>"$ref"</js>, <js>"http://foo.com"</js>);
<jc>// Retrieve a non-standard attribute.</jc>
URI ref = swagger.get(<js>"$ref"</js>, URI.<jk>class</jk>);
</p>
<p>
Swagger docs can be parsed back into Swagger beans using the following code:
</p>
<p class='bcode'>
Swagger swagger = JsonParser.<jsf>DEFAULT</jsf>.parse(swaggerJson, Swagger.<jk>class</jk>);
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-svl"></a>
<h2 class='topic' onclick='toggle(this)'>5 - juneau-svl</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-svl<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-svl-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.svl_7.0.0.jar
</p>
<!-- ======================================================================================================== -->
<a id="juneau-svl.SimpleVarLanguage"></a>
<h3 class='topic' onclick='toggle(this)'>5.1 - Simple Variable Language</h3>
<div class='topic'>
<p>
The <l>juneau-svl</l> module defines an API for a language called <l>Simple Variable Language</l>.
<br>In a nutshell, Simple Variable Language (or SVL) is text that contains variables of the form <js>"$varName{varKey}"</js>.
<br>It is used extensively in the Config, REST and Microservice APIs.
</p>
<p>
Most variables can be recursively nested within the varKey (e.g. <js>"$FOO{$BAR{xxx},$BAZ{xxx}}"</js>)
and can return values that themselves contain more variables.
</p>
<p>
The {@link org.apache.juneau.svl.VarResolver} class is used to resolve variables.
<br>The {@link org.apache.juneau.svl.VarResolver#DEFAULT} resolver is a reusable instance of this class
configured with the following basic variables:
</p>
<ul>
<li><code>$S{key}</code>,<code>$S{key,default}</code> - System properties.
<li><code>$E{key}</code>,<code>$E{key,default}</code> - Environment variables.
<li><code>$IF{booleanValue,thenValue[,elseValue]}</code> - If-else patterns.
<li><code>$SW{test,matchPattern,thenValue[,matchPattern,thenValue][,elseValue]}</code> - Switch patterns.
<li><code>$CO{arg1[,arg2...]}</code> - Coalesce variable.
<li><code>$CR{arg1[,arg2...]}</code> - Coalesce-and-recurse variable.
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Use the default variable resolver to resolve a string that contains $S (system property) variables</jc>
String myProperty = VarResolver.<jsf>DEFAULT</jsf>.resolve(<js>"The Java home directory is $S{java.home}"</js>);
</p>
<p>
The following shows how variables can be arbitrarily nested...
</p>
<p class='bcode'>
<jc>// Look up a property in the following order:
// 1) MYPROPERTY environment variable.
// 2) 'my.property' system property if environment variable not found.
// 3) 'not found' string if system property not found.</jc>
String myproperty = VarResolver.<jsf>DEFAULT</jsf>.resolve(<js>"$E{MYPROPERTY,$S{my.property,not found}}"</js>);
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-svl.SvlVariables"></a>
<h3 class='topic' onclick='toggle(this)'>5.2 - SVL Variables</h3>
<div class='topic'>
<p>
Variables are defined through the {@link org.apache.juneau.svl.Var} API.
<br>The API comes with several predefined variables and is easily extensible.
</p>
<p>
The following is an example of a variable that performs URL-Encoding on strings.
</p>
<p class='bcode'>
<jc>// First create our var.</jc>
<jk>public class</jk> UrlEncodeVar <jk>extends</jk> SimpleVar {
<jc>// Must have a no-arg constructor!</jc>
<jk>public</jk> UrlEncodeVar() {
<jk>super</jk>(<js>"UE"</js>);
}
<jc>// The method we must implement</jc>
<ja>@Override</ja>
<jk>public</jk> String resolve(VarResolverSession session, String key) {
<jk>return</jk> URLEncoder.<jsm>encode</jsm>(key, <js>"UTF-8"</js>);
}
}
<jc>// Next create a var resolver that extends the existing DEFAULT resolver
// that supports resolving system properties.</jc>
VarResolver r = VarResolver.<jsf>DEFAULT</jsf>
.builder()
.vars(UrlEncodeVar.<jk>class</jk>)
.build();
<jc>// Retrieve a system property and URL-encode it if necessary.</jc>
String myProperty = r.resolve(<js>"$UE{$S{my.property}}"</js>);
</p>
<p>
The following shows the class hierarchy of the {@link org.apache.juneau.svl.Var} class:
</p>
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.svl.Var} - Superclass of all vars.
<ul>
<li class='jac'>{@link org.apache.juneau.svl.SimpleVar} - Superclass of all vars that return strings.
<ul>
<li class='jac'>{@link org.apache.juneau.svl.DefaultingVar} - Variables that define a default value if the resolve method returns null.
<ul>
<li class='jac'>{@link org.apache.juneau.svl.MapVar} - Variables that pull values from maps.
</ul>
<li class='jac'>{@link org.apache.juneau.svl.MultipartVar} - Variables that consist of 2 or more comma-delimited arguments.
</ul>
<li class='jac'>{@link org.apache.juneau.svl.StreamedVar} - Superclass of all vars that stream their value to writers.
</ul>
</ul>
<p>
The following is the list of default variables defined in all modules:
</p>
<table class='styled' style='min-width:800px;width:50%'>
<tr>
<th>Module</th><th>Class</th><th>Pattern</th>
</tr>
<tr class='dark'>
<td rowspan="6" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-svl</td>
<td>{@link org.apache.juneau.svl.vars.EnvVariablesVar}</td>
<td class='code'>$E{envVar[,defaultValue]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.SystemPropertiesVar}</td>
<td class='code'>$S{systemProperty[,defaultValue]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.CoalesceVar}</td>
<td class='code'>$CO{arg1[,arg2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.CoalesceAndRecurseVar}</td>
<td class='code'>$CR{arg1[,arg2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.IfVar}</td>
<td class='code'>$IF{booleanArg,thenValue[,elseValue]}</td>
</tr>
<tr class='dark dd'>
<td>{@link org.apache.juneau.svl.vars.SwitchVar}</td>
<td class='code'>$SW{stringArg(,pattern,thenValue)+[,elseValue]}</td>
</tr>
<tr class='light dd'>
<td rowspan="1" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-config</td>
<td>{@link org.apache.juneau.config.vars.ConfigVar}</td>
<td class='code'>$C{key[,defaultValue]}</td>
</tr>
<tr class='dark'>
<td rowspan="14" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-rest-server</td>
<td>{@link org.apache.juneau.rest.vars.FileVar}</td>
<td class='code'>$F{path[,defaultValue]}}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.ServletInitParamVar}</td>
<td class='code'>$I{name[,defaultValue]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.LocalizationVar}</td>
<td class='code'>$L{key[,args...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestAttributeVar}</td>
<td class='code'>$RA{key1[,key2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestFormDataVar}</td>
<td class='code'>$RF{key1[,key2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestHeaderVar}</td>
<td class='code'>$RH{key1[,key2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestHeaderVar}</td>
<td class='code'>$RI{key}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestPathVar}</td>
<td class='code'>$RP{key1[,key2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestQueryVar}</td>
<td class='code'>$RQ{key1[,key2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestVar}</td>
<td class='code'>$R{key1[,key2...]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.SerializedRequestAttrVar}</td>
<td class='code'>$SA{contentType,key[,defaultValue]}</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.UrlVar}</td>
<td class='code'>$U{uri}></td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.UrlEncodeVar}</td>
<td class='code'>$UE{uriPart}</td>
</tr>
<tr class='dark dd'>
<td>{@link org.apache.juneau.rest.vars.WidgetVar}</td>
<td class='code'>$W{widgetName}</td>
</tr>
<tr class='light'>
<td rowspan="2" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-microservice-server</td>
<td>{@link org.apache.juneau.microservice.vars.ArgsVar}</td>
<td class='code'>$ARG{key[,defaultValue]}</td>
</tr>
<tr class='light dd'>
<td>{@link org.apache.juneau.microservice.vars.ManifestFileVar}</td>
<td class='code'>$MF{key[,defaultValue]}</td>
</tr>
</table>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-svl.VarResolvers"></a>
<h3 class='topic' onclick='toggle(this)'>5.3 - VarResolvers and VarResolverSessions</h3>
<div class='topic'>
<p>
The main class for performing variable resolution is {@link org.apache.juneau.svl.VarResolver}.
<br>Two methods are provided for resolving variables:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.svl.VarResolver}
<ul>
<li class='jm'>{@link org.apache.juneau.svl.VarResolver#resolve(String) resolve(String)}
- Resolves variables and returns the results as a simple string.
<li class='jm'>{@link org.apache.juneau.svl.VarResolver#resolveTo(String,Writer) resolveTo(String,Writer)}
- Resolves variables and sends results to a writer.
</ul>
</ul>
<p>
Var resolvers can rely on the existence of other objects.
<br>For example, {@link org.apache.juneau.config.vars.ConfigVar} relies on the existence of a {@link org.apache.juneau.config.Config}.
<br>This is accomplished through the following:
</p>
<ul class='spaced-list'>
<li>Context-objects - Objects set on the resolver.
<li>Session-objects - Objects set on the resolver session.
</ul>
<p>
The following two classes are identical in behavior except for which objects they can access:
</p>
<ul>
<li class='jc'>{@link org.apache.juneau.svl.VarResolver} - Has access to context objects only.
<li class='jc'>{@link org.apache.juneau.svl.VarResolverSession} - Has access to context and session objects.
</ul>
<p>
Context and session objects are set through the following methods:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.svl.VarResolverBuilder#contextObject(String,Object)} - Context objects.
<li class='jm'>{@link org.apache.juneau.svl.VarResolverSession#sessionObject(String,Object)} - Session objects.
<li class='jm'>{@link org.apache.juneau.svl.VarResolver#createSession(Map)} - Session objects.
</ul>
<p>
Both kinds of objects are accessible through the following method:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.svl.VarResolverSession#getSessionObject(Class, String)}
</ul>
<p>
Var resolvers can be cloned and extended by using the {@link org.apache.juneau.svl.VarResolver#builder()} method.
<br>Cloning a resolver will copy it's {@link org.apache.juneau.svl.Var} class names and context objects.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Create a resolver that copies the default resolver and adds $C and $ARG vars.</jc>
VarResolver myVarResolver = VarResolver.<jsf>DEFAULT</jsf>
.builder()
.vars(ConfigVar.<jk>class</jk>, ArgsVar.<jk>class</jk>)
.build();
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-svl.OtherNotes"></a>
<h3 class='topic' onclick='toggle(this)'>5.4 - Other Notes</h3>
<div class='topic'>
<ul class='spaced-list'>
<li>
The escape character <js>'\'</js> can be used when necessary to escape the following characters:
<code>$ , { }</code>
<li>
<b>WARNING:</b> It is possible to cause {@link java.lang.StackOverflowError StackOverflowErrors} if
your nested variables result in a recursive loop (e.g. the environment variable
<code>'MYPROPERTY'</code> has the value <code>'$E{MYPROPERTY}'</code>).
So don't do that!
<li>
As a general rule, this class tries to be as efficient as possible by not creating new strings when not
needed.
<br>For example, calling the resolve method on a string that doesn't contain variables (e.g.
<code>resolver.resolve(<js>"foobar"</js>)</code>) will simply be a no-op and return the same string.
</ul>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-config"></a>
<h2 class='topic' onclick='toggle(this)'>6 - juneau-config</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-config<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-config-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.config_7.0.0.jar
</p>
<!-- ======================================================================================================== -->
<a id="juneau-config.Overview"></a>
<h3 class='topic' onclick='toggle(this)'>6.1 - Overview</h3>
<div class='topic'>
<p>
The <code>juneau-config</code> library contains a powerful API for creating and using INI-style config files.
</p>
<p>
An example of the contents of a config file:
</p>
<p class='bcode'>
<cc># A set of entries</cc>
<cs>[Section1]</cs>
<cc># An integer</cc>
<ck>key1</ck> = <cv>1</cv>
<cc># A boolean</cc>
<ck>key2</ck> = <cv>true</cv>
<cc># An array</cc>
<ck>key3</ck> = <cv>1,2,3</cv>
<cc># A POJO</cc>
<ck>key4</ck> = <cv>http://bar</cv>
</p>
<p>
This code shows how the file can be accessed:
</p>
<p class='bcode'>
<jc>// Load our config file</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
<jc>// Read values from section #1</jc>
<jk>int</jk> key1 = c.getInt(<js>"Section1/key1"</js>);
<jk>boolean</jk> key2 = c.getBoolean(<js>"Section1/key2"</js>);
<jk>int</jk>[] key3 = c.getObject(<js>"Section1/key3"</js>, <jk>int</jk>[].<jk>class</jk>);
URL key4 = c.getObject(<js>"Section1/key4"</js>, URL.<jk>class</jk>);
</p>
<p>
The config language may look simple, but it is a very powerful feature with many capabilities including:
</p>
<ul class='spaced-list'>
<li>
Support for storing and retrieving any of the following data types:
<ul>
<li>Primitives
<li>POJOs
<li>Beans
<li>Arrays, Maps, and Collections of anything
<li>Binary data
</ul>
<li>
A listener API that allows you to, for example, reinitialize your REST resource if the config file
changes, or listen for changes to particular sections or values.
<li>
Filesystem watcher integration allows configs to reflect changes on the file system in real-time.
<li>
Config files can be modified through the Config class (e.g. add/remove/modify sections and keys, add/remove comments and whitespace, etc...).
<br>When using these APIs, you <b>DO NOT</b> lose formatting in your existing configuration file.
All existing whitespace and comments are preserved for you!
<li>
Support for encoding of values for added security.
<li>
Config sections can be used to directly populate beans.
<li>
Config sections can be accessed and manipulated through Java interface proxies.
<li>
An extensible storage API allows you to write your own config storage location for files such as databases or the cloud.
</ul>
<!-- ======================================================================================================== -->
<a id="juneau-config.SyntaxRules"></a>
<h4 class='topic' onclick='toggle(this)'>6.1.1 - Syntax Rules</h4>
<div class='topic'>
<ul class='spaced-list'>
<li>
Each config file contains zero or more sections containing zero or more entries:
<p class='bcode'>
<cs>[Section1]</cs>
<ck>key1</ck> = <cv>1</cv>
<cs>[Section2]</cs>
<ck>key1</ck> = <cv>2</cv>
</p>
<li>
Unicode escapes can be used in values.
<p class='bcode'>
<ck>key1</ck> = <cv>\u0070\u0075\u0062\u006c\u0069\u0063</cv>
</p>
<li>
Comment lines start with the <js>'#'</js> character and can be placed on lines before sections and entries:
<p class='bcode'>
<cc># A comment about this section</cc>
<cs>[Section1]</cs>
<cc># A comment about this entry</cc>
<ck>key1</ck> = <cv>1</cv>
</p>
<li>
Comments can also be placed on the same line as entries:
<p class='bcode'>
<ck>key1</ck> = <cv>1</cv> <cc># A comment about this entry</cc>
</p>
<li>
Values containing <js>'#'</js> must be escaped to prevent identification as a comment character:
<p class='bcode'>
<ck>valueContainingPound</ck> = <cv>Value containing \u0023 character</cv>
</p>
<br>Likewise, <js>'\'</js> should be escaped to prevent confusion with unicode escapes.
<li>
Values containing newlines can span multiple lines.
<br>Subsequent lines start with a tab character.
<p class='bcode'>
<ck>multiLineValue</ck> =
<cv>Line 1,</cv>
<cv>Line 2,</cv>
<cv>Line 3</cv>
</p>
<br>When retrieved, the above translates to <js>"Line1,\nLine2,\nLine3"</js>.
<li>
Leading and trailing whitespace on values are ignored.
<li>
Whitespace is not ignored within multi-line values (except for the leading tab character on each line).
<li>
Blank lines can be used anywhere in the file.
<p class='bcode'>
<cc># A comment line</cc>
<cc># Another comment line</cc>
<cs>[Section1]</cs>
...
</p>
<li>
Values located before any sections are considered part of the no-name section, meaning
they are accessed simply by key and not section/key.
<p class='bcode'>
<cc># Top of file</cc>
<cc># Use config.getString("key1") to retrieve.</cc>
<ck>key1</ck> = <cv>val1</cv>
<cc># The first section</cc>
<cs>[Section1]</cs>
<cc># Use config.getString("Section1/key2") to retrieve.</cc>
<ck>key2</ck> = <cv>val2</cv>
</p>
<li>
Section and key names must be at least one character long and not consist of any of the following
characters:
<p class='bcode'>
/ \ [ ] = #
</p>
<li>
Whitespace in section and key names is technically allowed but discouraged.
</ul>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.EntryTypes"></a>
<h3 class='topic' onclick='toggle(this)'>6.2 - Entry Types</h3>
<div class='topic'>
<p>
Configuration files can contain entries for anything from primitive types up to complex hierarchies of POJOs consisting of maps, collections, and/or beans.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-config.PrimitiveTypes"></a>
<h4 class='topic' onclick='toggle(this)'>6.2.1 - Primitive Types</h4>
<div class='topic'>
<p>
The most common case for configuration values are primitives.
</p>
<p class='bcode'>
<cc># A string</cc>
<ck>key1</ck> = <cv>foo</cv>
<cc># A boolean</cc>
<ck>key2</ck> = <cv>true</cv>
<cc># An integer</cc>
<ck>key3</ck> = <cv>123</cv>
<cc># A long</cc>
<ck>key4</ck> = <cv>10000000000</cv>
</p>
<p>
The following methods are provided for accessing primitive values:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#getString(String) getString(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getString(String,String) getString(String,String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getBoolean(String) getBoolean(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getBoolean(String,boolean) getBoolean(String,boolean)}
<li class='jm'>{@link org.apache.juneau.config.Config#getInt(String) getInt(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getInt(String,int) getInt(String,int)}
<li class='jm'>{@link org.apache.juneau.config.Config#getLong(String) getLong(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getLong(String,long) getLong(String,long)}
<li class='jm'>{@link org.apache.juneau.config.Config#getFloat(String) getFloat(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getFloat(String,float) getFloat(String,long)}
<li class='jm'>{@link org.apache.juneau.config.Config#getDouble(String) getDouble(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getDouble(String,double) getDouble(String,long)}
</ul>
</ul>
<p>
On integers and longs, <js>"K"</js>, <js>"M"</js>, and <js>"G"</js> can be used to identify kilo, mega, and giga.
</p>
<p class='bcode'>
<ck>key1</ck> = <cv>100K</cv> <cc># Same as 1024000</cc>
<ck>key2</ck> = <cv>100M</cv> <cc># Same as 104857600</cc>
</p>
<p>
Numbers can also use hexadecimal and octal notation:
</p>
<p class='bcode'>
<ck>hex1</ck> = <cv>0x12FE</cv>
<ck>hex2</ck> = <cv>0X12FE</cv>
<ck>octal1</ck> = <cv>01234</cv>
</p>
<p>
Strings with newlines get broken into separate lines:
</p>
<p class='bcode'>
<ck>key1</ck> = <cv>This is a particularly long sentence that we want to split</cv>
<cv>onto separate lines</cv>.
</p>
<p>
Typically, multi-line values are started on the next line for clarity like so:
</p>
<p class='bcode'>
<ck>key1</ck> =
<cv>This is a particularly long sentence that we want to split</cv>
<cv>onto separate lines</cv>.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.POJOs"></a>
<h4 class='topic' onclick='toggle(this)'>6.2.2 - POJOs</h4>
<div class='topic'>
<p>
The following methods are provided for accessing POJO values:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#getObject(String,Class) getObject(String,Class)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObjectWithDefault(String,Object,Class) getObjectWithDefault(String,T,Class)}
</ul>
</ul>
<p>
In theory, any <a class='doclink' href='#juneau-marshall.PojoCategories'>parsable</a> POJO type can be represented
as a config value.
<br>However in practice, we're typically talking about the following:
</p>
<ul>
<li>Objects convertable from Strings.
<li>Beans.
</ul>
<p>
An example of an object convertible from a String was already shown in an example above.
<br>In that case, it was a URL which has a public constructor that takes in a String:
</p>
<p class='bcode'>
<cc># A POJO</cc>
<ck>key4</ck> = <cv>http://bar</cv>
</p>
<p class='bcode'>
<jc>// Read values from section #1</jc>
URL key4 = c.getObject(<js>"Section1/key4"</js>, URL.<jk>class</jk>);
</p>
<p>
Beans are represented as Lax JSON by default:
</p>
<p class='bcode'>
<jc>// Contact information</jc>
<cs>[ContactInfo]</cs>
<ck>address</ck> =
<cv>{
street: '123 Main Street',
city: 'Anywhere',
state: 'NY',
zip: 12345
}</cv>
</p>
<p class='bcode'>
<jc>// Example bean</jc>
<jk>public class</jk> Address {
<jk>public</jk> String <jf>street</jf>, <jf>city</jf>;
<jk>public</jk> StateEnum <jf>state</jf>;
<jk>public int</jk> <jf>zip</jf>;
}
<jc>// Example usage</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
Address myAddress = c.getObject(<js>"ContactInfo/address"</js>, Address.<jk>class</jk>);
</p>
<p>
The format for beans depends on the serializer and parser registered on the Config which
is defined in the builder via the following methods:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.ConfigBuilder}
<ul>
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#serializer(Class) serializer(Class)}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#serializer(WriterSerializer) serializer(WriterSerializer)}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#parser(Class) parser(Class)}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#parser(ReaderParser) parser(ReaderParser)}
</ul>
</ul>
<p>
The default parser can also be overridden using the following getters:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#getObject(String,Parser,Class) getObject(String,Parser,Class)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObjectWithDefault(String,Parser,Object,Class) getObjectWithDefault(String,T,Parser,Class)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.Arrays"></a>
<h4 class='topic' onclick='toggle(this)'>6.2.3 - Arrays</h4>
<div class='topic'>
<p>
The following methods are provided for accessing arrays:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#getStringArray(String) getStringArray(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getStringArray(String,String[]) getStringArray(String,String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObject(String,Class) getObject(String,Class)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObject(String,Parser,Class) getObject(String,Parser,Class)}
</ul>
</ul>
<p>
The <code>getStringArray()</code> methods allow you to retrieve comma-delimited lists of values:
<p class='bcode'>
<ck>key1</ck> = <cv>foo, bar, baz</cv>
</p>
<p class='bcode'>
String[] key1 = c.getStringArray(<js>"key1"</js>);
</p>
<p>
String arrays can also be represented in JSON when using the <code>getObject()</code> methods:
</p>
<p class='bcode'>
<ck>key1</ck> = <cv>['foo','bar','baz']</cv>
</p>
<p class='bcode'>
String[] key1 = c.getObject(<js>"key1"</js>, String.<jk>class</jk>);
</p>
<p>
Primitive arrays can also be retrieved using the <code>getObject()</code> methods:
</p>
<p class='bcode'>
<ck>key1</ck> = <cv>[1,2,3]</cv>
</p>
<p class='bcode'>
<jk>int</jk>[] key1 = c.getObject(<js>"key1"</js>, <jk>int</jk>[].<jk>class</jk>);
</p>
<p>
Arrays of POJOs can also be retrieved using the <code>getObject()</code> methods:
</p>
<p class='bcode'>
<ck>addresses</ck> =
<cv>[
{
street: '123 Main Street',
city: 'Anywhere',
state: 'NY',
zip: 12345
}</cv>,
<cv>{
street: '456 Main Street',
city: 'Anywhere',
state: 'NY',
zip: 12345
}
]</cv>
</p>
<p class='bcode'>
Address[] addresses = c.getObject(<js>"addresses"</js>, Address[].<jk>class</jk>);
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.Collections"></a>
<h4 class='topic' onclick='toggle(this)'>6.2.4 - Collections</h4>
<div class='topic'>
<p>
The following methods are provided for accessing maps and collections:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#getObject(String,Type,Type...) getObject(String,Type,Type...)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObject(String,Parser,Type,Type...) getObject(String,Parser,Type,Type...)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObjectWithDefault(String,Object,Type,Type...) getObjectWithDefault(String,T,Type,Type...)}
<li class='jm'>{@link org.apache.juneau.config.Config#getObjectWithDefault(String,Parser,Object,Type,Type...) getObjectWithDefault(String,T,Parser,Type,Type...)}
</ul>
</ul>
<p>
The <code>Type,Type...</code> arguments allow you to specify the component types for maps and collections.
<br><code>List</code> class arguments can be followed by zero or one arguments representing the entry types.
<br><code>Map</code> class arguments can be followed by zero or two arguments representing the key and value types.
<br>The arguments can be chained to produce any data structure consisting of maps, collections, or POJOs.
</p>
<p>
<br>Examples are shown below:
</p>
<ul class='spaced-list'>
<li><code>getObject(<js>"..."</js>, List.<jk>class</jk>)</code>
<br>Produces: <code>List&lt;?&gt;</code>
<li><code>getObject(<js>"..."</js>, LinkedList.<jk>class</jk>)</code>
<br>Produces: <code>LinkedList&lt;?&gt;</code>
<li><code>getObject(<js>"..."</js>, HashSet.<jk>class</jk>, Integer.<jk>class</jk>)</code>
<br>Produces: <code>HashSet&lt;Integer&gt;</code>
<li><code>getObject(<js>"..."</js>, Map.<jk>class</jk>)</code>
<br>Produces: <code>Map&lt;?,?&gt;</code>
<li><code>getObject(<js>"..."</js>, HashMap.<jk>class</jk>)</code>
<br>Produces: <code>HashMap&lt;?,?&gt;</code>
<li><code>getObject(<js>"..."</js>, LinkedHashMap.<jk>class</jk>, String.<jk>class</jk>, MyBean.<jk>class</jk>)</code>
<br>Produces: <code>LinkedHashMap&lt;String,MyBean&gt;</code>
<li><code>getObject(<js>"..."</js>, HashMap.<jk>class</jk>, Integer.<jk>class</jk>, ArrayList.<jk>class</jk>, MyBean[].<jk>class</jk>)</code>
<br>Produces: <code>LinkedHashMap&lt;Integer,ArrayList&lt;MyBean[]&gt;&gt;</code>
</ul>
<p>
For example:
</p>
<p class='bcode'>
<ck>addresses</ck> =
<cv>[
{
street: '123 Main Street',
city: 'Anywhere',
state: 'NY',
zip: 12345
}</cv>,
<cv>{
street: '456 Main Street',
city: 'Anywhere',
state: 'NY',
zip: 12345
}
]</cv>
</p>
<p class='bcode'>
List&lt;Address&gt; addresses = c.getObject(<js>"addresses"</js>, ArrayList.<jk>class</jk>, Address.<jk>class</jk>);
</p>
<p>
Oftentimes, it might be useful to parse into the {@link org.apache.juneau.ObjectList} and {@link org.apache.juneau.ObjectMap}
classes that provide the various convenience methods for working with JSON-like data structures:
</p>
<ul>
<li><code>getObject(<js>"..."</js>, ObjectList.<jk>class</jk>)</code>
<li><code>getObject(<js>"..."</js>, ObjectMap.<jk>class</jk>)</code>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.BinaryData"></a>
<h4 class='topic' onclick='toggle(this)'>6.2.5 - Binary Data</h4>
<div class='topic'>
<p>
The following methods are provided for accessing binary data:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#getBytes(String) getBytes(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#getBytes(String,byte[]) getBytes(String,byte[])}
</ul>
</ul>
<p>
Binary data can be represented in 3 formats:
</p>
<ul class='spaced-list'>
<li>BASE-64 (default)
<br>Example: <code><js>"Zm9vYmFycw=="</js></code>
<li>Hexadecimal
<br>Example: <code><js>"666F6F62617273</js></code>
<li>Spaced hexadecimal
<br>Example: <code><js>"66 6F 6F 62 61 72 73</js></code>
</ul>
<p>
The binary data format is controlled via the following:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.config.Config#CONFIG_binaryFormat}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#binaryFormat(String)}
</ul>
<p>
For example:
</p>
<p class='bcode'>
<ck>bytes</ck> = <cv>Zm9vYmFycw==</cv>
</p>
<p class='bcode'>
<jk>byte</jk>[] bytes = c.getBytes(<js>"bytes"</js>);
</p>
<p>
Binary lines can be split up into separate lines for readability:
</p>
<p class='bcode'>
<ck>bytes</ck> =
<cv>Zm9vYm
Fycw==</cv>
</p>
<p>
Binary data line wrapping can be controlled via the following:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.config.Config#CONFIG_binaryLineLength}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#binaryLineLength(int)}
</ul>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.Variables"></a>
<h3 class='topic' onclick='toggle(this)'>6.3 - Variables</h3>
<div class='topic'>
<p>
Config files can contain variables that get resolved dynamically using the {@link org.apache.juneau.svl.VarResolver} API.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<cc>#--------------------------</cc>
<cc># My section</cc>
<cc>#--------------------------</cc>
<cs>[MySection]</cs>
<cc># A system property</cc>
<ck>locale</ck> = <cv>$S{java.locale, en_US}</cv>
<cc># An environment variable</cc>
<ck>path</ck> = <cv>$E{PATH, unknown}</cv>
<cc># Another system property</cc>
<ck>anInt</ck> = <cv>$C{anInt, -1}</cv>
<cc># Another value in this config file</cc>
<ck>sameAsAnInt</ck> = <cv>$C{MySection/anInt}</cv>
<cc># Look for system property, or env var if that doesn't exist, or a default value if that doesn't exist.</cc>
<ck>nested</ck> = <cv>$S{mySystemProperty,$E{MY_ENV_VAR,$C{MySection/anInt}}}</cv>
<cc># A POJO with embedded variables</cc>
<ck>aBean</ck> = <cv>{foo:'$S{foo}',baz:$C{MySection/anInt}}</cv>
</p>
<p class='bcode'>
Config c = Config.<jsf>create</jsf>().build();
Locale locale = cf.getObject(<js>"MySection/locale"</js>, Locale.<jk>class</jk>);
String path = cf.getString(<js>"MySection/path"</js>);
<jk>int</jk> sameAsAnInt = cf.getInt(<js>"MySection/sameAsAnInt"</js>);
ABean bean = cf.getObject(<js>"MySection/aBean"</js>, ABean.<jk>class</jk>);
</p>
<p>
By default, <code>Configs</code> use the {@link org.apache.juneau.svl.VarResolver#DEFAULT} variable resolver
which provides support for the following variables and constructs (in addition to the <code>$C</code> variable):
</p>
<ul class='spaced-list'>
<li><code>$S{key}</code>,<code>$S{key,default}</code> - {@link org.apache.juneau.svl.vars.SystemPropertiesVar}
<li><code>$E{key}</code>,<code>$E{key,default}</code> - {@link org.apache.juneau.svl.vars.EnvVariablesVar}
<li><code>$IF{booleanValue,thenValue[,elseValue]}</code> - {@link org.apache.juneau.svl.vars.IfVar}
<li><code>$SW{test,matchPattern,thenValue[,matchPattern,thenValue][,elseValue]}</code> - {@link org.apache.juneau.svl.vars.SwitchVar}
<li><code>$CO{arg1[,arg2...]}</code> - {@link org.apache.juneau.svl.vars.CoalesceVar}
<li><code>$CR{arg1[,arg2...]}</code> - {@link org.apache.juneau.svl.vars.CoalesceAndRecurseVar}
</ul>
<p>
The variable resolver can be overridden via the following:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.config.Config#CONFIG_varResolver}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#varResolver(Class)}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#varResolver(VarResolver)}
</ul>
<p>
Additionally, the following method can be used to retrieve a <code>Config</code> with a different variable resolver:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.config.Config#resolving(VarResolverSession)}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.EncodedEntries"></a>
<h3 class='topic' onclick='toggle(this)'>6.4 - Encoded Entries</h3>
<div class='topic'>
<p>
Encoded entries allow for sensitive information such as passwords to be obfuscated.
</p>
<p>
Encoded entries are denoted with a <js>'*'</js> character at the end of the key name.
</p>
<p>
For example, the following password is marked for encoding....
</p>
<p class='bcode'>
<cs>[MyHost]</cs>
<ck>url</ck> = <cv>http://localhost:9080/foo</cv>
<ck>user</ck> = <cv>me</cv>
<ck>password*</ck> = <cv>{AwwJVhwUQFZEMg==}</cv>
</p>
<p>
The default encoder is {@link org.apache.juneau.config.encode.ConfigXorEncoder} which is a simple XOR+Base64 encoder.
</p>
<p>
Custom encoders can be used to provide your own encoding support by implementing the {@link org.apache.juneau.config.encode.ConfigEncoder} interface.
</p>
<p>
Encoders are controlled via the following:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.config.Config#CONFIG_encoder}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#encoder(Class)}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#encoder(ConfigEncoder)}
</ul>
<p>
Encoded values can be set to plain-text values.
<br>The curly brackets around the value identify whether the value has been encoded or not.
</p>
<p>
Unencoded values are encoded when the file is saved using the {@link org.apache.juneau.config.Config#save()} method.
<br>They can also be encoded by calling {@link org.apache.juneau.config.Config#encodeEntries()}.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.SectionMaps"></a>
<h3 class='topic' onclick='toggle(this)'>6.5 - Section Maps</h3>
<div class='topic'>
<p>
Config sections can be retrieved in-bulk using the
{@link org.apache.juneau.config.Config#getSectionAsMap(String)} method:
</p>
<p class='bcode'>
<jc>// Example config file</jc>
<cs>[MyAddress]</cs>
<ck>street</ck> = <cv>123 Main Street</cv>
<ck>city</ck> = <cv>Anywhere</cv>
<ck>state</ck> = <cv>NY</cv>
<ck>zip</ck> = <cv>12345</cv>
</p>
<p class='bcode'>
<jc>// Example usage</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
ObjectMap m = c.getSectionAsMap(<js>"MyAddress"</js>);
String street = m.getString(<js>"street"</js>);
String city = m.getString(<js>"city"</js>);
String state = m.getString(<js>"state"</js>);
<jk>int</jk> zip = m.getInt(<js>"zip"</js>);
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.SectionBeans"></a>
<h3 class='topic' onclick='toggle(this)'>6.6 - Section Beans</h3>
<div class='topic'>
<p>
Config files can also be used to directly populate beans using the
{@link org.apache.juneau.config.Config#getSectionAsBean(String,Class,boolean)}:
</p>
<p class='bcode'>
<jc>// Example config file</jc>
<cs>[MyAddress]</cs>
<ck>street</ck> = <cv>123 Main Street</cv>
<ck>city</ck> = <cv>Anywhere</cv>
<ck>state</ck> = <cv>NY</cv>
<ck>zip</ck> = <cv>12345</cv>
</p>
<p class='bcode'>
<jc>// Example bean</jc>
<jk>public class</jk> Address {
public String street, city;
public StateEnum state;
public int zip;
}
<jc>// Example usage</jc>
Config cf = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
Address myAddress = cf.getSectionAsBean(<js>"MyAddress"</js>, Address.<jk>class</jk>);
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.SectionInterfaces"></a>
<h3 class='topic' onclick='toggle(this)'>6.7 - Section Interfaces</h3>
<div class='topic'>
<p>
Config sections can also be accessed via interface proxies using
{@link org.apache.juneau.config.Config#getSectionAsInterface(String,Class)}.
</p>
<p>
While section maps and beans retrieve copies of the configuration data at the time of the method
call, section interfaces can also be use to set values in the underlying configuration.
</p>
<p class='bcode'>
<jc>// Example config file</jc>
<cs>[MySection]</cs>
<ck>string</ck> = <cv>foo</cv>
<ck>int</ck> = <cv>123</cv>
<ck>enum</ck> = <cv>ONE</cv>
<ck>bean</ck> = <cv>{foo:'bar',baz:123}</cv>
<ck>int3dArray</ck> = <cv>[[[123,null],null],null]</cv>
<ck>bean1d3dListMap</ck> = <cv>{key:[[[[{foo:'bar',baz:123}]]]]}</cv>
</p>
<p class='bcode'>
<jc>// Example interface.</jc>
<jc>// Setters are optional.</jc>
<jk>public interface</jk> MyConfigInterface {
String getString();
<jk>void</jk> setString(String x);
<jk>int</jk> getInt();
<jk>void</jk> setInt(<jk>int</jk> x);
MyEnum getEnum();
<jk>void</jk> setEnum(MyEnum x);
MyBean getBean();
<jk>void</jk> setBean(MyBean x);
<jk>int</jk>[][][] getInt3dArray();
<jk>void</jk> setInt3dArray(<jk>int</jk>[][][] x);
Map&lt;String,List&lt;MyBean[][][]&gt;&gt; getBean1d3dListMap();
<jk>void</jk> setBean1d3dListMap(Map&lt;String,List&lt;MyBean[][][]&gt;&gt; x);
}
<jc>// Example usage.</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
MyConfigInterface ci = c.getSectionAsInterface(<js>"MySection"</js>, MyConfigInterface.<jk>class</jk>);
<jc>// Read a value.</jc>
<jk>int</jk> myInt = ci.getInt();
<jc>// Write a value.</jc>
ci.setBean(<jk>new</jk> MyBean());
<jc>// Save your changes.</jc>
c.save();
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.SettingValues"></a>
<h3 class='topic' onclick='toggle(this)'>6.8 - Setting Values</h3>
<div class='topic'>
<p>
The following methods allow you to add, remove, and modify entries and sections in a config file:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.config.Config}
<ul>
<li class='jm'>{@link org.apache.juneau.config.Config#set(String,Object) set(String,Object)}
<li class='jm'>{@link org.apache.juneau.config.Config#set(String,Object,Serializer) set(String,Object,Serializer)}
<li class='jm'>{@link org.apache.juneau.config.Config#set(String,Object,Serializer,ConfigMod,String,List) set(String,Object,Serializer,ConfigMod,String,List)}
<li class='jm'>{@link org.apache.juneau.config.Config#set(String,Object,Serializer,ConfigMod[],String,List) set(String,Object,Serializer,ConfigMod[],String,List)}
<li class='jm'>{@link org.apache.juneau.config.Config#set(String,String) set(String,String)}
<li class='jm'>{@link org.apache.juneau.config.Config#remove(String) remove(String)}
<li class='jm'>{@link org.apache.juneau.config.Config#setSection(String,List) setSection(String,List)}
<li class='jm'>{@link org.apache.juneau.config.Config#setSection(String,List,Map) setSection(String,List,Map)}
<li class='jm'>{@link org.apache.juneau.config.Config#removeSection(String) removeSection(String)}
</ul>
</ul>
<p class='bcode'>
<jc>// Construct the sample config file programmatically</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build()
.set(<js>"key1"</js>, 1)
.set(<js>"key2"</js>, <jk>true</jk>)
.set(<js>"key3"</js>, <jk>new int</jk>[]{1,2,3})
.set(<js>"key4"</js>, <jk>new</jk> URI(<js>"http://foo"</js>))
.set(<js>"Section1/key1"</js>, 2)
.set(<js>"Section1/key2"</js>, <jk>false</jk>)
.set(<js>"Section1/key3"</js>, <jk>new int</jk>[]{4,5,6})
.set(<js>"Section1/key4"</js>, <jk>new</jk> URI(<js>"http://bar"</js>))
.save();
</p>
<!-- ======================================================================================================== -->
<a id="juneau-config.CustomEntrySerialization"></a>
<h4 class='topic' onclick='toggle(this)'>6.8.1 - Custom Entry Serialization</h4>
<div class='topic'>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.BulkSettingValues"></a>
<h4 class='topic' onclick='toggle(this)'>6.8.2 - Setting Values in Bulk</h4>
<div class='topic'>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.Listeners"></a>
<h3 class='topic' onclick='toggle(this)'>6.9 - Listeners</h3>
<div class='topic'>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.Serializing"></a>
<h3 class='topic' onclick='toggle(this)'>6.10 - Serializing</h3>
<div class='topic'>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.ConfigStores"></a>
<h3 class='topic' onclick='toggle(this)'>6.11 - Config Stores</h3>
<div class='topic'>
<!-- ======================================================================================================== -->
<a id="juneau-config.ConfigMemoryStore"></a>
<h4 class='topic' onclick='toggle(this)'>6.11.1 - ConfigMemoryStore</h4>
<div class='topic'>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.ConfigFileStore"></a>
<h4 class='topic' onclick='toggle(this)'>6.11.2 - ConfigFileStore</h4>
<div class='topic'>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-config.ReadOnlyConfigs"></a>
<h3 class='topic' onclick='toggle(this)'>6.12 - Read-only Configs</h3>
<div class='topic'>
<p>
The following settings can be used to create read-only <code>Config</code> objects:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.config.Config#CONFIG_readOnly}
<li class='jm'>{@link org.apache.juneau.config.ConfigBuilder#readOnly()}
</ul>
<h6 class='figure'>Example:</h6>
<p class='bcode'>
<jc>// Create a read-only config</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).readOnly().build();
</p>
<p>
This causes all methods that make modifications to throw {@link java.lang.UnsupportedOperationException}.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="#juneau-config.ClosingConfigs"></a>
<h3 class='topic' onclick='toggle(this)'>6.13 - Closing Configs</h3>
<div class='topic'>
<p>
In general, it's good practice to close Config if you're only creating them temporarily so that
their listeners get unregistered from the underlying storage APIs.
</p>
<p class='bcode'>
<jc>// Create a transient config.</jc>
Config c = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
<jc>// Do stuff with it.</jc>
<jc>// Then close the config to unregister the listeners.</jc>
c.close();
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-rest-server"></a>
<h2 class='topic' onclick='toggle(this)'>7 - juneau-rest-server</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-rest-server<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-rest-server-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.rest.server_7.0.0.jar
</p>
<p>
The <l>juneau-rest-server</l> library allows you to quickly wrap POJOs and expose them as full-fledged REST
resources served up in a servlet container using a bare-minimum amount of code.
<br>The primary goal for Juneau was to make it as easy as possible to implement easy-to-read and self-documenting
REST resources using very little code.
</p>
<p>
One of the biggest advantages of the Juneau REST framework over similar architectures is that it hides the
serialization layer from the developer.
<br>The developer can work entirely with POJOs and let the Juneau framework handle all the serialization and
parsing work.
<br>The developer need never know what the <l>Accept</l> or <l>Content-Type</l> or <l>Accept-Encoding</l> (etc...)
header values are because those details are all handled by the framework.
</p>
<p>
The API builds upon the existing JEE Servlet API.
<br>The root class, {@link org.apache.juneau.rest.RestServlet} is nothing but a specialized
{@link javax.servlet.http.HttpServlet}, and the {@link org.apache.juneau.rest.RestRequest} and
{@link org.apache.juneau.rest.RestResponse} classes are nothing more than specialized
{@link javax.servlet.http.HttpServletRequest} and {@link javax.servlet.http.HttpServletResponse} objects.
<br>This allows maximum flexibility for the developer since you can let Juneau handle operations such as
serialization, or you can revert to the existing servlet APIs to do low-level processing of requests yourself.
<br>It also means you need nothing more than a Servlet container such as Jetty to use the REST framework.
</p>
<h5 class='topic'>Features</h5>
<ul class='spaced-list'>
<li>
Serializes POJOs to JSON, XML, HTML, URL-Encoding, UON, RDF/XML, N-Triple, Turtle, N3, SOAP, or
Java-serialized-object based on value of <l>Accept</l> header.
<br>No user code is required to handle these types.
<ul>
<li>Extensible design that provides ability to override existing content type handlers, or add the
ability to handle other kinds of content types.
</ul>
<li>
Parses content of POST/PUT request bodies to POJOs.
<li>
Automatic built-in ability to serialize POJO metadata to JSON+SCHEMA, XML+SCHEMA, or HTML+SCHEMA based on
<l>Accept</l> header.
<li>
Automatic negotiation of output Writer based on HTTP headers.
<ul>
<li>Automatic handling of <l>Accept-Charset</l> header for all character sets supported by the JVM.
<li>Automatic handling of <l>Accept-Encoding</l> header with registered encoders.
</ul>
<li>
Automatic error handling.
<ul>
<li>Automatic 401 errors (Unauthorized) on failed guards.
<li>Automatic 404 errors (Not Found) on unmatched path patterns.
<li>Automatic 405 errors (Method Not Implemented) on unimplemented methods.
<li>Automatic 406 errors (Not Acceptable) when no matching serializer was found to handle the
<l>Accept</l> header.
<li>Automatic 412 errors (Precondition Failed) when all matchers failed to match.
<li>Automatic 415 errors (Unsupported Media Type) when no matching parser was found was found to handle
the <l>Content-Type</l> header.
<li>Automatic 500 errors on uncaught exceptions.
</ul>
<li>
Self-documenting Swagger-based REST interfaces.
<li>
Various useful debugging features that make debugging using a browser extremely simple...
<ul>
<li>Ability to pass HTTP header values as URL GET parameters (e.g. <l>&amp;Accept=text/xml</l>).
<li>Ability to pass HTTP content on PUT/POST requests as a URL GET parameter
(e.g. <l>&amp;content={foo:"bar"}</l>).
<li>Ability to simulate non-GET requests using a <l>&amp;method</l> GET parameter
(e.g. <l>&amp;method=POST</l>).
<li>Ability to force <js>"text/plain"</js> on response using GET parameter <l>&amp;plainText=true</l>.
</ul>
<li>
Ability to implement overloaded HTTP methods through the use of the <l>&amp;method</l> attribute
(e.g. <l>&amp;method=FOO</l>).
<li>
Ability to match URL patterns (e.g. <l>/foo/{fooId}/bar/{barId}</l>) against URLs
(e.g. <l>/foo/123/bar/456/bing</l>).
<li>
Ability to associate guards at the resource or method levels through annotations.
<br>Typically useful for security, but can be used for a variety of purposes.
<li>
Ability to associate converters at the resource or method levels through annotations.
<br>Typically useful for performing conversions on input and output, such as for supporting older input and
output formats.
</ul>
<p>
Many of the examples in this document are pulled directly from <l>juneau-examples-rest</l>.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.HelloWorldExample"></a>
<h3 class='topic' onclick='toggle(this)'>7.1 - Hello World Example</h3>
<div class='topic'>
<p>
A REST resource is simply a Java class annotated with {@link org.apache.juneau.rest.annotation.RestResource}.
<br>The most common case is a class that extends {@link org.apache.juneau.rest.RestServlet}, which itself is simply an
extension of {@link javax.servlet.http.HttpServlet} which allows it to be deployed as a servlet.
</p>
<p>
In this example, we define a resource called <l>HelloWorldResource</l>.
<br>This example is located in the <l>juneau-examples-rest</l> project.
<br>It's assumed the reader is familiar with defining servlets in web applications.
</p>
<p>
Like any servlet, we could define our resource in the <l>web.xml</l> file of the web application like so...
</p>
<p class='bcode'>
<xt>&lt;?xml</xt> <xa>version</xa>=<xs>"1.0"</xs> <xa>encoding</xa>=<xs>"UTF-8"</xs><xt>?&gt;</xt>
<xt>&lt;web-app</xt> <xa>version</xa>=<xs>"2.3"</xs><xt>&gt;</xt>
<xt>&lt;servlet&gt;</xt>
<xt>&lt;servlet-name&gt;</xt>HelloWorldResource<xt>&lt;/servlet-name&gt;</xt>
<xt>&lt;servlet-class&gt;</xt>com.foo.sample.HelloWorldResource<xt>&lt;/servlet-class&gt;</xt>
<xt>&lt;/servlet&gt;</xt>
<xt>&lt;servlet-mapping&gt;</xt>
<xt>&lt;servlet-name&gt;</xt>HelloWorldResource<xt>&lt;/servlet-name&gt;</xt>
<xt>&lt;url-pattern&gt;</xt>/*<xt>&lt;/url-pattern&gt;</xt>
<xt>&lt;/servlet-mapping&gt;</xt>
<xt>&lt;/web-app&gt;</xt>
</p>
<p>
Our servlet code is shown below:
</p>
<p class='bcode'>
<jd>/**
* Sample REST resource that prints out a simple "Hello world!" message.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/helloWorld"</js>,
title=<js>"Hello World"</js>,
description=<js>"An example of the simplest-possible resource"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
},
aside={
<js>"&lt;div style='max-width:400px' class='text'&gt;"</js>,
<js>" &lt;p&gt;This page shows a resource that simply response with a 'Hello world!' message&lt;/p&gt;"</js>,
<js>" &lt;p&gt;The POJO serialized is a simple String.&lt;/p&gt;"</js>,
<js>"&lt;/div&gt;"</js>
}
)
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> RestServletDefault {
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>, summary=<js>"Responds with \"Hello world!\""</js>)
<jk>public</jk> String sayHello() {
<jk>return</jk> <js>"Hello world!"</js>;
}
}
</p>
<p>
This is what it looks like in a browser:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.HelloWorldExample.1.png' style='width:800px'>
<p>
It doesn't much simpler than that.
<br>In this case, we're simply returning a string that will be converted to any of the supported languages (e.g.
JSON, XML, HTML, ...).
<br>However, we could have returned any POJO consisting of beans, maps, collections, etc...
</p>
<p>
The {@link org.apache.juneau.rest.RestServletDefault} class that we're using here is a subclass of
{@link org.apache.juneau.rest.RestServlet} that provides default support for a variety of content types.
<br>Implementers can choose to use this class, or create their own subclass of
{@link org.apache.juneau.rest.RestServlet} with their own specialized serializers and parsers.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.ClassHierarchy"></a>
<h3 class='topic' onclick='toggle(this)'>7.2 - Class Hierarchy</h3>
<div class='topic'>
<p>
The class hierarchy for the REST servlet class is shown below:
</p>
<ul class='doctree'>
<li class='jac'>
{@link javax.servlet.http.HttpServlet javax.servlet.http.HttpServlet}
<ul>
<li class='jac'>
{@link org.apache.juneau.rest.RestServlet org.apache.juneau.rest.RestServlet}
<br>Contains all the main logic.
<ul>
<li class='jac'>{@link org.apache.juneau.rest.RestServletDefault org.apache.juneau.rest.RestServletDefault}
<br>Provides a default set of serializers, parsers, options page, stylesheet, and other common settings.
<br><b>Developers will typically subclass this when creating REST resources in JEE environments.</b>
<ul>
<li class='jac'>{@link org.apache.juneau.microservice.Resource org.apache.juneau.microservice.Resource}
<br>Identical to <l>RestServletDefault</l> but provides support for <code>$ARGS</code> and <code>$MF</code> variables.
<br><b>Developers will typically subclass this when creating microservices.</b>
<li class='jac'>{@link org.apache.juneau.rest.RestServletGroupDefault org.apache.juneau.rest.RestServletGroupDefault}
<br>A default implementation for "router" pages.
<ul>
<li class='jac'>{@link org.apache.juneau.microservice.ResourceGroup org.apache.juneau.microservice.ResourceGroup}
<br>Identical to <l>RestServletGroupDefault</l> but provides support for <code>$ARGS</code> and <code>$MF</code> variables.
<br><b>Developers will typically subclass this when creating microservice groups.</b>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>
The servlets with RDF support require Jena on the classpath.
<br>All other serializers and parsers do not have any external library dependencies.
<br>For this reason, we have separate servlets for supporting RDF so that you don't need Jena if you don't need to
support RDF.
</p>
<p>
Everything is configured through the following classes which you will see a lot:
</p>
<ul>
<li class='jc'>{@link org.apache.juneau.rest.RestContext} - Each resource class instance has one copy that holds all of its configuration.
<li class='jc'>{@link org.apache.juneau.rest.RestContextBuilder} - Builder for the class above.
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Instantiation"></a>
<h3 class='topic' onclick='toggle(this)'>7.3 - Instantiation</h3>
<div class='topic'>
<p>
REST resources are deployed in one of two ways:
</p>
<ul>
<li>Deployed in a J2EE container as a servlet.
<li>Deployed as a child of another REST resource.
</ul>
<p>
When deployed in a J2EE container, you MUST extend from one of the servlet classes.
<br>When deployed as a child of another resource, you MAY extend from one of the servlet classes but it's
not necessary.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestServlet"></a>
<h4 class='topic' onclick='toggle(this)'>7.3.1 - RestServlet</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestServlet} class is the entry point for your REST resources.
<br>It extends directly from <l>HttpServlet</l> and is deployed like any other servlet.
</p>
<p>
When the servlet <l>init()</l> method is called, it triggers the code to find and process the <l>@RestResource</l>
annotations on that class and all child classes.
<br>These get constructed into a {@link org.apache.juneau.rest.RestContext} object that holds all the configuration
information about your resource in a read-only object.
</p>
<p>
Most developers are not going to be using the <l>RestServlet</l> class itself, and instead will
extend from one of the preconfigured default servlets such as {@link org.apache.juneau.rest.RestServletDefault}.
<br>The <l>RestServlet</l> class by itself is not configured with any serializers and parsers, and therefore
not very useful on it's own.
<br>However, the class does provide a couple of convenience methods to be aware of:
</p>
<ul class='doctree'>
<li class='jac'><code>{@link org.apache.juneau.rest.RestServlet} <jk>extends</jk> HttpServlet</code>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestServlet#log(Level,String,Object...) log(Level,String,Object...)}
<li class='jf'>{@link org.apache.juneau.rest.RestServlet#log(Level,Throwable,String,Object...) log(Level,Throwable,String,Object...)}
<li class='jf'>{@link org.apache.juneau.rest.RestServlet#getContext() getContext()}
</ul>
</ul>
<p>
Since this is a servlet, you also have the ability to intercept calls to the <l>init</l> and <l>service</l> methods
in your subclass.
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestServletDefault"></a>
<h4 class='topic' onclick='toggle(this)'>7.3.2 - RestServletDefault</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestServletDefault} class is a subclass of {@link org.apache.juneau.rest.RestServlet}
preconfigured with the following:
</p>
<ul class='spaced-list'>
<li>A default set of serializers and parsers (pretty much all of them except for the RDF ones).
<li>Some basic HTML boilerplate for the HTML representation of your POJOs.
<li>Support for auto-generated Swagger documentation through OPTIONS page requests.
<li>Configuration of default CSS stylesheets.
</ul>
<p>
The entirety of the class is shown below.
<br>You should notice that very little code is being used and everything is configurable through
annotations:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
serializers={
HtmlDocSerializer.<jk>class</jk>,
HtmlStrippedDocSerializer.<jk>class</jk>,
HtmlSchemaDocSerializer.<jk>class</jk>,
JsonSerializer.<jk>class</jk>,
JsonSerializer.Simple.<jk>class</jk>,
JsonSchemaSerializer.<jk>class</jk>,
XmlDocSerializer.<jk>class</jk>,
XmlSchemaDocSerializer.<jk>class</jk>,
UonSerializer.<jk>class</jk>,
UrlEncodingSerializer.<jk>class</jk>,
MsgPackSerializer.<jk>class</jk>,
SoapXmlSerializer.<jk>class</jk>,
PlainTextSerializer.<jk>class</jk>
},
parsers={
JsonParser.<jk>class</jk>,
XmlParser.<jk>class</jk>,
HtmlParser.<jk>class</jk>,
UonParser.<jk>class</jk>,
UrlEncodingParser.<jk>class</jk>,
MsgPackParser<jk>.class</jk>,
PlainTextParser.<jk>class</jk>
},
properties={
<jc>// URI-resolution is disabled by default. Need to enable it.</jc>
<ja>@Property</ja>(name=<jsf>SERIALIZER_uriResolution</jsf>, value=<js>"ROOT_RELATIVE"</js>)
},
allowedMethodParams=<js>"OPTIONS"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
header={
<js>"&lt;h1&gt;$R{resourceTitle}&lt;/h1&gt;"</js>,
<js>"&lt;h2&gt;$R{methodSummary,resourceDescription}&lt;/h2&gt;"</js>,
<js>"&lt;a href='http://juneau.apache.org'&gt;&lt;img src='$U{servlet:/htdocs/juneau.png}' style='position:absolute;top:5;right:5;background-color:transparent;height:30px'/&gt;&lt;/a&gt;"</js>
},
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
},
stylesheet=<js>"servlet:/styles/light.css"</js>,
head={
<js>"&lt;link rel='icon' href='$U{servlet:/htdocs/juneau.png}'/&gt;"</js>
}
),
<jc>// Optional external configuration file.</jc>
config=<js>"$S{juneau.configFile}"</js>,
<jc>// These are static files that are served up by the servlet under the specified sub-paths.
// For example, "/servletPath/htdocs/javadoc.css" resolves to the file "[servlet-package]/htdocs/javadoc.css"</jc>
staticFiles={<js>"htdocs:htdocs"</js>,<js>"styles:styles"</js>}
)
<jk>public abstract class</jk> RestServletDefault <jk>extends</jk> RestServlet {
<jd>/**
* [OPTIONS /*] - Show resource options.
*
* @param req The HTTP request.
* @return A bean containing the contents for the OPTIONS page.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>OPTIONS</jsf>, path=<js>"/*"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"back: servlet:/"</js>,
<js>"json: servlet:/?method=OPTIONS&amp;Accept=text/json&amp;plainText=true"</js>
},
aside=<js>"NONE"</js>
),
summary=<js>"Swagger documentation",</js>
description=<js>"Auto-generated swagger documentation for this resource"</js>
)
<jk>public</jk> Swagger getOptions(RestRequest req) {
<jk>return</jk> req.getSwagger();
}
}
</p>
<p>
Your top-level resource will simply extend from this class, as shown in the Hello World example
from a couple sections back.
</p>
<p>
There's a lot going on in this class.
<br>But not to worry, the details will be described later.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Children"></a>
<h4 class='topic' onclick='toggle(this)'>7.3.3 - Children</h4>
<div class='topic'>
<p>
Child Resources are REST servlets or objects that are linked to parent resources through the
{@link org.apache.juneau.rest.annotation.RestResource#children() @RestResource.children()} annotation.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jd>/** Parent Resource */</jd>
<ja>@RestResource</ja>(
path=<js>"/parent"</js>,
children={FooResource.<jk>class</jk>}
)
<jk>public</jk> MyResource <jk>extends</jk> RestServletDefault {...}
</p>
<p class='bcode'>
<jd>/** Child Resource */</jd>
<ja>@RestResource</ja>(
path=<js>"/foo"</js> <jc>// Path relative to parent resource.</jc>
)
<jk>public</jk> FooResource {...} <jc>// Note that we don't need to extend from RestServlet.</jc>
</p>
<p>
The path of the child resource gets appended to the path of the parent resource.
<br>So in the example above, the child resource is accessed through the URL <l>/parent/foo</l>.
</p>
<p>
A HUGE advantage of using child resources is that they do not need to be declared in the JEE <l>web.xml</l>
file.
<br>Initialization of and access to the child resources occurs through the parent resource.
<br>Children can be nested arbitrary deep to create complex REST interfaces with a single top-level REST servlet.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_children}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RouterPages"></a>
<h4 class='topic' onclick='toggle(this)'>7.3.4 - Router Pages</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestServletGroupDefault} class provides a default "router" page for
child resources when a parent resource is nothing more than a grouping of child resources.
</p>
<p>
The <l>RootResources</l> class in the Samples project is an example of a router page:
</p>
<p class='bcode'>
<jd>/**
* Sample REST resource showing how to implement a "router" resource page.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/"</js>,
title=<js>"Root resources"</js>,
description=<js>"Example of a router resource page."</js>,
children={
HelloWorldResource.<jk>class</jk>,
MethodExampleResource.<jk>class</jk>,
RequestEchoResource.<jk>class</jk>,
TempDirResource.<jk>class</jk>,
AddressBookResource.<jk>class</jk>,
SampleRemoteableServlet.<jk>class</jk>,
PhotosResource.<jk>class</jk>,
AtomFeedResource.<jk>class</jk>,
JsonSchemaResource.<jk>class</jk>,
SqlQueryResource.<jk>class</jk>,
TumblrParserResource.<jk>class</jk>,
CodeFormatterResource.<jk>class</jk>,
UrlEncodedFormResource.<jk>class</jk>,
SourceResource.<jk>class</jk>,
ConfigResource.<jk>class</jk>,
LogsResource.<jk>class</jk>,
DockerRegistryResource.<jk>class</jk>,
ShutdownResource.<jk>class</jk>
}
)
<jk>public class</jk> RootResources <jk>extends</jk> RestServletGroupDefault {
<jc>// NO CODE!!!</jc>
}
</p>
<p>
When you bring up this resource in a browser, you see the following that provides a list
of navigable links to your child resources:
</p>
<img class='bordered' src="doc-files/juneau-rest-server.RouterPages.1.png" style='width:800px;'/>
<p>
The {@link org.apache.juneau.rest.RestServletGroupDefault} class is nothing more than a subclass of
{@link org.apache.juneau.rest.RestServletDefault} with a <l>getChildren()</l> method mapped to the servlet
root path.
<br>The method returns a POJO with is just a linked-list of beans with name/description properties.
</p>
<p class='bcode'>
<jk>public class</jk> RestServletGroupDefault <jk>extends</jk> RestServletDefault {
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>, description=<js>"Child resources"</js>)
<jk>public</jk> ChildResourceDescriptions getChildren(RestRequest req) {
<jk>return new</jk> ChildResourceDescriptions(<jk>this</jk>, req);
}
}
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.ResourceResolvers"></a>
<h4 class='topic' onclick='toggle(this)'>7.3.5 - Resource Resolvers</h4>
<div class='topic'>
<p>
By default, you can add the {@link org.apache.juneau.rest.annotation.RestResource @RestResource}
to any class as long as it has one of the following constructors:
</p>
<ul>
<li><code><jk>public</jk> T(RestContextBuilder)</code>
<li><code><jk>public</jk> T()</code>
</ul>
<p>
The former constructor can be used to get access to the {@link org.apache.juneau.rest.RestContextBuilder} object to make
any configurations to the resource before it's initialized.
</p>
<p>
Resource object resolution is controlled through the following API:
</p>
<ul class='doctree'>
<li class='jic'>{@link org.apache.juneau.rest.RestResourceResolver}
<ul>
<li class='jc'>{@link org.apache.juneau.rest.RestResourceResolverDefault}
</ul>
</ul>
<p>
This API can be extended to provide your own custom resource resolution.
<br>Later topics discuss how to use this API to instantiate resources using Spring.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_resourceResolver}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.LifecycleHooks"></a>
<h4 class='topic' onclick='toggle(this)'>7.3.6 - Lifecycle Hooks</h4>
<div class='topic'>
<p>
Lifecycle hooks allow you to hook into lifecycle events of the servlet/resource creation and REST calls.
</p>
<p>
For example, if you want to add an initialization method to your resource:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(...)
<jk>public class</jk> MyResource {
<jc>// Our database.</jc>
<jk>private</jk> Map&lt;Integer,Object&gt; <jf>myDatabase</jf>;
<ja>@RestHook</ja>(<jsf>INIT</jsf>)
<jk>public void</jk> initMyDatabase(RestContextBuilder builder) <jk>throws</jk> Exception {
<jf>myDatabase</jf> = <jk>new</jk> LinkedHashMap&lt;&gt;();
}
}
</p>
<p>
Or if you want to intercept REST calls:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(...)
<jk>public class</jk> MyResource {
<jc>// Add a request attribute to all incoming requests.</jc>
<ja>@RestHook</ja>(<jsf>PRE_CALL</jsf>)
<jk>public void</jk> onPreCall(RestRequest req) {
req.setAttribute(<js>"foo"</js>, <js>"bar"</js>);
}
}
</p>
<p>
The hook events can be broken down into two categories:
</p>
<ul class='spaced-list'>
<li>Resource lifecycle events:
<ul>
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#INIT INIT} - Right before initialization.
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#POST_INIT POST_INIT} - Right after initialization.
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#POST_INIT_CHILD_FIRST POST_INIT_CHILD_FIRST} - Right after initialization, but run child methods first.
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#DESTROY DESTROY} - Right before servlet destroy.
</ul>
<li>REST call lifecycle events:
<ul>
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#START_CALL START_CALL} - At the beginning of a REST call.
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#PRE_CALL PRE_CALL} - Right before the <ja>@RestMethod</ja> method is invoked.
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#POST_CALL POST_CALL} - Right after the <ja>@RestMethod</ja> method is invoked.
<li class='jf'>{@link org.apache.juneau.rest.annotation.HookEvent#END_CALL END_CALL} - At the end of the REST call after the response has been flushed.
</ul>
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestHook}
</ul>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestResource"></a>
<h3 class='topic' onclick='toggle(this)'>7.4 - @RestResource</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.RestResource @RestResource} annotation is the primary way of defining
and configuring REST resource classes.
<br>The functionality of the class itself is covered in detail in the topics below.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.AnnotationInheritance"></a>
<h4 class='topic' onclick='toggle(this)'>7.4.1 - Annotation Inheritance</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.RestResource @RestResource} annotation can also be used on parents and interfaces of resource classes.
<br>When multiple annotations are defined at different levels, the annotation values are combined.
</p>
<p>
This is a particularly useful feature because it allows you to define your own configured parent
resource classes that can be extended by all your child resources so that they all share common
settings.
</p>
<table class='styled' style='max-width: 800px;'>
<tr>
<th><l>Annotation</l></th>
<th><l>Inheritence Rules</l></th>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#guards() guards()}</td>
<td>
Guards on child are combined with those on parent class.
<br>Guards are executed child-to-parent in the order they appear in the annotation.
<br>Guards on methods are executed before those on classes.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#converters() converters()}</td>
<td>
Converters on child are combined with those on parent class.
<br>Converters are executed child-to-parent in the order they appear in the annotation.
<br>Converters on methods are executed before those on classes.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#beanFilters() beanFilters()}</td>
<td>
Bean filters on child are combined with those on parent class.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#pojoSwaps() pojoSwaps()}</td>
<td>
POJO swaps on child are combined with those on parent class.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#properties() properties()}</td>
<td>
Properties on child are combined with those on parent class.
<br>Properties are applied parent-to-child in the order they appear in the annotation.
<br>Properties on methods take precedence over those on classes.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#serializers() serializers()}</td>
<td>
Serializers on child are combined with those on parent class.
<br>Serializers on methods take precedence over those on classes.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#parsers() parsers()}</td>
<td>
Parsers on child are combined with those on parent class.
<br>Parsers on methods take precedence over those on classes.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#responseHandlers() responseHandlers()}</td>
<td>
Response handlers on child are combined with those on parent class.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#encoders() encoders()}</td>
<td>
Encoders on child are combined with those on parent class.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#defaultRequestHeaders() defaultRequestHeaders()}</td>
<td>
Headers on child are combined with those on parent class.
<br>Headers are applied parent-to-child in the order they appear in the annotation.
<br>Headers on methods take precedence over those on classes.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#defaultResponseHeaders() defaultResponseHeaders()}</td>
<td>
Headers on child are combined with those on parent class.
<br>Headers are applied parent-to-child in the order they appear in the annotation.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#children() children()}</td>
<td>
Children on child are combined with those on parent class.
<br>Children are list parent-to-child in the order they appear in the annotation.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#path() path()}</td>
<td>
Path is searched for in child-to-parent order.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#title() title()}</td>
<td>
Label is searched for in child-to-parent order.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#description() description()}</td>
<td>
Description is searched for in child-to-parent order.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#config() config()}</td>
<td>
Config file is searched for in child-to-parent order.
</td>
</tr>
<tr>
<td>{@link org.apache.juneau.rest.annotation.RestResource#staticFiles() staticFiles()}</td>
<td>
Static files on child are combined with those on parent class.
<br>Static files are are executed child-to-parent in the order they appear in the annotation.
</td>
</tr>
</table>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestContext"></a>
<h3 class='topic' onclick='toggle(this)'>7.5 - RestContext</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestContext} object is the workhorse class for all of the configuration
of a single REST resource class.
<br>It's by-far the most important class in the REST API.
</p>
<p>
Every class annotated with <l>@RestResource</l> ends up with an instance of this object.
<br>The object itself is read-only and unchangeable.
<br>It is populated through the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource} - Settings copied from the annotation during servlet initialization.
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder} - Builder used during servlet initialization.
</ul>
<p>
The annotation should be self-explanatory at this point.
<br>The builder allows you to perform all of the same configuration as the annotation programmatically.
</p>
<p>
The {@link org.apache.juneau.rest.RestContextBuilder} class extends {@link org.apache.juneau.BeanContextBuilder}
allowing you to programmatically set any properties defined on that builder class.
<br>It also implements {@link javax.servlet.ServletConfig}
</p>
<p>
To access this object, simply pass it in as a constructor argument or in an INIT hook:
</p>
<p class='bcode'>
<jc>// Option #1 - Pass in through constructor.</jc>
<jk>public</jk> MyResource(RestContextBuilder builder) {
builder
.pojoSwaps(CalendarSwap.<jsf>RFC2822DTZ</jsf>.<jk>class</jk>)
.set(<jsf>PARSER_debug</jsf>, <jk>true</jk>);
}
<jc>// Option #2 - Use an INIT hook.</jc>
<ja>@RestHook</ja>(<jsf>INIT</jsf>)
<jk>public void</jk> init(RestContextBuilder builder) <jk>throws</jk> Exception {
builder
.pojoSwaps(CalendarSwap.<jsf>RFC2822DTZ</jsf>.<jk>class</jk>)
.set(<jsf>PARSER_debug</jsf>, <jk>true</jk>);
}
</p>
<p>
Warning: This class is huge.
<br>Through it, you can configure bean/serializer/parser settings, define config files, children,
resource finders, info providers, etc...
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestMethod"></a>
<h3 class='topic' onclick='toggle(this)'>7.6 - @RestMethod</h3>
<div class='topic'>
<p>
REST Java methods are identified on REST servlets using the
{@link org.apache.juneau.rest.annotation.RestMethod @RestMethod} annotation.
<br>The annotation allows the framework to identify the available REST methods through reflection.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> String sayHello() {
<jk>return</jk> <js>"Hello world!"</js>;
}
</p>
<p>
There are no restrictions on the name of the Java method.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.MethodParameters"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.1 - Java Method Parameters</h4>
<div class='topic'>
<p>
Java methods can contain any of the following parameters in any order:
</p>
<ul class='spaced-list'>
<li>
<b>Parameters based on class types:</b>
<ul>
<li><b>Request/response objects:</b>
<ul>
<li class='jc'>{@link org.apache.juneau.rest.RestRequest} - The request object.
<li class='jc'>{@link javax.servlet.http.HttpServletRequest} - The superclass of <code>RestRequest</code>.
<li class='jc'>{@link org.apache.juneau.rest.RestResponse} - The response object.
<li class='jc'>{@link javax.servlet.http.HttpServletResponse} - The superclass of <code>RestResponse</code>.
</ul>
<li><b>Parsed request header values:</b>
<ul>
<li class='jc'>{@link org.apache.juneau.http.Accept}
<li class='jc'>{@link org.apache.juneau.http.AcceptCharset}
<li class='jc'>{@link org.apache.juneau.http.AcceptEncoding}
<li class='jc'>{@link org.apache.juneau.http.AcceptLanguage}
<li class='jc'>{@link org.apache.juneau.http.Authorization}
<li class='jc'>{@link org.apache.juneau.http.CacheControl}
<li class='jc'>{@link org.apache.juneau.http.Connection}
<li class='jc'>{@link org.apache.juneau.http.ContentLength}
<li class='jc'>{@link org.apache.juneau.http.ContentType}
<li class='jc'>{@link org.apache.juneau.http.Date}
<li class='jc'>{@link org.apache.juneau.http.Expect}
<li class='jc'>{@link org.apache.juneau.http.From}
<li class='jc'>{@link org.apache.juneau.http.Host}
<li class='jc'>{@link org.apache.juneau.http.IfMatch}
<li class='jc'>{@link org.apache.juneau.http.IfModifiedSince}
<li class='jc'>{@link org.apache.juneau.http.IfNoneMatch}
<li class='jc'>{@link org.apache.juneau.http.IfRange}
<li class='jc'>{@link org.apache.juneau.http.IfUnmodifiedSince}
<li class='jc'>{@link org.apache.juneau.http.MaxForwards}
<li class='jc'>{@link org.apache.juneau.http.Pragma}
<li class='jc'>{@link org.apache.juneau.http.ProxyAuthorization}
<li class='jc'>{@link org.apache.juneau.http.Range}
<li class='jc'>{@link org.apache.juneau.http.Referer}
<li class='jc'>{@link org.apache.juneau.http.TE}
<li class='jc'>{@link org.apache.juneau.http.UserAgent}
<li class='jc'>{@link org.apache.juneau.http.Upgrade}
<li class='jc'>{@link org.apache.juneau.http.Via}
<li class='jc'>{@link org.apache.juneau.http.Warning}
<li class='jc'>{@link java.util.TimeZone}
</ul>
<li><b>Direct streams on request/response:</b>
<ul>
<li class='jc'>{@link java.io.InputStream}
<li class='jc'>{@link javax.servlet.ServletInputStream}
<li class='jc'>{@link java.io.Reader}
<li class='jc'>{@link java.io.OutputStream}
<li class='jc'>{@link javax.servlet.ServletOutputStream}
<li class='jc'>{@link java.io.Writer}
</ul>
<li><b>Localization:</b>
<ul>
<li class='jc'>{@link java.util.ResourceBundle} - Client-localized resource bundle.
<li class='jc'>{@link org.apache.juneau.utils.MessageBundle} - A resource bundle with additional features.
<li class='jc'>{@link java.util.Locale} - Client locale.
</ul>
<li><b>Request APIs:</b>
<ul>
<li class='jc'>{@link org.apache.juneau.rest.RequestHeaders} - API for accessing request headers.
<li class='jc'>{@link org.apache.juneau.rest.RequestQuery} - API for accessing request query parameters.
<li class='jc'>{@link org.apache.juneau.rest.RequestFormData} - API for accessing request form data.
<li class='jc'>{@link org.apache.juneau.rest.RequestPathMatch} - API for accessing path variables.
<li class='jc'>{@link org.apache.juneau.rest.RequestBody} - API for accessing request body.
</ul>
<li><b>Other:</b>
<ul>
<li class='jc'>{@link org.apache.juneau.http.HttpMethod} - The method name matched (when using <code><ja>@RestMethod</ja>(name=<js>"*"</js>)</code>)
<li class='jc'>{@link org.apache.juneau.rest.RestLogger} - Logger with additional features.
<li class='jc'>{@link org.apache.juneau.rest.RestContext} - The resource read-only context.
<li class='jc'>{@link org.apache.juneau.parser.Parser} - The parser matching the request content type.
<li class='jc'>{@link org.apache.juneau.dto.swagger.Swagger} - The auto-generated Swagger doc.
<li class='jc'>{@link org.apache.juneau.config.Config} - The external config for the resource.
<li class='jc'>{@link org.apache.juneau.rest.RequestProperties} - API for modifying request-time configuration properties.
</ul>
</ul>
<li><b>Annotated parameters:</b>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.Path} - Variables in matched URL path patterns.
<li class='ja'>{@link org.apache.juneau.rest.annotation.FormData} - Multipart form post parameter values.
<li class='ja'>{@link org.apache.juneau.rest.annotation.HasFormData} - Denotes whether the form data parameter exists.
<li class='ja'>{@link org.apache.juneau.rest.annotation.Query} - Query parameters. Using this prevents the HTTP body from being processed as a URL-Encoded form post.
<li class='ja'>{@link org.apache.juneau.rest.annotation.HasQuery} - Denotes whether the query parameter exists.
<li class='ja'>{@link org.apache.juneau.rest.annotation.Header} - A header value.
<li class='ja'>{@link org.apache.juneau.rest.annotation.Method} - The HTTP method name.
<li class='ja'>{@link org.apache.juneau.rest.annotation.PathRemainder} - The remainder value after path pattern match.
<li class='ja'>{@link org.apache.juneau.rest.annotation.Body} - The HTTP content parsed as a POJO.
</ul>
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example1/{a1}/{a2}/{a3}/*"</js>)
<jk>public</jk> String doGetExample1(
RestRequest req,
RestResponse res,
<ja>@Method</ja> String method,
<ja>@Path</ja> String a1,
<ja>@Path</ja> <jk>int</jk> a2,
<ja>@Path</ja> UUID a3,
<ja>@Query</ja>(<js>"p1"</js>) <jk>int</jk> p1,
<ja>@Query</ja>(<js>"p2"</js>) String p2,
<ja>@Query</ja>(<js>"p3"</js>) UUID p3,
<ja>@HasQuery</ja>(<js>"p3"</js>) boolean hasP3,
<ja>@PathRemainder</ja> String remainder,
<ja>@Header</ja>(<js>"Accept-Language"</js>) String lang,
<ja>@Header</ja>(<js>"Accept"</js>) String accept,
<ja>@Header</ja>(<js>"DNT"</js>) <jk>int</jk> doNotTrack,
RequestProperties properties,
ResourceBundle nls
) {
<jc>// Do something with all of those</jc>
}
</p>
<h5 class='section'>Notes:</h5>
<ul>
<li>All annotations have programmatic equivalents on the {@link org.apache.juneau.rest.RestRequest} class.
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_paramResolvers} - For configuring custom parameter types.
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestRequest"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.2 - RestRequest</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestRequest} object is an extension of the <l>HttpServletRequest</l> class
with various built-in convenience methods for use in building REST interfaces.
<br>It can be accessed by passing it as a parameter on your REST Java method:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RestRequest req) {...}
</p>
<p>
There are many useful methods on this object, but the main ones are shown below:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RestRequest} <jk>extends</jk> HttpServletRequest</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getHeaders() getHeaders()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getQuery() getQuery()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getFormData() getFormData()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getBody() getBody()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getPathMatch() getPathMatch()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getLogger() getLogger()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getInfoProvider() getInfoProvider()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getSwagger() getSwagger()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getConfig() getConfig()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getVarResolverSession() getVarResolverSession()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getMessageBundle() getMessageBundle()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getProperties() getProperties()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String,boolean,MediaType) getClasspathReaderResource(String,boolean,MediaType)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestResponse"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.3 - RestResponse</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestResponse} object is an extension of the <l>HttpServletResponse</l> class
with various built-in convenience methods for use in building REST interfaces.
<br>It can be accessed by passing it as a parameter on your REST Java method:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RestResponse req) {...}
</p>
<p>
The important methods on this class are shown below:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RestResponse} <jk>extends</jk> HttpServletResponse</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestResponse#setOutput(Object) setOutput(Object)}
<li class='jm'>{@link org.apache.juneau.rest.RestResponse#getProperties() getProperties()}
<li class='jm'>{@link org.apache.juneau.rest.RestResponse#getHtmlDocBuilder() getHtmlDocBuilder()}
<li class='jm'>{@link org.apache.juneau.rest.RestResponse#getDirectWriter(String) getDirectWriter(String)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RequestBody"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.4 - RequestBody</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RequestBody} object is the API for accessing the body of an HTTP request.
<br>It can be accessed by passing it as a parameter on your REST Java method:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestBody body) {...}
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public void</jk> doPost(RequestBody body) {
<jc>// Convert body to a linked list of Person objects.</jc>
List&lt;Person&gt; l = body.asType(LinkedList.<jk>class</jk>, Person.<jk>class</jk>);
...
}
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.rest.RequestBody}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#getReader() getReader()}
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#getInputStream() getInputStream()}
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#asType(Class) asType(Class)}
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#asType(Type,Type...) asType(Type,Type...)}
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#asString() asString()}
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#asHex() asHex()}
<li class='jm'>{@link org.apache.juneau.rest.RequestBody#asSpacedHex() asSpacedHex()}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RequestHeaders"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.5 - RequestHeaders</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RequestHeaders} object is the API for accessing the headers of an HTTP request.
<br>It can be accessed by passing it as a parameter on your REST Java method:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestHeaders headers) {...}
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestHeaders headers) {
<jc>// Add a default value.</jc>
headers.addDefault(<js>"ETag"</js>, <jsf>DEFAULT_UUID</jsf>);
<jc>// Get a header value as a POJO.</jc>
UUID etag = headers.get(<js>"ETag"</js>, UUID.<jk>class</jk>);
<jc>// Get a standard header.</jc>
CacheControl = headers.getCacheControl();
}
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RequestHeaders} <jk>extends</jk> TreeMap&lt;String,String[]&gt;</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RequestHeaders#get(String,Class) get(String,Class)}
<li class='jm'>{@link org.apache.juneau.rest.RequestHeaders#get(String,Type,Type...) get(String,Type,Type)}
<li class='jm'>{@link org.apache.juneau.rest.RequestHeaders#getString(String,String) getString(String,String)}
<li class='jm'>{@link org.apache.juneau.rest.RequestHeaders#getInt(String,int) getInt(String,int)}
<li class='jm'>{@link org.apache.juneau.rest.RequestHeaders#getBoolean(String,boolean) getBoolean(String,boolean)}
<li class='jm'>{@link org.apache.juneau.rest.RequestHeaders#addDefault(String,Object) addDefault(String,Object)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RequestQuery"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.6 - RequestQuery</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RequestQuery} object is the API for accessing the GET query parameters of an HTTP request.
<br>It can be accessed by passing it as a parameter on your REST Java method:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestQuery query) {...}
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestQuery query) {
<jc>// Get query parameters converted to various types.</jc>
<jk>int</jk> p1 = query.get(<js>"p1"</js>, 0, <jk>int</jk>.<jk>class</jk>);
String p2 = query.get(<js>"p2"</js>, String.<jk>class</jk>);
UUID p3 = query.get(<js>"p3"</js>, UUID.<jk>class</jk>);
}
</p>
<p>
An important distinction between the behavior of this object and <l>HttpServletRequest.getParameter(String)</l> is
that the former will NOT load the body of the request on FORM POSTS and will only look at parameters
found in the query string.
<br>This can be useful in cases where you're mixing GET parameters and FORM POSTS and you don't want to
inadvertantly read the body of the request to get a query parameter.
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RequestQuery} <jk>extends</jk> LinkedHashMap&lt;String,String[]&gt;</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#get(String,Class) get(String,Class)}
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#get(String,Type,Type...) get(String,Type,Type)}
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#getString(String,String) getString(String,String)}
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#getInt(String,int) getInt(String,int)}
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#getBoolean(String,boolean) getBoolean(String,boolean)}
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#addDefault(String,Object) addDefault(String,Object)}
<li class='jm'>{@link org.apache.juneau.rest.RequestQuery#getSearchArgs() getSearchArgs()}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RequestFormData"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.7 - RequestFormData</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RequestFormData} object is the API for accessing the HTTP request body as form data.
<br>It can be accessed by passing it as a parameter on your REST Java method:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestFormData query) {...}
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestFormData formData) {
<jc>// Get query parameters converted to various types.</jc>
<jk>int</jk> p1 = formData.get(<js>"p1"</js>, 0, <jk>int</jk>.<jk>class</jk>);
String p2 = formData.get(<js>"p2"</js>, String.<jk>class</jk>);
UUID p3 = formData.get(<js>"p3"</js>, UUID.<jk>class</jk>);
}
</p>
<p>
Note that this object does NOT take GET parameters into account and only returns values found in the body of the request.
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RequestFormData} <jk>extends</jk> LinkedHashMap&lt;String,String[]&gt;</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RequestFormData#get(String,Class) get(String,Class)}
<li class='jm'>{@link org.apache.juneau.rest.RequestFormData#get(String,Type,Type...) get(String,Type,Type)}
<li class='jm'>{@link org.apache.juneau.rest.RequestFormData#getString(String,String) getString(String,String)}
<li class='jm'>{@link org.apache.juneau.rest.RequestFormData#getInt(String,int) getInt(String,int)}
<li class='jm'>{@link org.apache.juneau.rest.RequestFormData#getBoolean(String,boolean) getBoolean(String,boolean)}
<li class='jm'>{@link org.apache.juneau.rest.RequestFormData#addDefault(String,Object) addDefault(String,Object)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestMethodPath"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.8 - @RestMethod.path()</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.RestMethod#path() @RestMethod.path()} annotation allows
you to define URL path patterns to match against.
<br>These patterns can contain variables of the form <l>"{xxx}"</l> that can be passed in directly to the
Java methods as extra parameters.
</p>
<p>
In the following example, 3 separate GET request handlers are defined with different path patterns.
<br>Note how the variables are passed in as additional arguments on the method, and how those arguments are
automatically converted to the specified class type...
</p>
<p class='bcode'>
<jc>// Default method</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>)
<jk>public void</jk> doGetDefault() {
...
}
<jc>// Method with path pattern</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/xxx"</js>)
<jk>public void</jk> doGetNoArgs(...) {
...
}
<jc>// Method with path pattern with arguments</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/xxx/{foo}/{bar}/{baz}/{bing}"</js>)
<jk>public void</jk> doGetWithArgs(<ja>@Path</ja> String foo, <ja>@Path</ja> <jk>int</jk> bar, <ja>@Path</ja> MyEnum baz, <ja>@Path</ja> UUID bing) {
...
}
</p>
<p>
By default, path patterns are matched using a best-match heuristic.
<br>When overlaps occur, URLs are matched from most-specific to most-general order:
</p>
<p class='bcode'>
<jc>// Try first </jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/foo/bar"</js>)
<jk>public void</jk> method1() {
...
}
<jc>// Try second</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/foo/{bar}"</js>)
<jk>public void</jk> method2(...) {
...
}
<jc>// Try third</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/foo/*"</js>)
<jk>public void</jk> method3(...) {
...
}
<jc>// Try last</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>)
<jk>public void</jk> method4(...) {
...
}
</p>
<p>
The match heuristic behavior can be overridden by the
{@link org.apache.juneau.rest.annotation.RestMethod#priority() @RestMethod.priority()} annotation
property.
<br>However, in practice this is almost never needed.
</p>
<p>
Paths that end with <js>"/*"</js> will do a prefix match on the incoming URL.
<br>Any remainder after the match can be accessed through
{@link org.apache.juneau.rest.RequestPathMatch#getRemainder()} or parameters with the
{@link org.apache.juneau.rest.annotation.PathRemainder @PathRemainder} annotation.
<br>On the other hand, paths that don't end with <js>"/*"</js> (e.g. <js>"/"</js> or <js>"/foo"</js>) will
require an exact URL match, and if any remainder exists, a 404 (not found) error will be thrown.
</p>
<p>
The following example shows the distinction.
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>)
<jk>public void</jk> doGet(<ja>@PathRemainder</ja> String remainder) {
<jc>// URL path pattern can have remainder accessible through req.getRemainder().</jc>
}
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/"</js>)
<jk>public void</jk> doPut() {
<jc>// URL path pattern must match exactly and will cause a 404 error if a remainder exists.</jc>
}
</p>
<p>
Annotations are provided for easy access to URL parameters with automatic conversion to any <a class='doclink' href='#juneau-marshall.PojoCategories'>parsable</a> type.
<br>For example, the following example can process the URL <l>"/urlWithParams?foo=foo&amp;bar=[1,2,3]&amp;baz=067e6162-3b6f-4ae2-a171-2470b63dff00"</l>...
</p>
<p class='bcode'>
<jc>// Example GET request with access to query parameters</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/urlWithParams"</js>)
<jk>public</jk> String doGetWithParams(<ja>@Query</ja>(<js>"foo"</js>) String foo, <ja>@Query</ja>(<js>"bar"</js>) <jk>int</jk> bar, <ja>@Query</ja>(<js>"baz"</js>) UUID baz) <jk>throws</jk> Exception {
<jk>return</jk> <js>"GET /urlWithParams?foo="</js>+foo+<js>"&amp;bar="</js>+bar+<js>"&amp;baz="</js>+baz;
}
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_path}
<li class='ja'>{@link org.apache.juneau.rest.annotation.Path}
<li class='ja'>{@link org.apache.juneau.rest.annotation.PathRemainder}
<li class='jc'>{@link org.apache.juneau.rest.RequestPathMatch}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RequestPathMatch"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.9 - RequestPathMatch</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RequestPathMatch} object is the API for accessing the matched variables
and remainder on the URL path.
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object myMethod(RequestPathMatch path) {...}
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(..., path=<js>"/{foo}/{bar}/{baz}/*"</js>)
<jk>public void</jk> doGet(RequestPathMatch path) {
<jc>// Example URL: /123/qux/true/quux</jc>
<jk>int</jk> foo = pm.getInt(<js>"foo"</js>); <jc>// =123</jc>
String bar = pm.getString(<js>"bar"</js>); <jc>// =qux</jc>
<jk>boolean</jk> baz = pm.getBoolean(<js>"baz"</js>); <jc>// =true</jc>
String remainder = pm.getRemainder(); <jc>// =quux</jc>
}
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RequestPathMatch} <jk>extends</jk> TreeMap&lt;String,String&gt;</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#get(String,Class) get(String,Class)}
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#get(String,Type,Type...) get(String,Type,Type)}
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#getString(String) getString(String)}
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#getInt(String) getInt(String)}
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#getBoolean(String) getBoolean(String)}
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#getRemainder() getRemainder()}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.MethodReturnTypes"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.10 - Method Return Types</h4>
<div class='topic'>
<p>
The return type can be any serializable POJO as defined in <a class='doclink' href='#juneau-marshall.PojoCategories'>POJO Categories</a>.
<br>It can also be <jk>void</jk> if the method is not sending any output (e.g. a request redirect) or is
setting the output using the {@link org.apache.juneau.rest.RestResponse#setOutput(Object)} method.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>)
<jk>public</jk> String doGet() {
<jk>return</jk> <js>"Hello World!"</js>;
}
</p>
<p>
Out-of-the-box, besides POJOs, the following return types are handled as special cases:
</p>
<ul class='spaced-list'>
<li class='jc'>{@link java.io.InputStream}
<br>The contents are simply piped to the output stream returned by
{@link org.apache.juneau.rest.RestResponse#getNegotiatedOutputStream()}.
<br>Note that you should call {@link org.apache.juneau.rest.RestResponse#setContentType(String)} to set
the <l>Content-Type</l> header if you use this object type.
<li class='jc'>{@link java.io.Reader}
<br>The contents are simply piped to the output stream returned by
{@link org.apache.juneau.rest.RestResponse#getNegotiatedWriter()}.
<br>Note that you should call {@link org.apache.juneau.rest.RestResponse#setContentType(String)} to set
the <l>Content-Type</l> header if you use this object type.
<li class='jc'>{@link org.apache.juneau.rest.Redirect}
<br>Represents an HTTP redirect response.
<li class='jc'>{@link org.apache.juneau.Streamable}
<br>Interface that identifies that an object can be serialized directly to an output stream.
<li class='jc'>{@link org.apache.juneau.Writable}
<br>Interface that identifies that an object can be serialized directly to a writer.
<li class='jc'>{@link org.apache.juneau.utils.ZipFileList}
<br>Special interface for sending zip files as responses.
</ul>
<p>
This is controlled through the following extensible API:
</p>
<ul class='doctree'>
<li class='jic'>{@link org.apache.juneau.rest.ResponseHandler}
<ul>
<li class='jc'>{@link org.apache.juneau.rest.response.DefaultHandler}
<li class='jc'>{@link org.apache.juneau.rest.response.InputStreamHandler}
<li class='jc'>{@link org.apache.juneau.rest.response.ReaderHandler}
<li class='jc'>{@link org.apache.juneau.rest.response.RedirectHandler}
<li class='jc'>{@link org.apache.juneau.rest.response.StreamableHandler}
<li class='jc'>{@link org.apache.juneau.rest.response.WritableHandler}
<li class='jc'>{@link org.apache.juneau.rest.response.ZipFileListResponseHandler}
</ul>
</ul>
<p>
REST Java methods can generate output in any of the following ways:
</p>
<ul class='spaced-list'>
<li>
By returning a serializable POJO, or any of the following:
<br>{@link java.io.Reader}, {@link java.io.InputStream}, {@link org.apache.juneau.Streamable},
{@link org.apache.juneau.Writable}
<li>
By calling {@link org.apache.juneau.rest.RestResponse#setOutput(Object)} with any of the types above.
<li>
By accessing the {@link java.io.Writer} directly by calling
{@link org.apache.juneau.rest.RestResponse#getNegotiatedWriter()} and writing the output yourself.
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Equivalent method 1</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example1/{personId}"</js>)
<jk>public</jk> Person doGet1(<ja>@Path</ja> UUID personId) {
Person p = getPersonById(personId);
<jk>return</jk> p;
}
<jc>// Equivalent method 2</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example2/{personId}"</js>)
<jk>public void</jk> doGet2(RestResponse res, <ja>@Path</ja> UUID personId) {
Person p = getPersonById(personId);
res.setOutput(p);
}
<jc>// (Sorta) Equivalent method 3</jc>
<jc>// (Ignores any converters or method-level properties)</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example3/{personId}"</js>)
<jk>public void</jk> doGet3(RestRequest req, RestResponse res, <ja>@Path</ja> UUID personId) {
Person p = getPersonById(personId);
String accept = req.getHeader(<js>"Accept"</js>, <js>"text/json"</js>);
WriterSerializer s = res.getSerializerGroup().getWriterSerializer(accept);
res.setContentType(s.getResponseContentType());
s.serialize(p, res.getNegotiatedWriter());
}
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_responseHandlers} - For configuring custom response handlers.
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.ReaderResource"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.11 - ReaderResource</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.ReaderResource} class is a convenience object for defining thread-safe
reusable character-based responses.
<br>In essence, it's a container for character data with optional response headers and support for
resolving SVL variables.
</p>
<p>
The {@link org.apache.juneau.rest.ReaderResource} class implements the {@link org.apache.juneau.Writable}
interface which is handled by the {@link org.apache.juneau.rest.response.WritableHandler} class.
<br>This allows these objects to be returned as responses by REST methods.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object sayHello(RestRequest req) {
<jc>// Return a reader resource loaded from a file with support for request-time SVL variables.</jc>
<jk>return</jk> ReaderResource.<jsm>create</jsm>()
.contents(<jk>new</jk> File(<js>"helloWorld.txt"</js>))
.varResolver(req.getVarResolver())
.header(<js>"Cache-Control"</js>, <js>"no-cache"</js>)
.mediaType(<jsf>TEXT_PLAIN</jsf>)
.build();
}
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.rest.ReaderResourceBuilder}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.ReaderResourceBuilder#contents(Object...) contents(Object...)}
<li class='jm'>{@link org.apache.juneau.rest.ReaderResourceBuilder#header(String,Object) header(String,Object)}
<li class='jm'>{@link org.apache.juneau.rest.ReaderResourceBuilder#mediaType(MediaType) mediaType(MediaType)}
<li class='jm'>{@link org.apache.juneau.rest.ReaderResourceBuilder#varResolver(VarResolverSession) varResolver(VarResolverSession)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.StreamResource"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.12 - StreamResource</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.StreamResource} class is the binary equivalent to the {@link org.apache.juneau.rest.ReaderResource} object.
<br>In essence, it's a container for binary data with optional response headers.
</p>
<p>
The {@link org.apache.juneau.rest.StreamResource} class implements the {@link org.apache.juneau.Streamable}
interface which is handled by the {@link org.apache.juneau.rest.response.StreamableHandler} class.
<br>This allows these objects to be returned as responses by REST methods.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Object showPicture(RestRequest req) {
<jc>// Return a stream resource loaded from a file.</jc>
<jk>return</jk> StreamResource.<jsm>create</jsm>()
.contents(<jk>new</jk> File(<js>"mypicture.png"</js>))
.header(<js>"Cache-Control"</js>, <js>"no-cache"</js>)
.mediaType(<jsf>IMAGE_PNG</jsf>)
.build();
}
</p>
<p>
The important methods on this class are:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.rest.StreamResourceBuilder}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.StreamResourceBuilder#contents(Object...) contents(Object...)}
<li class='jm'>{@link org.apache.juneau.rest.StreamResourceBuilder#header(String,Object) header(String,Object)}
<li class='jm'>{@link org.apache.juneau.rest.StreamResourceBuilder#mediaType(MediaType) mediaType(MediaType)}
</ul>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Redirect"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.13 - Redirect</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.Redirect} object is a convenience shortcut for performing <code>HTTP 302</code> redirects.
</p>
<p>
<l>Redirect</l> objects are handled by the {@link org.apache.juneau.rest.response.RedirectHandler} class.
<br>This allows these objects to be returned as responses by REST methods.
</p>
<p>
The following example shows the difference between handling redirects via <l>RestResponse</l> and the simplified approach of using this class.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Redirect to "/contextPath/servletPath/foobar"</jc>
<jc>// Using RestRequest/RestResponse</jc>
<ja>@RestMethod</ja>(...)
<jk>public void</jk> redirectExample1(RestRequest req, RestResponse res) <jk>throws</jk> IOException {
res.sendRedirect(req.getServletURI() + <js>"/foobar"</js>);
}
<jc>// Using Redirect</jc>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Redirect redirectExample2() {
<jk>return new</jk> Redirect(<js>"foobar"</js>);
}
</p>
<p>
The constructor can use a <l>MessageFormat</l>-style pattern with multiple arguments.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Redirect redirectExample3() {
<jk>return new</jk> Redirect(<js>"foo/{0}/bar/{1}"</js>, id1, id2);
}
</p>
<p>
The arguments are automatically URL-encoded.
</p>
<p>
Redirecting to the servlet root can be accomplished by simply using the no-arg constructor.
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Simply redirect to the servlet root.
// Equivalent to res.sendRedirect(req.getServletURI()).</jc>
<ja>@RestMethod</ja>(...)
<jk>public</jk> Redirect redirectExample4() {
<jk>return new</jk> Redirect();
}
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestMethodMatchers"></a>
<h4 class='topic' onclick='toggle(this)'>7.6.14 - @RestMethod.matchers()</h4>
<div class='topic'>
<p>
{@link org.apache.juneau.rest.RestMatcher RestMatchers} are used to allow multiple Java methods to be
tied to the same HTTP method and path, but differentiated by some request attribute such as a specific
header value.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// GET method that gets invoked for administrators</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>, matchers=IsAdminMatcher.<jk>class</jk>)
<jk>public</jk> Object doGetForAdmin() {
...
}
<jc>// GET method that gets invoked for everyone else</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>)
<jk>public</jk> Object doGetForEveryoneElse() {
...
}
</p>
<p>
The interface for matchers is simple:
</p>
<p class='bcode'>
<jk>public class</jk> IsAdminMatcher <jk>extends</jk> RestMatcher {
<ja>@Override</ja> <jc>/* RestMatcher */</jc>
<jk>public boolean</jk> matches(RestRequest req) {
<jk>return</jk> req.isUserInRole(<js>"ADMINS_GROUP"</js>);
}
}
</p>
<h5 class='section'>Notes:</h5>
<ul class='spaced-list'>
<li>
If no methods are found with a matching matcher, a <l>412 Precondition Failed</l> status is returned.
<li>
If multiple matchers are specified on the same method, ONLY ONE matcher needs to match for the
method to be invoked.
<li>
Note that you CANNOT define identical paths on different methods UNLESS you use matchers.
<br>That includes paths that are only different in variable names (e.g. <l>"/foo/{bar}"</l> and
<l>"/foo/{baz}"</l>).
<br>If you try to do so, a <l>ServletException</l> will be thrown on startup.
<li>
Methods with matchers take precedence over methods without.
<br>Otherwise, methods are attempted in the order they appear in the class.
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#matchers}
<li class='jc'>{@link org.apache.juneau.rest.matchers.MultipartFormDataMatcher}
<li class='jc'>{@link org.apache.juneau.rest.matchers.UrlEncodedFormMatcher}
</ul>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Body"></a>
<h3 class='topic' onclick='toggle(this)'>7.7 - @Body</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.Body @Body} annotation provides easy access to the HTTP body content as any <a class='doclink' href='#juneau-marshall.PojoCategories'>parsable</a> POJO type
<br>In the example below, we're POSTing beans.
</p>
<p class='bcode'>
<jc>// Example POST of a bean</jc>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>)
<jk>public void</jk> doPost(<ja>@Body</ja> Person person) <jk>throws</jk> Exception {
<jc>// Do something with person.</jc>
}
</p>
<p>
The HTTP body of a request can be retrieved as a parsed POJO using either the
{@link org.apache.juneau.rest.RestRequest#getBody()} method, or a parameter annotated with
{@link org.apache.juneau.rest.annotation.Body @Body}.
</p>
<p class='bcode'>
<jc>// Equivalent method 1</jc>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/example1"</js>)
<jk>public void</jk> doPost1(<ja>@Body</ja> Person p) {
<jc>// Do something with p.</jc>
}
<jc>// Equivalent method 2</jc>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/example2"</js>)
<jk>public void</jk> doPost2(RestRequest req) {
Person p = req.getBody).asType(Person.<jk>class</jk>);
<jc>// Do something with p.</jc>
}
</p>
<p>
The Juneau framework will automatically determine the appropriate <l>Parser</l> to use based on the
<l>Content-Type</l> HTTP header.
<br>So the body content could be JSON or XML or any other supported parsing types.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.Body}
<li class='jc'>{@link org.apache.juneau.rest.RequestBody}
</ul>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.HandlingFormPosts"></a>
<h4 class='topic' onclick='toggle(this)'>7.7.1 - Handling Form Posts</h4>
<div class='topic'>
<p>
The best way to handle a form post is by using an input bean.
<br>The samples include a <l>UrlEncodedFormResource</l> class that takes in URL-Encoded form post of the
form <l>"aString=foo&amp;aNumber=123&amp;aDate=2001-07-04T15:30:45Z"</l>.
<br>The code is shown here:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/urlEncodedForm"</js>
)
<jk>public class</jk> UrlEncodedFormResource <jk>extends</jk> Resource {
<jd>/** POST request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>)
<jk>public</jk> Object doPost(<ja>@Body</ja> FormInputBean input) <jk>throws</jk> Exception {
<jc>// Just mirror back the request</jc>
<jk>return</jk> input;
}
<jk>public static class</jk> FormInputBean {
<jk>public</jk> String <jf>aString</jf>;
<jk>public int</jk> <jf>aNumber</jf>;
<ja>@BeanProperty</ja>(pojoSwaps=CalendarSwap.<jsf>ISO8601DT</jsf>.<jk>class</jk>)
<jk>public</jk> Calendar <jf>aDate</jf>;
}
}
</p>
<p>
Another possibility is to access the form parameters individually:
</p>
<p class='bcode'>
<jd>/** POST request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>)
<jk>public</jk> Object doPost(<ja>@FormData</ja>(<js>"aString"</js>) String aString, <ja>@FormData</ja>(<js>"aNumber"</js>) <jk>int</jk> aNumber, <ja>@FormData</ja>(<js>"aDate"</js>) Calendar aDate) <jk>throws</jk> Exception {
...
}
</p>
<p>
The advantage to the form input bean is that it can handle any of the parsable types (e.g. JSON, XML...)
in addition to URL-Encoding.
<br>The latter approach only supports URL-Encoding.
</p>
<ul class='doctree'>
<li class='warn'>
If you're using form input beans, DO NOT use the <l>@FormData</l> attribute or
{@link org.apache.juneau.rest.RestRequest#getParameter(String)} method since this will cause the
underlying JEE servlet to parse the HTTP body as a form post.
<br>Your input bean will end up being null since there won't be any content left after the servlet
has parsed the body of the request.
<br>This applies to WHENEVER you use <l>@Body</l> or {@link org.apache.juneau.rest.RestRequest#getBody()}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.HandlingMultiPartFormPosts"></a>
<h4 class='topic' onclick='toggle(this)'>7.7.2 - Handling Multi-Part Form Posts</h4>
<div class='topic'>
<p>
The Juneau framework does not natively support multipart form posts.
<br>However, it can be done in conjunction with the Apache Commons File Upload library.
</p>
<p>
The samples include a <l>TempDirResource</l> class that uses the File Upload library to allow files to
be uploaded as multipart form posts.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/tempDir"</js>
)
<jk>public class</jk> TempDirResource <jk>extends</jk> DirectoryResource {
<jd>/**
* [POST /upload] - Upload a file as a multipart form post.
* Shows how to use the Apache Commons ServletFileUpload class for handling multi-part form posts.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/upload"</js>, matchers=TempDirResource.MultipartFormDataMatcher.<jk>class</jk>)
<jk>public</jk> Redirect uploadFile(RestRequest req) <jk>throws</jk> Exception {
ServletFileUpload upload = <jk>new</jk> ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(req);
<jk>while</jk> (iter.hasNext()) {
FileItemStream item = iter.next();
<jk>if</jk> (item.getFieldName().equals(<js>"contents"</js>)) {
File f = <jk>new</jk> File(getRootDir(), item.getName());
IOPipe.<jsm>create</jsm>(item.openStream(), <jk>new</jk> FileOutputStream(f)).closeOut().run();
}
}
<jk>return new</jk> Redirect(); <jc>// Redirect to the servlet root.</jc>
}
<jd>/** Causes a 404 if POST isn't multipart/form-data */</jd>
<jk>public static class</jk> MultipartFormDataMatcher <jk>extends</jk> RestMatcher {
<ja>@Override</ja> <jc>/* RestMatcher */</jc>
<jk>public boolean</jk> matches(RestRequest req) {
String contentType = req.getContentType();
<jk>return</jk> contentType != <jk>null</jk> &amp;&amp; contentType.startsWith(<js>"multipart/form-data"</js>);
}
}
</p>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.FormData"></a>
<h3 class='topic' onclick='toggle(this)'>7.8 - @FormData</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.FormData @FormData} annotation is used to retrieve request form post entries.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>)
<jk>public void</jk> doPost(RestRequest req, RestResponse res,
<ja>@FormData</ja>(<js>"p1"</js>) <jk>int</jk> p1,
<ja>@FormData</ja>(<js>"p2"</js>) String p2,
<ja>@FormData</ja>(<js>"p3"</js>) UUID p3) {...}
</p>
<p>
This is functionally equivalent to the following code:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>)
<jk>public void</jk> doPost(RestRequest req, RestResponse res) {
RequestFormData fd = req.getFormData();
<jk>int</jk> p1 = fd.get(<js>"p1"</js>, 0, <jk>int</jk>.<jk>class</jk>);
String p2 = fd.get(<js>"p2"</js>, String.<jk>class</jk>);
UUID p3 = fd.get(<js>"p3"</js>, UUID.<jk>class</jk>);
}
</p>
<p>
The registered {@link org.apache.juneau.rest.RestContext#REST_partParser} is used to convert strings
to POJOs and controls what POJO types are supported.
<br>As a general rule, any POJO convertable from a String is supported.
</p>
<ul class='doctree'>
<li class='warn'>
This annotation should not be combined with the {@link org.apache.juneau.rest.annotation.Body @Body} annotation or {@link org.apache.juneau.rest.RestRequest#getBody()} method
for <code>application/x-www-form-urlencoded POST</code> posts, since it will trigger the underlying servlet
API to parse the body content as key-value pairs resulting in empty content.
<br>The {@link org.apache.juneau.rest.annotation.Query @Query} annotation can be used to retrieve a URL parameter in the URL string without triggering the
servlet to drain the body content.
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.FormData}
<li class='ja'>{@link org.apache.juneau.rest.annotation.HasFormData}
<li class='jc'>{@link org.apache.juneau.rest.RequestFormData}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Query"></a>
<h3 class='topic' onclick='toggle(this)'>7.9 - @Query</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.Query @Query} annotation is used to retrieve request URL query parameters.
<br>It's identical to {@link org.apache.juneau.rest.annotation.FormData @FormData}, but only retrieves the parameter from the URL string, not URL-encoded form posts.
</p>
<p>
Unlike {@link org.apache.juneau.rest.annotation.FormData @FormData}, using this annotation does not result in the servlet reading the contents of
URL-encoded form posts.
<br>Therefore, this annotation can be used in conjunction with the {@link org.apache.juneau.rest.annotation.Body @Body} annotation or
{@link org.apache.juneau.rest.RestRequest#getBody()} method for <code>application/x-www-form-urlencoded POST</code> calls.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>)
<jk>public void</jk> doGet(RestRequest req, RestResponse res,
<ja>@Query</ja>(<js>"p1"</js>) <jk>int</jk> p1,
<ja>@Query</ja>(<js>"p2"</js>) String p2,
<ja>@Query</ja>(<js>"p3"</js>) UUID p3) {...}
</p>
<p>
This is functionally equivalent to the following code:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>)
<jk>public void</jk> doGet(RestRequest req, RestResponse res) {
RequestQuery q = req.getQuery();
<jk>int</jk> p1 = q.get(<js>"p1"</js>, 0, <jk>int</jk>.<jk>class</jk>);
String p2 = q.get(<js>"p2"</js>, String.<jk>class</jk>);
UUID p3 = q.get(<js>"p3"</js>, UUID.<jk>class</jk>);
}
</p>
<p>
The registered {@link org.apache.juneau.rest.RestContext#REST_partParser} is used to convert strings
to POJOs and controls what POJO types are supported.
<br>As a general rule, any POJO convertable from a String is supported.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.Query}
<li class='ja'>{@link org.apache.juneau.rest.annotation.HasQuery}
<li class='jc'>{@link org.apache.juneau.rest.RequestQuery}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Header"></a>
<h3 class='topic' onclick='toggle(this)'>7.10 - @Header</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.Header @Header} is used to retrieve request headers.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>)
<jk>public void</jk> doGet(RestRequest req, RestResponse res, <ja>@Header</ja>(<js>"ETag"</js>) UUID etag) {...}
</p>
<p>
This is functionally equivalent to the following code:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>)
<jk>public void</jk> doPostPerson(RestRequest req, RestResponse res) {
RequestHeaders h = req.getHeaders();
UUID etag = h.get(<js>"ETag"</js>, UUID.<jk>class</jk>);
}
</p>
<p>
The registered {@link org.apache.juneau.rest.RestContext#REST_partParser} is used to convert strings
to POJOs and controls what POJO types are supported.
<br>As a general rule, any POJO convertible from a String is supported.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.Header}
<li class='jc'>{@link org.apache.juneau.rest.RequestHeaders}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Serializers"></a>
<h3 class='topic' onclick='toggle(this)'>7.11 - Serializers</h3>
<div class='topic'>
<p>
REST resources use the {@link org.apache.juneau.serializer.Serializer} API for defining serializers for
serializing response POJOs.
</p>
<p>
The servlet will pick which serializer to use by matching the request <l>Accept</l> header with the
media types defined through the {@link org.apache.juneau.serializer.Serializer#getMediaTypes()} method.
</p>
<p>
Serializers can be associated with REST servlets in the following ways:
</p>
<ul class='doctree'>
<li class='ja'>
{@link org.apache.juneau.rest.annotation.RestResource#serializers()}
- Annotation on resource Java class.
<li class='ja'>
{@link org.apache.juneau.rest.annotation.RestMethod#serializers()}
- Annotation on resource Java method.
<li class='jf'>
{@link org.apache.juneau.rest.RestContext#REST_serializers}
- Programmatic.
</ul>
<p>
The following are all equivalent ways of defining serializers used by a resource:
</p>
<p class='bcode'>
<jc>// Option #1 - Defined via annotation.</jc>
<ja>@RestResource</ja>(serializers={JsonSerializer.<jk>class</jk>, XmlSerializer.<jk>class</jk>})
<jk>public class</jk> MyResource {
<jc>// Option #2 - Defined via builder passed in through resource constructor.</jc>
<jk>public</jk> MyResource(RestContextBuilder builder) <jk>throws</jk> Exception {
<jc>// Using method on builder.</jc>
builder.serializers(JsonSerializer.<jk>class</jk>, XmlSerializer.<jk>class</jk>);
<jc>// Same, but use pre-instantiated parsers.</jc>
builder.serializers(JsonSerializer.<jsf>DEFAULT</jsf>, XmlSerializer.<jsf>DEFAULT</jsf>);
<jc>// Same, but using property.</jc>
builder.set(<jsf>REST_serializers</jsf>, JsonSerializer.<jk>class</jk>, XmlSerializer.<jk>class</jk>);
}
<jc>// Option #3 - Defined via builder passed in through init method.</jc>
<ja>@RestHook</ja>(<jsf>INIT</jsf>)
<jk>public void</jk> init(RestContextBuilder builder) <jk>throws</jk> Exception {
builder.serializers(JsonSerializer.<jk>class</jk>, XmlSerializer.<jk>class</jk>);
}
<jc>// Override at the method level.</jc>
<ja>@RestMethod</ja>(serializers={HtmlSerializer.<jk>class</jk>})
<jk>public</jk> MyPojo myMethod() {
<jc>// Return a POJO to be serialized.</jc>
<jk>return new</jk> MyPojo();
}
}
</p>
<h5 class='section'>See Also:</h5>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_serializers}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Parsers"></a>
<h3 class='topic' onclick='toggle(this)'>7.12 - Parsers</h3>
<div class='topic'>
<p>
REST resources use the {@link org.apache.juneau.parser.Parser} API for defining parsers for parsing request
body content and converting them into POJOs.
</p>
<p>
The servlet will pick which parser to use by matching the request <l>Content-Type</l> header with the
media types defined through the {@link org.apache.juneau.parser.Parser#getMediaTypes()} method.
</p>
<p>
Parsers can be associated with REST servlets in the following ways:
</p>
<ul class='doctree'>
<li class='ja'>
{@link org.apache.juneau.rest.annotation.RestResource#parsers()}
- Annotation on resource Java class.
<li class='ja'>
{@link org.apache.juneau.rest.annotation.RestMethod#parsers()}
- Annotation on resource Java method.
<li class='jm'>
{@link org.apache.juneau.rest.RestContextBuilder#parsers(Class[])}
- Programmatic.
</ul>
<p>
The following are all equivalent ways of defining parsers used by a resource:
</p>
<p class='bcode'>
<jc>// Option #1 - Defined via annotation.</jc>
<ja>@RestResource</ja>(parsers={JsonParser.<jk>class</jk>, XmlParser.<jk>class</jk>})
<jk>public class</jk> MyResource {
<jc>// Option #2 - Defined via builder passed in through resource constructor.</jc>
<jk>public</jk> MyResource(RestContextBuilder builder) <jk>throws</jk> Exception {
<jc>// Using method on builder.</jc>
builder.parsers(JsonParser.<jk>class</jk>, XmlParser.<jk>class</jk>);
<jc>// Same, but use pre-instantiated parsers.</jc>
builder.parsers(JsonParser.<jsf>DEFAULT</jsf>, XmlParser.<jsf>DEFAULT</jsf>);
<jc>// Same, but using property.</jc>
builder.set(<jsf>REST_parsers</jsf>, JsonParser.<jk>class</jk>, XmlParser.<jk>class</jk>);
}
<jc>// Option #3 - Defined via builder passed in through init method.</jc>
<ja>@RestHook</ja>(<jsf>INIT</jsf>)
<jk>public void</jk> init(RestContextBuilder builder) <jk>throws</jk> Exception {
builder.parsers(JsonParser.<jk>class</jk>, XmlParser.<jk>class</jk>);
}
<jc>// Override at the method level.</jc>
<ja>@RestMethod</ja>(parsers={HtmlParser.<jk>class</jk>})
<jk>public</jk> Object myMethod(<ja>@Body</ja> MyPojo myPojo) {
<jc>// Do something with your parsed POJO.</jc>
}
}
</p>
<h5 class='section'>See Also:</h5>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_parsers}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Properties"></a>
<h3 class='topic' onclick='toggle(this)'>7.13 - Properties</h3>
<div class='topic'>
<p>
As shown in previous sections, Juneau serializers and parsers are highly-configurable through properties.
(See <a class='doclink' href='#juneau-marshall.ConfigurableProperties'>Configurable Properties</a>)
</p>
<p>
These properties can be defined for serializers and parsers registered on a REST resource via the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#properties()}
<li class='jc'>{@link org.apache.juneau.rest.RestContextBuilder} - Various methods on the context builder.
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jk>import static</jk> org.apache.juneau.BeanContext.*;
<jk>import static</jk> org.apache.juneau.serializer.Serializer.*;
<jk>import static</jk> org.apache.juneau.json.JsonSerializer.*;
<jc>// Servlet with properties applied</jc>
<ja>@RestResource</ja>(
properties={
<jc>// Bean properties should be sorted alphabetically.</jc>
<ja>@Property</ja>(name=<jsf>BEAN_sortProperties</jsf>, value=<js>"true"</js>),
<jc>// Nulls should not be serialized</jc>
<ja>@Property</ja>(name=<jsf>SERIALIZER_trimNulls</jsf>, value=<js>"true"</js>),
<jc>// Solidus characters should be escaped in JSON</jc>
<ja>@Property</ja>(name=<jsf>JSON_escapeSolidus</jsf>, value=<js>"true"</js>)
}
)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServletDefault {...}
</p>
<p>
The programmatic equivalent to this is:
</p>
<p class='bcode'>
<jc>// Servlet with properties applied</jc>
<ja>@RestResource</ja>(...)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServletDefault {
<jk>public</jk> MyRestServlet(RestContextBuilder builder) {
builder
.sortProperties(); <jc>// Note: RestContextBuilder extends from BeanContextBuilder</jc>
.set(<jsf>SERIALIZER_trimNulls</jsf>, <jk>true</jk>);
.set(<jsf>JSON_escapeSolidus</jsf>, <jk>true</jk>);
}
}
</p>
<p>
Properties can also be overridden at the Java method level:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#properties()}
<li class='jc'>{@link org.apache.juneau.rest.RequestProperties}
</ul>
<p class='bcode'>
<jc>// GET method with method-level properties</jc>
<ja>@RestMethod</ja>(
name=<jsf>GET</jsf>, path=<js>"/*"</js>,
properties={
<jc>// Bean properties should be sorted alphabetically.</jc>
<ja>@Property</ja>(name=<jsf>BEAN_sortProperties</jsf>, value=<js>"true"</js>),
<jc>// Nulls should not be serialized</jc>
<ja>@Property</ja>(name=<jsf>SERIALIZER_trimNulls</jsf>, value=<js>"true"</js>),
<jc>// Solidus characters should be escaped in JSON</jc>
<ja>@Property</ja>(name=<jsf>JSON_escapeSolidus</jsf>, value=<js>"true"</js>)
}
<jk>public</jk> Object doGet() {
...
}
</p>
<p>
Using the {@link org.apache.juneau.rest.RequestProperties} object:
</p>
<p class='bcode'>
<jc>// Access it from RestRequest.</jc>
<jk>public</jk> Object doGet(RestRequest req) {
RequestProperties properties = req.getProperties();
properties.put(<jsf>JSON_escapeSolidus</jsf>, <jk>true</jk>);
}
<jc>// Or just pass in a RequestProperties object.</jc>
<jk>public</jk> Object doGet(RequestProperties properties) {
properties.put(<jsf>JSON_escapeSolidus</jsf>, <jk>true</jk>);
}
</p>
<p>
Properties set via {@link org.apache.juneau.rest.RequestProperties} are session-override
properties that are passed in through {@link org.apache.juneau.serializer.SerializerSessionArgs}
and {@link org.apache.juneau.parser.ParserSessionArgs} and can only be used on configuration settings
marked as <code>Session-overridable: <jk>true</jk></code>.
</p>
<p>
Properties are open-ended and can be used for other purposes.
<br>They're made available through the following methods:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestContext#getProperties()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getProperties()}
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#flags()} - Shorthand for boolean properties.
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#flags()} - Shorthand for boolean properties.
<li class='jc'>{@link org.apache.juneau.rest.RestContextProperties}
<li class='jc'>{@link org.apache.juneau.rest.RestMethodProperties}
<li class='jc'>{@link org.apache.juneau.rest.RequestProperties}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Transforms"></a>
<h3 class='topic' onclick='toggle(this)'>7.14 - Transforms</h3>
<div class='topic'>
<p>
The Juneau serializers and parsers can be configured on how to handle POJOs through the use of Transforms.
(See <a class='doclink' href='#juneau-marshall.Transforms'>Transforms</a>)
</p>
<p>
Transforms are associated serializers and parsers registered on a REST resource via the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#beanFilters()}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#pojoSwaps()}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#beanFilters()}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#pojoSwaps()}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#beanFilters(Object...)}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#pojoSwaps(Object...)}
</ul>
<p class='bcode'>
<jc>// Servlet with transforms applied</jc>
<ja>@RestResource</ja>(
pojoSwaps={
<jc>// Calendars should be serialized/parsed as ISO8601 date-time strings</jc>
CalendarSwap.<jsf>DEFAULT_ISO8601DT</jsf>.<jk>class</jk>,
<jc>// Byte arrays should be serialized/parsed as BASE64-encoded strings</jc>
ByteArrayBase64Swap.<jk>class</jk>
},
beanFilters={
<jc>// Subclasses of MyInterface will be treated as MyInterface objects.</jc>
<jc>// Bean properties not defined on that interface will be ignored.</jc>
}
)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServletDefault {...}
</p>
<p>
The programmatic equivalent to this is:
</p>
<p class='bcode'>
<jc>// Servlet with properties applied</jc>
<ja>@RestResource</ja>(...)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServletDefault {
<jk>public</jk> MyRestServlet(RestContextBuilder builder) {
builder
.pojoSwaps(
CalendarSwap.<jsf>DEFAULT_ISO8601DT</jsf>.<jk>class</jk>,
ByteArrayBase64Swap.<jk>class</jk>
)
.beanFilters(MyInterface.<jk>class</jk>);
}
}
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Guards"></a>
<h3 class='topic' onclick='toggle(this)'>7.15 - Guards</h3>
<div class='topic'>
<p>
Guards are classes that control access to REST classes and methods.
</p>
<p>
Guards are associated with resource classes and methods via the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#guards()}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#guards()}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#guards(Class...)}
</ul>
<p class='bcode'>
<jc>// Define a guard that only lets Billy make a request</jc>
<jk>public</jk> BillyGuard <jk>extends</jk> RestGuard {
<ja>@Override</ja> <jc>/* RestGuard */</jc>
<jk>public boolean</jk> isRequestAllowed(RestRequest req) {
<jk>return</jk> req.getUserPrincipal().getName().equals(<js>"Billy"</js>);
}
}
<jc>// Servlet with class-level guard applied</jc>
<ja>@RestResource</ja>(guards=BillyGuard.<jk>class</jk>)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServletDefult {
<jc>// Delete method that only Billy is allowed to call.</jc>
<ja>@RestMethod</ja>(name=<js>"DELETE"</js>)
<jk>public</jk> doDelete(RestRequest req, RestResponse res) <jk>throws</jk> Exception {...}
}
</p>
<p>
A common use for guards is to only allow admin access to certain Java methods...
</p>
<p class='bcode'>
<jc>// DELETE method</jc>
<ja>@RestMethod</ja>(name=<jsf>DELETE</jsf>, guards={AdminGuard.<jk>class</jk>})
<jk>public void</jk> doDelete(RestRequest req, RestResponse res) <jk>throws</jk> Exception {...}
</p>
<p class='bcode'>
<jk>public class</jk> AdminGuard <jk>extends</jk> RestGuard {
<ja>@Override</ja> <jc>/* RestGuard */</jc>
<jk>public boolean</jk> isRequestAllowed(RestRequest req) {
<jk>return</jk> req.getUserPrincipal().isUserInRole(<js>"ADMIN"</js>);
}
}
</p>
<p>
A guard failure results in an <l>HTTP 401 Unauthorized</l> response.
<br>However, this can be configured by overriding the
{@link org.apache.juneau.rest.RestGuard#guard(RestRequest,RestResponse)} and processing the response
yourself.
</p>
<p class='bcode'>
<jk>public class</jk> AdminGuard <jk>extends</jk> RestGuard {
<ja>@Override</ja> <jc>/* RestGuard */</jc>
<jk>public boolean</jk> guard(RestRequest req, RestResponse res) <jk>throws</jk> RestException {
<jk>if</jk> (! isOkay(req))
<jk>throw new</jk> RestException(<jsf>SC_FORBIDDEN</jsf>, <js>"Access denied!!!"</js>);
<jk>return true</jk>;
}
}
</p>
<p>
When guards are associated at the class-level, it's equivalent to associating guards on all Java methods on
the servlet.
<br>If multiple guards are present, ALL guards must pass.
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_guards}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Converters"></a>
<h3 class='topic' onclick='toggle(this)'>7.16 - Converters</h3>
<div class='topic'>
<p>
Converters can be thought of as "post-processors" for POJOs before they get passed to the serializers.
</p>
<p>
Converters are associated with resource classes and methods via the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#converters()}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#converters()}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#converters(Class...)}
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Associate the Traversable converter to all Java REST methods in this servlet</jc>
<ja>@RestResource</ja>(converters=Traversable.<jk>class</jk>)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServlet {
...
}
</p>
<p>
They can also be defined at the method level:
</p>
<p class='bcode'>
<jc>// GET person request handler.</jc>
<jc>// Traversable conversion enabled to allow nodes in returned POJO tree to be addressed.</jc>
<jc>// Queryable conversion enabled to allow returned POJO to be searched/viewed/sorted.</jc>
<ja>@RestMethod</ja>(
name=<jsf>GET</jsf>, path=<js>"/people/{id}/*"</js>,
converters={Traversable.<jk>class</jk>,Queryable.<jk>class</jk>}
)
<jk>public</jk> Person getPerson(<ja>@Path</ja> <jk>int</jk> id) {
<jk>return</jk> findPerson(id);
}
</p>
<p>
The following converter is used to provide support for addressing child nodes in a POJO tree with URL path
remainders.
<br>In this code, the 3rd parameter is the object that was returned by the Java method.
<br>The converter uses the {@link org.apache.juneau.utils.PojoRest} wrapper class to address nodes in the
tree.
</p>
<p class='bcode'>
<jd>/**
* Converter for enablement of PojoRest support on response objects returned by a @RestMethod method.
* When enabled, objects in a POJO tree returned by the REST method can be addressed through additional URL path information.
*/</jd>
<jk>public class</jk> Traversable <jk>implements</jk> RestConverter {
<ja>@Override</ja> <jc>/* RestConverter */</jc>
<jk>public</jk> Object convert(RestRequest req, Object o) <jk>throws</jk> RestException {
if (o == <jk>null</jk>)
<jk>return null</jk>;
String pathRemainder = req.getPathMatch().getRemainder();
<jk>if</jk> (pathRemainder != <jk>null</jk>) {
<jk>try</jk> {
<jc>// Use the PojoRest class to traverse our POJO model.</jc>
PojoRest p = <jk>new</jk> PojoRest(o);
o = p.get(pathRemainder);
} <jk>catch</jk> (PojoRestException e) {
<jk>throw new</jk> RestException(e.getStatus(), e);
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RestException(HttpServletResponse.<jsf>SC_INTERNAL_SERVER_ERROR</jsf>, e);
}
}
<jk>return</jk> o;
}
}
</p>
<p>
Juneau defines the following converters out-of-the-box:
</p>
<ul class='doctree'>
<li class='jic'>
{@link org.apache.juneau.rest.RestConverter}
<ul>
<li class='jc'>
{@link org.apache.juneau.rest.converters.Queryable}
<br>Provides query parameters that can be used to transform the response (i.e. search/view/sort the
POJO response before being serialized).
<li class='jc'>
{@link org.apache.juneau.rest.converters.Traversable}
<br>Allows nodes in the POJO response tree to be individually accessed through additional path info on
the request.
<li class='jc'>
{@link org.apache.juneau.rest.converters.Introspectable}
<br>Allows method calls to be made on the response POJO, and for the result of that method call to be
serialized as the response.
</ul>
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_converters}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Messages"></a>
<h3 class='topic' onclick='toggle(this)'>7.17 - Messages</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.RestResource#messages @RestResource.messages()} annotation is used to associate a resource bundle with a servlet class.
</p>
<p class='bcode'>
<jc>// Servlet with associated resource bundle</jc>
<ja>@RestResource</ja>(messages=<js>"nls/MyMessages"</js>)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServlet {
<jc>// Returns the localized greeting from the "greeting" key in MyMessages.properties</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> String printLocalizedGreeting(RestRequest req) {
<jk>return</jk> req.getMessage(<js>"greeting"</js>);
}
</p>
<p>
The resource bundle can also be passed into the method by simply specifying a parameter
of type {@link java.util.ResourceBundle} or {@link org.apache.juneau.utils.MessageBundle}:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>)
<jk>public</jk> String printLocalizedGreeting(MessageBundle messages) {
<jk>return</jk> messages.getString(<js>"greeting"</js>);
}
</p>
<p>
If a resource bundle is shared by multiple servlets, the label and description can be prefixed by the class
name:
</p>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# Contents of MyMessages.properties
#--------------------------------------------------------------------------------</cc>
<ck>greeting</ck> = Hello!
</p>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# Contents of shared MyMessages.properties
#--------------------------------------------------------------------------------</cc>
<ck>MyRestServlet.greeting</ck> = Hello!
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_messages}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Encoders"></a>
<h3 class='topic' onclick='toggle(this)'>7.18 - Encoders</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.RestResource#encoders @RestResource.encoders()} annotation can
be used to associate character encoders with a servlet class.
<br>Encoders can be used to enable various kinds of compression (e.g. <l>"gzip"</l>) on requests and responses
based on the request <l>Accept-Encoding</l> and <l>Content-Encoding</l> headers.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Servlet with automated support for GZIP compression</jc>
<ja>@RestResource</ja>(encoders={GzipEncoder.<jk>class</jk>})
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServlet {
...
}
</p>
<p>
Juneau defines the following encoders out-of-the-box:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.encoders.Encoder}
<ul>
<li class='jc'>
{@link org.apache.juneau.encoders.GzipEncoder}
<li class='jc'>
{@link org.apache.juneau.encoders.IdentityEncoder}
</ul>
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_encoders}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.SvlVariables"></a>
<h3 class='topic' onclick='toggle(this)'>7.19 - SVL Variables</h3>
<div class='topic'>
<p>
In the previous examples, there were several cases where embedded variables were contained within
annotation values:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
title=<js>"$L{my.label}"</js>
)
</p>
<p>
Variables take the form <l>$X{contents}</l> where <l>X</l> can consist of zero or more ASCII characters and <l>contents</l> can be virtually anything.
<br>This is called Simple Variable Language, or SVL, and is defined here: <a class='doclink' href='#juneau-svl'>juneau-svl</a>.
</p>
<h5 class='topic'>Features</h5>
<ul class='spaced-list'>
<li>
Variables can be nested arbitrarily deep (e.g. <l>"$X{$Y{foo}}"</l>).
<li>
Variables can contain arguments (e.g. <l>"$L{my.label,arg1,arg2}"</l>).
<li>
Variables are recursively resolved.
<br>i.e., if a variable results to a value with another variable in it, that variable will also be
resolved (restricted for security reasons on some variables).
</ul>
<p>
Variables are configured on resources via the following API:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#vars(Class[])}
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Defined a variable that simply wrapps all strings inside [] brackets.</jc>
<jc>// e.g. "$BRACKET{foobar}" -> "[foobar]"</jc>
<jk>public class</jk> BracketVar <jk>extends</jk> SimpleVar {
<jk>public</jk> BracketVar() {
<jk>super</jk>(<js>"BRACKET"</js>);
}
<ja>@Override</ja> <jc>/* Var */</jc>
<jk>public</jk> String resolve(VarResolverSession session, String arg) {
<jk>return</jk> <js>'['</js> + arg + <js>']'</js>;
}
}
<jc>// Register it with our resource.</jc>
<ja>@RestResource</ja>(...)
<jk>public class</jk> MyResource {
<jk>public</jk> MyResource(RestContextBuilder builder) {
builder.vars(BracketVar.<jk>class</jk>);
}
}
</p>
<p>
The methods involved with variables are:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestContext#getVarResolver()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getVarResolverSession()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String,boolean)}
</ul>
<p>
There are two distinct groups of variables:
</p>
<ul>
<li>Initialization-time variables.
<br>These are variables that can be used in many of the annotations in {@link org.apache.juneau.rest.annotation.RestResource @RestResource}.
<br>The {@link org.apache.juneau.rest.RestContext#getVarResolver()} method returns initialization-time variables only.
<li>Request-time variables.
<br>These are variables that are available during HTTP-requests and can be used on annotation such as {@link org.apache.juneau.rest.annotation.HtmlDoc @HtmlDoc}.
<br>{@link org.apache.juneau.rest.RestRequest#getVarResolverSession()} method returns initialization and request-time variables.
</ul>
<p>
The following is the default list of supported variables.
</p>
<a id='DefaultRestSvlVariables'></a>
<h5 class='figure'>Default REST SVL Variables:</h5>
<table class='styled' style='min-width:800px;width:50%'>
<tr>
<th>Module</th><th>Class</th><th>Pattern</th><th>Initialization<br>time</th><th>Request<br>time</th>
</tr>
<tr class='dark'>
<td rowspan="6" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-svl</td>
<td>{@link org.apache.juneau.svl.vars.EnvVariablesVar}</td>
<td class='code'>$E{envVar[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.SystemPropertiesVar}</td>
<td class='code'>$S{systemProperty[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.CoalesceVar}</td>
<td class='code'>$CO{arg1[,arg2...]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.CoalesceAndRecurseVar}</td>
<td class='code'>$CR{arg1[,arg2...]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.svl.vars.IfVar}</td>
<td class='code'>$IF{booleanArg,thenValue[,elseValue]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark dd'>
<td>{@link org.apache.juneau.svl.vars.SwitchVar}</td>
<td class='code'>$SW{stringArg(,pattern,thenValue)+[,elseValue]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='light dd'>
<td rowspan="1" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-config</td>
<td>{@link org.apache.juneau.config.vars.ConfigVar}</td>
<td class='code'>$C{key[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td rowspan="14" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-rest-server</td>
<td>{@link org.apache.juneau.rest.vars.FileVar}</td>
<td class='code'>$F{path[,defaultValue]}}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.ServletInitParamVar}</td>
<td class='code'>$I{name[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.LocalizationVar}</td>
<td class='code'>$L{key[,args...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestAttributeVar}</td>
<td class='code'>$RA{key1[,key2...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestFormDataVar}</td>
<td class='code'>$RF{key1[,key2...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestHeaderVar}</td>
<td class='code'>$RH{key1[,key2...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestHeaderVar}</td>
<td class='code'>$RI{key}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestPathVar}</td>
<td class='code'>$RP{key1[,key2...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestQueryVar}</td>
<td class='code'>$RQ{key1[,key2...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.RequestVar}</td>
<td class='code'>$R{key1[,key2...]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.SerializedRequestAttrVar}</td>
<td class='code'>$SA{contentType,key[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.UrlVar}</td>
<td class='code'>$U{uri}></td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark'>
<td>{@link org.apache.juneau.rest.vars.UrlEncodeVar}</td>
<td class='code'>$UE{uriPart}</td>
<td style='text-align:center;font-weight:bold'>yes</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='dark dd'>
<td>{@link org.apache.juneau.rest.vars.WidgetVar}</td>
<td class='code'>$W{widgetName}</td>
<td style='text-align:center;font-weight:bold'>no</td>
<td style='text-align:center;font-weight:bold'>yes</td>
</tr>
<tr class='light'>
<td rowspan="2" style='text-align:center;font-weight:bold;padding:20px;' class='code'>juneau-microservice-server</td>
<td>{@link org.apache.juneau.microservice.vars.ArgsVar}</td>
<td class='code'>$ARG{key[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>yes*</td>
<td style='text-align:center;font-weight:bold'>yes*</td>
</tr>
<tr class='light dd'>
<td>{@link org.apache.juneau.microservice.vars.ManifestFileVar}</td>
<td class='code'>$MF{key[,defaultValue]}</td>
<td style='text-align:center;font-weight:bold'>yes*</td>
<td style='text-align:center;font-weight:bold'>yes*</td>
</tr>
</table>
<p>
* = Only if extending from {@link org.apache.juneau.microservice.Resource}
<p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.ConfigurationFiles"></a>
<h3 class='topic' onclick='toggle(this)'>7.20 - Configuration Files</h3>
<div class='topic'>
<p>
The Server API provides methods for associating configuration files with REST servlets so that
configuration properties can be defined in external files.
</p>
<p>
In recap, the Configuration API provides support for INI-style configuration files with embedded string variables:
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<cc>#--------------------------</cc>
<cc># Examples </cc>
<cc>#--------------------------</cc>
<cs>[MyProperties]</cs>
<ck>path</ck> = <cv>$E{PATH}</cv>
<ck>javaHome</ck> = <cv>$S{java.home}</cv>
<ck>customMessage</ck> = <cv>Java home is $C{MyProperties/javaHome} and the environment path is $C{MyProperties/path}.</cv>
</p>
<p>
These properties are then accessible through the {@link org.apache.juneau.config.Config} class.
</p>
<p class='bcode'>
Config cf = Config.<jsm>create</jsm>().name(<js>"myconfig.cfg"</js>).build();
String path = cf.getString(<js>"MyProperties/path"</js>);
File javaHome = cf.getObject(<js>"MyProperties/javaHome"</js>, File.<jk>class</jk>);
String customMessage = cf.getString(<js>"MyProperties/customMessage"</js>);
</p>
<p>
Configuration files are associated with REST resources through the following:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#config()}
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestResource</ja>(
<jc>// Config file is located at ./config_dir/myconfig.cfg</jc>
config=<js>"config_dir/myconfig.cfg"</js>,
...
)
<jk>public class</jk> MyResource {...}
</p>
<p>
The annotation itself can contain string variables.
<br>For example, the Microservice API {@link org.apache.juneau.microservice.Resource} class defines the
location of the config file as a system property <l>"juneau.configFile"</l>:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
<jc>// Config file location is defined as a system property</jc>
config=<js>"$S{juneau.configFile}"</js>,
...
)
<jk>public class</jk> MyResource {...}
</p>
<p>
Once a config file has been associated with a REST resource, it can be accessed through the
{@link org.apache.juneau.rest.RestContextBuilder#getConfig()} method.
</p>
<p>
A common usage is to use this method to initialize fields in your servlet.
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
<jc>// Config file is located at ./config_dir/myconfig.cfg</jc>
config=<js>"config_dir/myconfig.cfg"</js>,
...
)
<jk>public class</jk> MyResource {
<jk>private final</jk> String <jf>path</jf>;
<jk>private final</jk> File <jf>javaHome</jf>;
<jk>public</jk> MyResource(RestContextBuilder builder) {
Config cf = builder.getConfig();
<jf>path</jf> = cf.getString(<js>"MyProperties/path"</js>);
<jf>javaHome</jf> = cf.getObject(File.<jk>class</jk>, <js>"MyProperties/javaHome"</js>);
}
</p>
<p>
Another common usage is to refer to config properties through <ck>$C</ck> variables in your annotations:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
<jc>// Get stylesheet from myconfig.cfg, but default to devops.css if it's not specified</jc>
htmldoc=<ja>@HtmlDoc</ja>(
stylesheet=<js>"$C{MyServlet/stylesheet,servlet:/styles/devops.css}"</js>,
)
...
)
<jk>public class</jk> MyResource {...}
</p>
<p>
It's even possible to reference request-level variables in your config file if you use
{@link org.apache.juneau.rest.RestRequest#getConfig()} to access the config file:
</p>
<p class='bcode'>
<cc>#-------------------------------------</cc>
<cc># Contents of config_dir/myconfig.cfg </cc>
<cc>#-------------------------------------</cc>
<cs>[HelloWorldResource]</cs>
<ck>message</ck> = <cv>Hello $RQ{person}!</cv>
</p>
<p class='bcode'>
<jd>/**
* Sample REST resource that prints out a simple "Hello world!" message.
*/</jd>
<ja>@RestResource</ja>(
config=<js>"config_dir/myconfig.cfg"</js>,
...
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> RestServletDefault {
<jd>/**
* GET request handler.
* Specify the GET parameter "?person=X" for a specialized message!
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> String sayHello(RestRequest req) {
<jk>return</jk> req.getConfig().getString(<js>"HelloWorldResource/message"</js>);
}
}
</p>
<p>
You can even add resource bundles into the mix:
</p>
<p class='bcode'>
<cc>#-------------------------------------</cc>
<cc># Contents of config_dir/myconfig.cfg </cc>
<cc>#-------------------------------------</cc>
<cs>[HelloWorldResource]</cs>
<ck>message</ck> = <cv>$L{localizedMessage,$RQ{person}}</cv>
</p>
<p class='bcode'>
<cc>#-------------------------------------------</cc>
<cc># Contents of HelloWorldResource.properties </cc>
<cc>#-------------------------------------------</cc>
<ck>localizedMessage</ck> = <cv>Hello {0}!</cv>
</p>
<p class='bcode'>
<jd>/**
* Sample REST resource that prints out a simple "Hello world!" message.
*/</jd>
<ja>@RestResource</ja>(
messages=<js>"HelloWorldResources"</js>,
config=<js>"config_dir/myconfig.cfg"</js>,
...
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> RestServletDefault {
<jd>/**
* GET request handler.
* Specify the GET parameter "?person=X" for a specialized message!
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> String sayHello(RestRequest req) {
<jk>return</jk> req.getConfig().getString(<js>"HelloWorldResource/message"</js>);
}
}
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.StaticFiles"></a>
<h3 class='topic' onclick='toggle(this)'>7.21 - Static files</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.RestResource#staticFiles @RestResource.staticFiles()}
annotation is used to define paths and locations of statically-served files such as images or HTML
documents.
</p>
<p>
The value is a JSON map of paths to packages/directories located on either the classpath or working
directory.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jk>package</jk> com.foo.mypackage;
<ja>@RestResource</ja>(
path=<js>"/myresource"</js>,
staticFiles={<js>"htdocs:docs"</js>}
)
<jk>public class</jk> MyResource <jk>extends</jk> RestServletDefault {...}
</p>
<p>
Static files are found by calling {@link java.lang.Class#getResource(String)} up the class hierarchy.
If not found, then an attempt is made to find the class in the Java working directory.
</p>
<p>
In the example above, given a GET request to <l>/myresource/htdocs/foobar.html</l>, the servlet will
attempt to find the <l>foobar.html</l> file in the following ordered locations:
</p>
<ol>
<li><l>com.foo.mypackage.docs</l> package.
<li><l>[working-dir]/docs</l> directory.
</ol>
<h5 class='section'>Notes:</h5>
<ul class='spaced-list'>
<li>
Mappings are cumulative from parent to child.
<br>Child resources can override mappings made on parent resources.
<li>
The media type on the response is determined by the
{@link org.apache.juneau.rest.RestContext#getMediaTypeForName(String)} method.
</ul>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_staticFiles}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.ClientVersioning"></a>
<h3 class='topic' onclick='toggle(this)'>7.22 - Client Versioning</h3>
<div class='topic'>
<p>
Client version headers are used to support backwards compatibility for breaking REST interface changes.
<br>Using them, you're able to return different responses based on which client is making a request.
</p>
<p>
The APIs involved with defining client version headers are:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#clientVersionHeader()}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#clientVersionHeader(String)}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#clientVersion()}
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Option #1 - Defined via annotation resolving to a config file setting with default value.</jc>
<ja>@RestResource</ja>(clientVersionHeader=<js>"Client-Version"</js>)
<jk>public class</jk> MyResource {
<jc>// Call this method if Client-Version is at least 2.0.
// Note that this also matches 2.0.1.</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/foobar"</js>, clientVersion=<js>"2.0"</js>)
<jk>public</jk> Object method1() {
...
}
<jc>// Call this method if Client-Version is at least 1.1, but less than 2.0.</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/foobar"</js>, clientVersion=<js>"[1.1,2.0)"</js>)
<jk>public</jk> Object method2() {
...
}
<jc>// Call this method if Client-Version is less than 1.1.</jc>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/foobar"</js>, clientVersion=<js>"[0,1.1)"</js>)
<jk>public</jk> Object method3() {
...
}
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_clientVersionHeader}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.OptionsPages"></a>
<h3 class='topic' onclick='toggle(this)'>7.23 - OPTIONS pages</h3>
<div class='topic'>
<p>
One of the most useful features of Juneau is the ability to generate Swagger-based OPTIONS pages for self-documenting designs
(i.e. REST interfaces that document themselves).
</p>
<h5 class='figure'>OPTIONS page for HelloWorld sample resource</h5>
<img class='bordered' src='doc-files/juneau-rest-server.OptionsPages.1.png' style='width:800px;'>
<p>
The {@link org.apache.juneau.rest.RestServletDefault} class implements the page by creating a method
mapped to the <l>OPTIONS</l> HTTP method that simply returns a Swagger bean:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(...)
<jk>public class</jk> RestServletDefault <jk>extends</jk> RestServlet {
<ja>@RestMethod</ja>(name=<jsf>OPTIONS</jsf>, path=<js>"/*"</js>,
summary=<js>"Resource options"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"back: servlet:/,"</js>,
<js>"json: servlet:/?method=OPTIONS&amp;Accept=text/json&amp;plainText=true"</js>
}
)
)
<jk>public</jk> Swagger getOptions(RestRequest req) {
<jk>return</jk> req.getSwagger();
}
}
</p>
<p>
This page is constructed using the Info Provider API described next.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestInfoProvider"></a>
<h4 class='topic' onclick='toggle(this)'>7.23.1 - RestInfoProvider</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestInfoProvider} class is used to find the title
and description for your resource and also generate the Swagger documentation.
<br>It can be overridden to provide your own custom Swagger documentation.
</p>
<p>
The methods on this interface are:
</p>
<ul class='doctree'>
<li class='jic'>{@link org.apache.juneau.rest.RestInfoProvider}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProvider#getSwagger(RestRequest) getSwagger(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProvider#getSiteName(RestRequest) getSiteName(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProvider#getTitle(RestRequest) getTitle(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProvider#getDescription(RestRequest) getDescription(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProvider#getMethodSummary(Method,RestRequest) getMethodSummary(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProvider#getMethodDescription(Method,RestRequest) getMethodDescription(Method,RestRequest)}
</ul>
</ul>
<p>
The info provider in turn supplies the information returned by the following methods:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.rest.RestRequest}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getSwagger() getSwagger()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getSiteName() getSiteName()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getResourceTitle() getResourceTitle()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getResourceDescription() getResourceDescription()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getMethodSummary() getMethodSummary()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getMethodDescription() getMethodDescription()}
</ul>
</ul>
<p>
Info providers are registered through the following property:
</p>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_infoProvider}
</ul>
<p>
While you can implement this interface from scratch, you may want to instead consider extending
from the <l>RestInfoProviderDefault</l> class described next.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RestInfoProviderDefault"></a>
<h4 class='topic' onclick='toggle(this)'>7.23.2 - RestInfoProviderDefault</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestInfoProviderDefault} class is the default implementation of the
{@link org.apache.juneau.rest.RestInfoProvider} interface.
</p>
<p>
It finds and collects information gathered from the following locations:
</p>
<ul>
<li>Localized JSON Swagger files in the classpath.
<li>Reflection.
<li> annotations.
<li>Info provided in properties files.
</ul>
<p>
The class itself is designed to be extended if you wish to rely mostly on the default behavior, but tweak
certain aspects.
</p>
<p>
In addition to the methods defined on the <l>RestInfoProvider</l> interface, it also includes the following methods:
</p>
<ul class='doctree'>
<li class='jc'><code>{@link org.apache.juneau.rest.RestInfoProviderDefault} <jk>implements</jk> {@link org.apache.juneau.rest.RestInfoProvider}</code>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getVersion(RestRequest) getVersion(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getContact(RestRequest) getContact(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getConsumes(RestRequest) getConsumes(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getProduces(RestRequest) getProduces(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getLicense(RestRequest) getLicense(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getTags(RestRequest) getTags(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getTermsOfService(RestRequest) getTermsOfService(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getExternalDocs(RestRequest) getExternalDocs(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodSummary(Method,RestRequest) getMethodSummary(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodDescription(Method,RestRequest) getMethodDescription(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodOperationId(Method,RestRequest) getMethodOperationId(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodConsumes(Method,RestRequest) getMethodConsumes(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodProduces(Method,RestRequest) getMethodProduces(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodParameters(Method,RestRequest) getMethodParameters(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodResponses(Method,RestRequest) getMethodResponses(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getMethodTags(Method,RestRequest) getMethodTags(Method,RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.RestInfoProviderDefault#getSwaggerFromFile(RestRequest) getSwaggerFromFile(RestRequest)}
</ul>
</ul>
<p>
The default provider provides several options for defining Swagger documentation on your resource:
</p>
<ul class='spaced-list'>
<li>
Provide nothing.
<br>You'll still get an auto-generated Swagger doc with information gather solely through reflection, including methods, parameters, consumes/produces, etc...
<li>
Specify localized JSON Swagger files on your classpath.
<br><h5 class='figure'>Example:</h5>
<p class='bcode'>
MyResource_ja_JP.json
</p>
<li>
Use {@link org.apache.juneau.rest.annotation.ResourceSwagger @ResourceSwagger} and {@link org.apache.juneau.rest.annotation.MethodSwagger @MethodSwagger}
annotations on your resource classes and methods.
<br><h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(
swagger=<ja>@MethodSwagger</ja>(tags=<js>"foo,bar,baz"</js>)
)
<jk>public</jk> Object myMethod() {...}
</p>
<li>
Use properties files identified by the {@link org.apache.juneau.rest.annotation.RestResource#messages @RestResource.messages()} annotation.
<br><h5 class='figure'>Example:</h5>
<p class='bcode'>
<ck>MyResource.myMethod.tags</ck> = <cv>foo,bar,baz</cv>
</p>
<li>
Use any combination of the above.
<li>
Extend the <l>RestInfoProviderDefault</l> and provide customized behavior.
<br><h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Our customized info provider.</jc>
<jc>// Extend from the default implementation and selectively override values.</jc>
<jk>public class</jk> MyRestInfoProvider <jk>extends</jk> RestInfoProviderDefault {
<jc>// Must provide this constructor!</jc>
<jk>public</jk> MyRestInfoProvider(RestContext context) {
<jk>super</jk>(context);
}
<ja>@Override</ja> <jc>/* RestInfoProvider */</jc>
<jk>public</jk> Swagger getSwagger(RestRequest req) <jk>throws</jk> RestException {
Swagger s = <jk>super</jk>.getSwagger(req);
<jc>// Made inline modifications to generated swagger.</jc>
<jk>return</jk> s;
}
}
<jc>// Registered via annotation</jc>
<ja>@RestResource</ja>(infoProvider=MyRestInfoProvider.<jk>class</jk>)
<jk>public class</jk> MyResource {...}
</p>
</ul>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.HtmlDocAnnotation"></a>
<h3 class='topic' onclick='toggle(this)'>7.24 - @HtmlDoc</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.annotation.HtmlDoc @HtmlDoc} annotation is used to customize the HTML
view of your serialized POJOs.
<br>It's used in the following locations:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestResource#htmldoc()}
<li class='ja'>{@link org.apache.juneau.rest.annotation.RestMethod#htmldoc()}
</ul>
<p>
The annotation itself is just a convenience for setting configuration properties set
on the {@link org.apache.juneau.html.HtmlDocSerializer} class.
<br>For example, the following two pieces of code are equivalent:
</p>
<p class='bcode'>
<jc>// Title defined via property.</jc>
<ja>@RestResource</ja>(
properties={
<ja>@Property</ja>(name=<jsf>HTMLDOC_title</jsf>, value=<js>"My Resource Page"</js>)
}
)
<jc>// Title defined via @HtmlDoc annotation.</jc>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
title=<js>"My Resource Page"</js>
)
)
</p>
<p>
The purpose of these annotation is to populate the HTML document view which by default consists of the following
structure:
</p>
<p class='bcode'>
<xt>&lt;html&gt;
&lt;head&gt;
&lt;style <xa>type</xa>=<xs>'text/css'</xs>&gt;
<xv>CSS styles and links to stylesheets</xv>
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;header&gt;
<xv>Page header</xv>
&lt;/header&gt;
&lt;nav&gt;
<xv>Navigation links</xv>
&lt;/nav&gt;
&lt;aside&gt;
<xv>Side-bar text</xv>
&lt;/aside&gt;
&lt;article&gt;
<xv>Contents of serialized object</xv>
&lt;/article&gt;
&lt;footer&gt;
<xv>Footer message</xv>
&lt;/footer&gt;
&lt;/body&gt;
&lt;/html&gt;</xt>
</p>
<p>
The outline above is controlled by the {@link org.apache.juneau.html.HtmlDocTemplate} interface
which can be overridden via the {@link org.apache.juneau.rest.annotation.HtmlDoc#template @HtmlDoc.template()} annotation.
</p>
<p>
The <l>HelloWorldResource</l> class was an example of the <l>@HtmlDoc</l> annotation in use:
</p>
<p class='bcode'>
<jd>/**
* Sample REST resource that prints out a simple "Hello world!" message.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/helloWorld"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
},
aside={
<js>"&lt;div style='max-width:400px' class='text'&gt;"</js>,
<js>" &lt;p&gt;This page shows a resource that simply response with a 'Hello world!' message&lt;/p&gt;"</js>,
<js>" &lt;p&gt;The POJO serialized is a simple String.&lt;/p&gt;"</js>,
<js>"&lt;/div&gt;"</js>
}
)
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> RestServletDefault {...}
</p>
<p>
SVL variables can be used in any of these annotations:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/helloWorld"</js>,
<jc>// Register a config file.</jc>
config=<js>"MyConfig.cfg"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>,
<jc>// Add a nav link to view the source code for this class.</jc>
<js>"source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java"</js>
},
aside={
<jc>// Localize our messages.</jc>
<js>"&lt;div style='max-width:400px' class='text'&gt;"</js>,
<js>" &lt;p&gt;$L{localizedMessage1}&lt;/p&gt;"</js>,
<js>" &lt;p&gt;$L{localizedMessage2}&lt;/p&gt;"</js>,
<js>"&lt;/div&gt;"</js>
}
)
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> RestServletDefault {...}
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.HtmlDoc}
<li class='jc'>{@link org.apache.juneau.rest.HtmlDocBuilder}
</ul>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Widgets"></a>
<h4 class='topic' onclick='toggle(this)'>7.24.1 - Widgets</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.widget.Widget} class allows you to add arbitrary HTML, CSS, and Javascript
to HTML pages.
<br>They are registered in the following locations:
</p>
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.HtmlDoc#widgets() @HtmlDoc.widgets}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#widgets(Class...)}
<li class='jm'>{@link org.apache.juneau.rest.RestContextBuilder#widgets(Widget...)}
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_widgets}
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<ja>@RestMethod</ja>(
widgets={
MyWidget.<jk>class</jk>
}
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"$W{MyWidget}"</js>
},
aside={
<js>"Check out this widget: $W{MyWidget}"</js>
}
)
)
</p>
<p>
The <l>Widget</l> class is composed of the following methods:
</p>
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.rest.widget.Widget}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.widget.Widget#getHtml(RestRequest) getHtml(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.widget.Widget#getStyle(RestRequest) getStyle(RestRequest)}
<li class='jm'>{@link org.apache.juneau.rest.widget.Widget#getScript(RestRequest) getScript(RestRequest)}
</ul>
</ul>
<p>
The HTML content returned by the {@link org.apache.juneau.rest.widget.Widget#getHtml(RestRequest) getHtml(RestRequest)}
method is added wherever the <js>"$W{...}"</js> variable is used.
</p>
<p>
The CSS returned by {@link org.apache.juneau.rest.widget.Widget#getScript(RestRequest) getScript(RestRequest)}
is added to the style section in the page header.
</p>
<p>
The Javascript returned by {@link org.apache.juneau.rest.widget.Widget#getScript(RestRequest) getScript(RestRequest)}
is added to the script section in the page header.
</p>
<p>
The following examples shows how to associate a widget with a REST method and then have it rendered in the links
and aside section of the page.
<br>It shows an example of a widget that renders an image located in the <code>htdocs</code> static files
directory in your classpath (see {@link org.apache.juneau.rest.annotation.RestResource#staticFiles() @RestResource.staticFiles()}):
</p>
<p class='bcode'>
<jk>public class</jk> MyWidget <jk>extends</jk> Widget {
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getHtml(RestRequest req) <jk>throws</jk> Exception {
UriResolver r = req.getUriResolver(); <jc>// API used for resolving URIs.</jc>
<jk>return</jk> <js>"&lt;img class='myimage' onclick='myalert(this)' src='"</js>+r.resolve(<js>"servlet:/htdocs/myimage.png"</js>)+<js>"'&gt;"</js>;
}
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getScript(RestRequest req) <jk>throws</jk> Exception {
<jk>return</jk> <js>""</js>
+ <js>"\n function myalert(imageElement) {"</js>
+ <js>"\n alert('cool!');"</js>
+ <js>"\n }"</js>;
}
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getStyle(RestRequest req) <jk>throws</jk> Exception {
<jk>return</jk> <js>""</js>
+ <js>"\n .myimage {"</js>
+ <js>"\n border: 10px solid red;"</js>
+ <js>"\n }"</js>;
}
}
</p>
<p>
The <l>Widget</l> class also defines the following two convenience methods for loading Javascript and CSS
files from the classpath or file system.
</p>
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.rest.widget.Widget}
<ul>
<li class='jm'>{@link org.apache.juneau.rest.widget.Widget#getClasspathResourceAsString(String) getClasspathResourceAsString(String)}
<li class='jm'>{@link org.apache.juneau.rest.widget.Widget#getClasspathResourceAsString(String,Locale) getClasspathResourceAsString(String,Locale)}
</ul>
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jk>public class</jk> MyWidget <jk>extends</jk> Widget {
...
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getScript(RestRequest req) <jk>throws</jk> Exception {
<jk>return</jk> getClasspathResourceAsString(<js>"MyWidget.js"</js>);
}
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getStyle(RestRequest req) <jk>throws</jk> Exception {
<jk>return</jk> getClasspathResourceAsString(<js>"MyWidget.css"</js>);
}
}
</p>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jf'>{@link org.apache.juneau.rest.RestContext#REST_widgets}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.PredefinedWidgets"></a>
<h4 class='topic' onclick='toggle(this)'>7.24.2 - Predefined Widgets</h4>
<div class='topic'>
TODO
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.UiCustomization"></a>
<h4 class='topic' onclick='toggle(this)'>7.24.3 - UI Customization</h4>
<div class='topic'>
<p>
The HTML views of POJOs can somewhat be considered a rudimentary User Interface.
<br>In reality, a better term for them would be a Developer Interface as they're meant to be used
primarily by developers and not end users.
<br>Despite that distinction, it is possible to 'brand' the HTML page to whatever you desire.
</p>
<p>
The sample root page below includes some default branding for Juneau and Apache:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.UiCustomization.1.png' style='width:800px'/>
<p>
In particular, you may want to replace these icons:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.UiCustomization.2.png'/>
<img class='bordered' src='doc-files/juneau-rest-server.UiCustomization.3.png'/>
<p>
The Juneau REST framework does not provide specific branding support (i.e. there is no concept of a brand icon).
<br>Instead, it just uses the existing open-ended API for defining branding.
</p>
<p>
The Juneau icon shown is a result of the header annotation on the {@link org.apache.juneau.rest.RestServletDefault} class:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
...
htmldoc=<ja>@HtmlDoc</ja>(
header={
<js>"&lt;h1&gt;$R{resourceTitle}&lt;/h1&gt;"</js>,
<js>"&lt;h2&gt;$R{methodSummary,resourceDescription}&lt;/h2&gt;"</js>,
<js>"&lt;a href='http://juneau.apache.org'&gt;"</js>
+<js>"&lt;img src='$U{servlet:/htdocs/juneau.png}' style='position:absolute;top:5;right:5;background-color:transparent;height:30px'/&gt;"</js>
+<js>"&lt;/a&gt;"</js>
},
head={
<jc>// Browser tab icon.</jc>
<js>"&lt;link rel='icon' href='$U{servlet:/htdocs/juneau.png}'/&gt;"</js>
}
),
staticFiles={<js>"htdocs:htdocs"</js>}
)
<jk>public abstract class</jk> RestServletDefault <jk>extends</jk> RestServlet {...}
</p>
<p>
The <js>"juneau.png"</js> image file is located in <code>org.apache.juneau.rest.htdocs</code> package and
is served up via the <code>staticFiles</code> annotation (i.e. anything in the <code>org.apache.juneau.rest.htdocs</code>
package is served up under the path <code>/servlet-path/htdocs</code>).
<br>Then we just reference using a URI resolution variable <js>"$U{servlet:/htdocs/juneau.png}"</js>.
</p>
<p>
To change this image, you can extend the <l>RestServletDefault</l> class and simply override the annotations
pointing to your own icon.
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
...
htmldoc=<ja>@HtmlDoc</ja>(
header={
<js>"&lt;h1&gt;$R{resourceTitle}&lt;/h1&gt;"</js>,
<js>"&lt;h2&gt;$R{methodSummary,resourceDescription}&lt;/h2&gt;"</js>,
<js>"&lt;a href='http://my.project.org'&gt;"</js>
+<js>"&lt;img src='$U{servlet:/my-htdocs/my-project.png}' style='position:absolute;top:5;right:5;background-color:transparent;height:30px'/&gt;"</js>
+<js>"&lt;/a&gt;"</js>
},
head={
<jc>// Browser tab icon.</jc>
<js>"&lt;link rel='icon' href='$U{servlet:/my-htdocs/my-project.png}'/&gt;"</js>
}
),
staticFiles={<js>"my-htdocs:my-htdocs"</js>}
)
<jk>public class</jk> MyResourceBaseClass <jk>extends</jk> RestServletDefault {...}
</p>
<p>
The footer icon shown is generated by a predefined widget:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
widgets={
PoweredByApache.<jk>class</jk>
},
footer=<js>"$W{PoweredByApache}"</js>
),
...
)
<jk>public class</jk> RootResources <jk>extends</jk> ResourceJenaGroup {...}
</p>
<p>
The widget definition is shown below:
</p>
<p class='bcode'>
<jk>public class</jk> PoweredByApache <jk>extends</jk> Widget {
<jd>/**
* Returns an Apache image tag hyperlinked to <js>"http://apache.org"</js>
*/</jd>
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getHtml(RestRequest req) <jk>throws</jk> Exception {
UriResolver r = req.getUriResolver();
<jk>return</jk> <js>"&lt;a href='http://apache.org'&gt;&lt;img style='float:right;padding-right:20px;height:32px' src='"</js>+r.resolve(<js>"servlet:/htdocs/asf.png"</js>)+<js>"'&gt;"</js>;
}
}
</p>
<p>
To provide your own footer icon, simply define it in your own footer section:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
footer=<js>"&lt;img style='float:right;padding-right:20px;height:32px' src='$U{servlet:/my-htdocs/my-project.png}'&gt;"</js>
),
staticFiles={<js>"my-htdocs:my-htdocs"</js>}
...
)
<jk>public class</jk> MyResourceBaseClass <jk>extends</jk> RestServletDefault {...}
</p>
<p>
Note how the "User Interface" is open-ended to pretty much lets you do whatever you want.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.Stylesheets"></a>
<h4 class='topic' onclick='toggle(this)'>7.24.4 - Stylesheets</h4>
<div class='topic'>
<p>
The sample root page renders in the default "devops" look-and-feel:
</p>
<img class='bordered' src='doc-files/UiCustomization.1.png' style='width:800px'/>
<p>
The sample root page provides a dropdown widget to try out the other default look-and-feels:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.Stylesheets.1.png'/>
<p>
For example, the "light" look-and-feel:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.Stylesheets.2.png' style='width:800px'/>
<p>
And the "dark" look-and-feel:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.Stylesheets.3.png' style='width:800px'/>
<p>
The stylesheet URL is controlled by the {@link org.apache.juneau.rest.annotation.HtmlDoc#stylesheet() @HtmlDoc.stylesheet()} annotation.
<br>The {@link org.apache.juneau.rest.RestServletDefault} class defines the stylesheet served up as a static file:
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
stylesheet=<js>"$C{REST/stylesheet,servlet:/styles/devops.css}"</js>,
),
staticFiles={<js>"styles:styles"</js>}
)
<jk>public abstract class</jk> RestServletDefault <jk>extends</jk> RestServlet {...}
</p>
<p>
The <js>"$C{REST/stylesheet,servlet:/styles/devops.css}"</js> variable says to use the URI defined
in your servlet's config file, if there is one, and to default to serving up the file
<code>org/apache/juneau/rest/styles/devops.css</code>.
</p>
<p>
To provide your own stylesheet, simply override the stylesheet attribute and point to a different
file:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
stylesheet=<js>"servlet:/my-styles/my-style.css}"</js>,
),
staticFiles={<js>"my-styles:my-styles"</js>}
)
<jk>public class</jk> MyResourceBaseClass <jk>extends</jk> RestServletDefault {...}
</p>
<p>
You can try out different stylesheets by passing in a <code>stylesheet</code> attribute in the request
URL.
<br>The example above show this in use.
</p>
<p>
In case you're curious about how the menu item works, it's defined via a widget:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
widgets={
PoweredByApache.<jk>class</jk>,
ContentTypeMenuItem.<jk>class</jk>,
StyleMenuItem.<jk>class</jk>
},
navlinks={
<js>"options: ?method=OPTIONS"</js>,
<js>"$W{ContentTypeMenuItem}"</js>,
<js>"$W{StyleMenuItem}"</js>,
<js>"source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java"</js>
},
)
<jk>public class</jk> RootResources <jk>extends</jk> ResourceJenaGroup {...}
</p>
<p>
The <l>StyleMenuItem</l> is a widget that extends from {@link org.apache.juneau.rest.widget.MenuItemWidget}, a
specialized widget for creating pop-up menus.
<br>In the case of <l>StyleMenuItem</l>, it's simply returning a list of links wrapped in a div tag:
</p>
<p class='bcode'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
<jk>public class</jk> StyleMenuItem <jk>extends</jk> MenuItemWidget {
<jk>private static final</jk> String[] <jsf>BUILT_IN_STYLES</jsf> = {<js>"devops"</js>, <js>"light"</js>, <js>"original"</js>, <js>"dark"</js>};
<ja>@Override</ja> <jc>/* Widget */</jc>
<jk>public</jk> String getLabel(RestRequest req) {
<jk>return</jk> <js>"styles"</js>;
}
<ja>@Override</ja> <jc>/* MenuItemWidget */</jc>
<jk>public</jk> Div getContent(RestRequest req) <jk>throws</jk> Exception {
Div div = <jsm>div</jsm>();
<jk>for</jk> (String s : <jsf>BUILT_IN_STYLES</jsf>) {
java.net.URI uri = req.getUri(<jk>true</jk>, <jk>new</jk> AMap&lt;String,String&gt;().append(<js>"stylesheet"</js>, <js>"styles/"</js>+s+<js>".css"</js>));
div.children(<jsm>a</jsm>(uri, s), <jsm>br</jsm>());
}
<jk>return</jk> div;
}
}
</p>
</div>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.DefaultHeaders"></a>
<h3 class='topic' onclick='toggle(this)'>7.25 - Default Headers</h3>
<div class='topic'>
<p>
The following annotations are provided for specifying default header values for requests and responses:
</p>
<ul class='doctree'>
<li class='ja'>
{@link org.apache.juneau.rest.annotation.RestResource#defaultRequestHeaders() @RestResource.defaultRequestHeaders()}
<br>Defines default headers on request when the client doesn't specify them.
<li class='ja'>
{@link org.apache.juneau.rest.annotation.RestResource#defaultResponseHeaders() @RestResource.defaultResponseHeaders()}
<br>Appends the specified headers if they weren't already set programmatically.
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Servlet with default headers</jc>
<ja>@RestResource</ja>(
<jc>// Assume "text/json" Accept value when Accept not specified</jc>
defaultRequestHeaders={<js>"Accept: text/json"</js>},
<jc>// Add a version header attribute to all responses</jc>
defaultResponseHeaders={<js>"X-Version: 1.0"</js>}
)
<jk>public</jk> MyRestServlet <jk>extends</jk> RestServlet {
...
}
</p>
<p>
Default headers can also be specified programmatically by overriding the following methods:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.rest.RestContextBuilder}
<ul>
<li class='jm'>
{@link org.apache.juneau.rest.RestContextBuilder#defaultRequestHeaders(String[])}
<li class='jm'>
{@link org.apache.juneau.rest.RestContextBuilder#defaultResponseHeaders(String[])}
</ul>
</li>
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.LoggingAndErrorHandling"></a>
<h3 class='topic' onclick='toggle(this)'>7.26 - Logging and Error Handling</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.RestContext#REST_logger} property allows you to configure
logging for your resource.
<br>The interface is shown below:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.rest.RestLogger}
<ul>
<li class='jm'>
{@link org.apache.juneau.rest.RestLogger#log(Level,String,Object[]) log(Level,String,Object[])}
<li class='jm'>
{@link org.apache.juneau.rest.RestLogger#log(Level,Throwable,String,Object[]) log(Level,Throwable,String,Object[])}
<li class='jm'>
{@link org.apache.juneau.rest.RestLogger#logObjects(Level,String,Object[]) logObjects(Level,String,Object[])}
<li class='jm'>
{@link org.apache.juneau.rest.RestLogger#onError(HttpServletRequest,HttpServletResponse,RestException) onError(HttpServletRequest,HttpServletResponse,RestException)}
<br>Gets called when an error occurs on a request call.
<br>Default implementation logs the error.
</ul>
</li>
</ul>
<p>
The {@link org.apache.juneau.rest.RestLogger#logObjects(Level,String,Object[]) logObjects()} method is particularly useful because it allows you to pass in POJOs as arguments
that serialized using {@link org.apache.juneau.json.JsonSerializer#DEFAULT_LAX_READABLE}, but only
if the message is actually logged.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
logger.logObjects(<jsf>DEBUG</jsf>, <js>"Pojo contents:\n{0}"</js>, myPojo);
</p>
<p>
By default, the Juneau framework uses the built-in Java Logging API for logging.
<br>But you can define your own implementation to use any framework you wish.
</p>
<p>
The {@link org.apache.juneau.rest.RestLogger} instance is accessible via the following:
</p>
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestContext#getLogger()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getLogger()}
</ul>
<p>
In addition, the logger can be accessed by passing it as a parameter to your REST java method:
</p>
<p class='bcode'>
<ja>@RestMethod()</ja>
<jk>public</jk> Object doSomething(RestLogger logger) {...}
</p>
<p>
If your resource extends from {@link org.apache.juneau.rest.RestServlet}, you can also
use and override the following methods:
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestServlet#log(Level,String,Object...)}
<li class='jm'>{@link org.apache.juneau.rest.RestServlet#log(Level,Throwable,String,Object...)}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.HttpStatusCodes"></a>
<h3 class='topic' onclick='toggle(this)'>7.27 - HTTP Status Codes</h3>
<div class='topic'>
<p>
By default, a 200 (OK) status is automatically set as the HTTP status when a Java method executes
successfully.
</p>
<p>
Other status codes can be generated by throwing a {@link org.apache.juneau.rest.RestException} with a
specific HTTP status code, or calling {@link javax.servlet.http.HttpServletResponse#setStatus(int)}.
</p>
<p>
Non-OK (200) status codes are automatically triggered by the following conditions:
</p>
<table class='styled' style='max-width:800px;'>
<tr>
<th><l>Code</l></th>
<th><l>Description</l></th>
<th><l>When triggered</l></th>
</tr>
<tr>
<td><l>401</l></td>
<td>Unauthorized</td>
<td>A {@link org.apache.juneau.rest.RestGuard guard} prevented the method from being executed</td>
</tr>
<tr>
<td><l>404</l></td>
<td>Not Found</td>
<td>No matching path patterns were found on any method</td>
</tr>
<tr>
<td><l>405</l></td>
<td>Method Not Implemented</td>
<td>A path pattern matched, but no Java methods were found for the HTTP method</td>
</tr>
<tr>
<td><l>406</l></td>
<td>Not Acceptable</td>
<td>
A path pattern matched, but no Java methods were found with a matching serializer for the
<l>Accept</l> on the request
</td>
</tr>
<tr>
<td><l>412</l></td>
<td>Precondition Failed</td>
<td>
A path pattern matched, but no Java methods were found that were not rejected by
{@link org.apache.juneau.rest.RestMatcher matchers}
</td>
</tr>
<tr>
<td><l>415</l></td>
<td>Unsupported Media Type</td>
<td>
A path pattern matched, but no Java methods were found with a matching parser for the
<l>Content-Type</l> on the request
</td>
</tr>
<tr>
<td><l>500</l></td>
<td>Internal Server Error</td>
<td>The Java method threw an exception other than {@link org.apache.juneau.rest.RestException}</td>
</tr>
</table>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.OverloadingHttpMethods"></a>
<h3 class='topic' onclick='toggle(this)'>7.28 - Overloading HTTP Methods</h3>
<div class='topic'>
<p>
Through the use of the built-in <l>"method"</l> GET parameter, you can implement requests beyond the basic
REST http method types.
</p>
<p>
For example, the URL <l>"/sample/foo?method=BAR"</l> will cause the following method to be invoked...
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<js>"BAR"</js>)
<jk>public void</jk> doBar(RestRequest req, RestResponse res) {
<jc>// Handle BAR requests</jc>
}
</p>
<p>
To support overloaded methods, the {@link org.apache.juneau.rest.annotation.RestResource#allowedMethodParams() @RestResource.allowedMethodParams()}
setting must be enabled on your servlet.
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
<jc>// Allow &amp;method parameter on BAR requests</jc>
allowedMethodParams=<js>"BAR"</js>
)
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.BuiltInParameters"></a>
<h3 class='topic' onclick='toggle(this)'>7.29 - Built-in Parameters</h3>
<div class='topic'>
<p>
The following URL parameters have special meaning and can be passed in through the URL of the request:
</p>
<table class='styled' style='max-width:800px'>
<tr>
<th><l>GET Parameter</l></th>
<th><l>Description</l></th>
</tr>
<tr>
<td class='code'>&amp;plainText=true</td>
<td>
Response will always be <l>Content-Type: text/plain</l> and the returned text will be human-readable
({@link org.apache.juneau.serializer.Serializer#SERIALIZER_useWhitespace SERIALIZER_useWhitespace} enabled).
<br>Useful for debugging.
</td>
</tr>
<tr>
<td class='code'>&amp;debug=true</td>
<td>
Request body content will be dumped to log file.
</td>
</tr>
<tr>
<td class='code'>&amp;noTrace=true</td>
<td>
If an error occurs, don't log the stack trace to the log file.
<br>Useful for automated JUnit testcases testing error states to prevent the log file from filling
up with useless stack traces.
</td>
</tr>
<tr>
<td class='code'>&amp;method=X</td>
<td>
Overload the HTTP method as a GET parameter (e.g <l>"POST"</l>).
<br>Must be enabled via {@link org.apache.juneau.rest.annotation.RestResource#allowedMethodParams() @RestResource.allowedMethodParams()} setting.
</td>
</tr>
<tr>
<td class='code'>&amp;Header-Name=headerValue</td>
<td>
Specify a header value as a GET parameter.
<br>Must be enabled via {@link org.apache.juneau.rest.annotation.RestResource#allowHeaderParams() @RestResource.allowHeaderParams()} setting.
</td>
</tr>
<tr>
<td class='code'>&amp;body=X</td>
<td>
Pass in the HTTP body content on PUT and POST methods as a UON-encoded GET parameter.
<br>Must be enabled via {@link org.apache.juneau.rest.annotation.RestResource#allowBodyParam() @RestResource.allowBodyParam()} setting.
</td>
</tr>
<tr>
<td class='code'>&amp;x-response-headers=X</td>
<td>
Pass-through headers to the response.
<br>Must be a UON-encoded map of key-value pairs.
</td>
</tr>
</table>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.CustomSerializersAndParsers"></a>
<h3 class='topic' onclick='toggle(this)'>7.30 - Custom Serializers and Parsers</h3>
<div class='topic'>
<p>
A very easy-to-use API is provided for defining your own serializers and parsers at both the servlet and
method levels.
</p>
<p>
The following examples show a custom serializer and parser defined at the method level.
It's the <l>PhotosResource</l> class pulled from the Samples project.
It shows an example of defining a serializer and parser to handle images.
</p>
<p class='bcode'>
<jd>/**
* Sample resource that allows images to be uploaded and retrieved.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/photos"</js>,
messages=<js>"nls/PhotosResource"</js>,
title=<js>"Photo REST service"</js>,
description=<js>"Use a tool like Poster to upload and retrieve jpeg and png images."</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"options: ?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> PhotosResource <jk>extends</jk> RestServletDefault {
<jc>// Our cache of photos</jc>
<jk>private</jk> Map&lt;Integer,Photo&gt; photos = <jk>new</jk> TreeMap&lt;Integer,Photo&gt;();
<jd>/** Bean class for storing photos */</jd>
<jk>public static class</jk> Photo {
<jk>private int</jk> <jf>id</jf>;
BufferedImage <jf>image</jf>;
Photo(int id, BufferedImage image) {
<jk>this</jk>.<jf>id</jf> = id;
<jk>this</jk>.<jf>image</jf> = image;
}
<jk>public</jk> URI getURI() <jk>throws</jk> URISyntaxException {
<jk>return new</jk> URI(<js>"photos/"</js>+<jf>id</jf>);
}
<jk>public int</jk> getID() {
<jk>return</jk> <jf>id</jf>;
}
}
<jd>/** GET request handler for list of all photos */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> Collection&lt;Photo&gt; getAllPhotos(RestRequest req, RestResponse res) <jk>throws</jk> Exception {
res.setPageTitle(<js>"Photo REST service"</js>);
res.setPageText(<js>"Use a tool like Poster to upload and retrieve jpeg and png images."</js>);
<jk>return</jk> photos.values();
}
<jd>/** GET request handler for single photo */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/{id}"</js>, serializers=ImageSerializer.<jk>class</jk>)
<jk>public</jk> BufferedImage getPhoto(RestRequest req, <ja>@Path</ja> int id) <jk>throws</jk> Exception {
Photo p = photos.get(id);
if (p == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Photo not found"</js>);
<jk>return</jk> p.image;
}
<jd>/** PUT request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/{id}"</js>, parsers=ImageParser.<jk>class</jk>)
<jk>public</jk> String addPhoto(RestRequest req, <ja>@Path</ja> <jk>int</jk> id, <ja>@Body</ja> BufferedImage image) <jk>throws</jk> Exception {
photos.put(id, <jk>new</jk> Photo(id, image));
<jk>return</jk> <js>"OK"</js>;
}
<jd>/** POST request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>, parsers=ImageParser.<jk>class</jk>)
<jk>public</jk> Photo setPhoto(RestRequest req, <ja>@Body</ja> BufferedImage image) <jk>throws</jk> Exception {
<jk>int</jk> id = photos.size();
Photo p = <jk>new</jk> Photo(id, image);
photos.put(id, p);
<jk>return</jk> p;
}
<jd>/** DELETE request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>DELETE</jsf>, path=<js>"/{id}"</js>)
<jk>public</jk> String deletePhoto(RestRequest req, <ja>@Path</ja> <jk>int</jk> id) <jk>throws</jk> Exception {
Photo p = photos.remove(id);
if (p == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Photo not found"</js>);
<jk>return</jk> <js>"OK"</js>;
}
<jd>/** OPTIONS request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>OPTIONS</jsf>, path=<js>"/*"</js>)
<jk>public</jk> Swagger getOptions(RestRequest req) {
<jk>return</jk> req.getSwagger();
}
<jd>/** Serializer for converting images to byte streams */</jd>
<ja>@Produces</ja>(<js>"image/png,image/jpeg"</js>)
<jk>public static class</jk> ImageSerializer <jk>extends</jk> OutputStreamSerializer {
<ja>@Override</ja> <jc>/* Serializer */</jc>
<jk>public void</jk> serialize(Object o, OutputStream out, SerializerSession session) <jk>throws</jk> IOException, SerializeException {
RenderedImage image = (RenderedImage)o;
String mediaType = ctx.getMediaType();
ImageIO.<jsm>write</jsm>(image, mediaType.substring(mediaType.indexOf(<js>'/'</js>)+1), out);
}
}
<jd>/** Parser for converting byte streams to images */</jd>
<ja>@Consumes</ja>(<js>"image/png,image/jpeg"</js>)
<jk>public static class</jk> ImageParser <jk>extends</jk> InputStreamParser {
<ja>@Override</ja> <jc>/* Parser */</jc>
<jk>public</jk> &lt;T&gt; T parse(InputStream in, ClassMeta&lt;T&gt; type, ParserSession session) <jk>throws</jk> ParseException, IOException {
BufferedImage image = ImageIO.<jsm>read</jsm>(in);
<jk>return</jk> (T)image;
}
}
}
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.UsingWithOsgi"></a>
<h3 class='topic' onclick='toggle(this)'>7.31 - Using with OSGi</h3>
<div class='topic'>
<p>
Since REST servlets are basically just <l>HttpServlets</l>, incorporating them into an OSGi environment
is pretty straightforward.
</p>
<p>
The following code shows how to register your REST servlets in an OSGi <l>Activator</l>:
</p>
<p class='bcode'>
<jk>package</jk> org.apache.juneau.examples.rest;
<jk>import</jk> org.osgi.framework.*;
<jk>import</jk> org.osgi.service.http.*;
<jk>import</jk> org.osgi.util.tracker.*;
<jk>import</jk> org.apache.juneau.rest.samples.*;
<jd>/**
* Activator class used when running samples as a bundle in an OSGi environment.
*/</jd>
<jk>public class</jk> Activator <jk>implements</jk> BundleActivator, ServiceTrackerCustomizer {
<jk>private</jk> ServiceTracker <jf>httpServiceTracker</jf>;
<jk>private</jk> BundleContext <jf>context</jf>;
<ja>@Override</ja> <jc>/* BundleActivator */</jc>
<jk>public void</jk> start(BundleContext context) <jk>throws</jk> Exception {
<jk>this</jk>.<jf>context</jf> = context;
<jf>httpServiceTracker</jf> = <jk>new</jk> ServiceTracker(context, HttpService.<jk>class</jk>.getName(), <jk>this</jk>);
<jf>httpServiceTracker</jf>.open();
}
<ja>@Override</ja> <jc>/* BundleActivator */</jc>
<jk>public void</jk> stop(BundleContext context) <jk>throws</jk> Exception {
<jf>httpServiceTracker</jf>.close();
}
<ja>@Override</ja> <jc>/* ServiceTrackerCustomizer */</jc>
<jk>public</jk> Object addingService(ServiceReference reference) {
Object service = <jf>context</jf>.getService(reference);
<jk>if</jk> (service <jk>instanceof</jk> HttpService) {
HttpService s = (HttpService)service;
<jk>try</jk> {
s.registerServlet(<js>"/sample"</js>, <jk>new</jk> MyRestServlet(), <jk>null</jk>, <jk>null</jk>);
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RuntimeException(e);
}
}
<jk>return</jk> service;
}
<ja>@Override</ja> <jc>/* ServiceTrackerCustomizer */</jc>
<jk>public void</jk> modifiedService(ServiceReference reference, Object service) {
}
<ja>@Override</ja> <jc>/* ServiceTrackerCustomizer */</jc>
<jk>public void</jk> removedService(ServiceReference reference, Object service) {
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-server.RemoteableProxies"></a>
<h3 class='topic' onclick='toggle(this)'>7.32 - Remoteable Proxies</h3>
<div class='topic'>
<p>
The Remoteable Service API allows for client side code to use interface proxies for calling methods on POJOs on
the server side.
</p>
<p>
Proxy interfaces are retrieved using the {@link org.apache.juneau.rest.client.RestClient#getRemoteableProxy(Class)}
method.
The remoteable servlet is a specialized subclass of {@link org.apache.juneau.rest.RestServlet} that provides a
full-blown REST interface for calling remoteable services (e.g. POJOs) remotely.
</p>
<p>
The following simplified example shows how a method on a POJO on a server can be called through an interface
on a client...
</p>
<p class='bcode'>
<jk>public interface</jk> IAddressBook {
Person createPerson(CreatePerson cp) <jk>throws</jk> Exception;
Person findPerson(<jk>int</jk> id);
Address findAddress(<jk>int</jk> id);
Person findPersonWithAddress(<jk>int</jk> id);
}
</p>
<p>
The client side code for invoking this method is shown below...
</p>
<p class='bcode'>
<jc>// Create a RestClient using JSON for serialization, and point to the server-side remoteable servlet.</jc>
RestClient client = RestClient.<jsm>create</jsm>()
.rootUrl(<js>"https://localhost:9080/juneau/sample/remoteable"</js>)
.build();
<jc>// Create a proxy interface.</jc>
IAddressBook ab = client.getRemoteableProxy(IAddressBook.<jk>class</jk>);
<jc>// Invoke a method on the server side and get the returned result.</jc>
Person p = ab.createPerson(
<jk>new</jk> CreatePerson(<js>"Test Person"</js>,
AddressBook.<jsm>toCalendar</jsm>(<js>"Aug 1, 1999"</js>),
<jk>new</jk> CreateAddress(<js>"Test street"</js>, <js>"Test city"</js>, <js>"Test state"</js>, 12345, <jk>true</jk>))
);
</p>
<p>
The requirements for a method to be callable through the remoteable service are:
</p>
<ul class='spaced-list'>
<li>
The method must be public.
<li>
The parameter and return types must be <a class='doclink' href='#juneau-marshall.PojoCategories'>serializable and parsable</a>.
</ul>
<p>
Juneau provides the capability of calling methods on POJOs on a server through client-side proxy interfaces.
It offers a number of advantages over other similar remote proxy interfaces, such as being much simpler to
define and use, and allowing much more flexibility in the types of objects serialized.
</p>
<p>
The remote proxy interface API allows you to invoke server-side POJO methods on the client side using REST as
the communications protocol:
</p>
<p class='bcode'>
<jc>// Create a client with basic JSON support.</jc>
RestClient client = RestClient.<jsm>create</jsm>().rootUrl(<js>"http://localhost/remoteable"</js>).build();
<jc>// Get an interface proxy.</jc>
IAddressBook ab = client.getRemoteableProxy(IAddressBook.<jk>class</jk>);
<jc>// Invoke a method on the server side and get the returned result.</jc>
Person p = ab.createPerson(
<jk>new</jk> Person(
<js>"John Smith"</js>,
<js>"Aug 1, 1999"</js>,
<jk>new</jk> Address(<js>"My street"</js>, <js>"My city"</js>, <js>"My state"</js>, 12345, <jk>true</jk>)
)
);
</p>
<p>
Under the covers, this method call gets converted to a REST POST.
</p>
<p class='bcode'>
HTTP POST http://localhost/remoteable/org.apache.juneau.examples.rest.IAddressBook/createPerson
Accept: application/json
Content-Type: application/json
[
{
"name":"John Smith",
"birthDate":"Aug 1, 1999",
"addresses":[
{
"street":"My street",
"city":"My city",
"state":"My state",
"zip":12345,
"isCurrent":true
}
]
}
]
</p>
<p>
Note that the body of the request is an array. This array contains the serialized arguments of the method.
The object returned by the method is then serialized as the body of the response.
</p>
<p>
To define a remoteable interface, simply add the {@link org.apache.juneau.remoteable.Remoteable @Remoteable}
annotation to your interface class.
</p>
<p class='bcode'>
<ja>@Remoteable</ja>
<jk>public interface</jk> IAddressBook {...}
</p>
<p>
This annotation tells the framework that all methods defined on this interface can be executed remotely.
It can be applied to super-interfaces, super-classes, etc..., and exposes the methods at whatever level it is
defined.
</p>
<p>
The {@link org.apache.juneau.remoteable.RemoteMethod @RemoteMethod} annotation can also be used on individual
methods to tailor which methods are exposed or their paths.
</p>
<p>
There are two ways to expose remoteable proxies on the server side:
</p>
<ol class='spaced-list'>
<li>
Extending from <code>RemoteableServlet</code>.
<li>
Using a <code><ja>@RestMethod</ja>(name=<jsf>PROXY</jsf>)</code> annotation on a Java method.
</ol>
<p>
The <code>RemoteableServlet</code> class is a simple specialized servlet with an abstract
<code>getServiceMap()</code> method to define the server-side POJOs:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/remote"</js>
)
<jk>public class</jk> SampleRemoteableServlet <jk>extends</jk> RemoteableServlet {
<jc>// Our server-side POJO.</jc>
AddressBook <jf>addressBook</jf> = <jk>new</jk> AddressBook();
<ja>@Override</ja> <jc>/* RemoteableServlet */</jc>
<jk>protected</jk> Map&lt;Class&lt;?&gt;,Object&gt; getServiceMap() <jk>throws</jk> Exception {
Map&lt;Class&lt;?&gt;,Object&gt; m = <jk>new</jk> LinkedHashMap&lt;Class&lt;?&gt;,Object&gt;();
<jc>// In this simplified example, we expose the same POJO service under two different interfaces.
// One is IAddressBook which only exposes methods defined on that interface, and
// the other is AddressBook itself which exposes all methods defined on the class itself (dangerous!).</jc>
m.put(IAddressBook.<jk>class</jk>, <jf>addressBook</jf>);
m.put(AddressBook.<jk>class</jk>, <jf>addressBook</jf>);
<jk>return</jk> m;
}
}
</p>
<p>
The <code><ja>@RestMethod</ja>(name=<jsf>PROXY</jsf>)</code> approach is easier if you only have a single
interface you want to expose.
You simply define a Java method whose return type is an interface, and return the implementation of that
interface:
</p>
<p class='bcode'>
<jc>// Our exposed proxy object.</jc>
<ja>@RestMethod</ja>(name=<jsf>PROXY</jsf>, path=<js>"/addressbookproxy/*"</js>)
<jk>public</jk> IAddressBook getProxy() {
<jk>return</jk> addressBook;
}
</p>
<p>
In either case, the proxy communications layer is pure REST.
Therefore, in cases where the interface classes are not available on the client side, the same method calls can
be made through pure REST calls.
This can also aid significantly in debugging, since calls to the remoteable service can be made directly from
a browser with no coding involved.
</p>
<p>
The parameters and return types of the Java methods can be any of the supported <a class='doclink' href='#juneau-marshall.PojoCategories'>serializable and parsable types</a>.
This ends up being WAY more flexible than other proxy interfaces since Juneau can handle so may POJO types
out-of-the-box.
Most of the time you don't even need to modify your existing Java implementation code.
</p>
<p>
The <code>RemoteableServlet</code> class itself shows how sophisticated REST interfaces can be built on the Juneau
RestServlet API using very little code.
The class consists of only 53 lines of code, yet is a sophisticated discoverable and
self-documenting REST interface.
And since the remote proxy API is built on top of REST, it can be debugged using just a browser.
</p>
<p>
The requirements for a method to be callable through a remoteable service are:
</p>
<ul class='spaced-list'>
<li>
The method must be public.
<li>
The parameter and return types must be <a href='#juneau-marshall.PojoCategories'>serializable and parsable</a>.
Parameterized types are supported.
<li>
Methods can throw <code>Throwables</code> with public no-arg or single-arg-string constructors which will
be automatically recreated on the client side.
</ul>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RemoteableProxiesClientSide"></a>
<h4 class='topic' onclick='toggle(this)'>7.32.1 - Client Side</h4>
<div class='topic'>
<p>
Remoteable interface proxies are retrieved through the existing {@link org.apache.juneau.rest.client.RestClient}
class.
</p>
<p>
It may seem that the client-side code would need to be complex.
In reality, it builds upon existing serializing, parsing, and REST capabilities in Juneau resulting in very
little additional code.
The entire code for the <code>RestClient.getRemoteableProxy(Class)</code> method is shown below:
</p>
<p class='bcode'>
<jk>public</jk> &lt;T&gt; T getRemoteableProxy(<jk>final</jk> Class&lt;T&gt; interfaceClass) {
<jk>return</jk> (T)Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
<jk>new</jk> Class[] { interfaceClass },
<jk>new</jk> InvocationHandler() {
<ja>@Override</ja> <jc>/* InvocationHandler */</jc>
<jk>public</jk> Object invoke(Object proxy, Method method, Object[] args) {
<jk>try</jk> {
String uri = <jf>remoteableServletUri</jf> + '/' + interfaceClass.getName() + '/' + ClassUtils.<jsm>getMethodSignature</jsm>(method);
<jk>return</jk> doPost(uri, args).getResponse(method.getReturnType());
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RuntimeException(e);
}
}
});
}
</p>
<p>
Since we build upon the existing <code>RestClient</code> API, we inherit all of it's features.
For example, convenience methods for setting POJO filters and properties to customize the behavior of the
serializers and parsers, and the ability to provide your own customized Apache <code>HttpClient</code> for
handling various scenarios involving authentication and Internet proxies.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RemoteableProxiesServerSide"></a>
<h4 class='topic' onclick='toggle(this)'>7.32.2 - Server Side</h4>
<div class='topic'>
<p>
The server side is only slightly more complex, but boasts useful debugging and discovery capabilities.
</p>
<p>
The {@link org.apache.juneau.rest.remoteable.RemoteableServlet} class is an implementation of
{@link org.apache.juneau.rest.RestServlet} that provides a REST interface for invoking calls on POJOs.
The <code>RemoteableServlet</code> class is abstract and must implement a single method for providing the set
of POJOs to expose as remote interfaces.
</p>
<p>
The samples bundle includes a sample implementation of a remoteable service that can be used to interact with
the address book POJO also included in the bundle.
The method that must be implemented is {@link org.apache.juneau.rest.remoteable.RemoteableServlet#getServiceMap()}
that simply returns a mapping of Java interfaces (or classes) to POJO instances.
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/remoteable"</js>
)
<jk>public class</jk> SampleRemoteableServlet <jk>extends</jk> RemoteableServlet {
<jc>// The POJO being manipulated (i.e. the remoteable service)</jc>
AddressBook <jf>addressBook</jf> = <jk>new</jk> AddressBook();
<ja>@Override</ja> <jc>/* RemoteableServlet */</jc>
<jk>protected</jk> Map&lt;Class&lt;?&gt;,Object&gt; getServiceMap() <jk>throws</jk> Exception {
Map&lt;Class&lt;?&gt;,Object&gt; m = <jk>new</jk> LinkedHashMap&lt;Class&lt;?&gt;,Object&gt;();
<jc>// In this simplified example, we expose the same POJO service under two different interfaces.
// One is IAddressBook which only exposes methods defined on that interface, and
// the other is AddressBook itself which exposes all public methods defined on the class itself.</jc>
m.put(IAddressBook.<jk>class</jk>, addressBook);
m.put(AddressBook.<jk>class</jk>, addressBook);
<jk>return</jk> m;
}
}
</p>
<p>
Since this class is a servlet, and can be deployed as such.
In the sample code, it's listed as a child resource to <code>org.apache.juneau.rest.samples.RootResources</code>
which makes it available under the URL <code>/juneau/sample/remoteable</code>.
</p>
<p>
If you point your browser to that URL, you get a list of available interfaces:
</p>
<img class='bordered' src="doc-files/juneau-rest-server.RemoteableProxiesServerSide.1.png">
<p>
Clicking the hyperlinks on each shows you the list of methods that can be invoked on that service.
Note that the <code>IAddressBook</code> link shows that you can only invoke methods defined on that
interface, whereas the <code>AddressBook</code> link shows ALL public methods defined on that class.
Since <code>AddressBook</code> extends from <code>LinkedList</code>, you may notice familiar collections
framework methods listed.
</p>
<img class='bordered' src="doc-files/juneau-rest-server.RemoteableProxiesServerSide.2.png">
<img class='bordered' src="doc-files/juneau-rest-server.RemoteableProxiesServerSide.3.png">
<p>
Let's see how we can interact with this interface through nothing more than REST calls to get a better idea on
how this works.
We'll use the same method call as in the introduction.
First, we need to create the serialized form of the arguments:
</p>
<p class='bcode'>
Object[] args = <jk>new</jk> Object[] {
<jk>new</jk> CreatePerson(<js>"Test Person"</js>,
AddressBook.<jsm>toCalendar</jsm>(<js>"Aug 1, 1999"</js>),
<jk>new</jk> CreateAddress(<js>"Test street"</js>, <js>"Test city"</js>, <js>"Test state"</js>, 12345, <jk>true</jk>))
};
String asJson = JsonSerializer.<jsf>DEFAULT_LAX_READABLE</jsf>.toString(args);
System.<jsf>err</jsf>.println(asJson);
</p>
<p>
That produces the following JSON output:
</p>
<p class='bcode'>
[
{
name: <js>'Test Person'</js>,
birthDate: <js>'Aug 1, 1999'</js>,
addresses: [
{
street: <js>'Test street'</js>,
city: <js>'Test city'</js>,
state: <js>'Test state'</js>,
zip: 12345,
isCurrent: <jk>true</jk>
}
]
}
]
</p>
<p>
Note that in this example we're using JSON.
However, various other content types can also be used such as XML, URL-Encoding, UON, or HTML.
In practice however, JSON will preferred since it is often the most efficient.
</p>
<p>
Next, we can use a tool such as Poster to make the REST call.
Methods are invoked by POSTing the serialized object array to the URI of the interface method.
In this case, we want to POST our JSON to <code>/juneau/sample/remoteable/org.apache.juneau.examples.addressbook.IAddressBook/createPerson(org.apache.juneau.examples.addressbook.CreatePerson)</code>.
Make sure that we specify the <code>Content-Type</code> of the body as <code>text/json</code>.
We also want the results to be returned as JSON, so we set the <code>Accept</code> header to
<code>text/json</code> as well.
</p>
<img class='bordered' src="doc-files/juneau-rest-server.RemoteableProxiesServerSide.4.png">
<p>
When we execute the POST, we should see the following successful response whose body contains the returned
<code>Person</code> bean serialized to JSON:
</p>
<img class='bordered' src="doc-files/juneau-rest-server.RemoteableProxiesServerSide.5.png">
<p>
From there, we could use the following code snippet to reconstruct the response object from JSON:
</p>
<p class='bcode'>
String response = <js>"<i>output from above</i>"</js>;
Person p = JsonParser.<jsf>DEFAULT</jsf>.parse(response, Person.<jk>class</jk>);
</p>
<p>
If we alter our servlet to allow overloaded GET requests, we can invoke methods using nothing more than a
browser...
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/remoteable"</js>,
<jc>// Allow us to use method=POST from a browser.</jc>
allowedMethodParams=<js>"*"</js>
)
<jk>public class</jk> SampleRemoteableServlet <jk>extends</jk> RemoteableServlet {
</p>
<p>
For example, here we call the <code>findPerson(<jk>int</jk>)</code> method to retrieve a person and get the
returned POJO (in this case as HTML since that's what's in the <code>Accept</code> header when calling from a
browser):
</p>
<img class='bordered' src="doc-files/juneau-rest-server.RemoteableProxiesServerSide.6.png">
<p>
When specifying the POST body as a <code>&amp;content</code> parameter, the method arguments should be in UON
notation.
See {@link org.apache.juneau.uon.UonSerializer} for more information about this encoding.
Usually you can also pass in JSON if you specify <code>&amp;Content-Type=text/json</code> in the URL parameters
but passing in unencoded JSON in a URL may not work in all browsers.
Therefore, UON is preferred.
</p>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.RemoteableProxiesRemoteableAnnotation"></a>
<a id="RemoteableAnnotation"></a>
<h4 class='topic' onclick='toggle(this)'>7.32.3 - @Remoteable Annotation</h4>
<div class='topic'>
<p>
What if you want fine-tuned control over which methods are exposed in an interface instead of just all public
methods?
For this, the {@link org.apache.juneau.remoteable.Remoteable @Remoteable} annotation is provided.
It can be applied to individual interface methods to only expose those methods through the remoteable servlet.
</p>
<p>
For example, to expose only the first 2 methods in our <code>IAddressBook</code> interface...
</p>
<p class='bcode'>
<jk>public interface</jk> IAddressBook {
<ja>@Remoteable</ja> Person createPerson(CreatePerson cp) <jk>throws</jk> Exception;
<ja>@Remoteable</ja> Person findPerson(<jk>int</jk> id);
Address findAddress(<jk>int</jk> id);
Person findPersonWithAddress(<jk>int</jk> id);
}
</p>
<p>
On the server side, the option to restrict access to only annotated methods is defined through a property:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/remoteable"</js>,
properties={
<jc>// Only expose methods annotated with @Remoteable.</jc>
<ja>@Property</ja>(name=<jsf>REMOTEABLE_includeOnlyRemotableMethods</jsf>, value=<js>"true"</js>)
}
)
<jk>public class</jk> SampleRemoteableServlet <jk>extends</jk> RemoteableServlet {
</p>
<p>
The <ja>@Remoteable</ja> annotation can also be applied to the interface class to expose all public methods
defined on that interface.
</p>
<p class='bcode'>
<ja>@Remoteable</ja>
<jk>public interface</jk> IAddressBook {
Person createPerson(CreatePerson cp) <jk>throws</jk> Exception;
Person findPerson(<jk>int</jk> id);
Address findAddress(<jk>int</jk> id);
Person findPersonWithAddress(<jk>int</jk> id);
}
</p>
</div>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-server.Injection"></a>
<h3 class='topic' onclick='toggle(this)'>7.33 - Using with Spring and Injection frameworks</h3>
<div class='topic'>
<p>
The Juneau REST server API is compatible with dependency injection frameworks such as Spring.
</p>
<p>
The important class is the {@link org.apache.juneau.rest.RestResourceResolver} class which is used
to resolve child servlet/resource implementation classes inside parent contexts.
In other words, it's used for resolving {@link org.apache.juneau.rest.annotation.RestResource#children() @RestResource.children()} instances.
</p>
<p>
The general approach starts with defining a resolver that uses the Spring application context for resolution:
</p>
<p class='bcode'>
<jk>public class</jk> SpringRestResourceResolver <jk>extends</jk> RestResourceResolverSimple {
<jk>private final</jk> ApplicationContext <jf>appContext</jf>;
<jk>public</jk> SpringRestResourceResolver(ApplicationContext appContext) {
<jk>this</jk>.<jf>appContext</jf> = appContext;
}
<jk>@Override</jk> <jc>/* RestResourceResolverSimple */</jc>
<jk>public</jk> Object resolve(Class&lt;?&gt; resourceType, RestContextBuilder builder) <jk>throws</jk> Exception {
Object resource = <jf>appContext.</jf>getBean(type);
<jc>// If Spring can't resolve it, use default resolution (just look for no-arg constructor).</jc>
<jk>if</jk> (resource == <jk>null</jk>) {
resource = <jk>super</jk>.resolve(resourceType, builder);
}
<jk>return</jk> resource;
}
}
</p>
<p>
Next, define the Spring configuration to return our resolver:
</p>
<p class='bcode'>
<ja>@Configuration</ja>
<jk>public abstract class</jk> MySpringConfiguration {
<ja>@Autowired</ja>
<jk>private static</jk> ApplicationContext <jsf>appContext</jsf>;
<jk>public static</jk> ApplicationContext getAppContext(){
<jk>return</jk> <jsf>appContext</jsf>;
}
<jk>public static void</jk> setAppContext(ApplicationContext appContext){
MySpringConfiguration.<jsf>appContext</jsf> = appContext;
}
<ja>@Bean</ja>
<jk>public</jk> RestResourceResolver restResourceResolver(ApplicationContext appContext) {
<jk>return new</jk> SpringRestResourceResolver(appContext);
}
}
</p>
<p>
Finally, define your <code>Root</code> resource with a constructor that takes in our rest resource resolver and
sets it on the config object during initialization.
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
children={
...
}
)
<jk>public class</jk> Root <jk>extends</jk> RestServletGroupDefault {
<jk>private final</jk> RestResourceResolver <jf>resolver</jf>;
<ja>@Inject</ja>
<jk>public</jk> Root(RestResourceResolver resolver) {
<jk>this</jk>.<jf>resolver</jf> = resolver;
}
<ja>@RestHook</ja>(<jsf>INIT</jsf>)
<jk>public void</jk> initSpring(RestContextBuilder builder) <jk>throws</jk> Exception {
builder.setResourceResolver(<jf>resolver</jf>);
}
}
</p>
<p>
After that, just define constructors on your child resources to take in Spring beans:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/child"</js>
)
<jk>public class</jk> MyChildResource <jk>extends</jk> RestServletDefault {
<jk>private final</jk> Bean1 <jf>bean1</jf>;
<jk>private final</jk> Bean2 <jf>bean2</jf>;
<jk>private final</jk> Bean3 <jf>bean3</jf>;
<ja>@Inject</ja>
<jk>public</jk> MyChildResource(Bean1 bean1, Bean2 bean2, Bean3 bean3) {
<jk>this</jk>.<jf>bean1</jf> = bean1;
<jk>this</jk>.<jf>bean2</jf> = bean2;
<jk>this</jk>.<jf>bean3</jf> = bean3;
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-server.HTTP2"></a>
<h3 class='topic' onclick='toggle(this)'>7.34 - Using HTTP/2 features</h3>
<div class='topic'>
<p>
Juneau is built as a veneer on top of the Servlet API, allowing you to use low-level Servlet APIs
whenever needed.
<br>This allows you to take advantage of the newest HTTP/2 features implemented in the new Servlet 4.0
specification.
</p>
<p>
Coming soon (sorry)
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-server.PredefinedLabelBeans"></a>
<h3 class='topic' onclick='toggle(this)'>7.35 - Predefined Label Beans</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.labels} package contains some reusable beans that are useful for
creating linked items in HTML views.
</p>
<p>
The {@link org.apache.juneau.rest.labels.ResourceDescription} class is a bean with name/description
properties for labeling and linking to child resources.
<br>The following examples is pulled from the REST examples:
</p>
<p class='bcode'>
<jk>public class</jk> PredefinedLabelsResource <jk>extends</jk> Resource {
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> ResourceDescription[] getChildMethods() {
<jk>return new</jk> ResourceDescription[] {
<jk>new</jk> ResourceDescription(<js>"beanDescription"</js>, <js>"BeanDescription"</js>),
<jk>new</jk> ResourceDescription(<js>"htmlLinks"</js>, <js>"HtmlLink"</js>)
};
}
}
</p>
<p>
It get rendered as a table of name/description columns with links to child methods:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.PredefinedLabelBeans.1.png' style='width:240px'/>
<p>
The internals of the class show it simply has two bean properties with a link annotation
defined on the name property:
</p>
<p class='bcode'>
<jk>public class</jk> ResourceDescription {
<ja>@Html</ja>(link=<js>"servlet:/{name}"</js>)
<jk>public</jk> Object getName() {...}
<jk>public</jk> Object getDescription() {...}
}
</p>
<p>
The {@link org.apache.juneau.rest.labels.BeanDescription} class provides a simple view
of a bean and it's properties.
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/beanDescription"</js>)
<jk>public</jk> BeanDescription getBeanDescription() {
<jk>return new</jk> BeanDescription(Person.<jk>class</jk>);
}
</p>
<p>
This example renders the following:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.PredefinedLabelBeans.2.png' style='width:584px'/>
<p>
The {@link org.apache.juneau.html.annotation.HtmlLink @HtmlLink} annotation can also be useful
for rendering custom hyperlinks:
</p>
<p class='bcode'>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/htmlLinks"</js>)
<jk>public</jk> ALink[] htmlLinks() {
<jk>return new</jk> ALink[] {
<jk>new</jk> ALink(<js>"apache"</js>, <js>"http://apache.org"</js>),
<jk>new</jk> ALink(<js>"juneau"</js>, <js>"http://juneau.apache.org"</js>)
};
}
<ja>@HtmlLink</ja>(nameProperty=<js>"n"</js>, hrefProperty=<js>"l"</js>)
<jk>public static class</jk> ALink {
<jk>public</jk> String <jf>n</jf>, <jf>l</jf>;
<jk>public</jk> ALink(String n, String l) {
<jk>this</jk>.<jf>n</jf> = n;
<jk>this</jk>.<jf>l</jf> = l;
}
}
</p>
<p>
This example renders the following consisting of a list of hyperlinks:
</p>
<img class='bordered' src='doc-files/juneau-rest-server.PredefinedLabelBeans.3.png' style='width:92px'/>
<h5 class='section'>See Also:</h5>
<ul>
<li class='jc'>{@link org.apache.juneau.dto.LinkString}
</ul>
</div>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server.OtherNotes"></a>
<h3 class='topic' onclick='toggle(this)'>7.36 - Other Notes</h3>
<div class='topic'>
<ul class='spaced-list'>
<li>
Subclasses can use either {@link javax.servlet.http.HttpServlet#init(ServletConfig)}
or {@link javax.servlet.http.HttpServlet#init()} for initialization just like any other servlet.
<li>
The <l>X-Response-Headers</l> header can be used to pass through header values into the response.
The value should be a URL-encoded map of key-value pairs.
For example, to add a <l>"Refresh: 1"</l> header to the response to auto-refresh a page, the following
parameter can be specified: <l>"/sample?X-Response-Headers={Refresh=1}"</l>
</ul>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-rest-server-jaxrs"></a>
<h2 class='topic' onclick='toggle(this)'>8 - juneau-rest-server-jaxrs</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-rest-server-jaxrs<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-rest-server-jaxrs-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.rest.server_7.0.0.jar
</p>
<p>
The <code>juneau-rest-server-jaxrs</code> library provides an implementation of a <code>MessageBodyReader</code>
and <code>MessageBodyWriter</code> to allow any of the Juneau serializers and parsers to be used in a
JAX/RS environment.
</p>
<!-- ======================================================================================================== -->
<a id="juneau-rest-server-jaxrs.BaseProvider"></a>
<h3 class='topic' onclick='toggle(this)'>8.1 - Juneau JAX-RS Provider</h3>
<div class='topic'>
<p>
The Juneau framework contains the <l>juneau-rest-server-jaxrs</l> bundle for performing simple
integration of Juneau serializers and parsers in JAX-RS compliant environments.
</p>
<p>
It should be noted that although some of the functionality of the Juneau Server API is provided through the JAX-RS
integration components, it is not nearly as flexible as using the {@link org.apache.juneau.rest.RestServlet} class directly.
</p>
<p>
What you can do with the Juneau JAX-RS provider classes:
</p>
<ul class='spaced-list'>
<li>
Use existing Juneau serializers and parsers for converting streams to POJOs and vis-versa.
<li>
Use annotations to specify filters and properties using the {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod}
and {@link org.apache.juneau.rest.jaxrs.JuneauProvider} annotations.
</ul>
<p>
What you can't do with the Juneau JAX-RS provider classes:
</p>
<ul class='spaced-list'>
<li>
Specify or override serializers/parsers at the Java class and method levels.
<br>JAX-RS does not provide the capability to use different providers for the same media types
at the class or method levels.
<li>
Specify or override filters and properties at the Java class level.
<li>
Default stylesheets for the {@link org.apache.juneau.html.HtmlDocSerializer} class.
<br>It will produce HTML, but it won't contain any styles applied.
<li>
The ability to specify HTTP method, headers, and content using GET parameters.
<br>These make debugging REST interfaces using only a browser possible.
<li>
Class or method level encoding.
<li>
Class or method level guards.
<li>
Class or method level converters.
</ul>
<p>
The Juneau JAX-RS provider API consists of the following classes:
</p>
<ul class='spaced-list'>
<li class='jc'>
{@link org.apache.juneau.rest.jaxrs.BaseProvider} - The base provider class that implements the JAX-RS
<code>MessageBodyReader</code> and <code>MessageBodyWriter</code> interfaces.
<li class='jc'>
{@link org.apache.juneau.rest.jaxrs.JuneauProvider} - Annotation that is applied to subclasses of <code>BaseProvider</code>
to specify the serializers/parsers associated with a provider, and optionally filters and properties to
apply to those serializers and parsers.
<li class='jc'>
{@link org.apache.juneau.rest.jaxrs.DefaultProvider} - A default provider that provides the same level
of media type support as the {@link org.apache.juneau.rest.RestServletDefault} class.
</ul>
<p>
For the most part, when using these components, you'll either use the existing <l>DefaultProvider</l> or
<l>JuneauProvider</l> providers, or define your own by subclassing <l>BaseProvider</l>.
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-rest-client"></a>
<h2 class='topic' onclick='toggle(this)'>9 - juneau-rest-client</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-rest-client<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-rest-client-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.rest.client_7.0.0.jar
</p>
<p>
The REST client API provides the ability to access remote REST interfaces and transparently convert the input
and output to and from POJOs using any of the provided serializers and parsers.
</p>
<p>
Built upon the <l>Apache HttpClient</l> libraries, it extends that API and provides specialized APIs for working with
REST interfaces while maintaining all the functionality available in the HttpClient API.
</p>
<p class='bcode'>
<jc>// Create a reusable JSON client.</jc>
<jk>try</jk> (RestClient client = RestClient.<jsm>create</jsm>().build()) {
<jc>// The address of the root resource.</jc>
String url = <js>"http://localhost:9080/sample/addressBook"</js>;
<jc>// Do a REST GET against a remote REST interface and convert
// the response to an unstructured ObjectMap object.</jc>
ObjectMap m1 = client.doGet(url).getResponse(ObjectMap.<jk>class</jk>);
<jc>// Same as above, except parse the JSON as a bean.</jc>
AddressBook a2 = client.doGet(url).getResponse(AddressBook.<jk>class</jk>);
}
<jk>try</jk> (RestClient client = RestClient.<jsm>create</jsm>().serializer(XmlSerializer.<jk>class</jk>).parser(XmlSerializer.<jk>class</jk>).build()) {
<jc>// Add a person to the address book.
// Use XML as the transport medium.</jc>
Person p = <jk>new</jk> Person(<js>"Joe Smith"</js>, 21);
<jk>int</jk> returnCode = client.doPost(url + <js>"/entries"</js>, p).run();
}
</p>
<p>
Juneau provides an HTTP client API that makes it extremely simple to connect to remote REST interfaces and
seemlessly send and receive serialized POJOs in requests and responses.
</p>
<h5 class='topic'>Features</h5>
<ul class='spaced-list'>
<li>
Converts POJOs directly to HTTP request message bodies using {@link org.apache.juneau.serializer.Serializer}
classes.
<li>
Converts HTTP response message bodies directly to POJOs using {@link org.apache.juneau.parser.Parser}
classes.
<li>
Exposes the full functionality of the Apache HttpClient API by exposing all methods defined on the
{@link org.apache.http.impl.client.HttpClientBuilder} class.
<li>
Provides various convenience methods for setting up common SSL and authentication methods.
<li>
Provides a fluent interface that allows you to make complex REST calls in a single line of code.
</ul>
<p>
The client API is designed to work as a thin layer on top of the proven Apache HttpClient API.
By leveraging the HttpClient library, details such as SSL certificate negotiation, proxies, encoding, etc...
are all handled in Apache code.
</p>
<p>
The Juneau client API prereq's Apache HttpClient 4.5+.
At a minimum, the following jars are required:
</p>
<ul>
<li><code>httpclient-4.5.jar</code>
<li><code>httpcore-4.4.1.jar</code>
<li><code>httpmime-4.5.jar</code>
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Examples below use the Juneau Address Book resource example</jc>
<jc>// Create a reusable client with JSON support</jc>
<jk>try</jk> (RestClient client = RestClient.<jsm>create</jsm>().build()) {
<jc>// GET request, ignoring output</jc>
<jk>try</jk> {
<jk>int</jk> rc = client.doGet(<js>"http://localhost:9080/sample/addressBook"</js>).run();
<jc>// Succeeded!</jc>
} <jk>catch</jk> (RestCallException e) {
<jc>// Failed!</jc>
System.<jsf>err</jsf>.println(
String.<jsm>format</jsm>(<js>"status=%s, message=%s"</js>, e.getResponseStatus(), e.getResponseMessage())
);
}
<jc>// Remaining examples ignore thrown exceptions.</jc>
<jc>// GET request, secure, ignoring output</jc>
client.doGet(<js>"https://localhost:9443/sample/addressBook"</js>).run();
<jc>// GET request, getting output as a String. No POJO parsing is performed.
// Note that when calling one of the getX() methods, you don't need to call connect() or disconnect(), since
// it's automatically called for you.</jc>
String output = client.doGet(<js>"http://localhost:9080/sample/addressBook"</js>)
.getResponseAsString();
<jc>// GET request, getting output as a Reader</jc>
Reader r = client.doGet(<js>"http://localhost:9080/sample/addressBook"</js>)
.getReader();
<jc>// GET request, getting output as an untyped map</jc>
<jc>// Input must be an object (e.g. "{...}")</jc>
ObjectMap m = client.doGet(<js>"http://localhost:9080/sample/addressBook/0"</js>)
.getResponse(ObjectMap.<jk>class</jk>);
<jc>// GET request, getting output as an untyped list</jc>
<jc>// Input must be an array (e.g. "[...]")</jc>
ObjectList l = client.doGet(<js>"http://localhost:9080/sample/addressBook"</js>)
.getResponse(ObjectList.<jk>class</jk>);
<jc>// GET request, getting output as a parsed bean</jc>
<jc>// Input must be an object (e.g. "{...}")</jc>
<jc>// Note that you don't have to do any casting!</jc>
Person p = client.doGet(<js>"http://localhost:9080/sample/addressBook/0"</js>)
.getResponse(Person.<jk>class</jk>);
<jc>// GET request, getting output as a parsed bean</jc>
<jc>// Input must be an array of objects (e.g. "[{...},{...}]")</jc>
Person[] pa = client.doGet(<js>"http://localhost:9080/sample/addressBook"</js>)
.getResponse(Person[].<jk>class</jk>);
<jc>// Same as above, except as a List&lt;Person&gt;</jc>
List&lt;Person&gt; pl = client.doGet(<js>"http://localhost:9080/sample/addressBook"</js>)
.getResponse(List.<jk>class</jk>, Person.<jk>class</jk>);
<jc>// GET request, getting output as a parsed string</jc>
<jc>// Input must be a string (e.g. "&lt;string&gt;foo&lt;/string&gt;" or "'foo'")</jc>
String name = client.doGet(<js>"http://localhost:9080/sample/addressBook/0/name"</js>)
.getResponse(String.<jk>class</jk>);
<jc>// GET request, getting output as a parsed number</jc>
<jc>// Input must be a number (e.g. "&lt;number&gt;123&lt;/number&gt;" or "123")</jc>
<jk>int</jk> age = client.doGet(<js>"http://localhost:9080/sample/addressBook/0/age"</js>)
.getResponse(Integer.<jk>class</jk>);
<jc>// GET request, getting output as a parsed boolean</jc>
<jc>// Input must be a boolean (e.g. "&lt;boolean&gt;true&lt;/boolean&gt;" or "true")</jc>
<jk>boolean</jk> isCurrent = client.doGet(<js>"http://localhost:9080/sample/addressBook/0/addresses/0/isCurrent"</js>)
.getResponse(Boolean.<jk>class</jk>);
}
<jc>// GET request, getting a filtered object</jc>
<jk>try</jk> (RestClient client = RestClient.<jsm>create</jsm>().pojoSwaps(CalendarSwap.<jsf>ISO8601</jsf>.<jk>class</jk>).build()) {
Calendar birthDate = client.doGet(<js>"http://localhost:9080/sample/addressBook/0/birthDate"</js>)
.getResponse(GregorianCalendar.<jk>class</jk>);
<jc>// PUT request on regular field</jc>
String newName = <js>"John Smith"</js>;
<jk>int</jk> rc = client.doPut(<js>"http://localhost:9080/addressBook/0/name"</js>, newName).run();
<jc>// PUT request on filtered field</jc>
Calendar newBirthDate = <jk>new</jk> GregorianCalendar(1, 2, 3, 4, 5, 6);
rc = client.doPut(<js>"http://localhost:9080/sample/addressBook/0/birthDate"</js>, newBirthDate).run();
<jc>// POST of a new entry to a list</jc>
Address newAddress = <jk>new</jk> Address(<js>"101 Main St"</js>, <js>"Anywhere"</js>, <js>"NY"</js>, 12121, <jk>false</jk>);
rc = client.doPost(<js>"http://localhost:9080/addressBook/0/addresses"</js>, newAddress).run();
}
</p>
<h5 class='section'>Notes:</h5>
<ul class='spaced-list'>
<li>
The {@link org.apache.juneau.rest.client.RestClient} class exposes all the builder methods on the Apache
HttpClient {@link org.apache.http.impl.client.HttpClientBuilder} class.
<br>Use these methods to provide any customized HTTP client behavior.
</ul>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.3rdPartyProxies"></a>
<h3 class='topic' onclick='toggle(this)'>9.1 - Interface Proxies Against 3rd-party REST Interfaces</h3>
<div class='topic'>
<p>
The <code>juneau-rest-client</code> library can also be used to define interface proxies against 3rd-party REST interfaces.
<br>This is an extremely powerful feature that allows you to quickly define easy-to-use interfaces against
virtually any REST interface.
</p>
<p>
Similar in concept to remoteable services defined above, but in this case we simply define our interface with
special annotations that tell us how to convert input and output to HTTP headers, query parameters, form
post parameters, or request/response bodies.
</p>
<p class='bcode'>
<jc>// Our interface.</jc>
<ja>@Remoteable</ja>
<jk>public interface</jk> MyProxyInterface {
<ja>@RemoteMethod</ja>(httpMethod=<jsf>POST</jsf>, path=<js>"/method"</js>)
String callMyMethod(<ja>@Header</ja>(<js>"E-Tag"</js>) UUID etag, <ja>@Query</ja>(<js>"debug"</js>) <jk>boolean</jk> debug, <ja>@Body</ja> MyPojo pojo);
}
<jc>// Use a RestClient with default JSON support.</jc>
<jk>try</jk> (RestClient client = RestClient.<jsm>create</jsm>().build()) {
MyProxyInterface p = client.getRemoteableProxy(MyProxyInterface.<jk>class</jk>, <js>"http://hostname/some/rest/interface"</js>);
String response = p.callMyMethod(UUID.<jsm>randomUUID</jsm>(), <jk>true</jk>, <jk>new</jk> MyPojo());
}
</p>
<p>
The call above translates to the following REST call:
</p>
<p class='bcode'>
POST http://hostname/some/rest/interface/method?debug=true HTTP/1.1
Accept: application/json
Content-Type: application/json
E-Tag: 475588d4-0b27-4f56-9296-cc683251d314
{ "foo": "bar", "baz": 123, "qux": true}
</p>
<p>
The Java method arguments can be annotated with any of the following:
</p>
<ul class='spaced-list'>
<li class='ja'>
{@link org.apache.juneau.remoteable.Query} - A URL query parameter.
<br>The argument can be any of the following types:
<ul>
<li class='normal'>Any serializable POJO
- Converted to text using {@link org.apache.juneau.httppart.SimpleUonPartSerializer#serialize(HttpPartType,Object)}.
<li class='normal'><code>Map&lt;String,Object&gt;</code>
- Individual name-value pairs.
<br>Values are converted to text using {@link org.apache.juneau.httppart.SimpleUonPartSerializer#serialize(HttpPartType,Object)}.
<li class='normal'><code>String</code>
- Treated as a query string.
</ul>
<li class='ja'>
{@link org.apache.juneau.remoteable.QueryIfNE}
- Same as <ja>@Query</ja> except skips the value if it's null/empty.
<li class='ja'>
{@link org.apache.juneau.remoteable.FormData}
- A form-data parameter.
<br>Note that this is only available if the HTTP method is <code>POST</code>.
<br>The argument can be any of the following types:
<ul>
<li class='normal'>Any serializable POJO
- Converted to text using {@link org.apache.juneau.httppart.SimpleUonPartSerializer#serialize(HttpPartType,Object)}.
<li class='normal'>{@link org.apache.juneau.rest.client.NameValuePairs}
- Individual name-value pairs.
<li class='normal'><code>Map&lt;String,Object&gt;</code>
- Individual name-value pairs.
<br>Values are converted to text using {@link org.apache.juneau.httppart.SimpleUonPartSerializer#serialize(HttpPartType,Object)}.
</ul>
<li class='ja'>
{@link org.apache.juneau.remoteable.FormDataIfNE}
- Same as <ja>@FormData</ja> except skips the value if it's null/empty.
<li class='ja'>
{@link org.apache.juneau.remoteable.Header}
- A request header.
<br>The argument can be any of the following types:
<ul>
<li class='normal'>Any serializable POJO
- Converted to text using {@link org.apache.juneau.httppart.SimpleUonPartSerializer#serialize(HttpPartType,Object)}.
<li class='normal'><code>Map&lt;String,Object&gt;</code>
- Individual name-value pairs.
<br>Values are converted to text using {@link org.apache.juneau.httppart.SimpleUonPartSerializer#serialize(HttpPartType,Object)}.
</ul>
<li class='ja'>
{@link org.apache.juneau.remoteable.HeaderIfNE}
- Same as <ja>@Header</ja> except skips the value if it's null/empty.
<li class='ja'>
{@link org.apache.juneau.remoteable.Body}
- The HTTP request body.
<br>The argument can be any of the following types:
<ul>
<li class='normal'>Any serializable POJO
- Converted to text/bytes using the {@link org.apache.juneau.serializer.Serializer} registered
with the <code>RestClient</code>.
<li class='normal'>{@link java.io.Reader}
- Raw contents of reader will be serialized to remote resource.
<li class='normal'>{@link java.io.InputStream}
- Raw contents of input stream will be serialized to remote resource.
<li class='normal'>{@link org.apache.http.HttpEntity}
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
<li class='normal'>{@link org.apache.juneau.rest.client.NameValuePairs}
- Converted to a URL-encoded FORM post.
</ul>
</ul>
<p>
The return type of the Java method can be any of the following:
</p>
<ul class='spaced-list'>
<li>
<jk>void</jk>
- Don't parse any response.
<br>Note that the method will still throw a runtime exception if an error HTTP status is returned.
<li>
Any <a class='doclink' href='#juneau-marshall.PojoCategories'>parsable</a> POJO
- The body of the response will be converted to the POJO using the parser defined on the
<code>RestClient</code>.
<li>
<code>HttpResponse</code>
- Returns the raw <code>HttpResponse</code> returned by the inner <code>HttpClient</code>.
<li>
{@link java.io.Reader}
- Returns access to the raw reader of the response.
<br>Note that if you don't want your response parsed as a POJO, you'll want to get the response reader
directly.
<li>
{@link java.io.InputStream}
- Returns access to the raw input stream of the response.
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.SSL"></a>
<h3 class='topic' onclick='toggle(this)'>9.2 - SSL Support</h3>
<div class='topic'>
<p>
The simplest way to enable SSL support in the client is to use the
{@link org.apache.juneau.rest.client.RestClientBuilder#enableSSL(SSLOpts)} method and one of the predefined
{@link org.apache.juneau.rest.client.SSLOpts} instances:
</p>
<ul class='doctree'>
<li class='jf'>{@link org.apache.juneau.rest.client.SSLOpts#DEFAULT} - Normal certificate and hostname validation.
<li class='jf'>{@link org.apache.juneau.rest.client.SSLOpts#LAX} - Allows for self-signed certificates.
</ul>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Create a client that ignores self-signed or otherwise invalid certificates.</jc>
RestClientBuilder builder = RestClient.<jsm>create</jsm>()
.enableSSL(SSLOpts.<jsf>LAX</jsf>);
<jc>// ...or...</jc>
RestClientBuilder builder = RestClient.<jsm>create</jsm>()
.enableLaxSSL();
</p>
<p>
This is functionally equivalent to the following:
</p>
<p class='bcode'>
RestClientBuilder builder = RestClient.<jsm>create</jsm>();
HostnameVerifier hv = <jk>new</jk> NoopHostnameVerifier();
TrustManager tm = <jk>new</jk> SimpleX509TrustManager(<jk>true</jk>);
<jk>for</jk> (String p : <jk>new</jk> String[]{<js>"SSL"</js>,<js>"TLS"</js>,<js>"SSL_TLS"</js>}) {
SSLContext ctx = SSLContext.<jsm>getInstance</jsm>(p);
ctx.init(<jk>null</jk>, <jk>new</jk> TrustManager[] { tm }, <jk>null</jk>);
SSLConnectionSocketFactory sf = <jk>new</jk> SSLConnectionSocketFactory(ctx, hv);
builder.setSSLSocketFactory(sf);
Registry&lt;ConnectionSocketFactory&gt; r = RegistryBuilder.&lt;ConnectionSocketFactory&gt;<jsm>.create</jsm>()
.register(<js>"https"</js>, sf).build();
builder.setConnectionManager(<jk>new</jk> PoolingHttpClientConnectionManager(r));
}
</p>
<p>
More complex SSL support can be enabled through the various {@link org.apache.http.impl.client.HttpClientBuilder}
methods defined on the class.
</p>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.SSLOpts"></a>
<h4 class='topic' onclick='toggle(this)'>9.2.1 - SSLOpts Bean</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.client.SSLOpts} class itself is a bean that can be created by the
parsers.
For example, SSL options can be specified in a config file and retrieved as a bean using the
{@link org.apache.juneau.config.Config} class.
</p>
<h5 class='figure'>Contents of <code>MyConfig.cfg</code></h5>
<p class='bcode'>
<cc>#================================================================================
# My Connection Settings
#================================================================================</cc>
<cs>[Connection]</cs>
<ck>url</ck> = <cv>https://myremotehost:9443</cv>
<ck>ssl</ck> = <cv>{certValidate:'LAX',hostVerify:'LAX'}</cv>
</p>
<h5 class='figure'>Code that reads an <code>SSLOpts</code> bean from the config file</h5>
<p class='bcode'>
<jc>// Read config file and set SSL options based on what's in that file.</jc>
Config cf = Config.<jsm>create</jsm>().name(<js>"MyConfig.cfg"</js>).build();
SSLOpts ssl = cf.getObject(SSLOpts.<jk>class</jk>, <js>"Connection/ssl"</js>);
RestClient rc = RestClient.<jsm>create</jsm>().enableSSL(ssl).build();
</p>
</div>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.Authentication"></a>
<h3 class='topic' onclick='toggle(this)'>9.3 - Authentication</h3>
<div class='topic'>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.BASIC"></a>
<h4 class='topic' onclick='toggle(this)'>9.3.1 - BASIC Authentication</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.client.RestClientBuilder#basicAuth(String,int,String,String)} method
can be used to quickly enable BASIC authentication support.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Create a client that performs BASIC authentication using the specified user/pw.</jc>
RestClient restClient = RestClient.<jsm>create</jsm>()
.basicAuth(<jsf>HOST</jsf>, <jsf>PORT</jsf>, <jsf>USER</jsf>, <jsf>PW</jsf>)
.build();
</p>
<p>
This is functionally equivalent to the following:
</p>
<p class='bcode'>
RestClientBuilder builder = RestClient.<jsm>create</jsm>();
AuthScope scope = <jk>new</jk> AuthScope(<jsf>HOST</jsf>, <jsf>PORT</jsf>);
Credentials up = <jk>new</jk> UsernamePasswordCredentials(<jsf>USER</jsf>, <jsf>PW</jsf>);
CredentialsProvider p = <jk>new</jk> BasicCredentialsProvider();
p.setCredentials(scope, up);
builder.setDefaultCredentialsProvider(p);
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.FORM"></a>
<h4 class='topic' onclick='toggle(this)'>9.3.2 - FORM-based Authentication</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.client.RestClientBuilder} class does not itself provide FORM-based
authentication since there is no standard way of providing such support.
<br>Typically, to perform FORM-based or other types of authentication, you'll want to create your own
subclass of {@link org.apache.juneau.rest.client.RestClientBuilder} and override the
{@link org.apache.juneau.rest.client.RestClientBuilder#createHttpClient()} method to provide an
authenticated client.
</p>
<p>
The following example shows how the <code>JazzRestClient</code> class provides FORM-based
authentication support.
</p>
<p class='bcode'>
<jd>/**
* Constructor.
*/</jd>
<jk>public</jk> JazzRestClientBuilder(URI jazzUri, String user, String pw) <jk>throws</jk> IOException {
...
}
<jd>/**
* Override the createHttpClient() method to return an authenticated client.
*/</jd>
<ja>@Override</ja> <jc>/* RestClientBuilder */</jc>
<jk>protected</jk> CloseableHttpClient createHttpClient() <jk>throws</jk> Exception {
CloseableHttpClient client = <jk>super</jk>.createHttpClient();
formBasedAuthenticate(client);
visitAuthenticatedURL(client);
<jk>return</jk> client;
}
<jc>/*
* Performs form-based authentication against the Jazz server.
*/</jc>
<jk>private void</jk> formBasedAuthenticate(HttpClient client) <jk>throws</jk> IOException {
URI uri2 = <jf>jazzUri</jf>.resolve(<js>"j_security_check"</js>);
HttpPost request = <jk>new</jk> HttpPost(uri2);
request.setConfig(RequestConfig.<jsm>custom</jsm>().setRedirectsEnabled(<jk>false</jk>).build());
<jc>// Charset must explicitly be set to UTF-8 to handle user/pw with non-ascii characters.</jc>
request.addHeader(<js>"Content-Type"</js>, <js>"application/x-www-form-urlencoded; charset=utf-8"</js>);
NameValuePairs params = <jk>new</jk> NameValuePairs()
.append(<jk>new</jk> BasicNameValuePair(<js>"j_username""</js>, <jf>user</jf>))
.append(<jk>new</jk> BasicNameValuePair(<js>"j_password"</js>, <jf>pw</jf>));
request.setEntity(<jk>new</jk> UrlEncodedFormEntity(params));
HttpResponse response = client.execute(request);
<jk>try</jk> {
<jk>int</jk> rc = response.getStatusLine().getStatusCode();
Header authMsg = response.getFirstHeader(<js>"X-com-ibm-team-repository-web-auth-msg"</js>);
<jk>if</jk> (authMsg != <jk>null</jk>)
<jk>throw new</jk> IOException(authMsg.getValue());
<jc>// The form auth request should always respond with a 200 ok or 302 redirect code</jc>
<jk>if</jk> (rc == <jsf>SC_MOVED_TEMPORARILY</jsf>) {
<jk>if</jk> (response.getFirstHeader(<js>"Location"</js>).getValue().matches(<js>"^.*/auth/authfailed.*$"</js>))
<jk>throw new</jk> IOException(<js>"Invalid credentials."</js>);
} <jk>else if</jk> (rc != <jsf>SC_OK</jsf>) {
<jk>throw new</jk> IOException(<js>"Unexpected HTTP status: "</js> + rc);
}
} <jk>finally</jk> {
EntityUtils.<jsm>consume</jsm>(response.getEntity());
}
}
<jc>/*
* This is needed for Tomcat because it responds with SC_BAD_REQUEST when the j_security_check URL is visited before an
* authenticated URL has been visited. This same URL must also be visited after authenticating with j_security_check
* otherwise tomcat will not consider the session authenticated
*/</jc>
<jk>private int</jk> visitAuthenticatedURL(HttpClient httpClient) <jk>throws</jk> IOException {
HttpGet authenticatedURL = <jk>new</jk> HttpGet(<jf>jazzUri</jf>.resolve(<js>"authenticated/identity"</js>));
HttpResponse response = httpClient.execute(authenticatedURL);
<jk>try</jk> {
<jk>return</jk> response.getStatusLine().getStatusCode();
} <jk>finally</jk> {
EntityUtils.<jsm>consume</jsm>(response.getEntity());
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.OIDC"></a>
<h4 class='topic' onclick='toggle(this)'>9.3.3 - OIDC Authentication</h4>
<div class='topic'>
<p>
The following example shows how the <code>JazzRestClient</code> class provides OIDC authentication
support.
</p>
<p class='bcode'>
<jd>/**
* Constructor.
*/</jd>
<jk>public</jk> JazzRestClientBuilder(URI jazzUri, String user, String pw) <jk>throws</jk> IOException {
...
}
<jd>/**
* Override the createHttpClient() method to return an authenticated client.
*/</jd>
<ja>@Override</ja> <jc>/* RestClientBuilder */</jc>
<jk>protected</jk> CloseableHttpClient createHttpClient() <jk>throws</jk> Exception {
CloseableHttpClient client = <jk>super</jk>.createHttpClient();
oidcAuthenticate(client);
<jk>return</jk> client;
}
<jk>private void</jk> oidcAuthenticate(HttpClient client) <jk>throws</jk> IOException {
HttpGet request = <jk>new</jk> HttpGet(<jf>jazzUri</jf>);
request.setConfig(RequestConfig.<jsm>custom</jsm>().setRedirectsEnabled(<jk>false</jk>).build());
<jc>// Charset must explicitly be set to UTF-8 to handle user/pw with non-ascii characters.</jc>
request.addHeader(<js>"Content-Type"</js>, <js>"application/x-www-form-urlencoded; charset=utf-8"</js>);
HttpResponse response = client.execute(request);
<jk>try</jk> {
<jk>int</jk> code = response.getStatusLine().getStatusCode();
<jc>// Already authenticated</jc>
<jk>if</jk> (code == <jsf>SC_OK</jsf>)
<jk>return</jk>;
<jk>if</jk> (code != <jsf>SC_UNAUTHORIZED</jsf>)
<jk>throw new</jk> RestCallException(<js>"Unexpected response during OIDC authentication: "</js>
+ response.getStatusLine());
<jc>// x-jsa-authorization-redirect</jc>
String redirectUri = getHeader(response, <js>"X-JSA-AUTHORIZATION-REDIRECT"</js>);
<jk>if</jk> (redirectUri == <jk>null</jk>)
<jk>throw new</jk> RestCallException(<js>"Expected a redirect URI during OIDC authentication: "</js>
+ response.getStatusLine());
<jc>// Handle Bearer Challenge</jc>
HttpGet method = <jk>new</jk> HttpGet(redirectUri + <js>"&amp;prompt=none"</js>);
addDefaultOidcHeaders(method);
response = client.execute(method);
code = response.getStatusLine().getStatusCode();
<jk>if</jk> (code != <jsf>SC_OK</jsf>)
<jk>throw new</jk> RestCallException(<js>"Unexpected response during OIDC authentication phase 2: "</js>
+ response.getStatusLine());
String loginRequired = getHeader(response, <js>"X-JSA-LOGIN-REQUIRED"</js>);
<jk>if</jk> (! <js>"true"</js>.equals(loginRequired))
<jk>throw new</jk> RestCallException(<js>"X-JSA-LOGIN-REQUIRED header not found on response during OIDC authentication phase 2: "</js>
+ response.getStatusLine());
method = <jk>new</jk> HttpGet(redirectUri + <js>"&amp;prompt=none"</js>);
addDefaultOidcHeaders(method);
response = client.execute(method);
code = response.getStatusLine().getStatusCode();
<jk>if</jk> (code != <jsf>SC_OK</jsf>)
<jk>throw new</jk> RestCallException(<js>"Unexpected response during OIDC authentication phase 3: "</js>
+ response.getStatusLine());
<jc>// Handle JAS Challenge</jc>
method = <jk>new</jk> HttpGet(redirectUri);
addDefaultOidcHeaders(method);
response = client.execute(method);
code = response.getStatusLine().getStatusCode();
<jk>if</jk> (code != <jsf>SC_OK</jsf>)
<jk>throw new</jk> RestCallException(<js>"Unexpected response during OIDC authentication phase 4: "</js>
+ response.getStatusLine());
<jf>cookie</jf> = getHeader(response, <js>"Set-Cookie"</js>);
Header[] defaultHeaders = <jk>new</jk> Header[] {
<jk>new</jk> BasicHeader(<js>"User-Agent"</js>, <js>"Jazz Native Client"</js>),
<jk>new</jk> BasicHeader(<js>"X-com-ibm-team-configuration-versions"</js>,
<js>"com.ibm.team.rtc=6.0.0,com.ibm.team.jazz.foundation=6.0"</js>),
<jk>new</jk> BasicHeader(<js>"Accept"</js>, <js>"text/json"</js>),
<jk>new</jk> BasicHeader(<js>"Authorization"</js>, <js>"Basic "</js>
+ StringUtils.<jsm>base64EncodeToString</jsm>(<jf>user</jf> + <js>":"</js> + <jf>pw</jf>)),
<jk>new</jk> BasicHeader(<js>"Cookie"</js>, cookie)
};
setDefaultHeaders(Arrays.<jsm>asList</jsm>(defaultHeaders));
} <jk>finally</jk> {
EntityUtils.<jsm>consume</jsm>(response.getEntity());
}
}
<jk>private void</jk> addDefaultOidcHeaders(HttpRequestBase method) {
method.addHeader(<js>"User-Agent"</js>, <js>"Jazz Native Client"</js>);
method.addHeader(<js>"X-com-ibm-team-configuration-versions"</js>,
<js>"com.ibm.team.rtc=6.0.0,com.ibm.team.jazz.foundation=6.0"</js>);
method.addHeader(<js>"Accept"</js>, <js>"text/json"</js>);
<jk>if</jk> (<jf>cookie</jf> != <jk>null</jk>) {
method.addHeader(<js>"Authorization"</js>, <js>"Basic "</js>
+ StringUtils.<jsm>base64EncodeToString</jsm>(<jf>user</jf> + <js>":"</js> + <jf>pw</jf>));
method.addHeader(<js>"Cookie"</js>, cookie);
}
}
</p>
</div>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.ResponsePatterns"></a>
<h3 class='topic' onclick='toggle(this)'>9.4 - Using Response Patterns</h3>
<div class='topic'>
<p>
One issue with REST (and HTTP in general) is that the HTTP response code must be set as a header before the
body of the request is sent.
<br>This can be problematic when REST calls invoke long-running processes, pipes
the results through the connection, and then fails after an HTTP 200 has already been sent.
</p>
<p>
One common solution is to serialize some text at the end to indicate whether the long-running process
succeeded (e.g. <js>"FAILED"</js> or <js>"SUCCEEDED"</js>).
</p>
<p>
The {@link org.apache.juneau.rest.client.RestClient} class has convenience methods for scanning the
response without interfering with the other methods used for retrieving output.
</p>
<p>
The following example shows how the {@link org.apache.juneau.rest.client.RestCall#successPattern(String)}
method can be used to look for a SUCCESS message in the output:
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Throw a RestCallException if SUCCESS is not found in the output.</jc>
restClient.doPost(<jsf>URL</jsf>)
.successPattern(<js>"SUCCESS"</js>)
.run();
</p>
<p>
The {@link org.apache.juneau.rest.client.RestCall#failurePattern(String)} method does the opposite.
It throws an exception if a failure message is detected.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Throw a RestCallException if FAILURE or ERROR is found in the output.</jc>
restClient.doPost(<jsf>URL</jsf>)
.failurePattern(<js>"FAILURE|ERROR"</js>)
.run();
</p>
<p>
These convenience methods are specialized methods that use the
{@link org.apache.juneau.rest.client.RestCall#responsePattern(ResponsePattern)} method which uses regular
expression matching against the response body.
<br>This method can be used to search for arbitrary patterns in the response body.
</p>
<p>
The following example shows how to use a response pattern finder to find and capture patterns for
<js>"x=number"</js> and <js>"y=string"</js> from a response body.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jk>final</jk> List&lt;Number&gt; xList = <jk>new</jk> ArrayList&lt;Number&gt;();
<jk>final</jk> List&lt;String&gt; yList = <jk>new</jk> ArrayList&lt;String&gt;();
String responseText = restClient.doGet(<jsf>URL</jsf>)
.responsePattern(
<jk>new</jk> ResponsePattern(<js>"x=(\\d+)"</js>) {
<ja>@Override</ja>
<jk>public void</jk> onMatch(RestCall restCall, Matcher m) <jk>throws</jk> RestCallException {
xList.add(Integer.<jsm>parseInt</jsm>(m.group(1)));
}
<ja>@Override</ja>
<jk>public void</jk> onNoMatch(RestCall restCall) <jk>throws</jk> RestCallException {
<jk>throw new</jk> RestCallException(<js>"No X's found!"</js>);
}
}
)
.responsePattern(
<jk>new</jk> ResponsePattern(<js>"y=(\\S+)"</js>) {
<ja>@Override</ja>
<jk>public void</jk> onMatch(RestCall restCall, Matcher m) <jk>throws</jk> RestCallException {
yList.add(m.group(1));
}
<ja>@Override</ja>
<jk>public void</jk> onNoMatch(RestCall restCall) <jk>throws</jk> RestCallException {
<jk>throw new</jk> RestCallException(<js>"No Y's found!"</js>);
}
}
)
.getResponseAsString();
</p>
<p>
Using response patterns does not affect the functionality of any of the other methods
used to retrieve the response such as {@link org.apache.juneau.rest.client.RestCall#getResponseAsString()}
or {@link org.apache.juneau.rest.client.RestCall#getResponse(Class)}.
<br>HOWEVER, if you want to retrieve the entire text of the response from inside the match methods,
use {@link org.apache.juneau.rest.client.RestCall#getCapturedResponse()} since this method will not absorb
the response for those other methods.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.PipingOutput"></a>
<h3 class='topic' onclick='toggle(this)'>9.5 - Piping Response Output</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.client.RestCall} class provides various convenience <code>pipeTo()</code>
methods to pipe output to output streams and writers.
</p>
<p>
If you want to pipe output without any intermediate buffering, you can use the
{@link org.apache.juneau.rest.client.RestCall#byLines()} method.
This will cause the output to be piped and flushed after every line.
This can be useful if you want to display the results in real-time from a long running process producing
output on a REST call.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Pipe output from REST call to System.out in real-time.</jc>
restClient.doPost(<jsf>URL</jsf>).byLines().pipeTo(<jk>new</jk> PrintWriter(System.<jk>out</jk>)).run();
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.Debugging"></a>
<h3 class='topic' onclick='toggle(this)'>9.6 - Debugging</h3>
<div class='topic'>
<p>
Use the {@link org.apache.juneau.rest.client.RestClientBuilder#debug()} method to enable logging for HTTP requests
made from the client.
</p>
<p>
Under-the-covers, this is simply a shortcut for adding the {@link org.apache.juneau.rest.client.RestCallLogger#DEFAULT}
interceptor to the client.
<br>This causes the following output to be generated by the Java <code>org.apache.juneau.rest.client</code>
logger at <jsf>WARNING</jsf> level:
</p>
<p class='bcode'>
=== HTTP Call (outgoing) =======================================================
=== REQUEST ===
POST http://localhost:10000/testUrl HTTP/1.1
---request headers---
Debug: true
No-Trace: true
Accept: application/json
---request entity---
Content-Type: application/json
---request content---
{"foo":"bar","baz":123}
=== RESPONSE ===
HTTP/1.1 200 OK
---response headers---
Content-Type: application/json;charset=utf-8
Content-Length: 21
Server: Jetty(8.1.0.v20120127)
---response content---
{"message":"OK then"}
=== END ========================================================================
</p>
<p>
This setting also causes a <code>Debug: true</code> header value to trigger logging of the request on the
server side as well.
</p>
<p class='bcode'>
=== HTTP Request (incoming) ====================================================
HTTP POST /testUrl
---Headers---
Host: localhost:10000
Transfer-Encoding: chunked
Accept: application/json
Content-Type: application/json
User-Agent: Apache-HttpClient/4.5 (Java/1.6.0_65)
Connection: keep-alive
Debug: true
Accept-Encoding: gzip,deflate
---Default Servlet Headers---
---Body---
{"foo":"bar","baz":123}
=== END ========================================================================
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.Logging"></a>
<h3 class='topic' onclick='toggle(this)'>9.7 - Logging</h3>
<div class='topic'>
<p>
Use the {@link org.apache.juneau.rest.client.RestClientBuilder#logTo(Level,Logger)} and
{@link org.apache.juneau.rest.client.RestCall#logTo(Level,Logger)} methods to log HTTP calls.
<br>These methods will cause the HTTP request and response headers and body to be logged to the specified logger.
</p>
<h5 class='figure'>Example:</h5>
<p class='bcode'>
<jc>// Log the HTTP request/response to the specified logger.</jc>
<jk>int</jk> rc = restClient.doGet(<jsf>URL</jsf>).logTo(<jsf>INFO</jsf>, getLogger()).run();
</p>
<p>
The method call is ignored if the logger level is below the specified level.
</p>
<p>
Customized logging can be handled by sub-classing the {@link org.apache.juneau.rest.client.RestCallLogger}
class and using the {@link org.apache.juneau.rest.client.RestCall#interceptor(RestCallInterceptor)} method.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.Interceptors"></a>
<h3 class='topic' onclick='toggle(this)'>9.8 - Interceptors</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.client.RestClientBuilder#interceptors(RestCallInterceptor...)} and
{@link org.apache.juneau.rest.client.RestCall#interceptor(RestCallInterceptor)} methods can be used to
intercept responses during specific connection lifecycle events.
</p>
<p>
The {@link org.apache.juneau.rest.client.RestCallLogger} class is an example of an interceptor that uses
the various lifecycle methods to log HTTP requests.
</p>
<p class='bcode'>
<jd>/**
* Specialized interceptor for logging calls to a log file.
*/</jd>
<jk>public class</jk> RestCallLogger <jk>extends</jk> RestCallInterceptor {
<jk>private</jk> Level <jf>level</jf>;
<jk>private</jk> Logger <jf>log</jf>;
<jd>/**
* Constructor.
*
* <ja>@param</ja> level The log level to log messages at.
* <ja>@param</ja> log The logger to log to.
*/</jd>
<jk>protected</jk> RestCallLogger(Level level, Logger log) {
<jk>this</jk>.<jf>level</jf> = level;
<jk>this</jk>.<jf>log</jf> = log;
}
<ja>@Override</ja> <jc>/* RestCallInterceptor */</jc>
<jk>public void</jk> onInit(RestCall restCall) {
<jk>if</jk> (<jf>log</jf>.isLoggable(<jf>level</jf>))
restCall.captureResponse();
}
<ja>@Override</ja> <jc>/* RestCallInterceptor */</jc>
<jk>public void</jk> onConnect(RestCall restCall, <jk>int</jk> statusCode, HttpRequest req, HttpResponse res) {
<jc>// Do nothing.</jc>
}
<ja>@Override</ja> <jc>/* RestCallInterceptor */</jc>
<jk>public void</jk> onRetry(RestCall restCall, <jk>int</jk> statusCode, HttpRequest req, HttpResponse res) {
<jk>if</jk> (<jf>log</jf>.isLoggable(<jf>level</jf>))
<jf>log</jf>.log(level, MessageFormat.<jsm>format</jsm>(<js>"Call to {0} returned {1}. Will retry."</js>, req.getRequestLine().getUri(), statusCode));
}
<ja>@Override</ja> <jc>/* RestCallInterceptor */</jc>
<jk>public void</jk> onClose(RestCall restCall) <jk>throws</jk> RestCallException {
<jk>try</jk> {
<jk>if</jk> (<jf>log</jf>.isLoggable(<jf>level</jf>)) {
String output = restCall.getCapturedResponse();
StringBuilder sb = <jk>new</jk> StringBuilder();
HttpUriRequest req = restCall.getRequest();
HttpResponse res = restCall.getResponse();
<jk>if</jk> (req != <jk>null</jk>) {
sb.append(<js>"\n=== HTTP Call (outgoing) ========================================================="</js>);
sb.append(<js>"\n=== REQUEST ===\n"</js>).append(req);
sb.append(<js>"\n---request headers---"</js>);
<jk>for</jk> (Header h : req.getAllHeaders())
sb.append(<js>"\n"</js>).append(h);
<jk>if</jk> (req <jk>instanceof</jk> HttpEntityEnclosingRequestBase) {
sb.append(<js>"\n---request entity---"</js>);
HttpEntityEnclosingRequestBase req2 = (HttpEntityEnclosingRequestBase)req;
HttpEntity e = req2.getEntity();
<jk>if</jk> (e == <jk>null</jk>)
sb.append(<js>"\nEntity is null"</js>);
<jk>else</jk> {
<jk>if</jk> (e.getContentType() != <jk>null</jk>)
sb.append(<js>"\n"</js>).append(e.getContentType());
<jk>if</jk> (e.getContentEncoding() != <jk>null</jk>)
sb.append(<js>"\n"</js>).append(e.getContentEncoding());
<jk>if</jk> (e.isRepeatable()) {
<jk>try</jk> {
sb.append(<js>"\n---request content---\n"</js>).append(EntityUtils.<jsm>toString</jsm>(e));
} <jk>catch</jk> (Exception ex) {
<jk>throw new</jk> RuntimeException(ex);
}
}
}
}
}
<jk>if</jk> (res != <jk>null</jk>) {
sb.append(<js>"\n=== RESPONSE ===\n"</js>).append(res.getStatusLine());
sb.append(<js>"\n---response headers---"</js>);
<jk>for</jk> (Header h : res.getAllHeaders())
sb.append(<js>"\n"</js>).append(h);
sb.append(<js>"\n---response content---\n"</js>).append(output);
sb.append(<js>"\n=== END ========================================================================"</js>);
}
<jf>log</jf>.log(<jf>level</jf>, sb.toString());
}
} <jk>catch</jk> (IOException e) {
<jf>log</jf>.log(Level.<jsf>SEVERE</jsf>, e.getLocalizedMessage(), e);
}
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.Remoteable"></a>
<h3 class='topic' onclick='toggle(this)'>9.9 - Remoteable Proxies</h3>
<div class='topic'>
<p>
Juneau provides the capability of calling methods on POJOs on a server through client-side proxy interfaces.
<br>It offers a number of advantages over other similar remote proxy interfaces, such as being much simpler to
use and allowing much more flexibility.
</p>
<p>
Proxy interfaces are retrieved using the {@link org.apache.juneau.rest.client.RestClient#getRemoteableProxy(Class)}
<br>method.
The remoteable servlet is a specialized subclass of {@link org.apache.juneau.rest.RestServlet} that
provides a full-blown REST interface for calling interfaces remotely.
</p>
<p>
In this example, we have the following interface defined that we want to call from the client side against
a POJO on the server side (i.e. a Remoteable Service)...
</p>
<p class='bcode'>
<jk>public interface</jk> IAddressBook {
Person createPerson(CreatePerson cp) <jk>throws</jk> Exception;
}
</p>
<p>
The client side code for invoking this method is shown below...
</p>
<p class='bcode'>
<jc>// Create a RestClient using JSON for serialization, and point to the server-side remoteable servlet.</jc>
RestClient client = RestClient.<jsm>create</jsm>()
.rootUrl(<js>"https://localhost:9080/juneau/sample/remoteable"</js>)
.build();
<jc>// Create a proxy interface.</jc>
IAddressBook ab = client.getRemoteableProxy(IAddressBook.<jk>class</jk>);
<jc>// Invoke a method on the server side and get the returned result.</jc>
Person p = ab.createPerson(
<jk>new</jk> CreatePerson(<js>"Test Person"</js>,
AddressBook.<jsm>toCalendar</jsm>(<js>"Aug 1, 1999"</js>),
<jk>new</jk> CreateAddress(<js>"Test street"</js>, <js>"Test city"</js>, <js>"Test state"</js>, 12345, <jk>true</jk>))
);
</p>
<p>
The requirements for a method to be callable through a remoteable service are:
</p>
<ul class='spaced-list'>
<li>
The method must be public.
<li>
The parameter and return types must be <a class='doclink' href='#juneau-marshall.PojoCategories'>serializable and parsable</a>.
</ul>
<p>
One significant feature is that the remoteable services servlet is a full-blown REST interface.
<br>Therefore, in cases where the interface classes are not available on the client side, the same method calls
can be made through pure REST calls.
<br>This can also aid significantly in debugging since calls to the remoteable service can be called directly
from a browser with no code involved.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-rest-client.Other"></a>
<h3 class='topic' onclick='toggle(this)'>9.10 - Other Useful Methods</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.rest.client.RestClientBuilder#rootUrl(Object)} method can be used to specify a
root URL on all requests so that you don't have to use absolute paths on individual calls.
</p>
<p class='bcode'>
<jc>// Create a rest client with a root URL</jc>
RestClient rc = RestClient.<jsm>create</jsm>().rootUrl(<js>"http://localhost:9080/foobar"</js>).build();
String r = rc.doGet(<js>"/baz"</js>).getResponseAsString(); <jc>// Gets "http://localhost:9080/foobar/baz"</jc>
</p>
<p>
The {@link org.apache.juneau.rest.client.RestClientBuilder#set(String,Object)} method can be used to
set serializer and parser properties.
<br>For example, if you're parsing a response into POJOs and you want to ignore fields that aren't on the
POJOs, you can use the {@link org.apache.juneau.BeanContext#BEAN_ignoreUnknownBeanProperties} property.
</p>
<p class='bcode'>
<jc>// Create a rest client that ignores unknown fields in the response</jc>
RestClient rc = RestClient.<jsm>create</jsm>()
.set(<jsf>BEAN_ignoreUnknownBeanProperties</jsf>, <jk>true</jk>)
<jc>// or .ignoreUnknownBeanProperties(true)</jc>
.build();
MyPojo myPojo = rc.doGet(<jsf>URL</jsf>).getResponse(MyPojo.<jk>class</jk>);
</p>
<p>
The {@link org.apache.juneau.rest.client.RestCall#retryable(int,long,RetryOn)} method can be used to
automatically retry requests on failures.
<br>This can be particularly useful if you're attempting to connect to a REST resource that may be in the
process of still initializing.
</p>
<p class='bcode'>
<jc>// Create a rest call that retries every 10 seconds for up to 30 minutes as long as a connection fails
// or a 400+ is received.</jc>
restClient.doGet(<jsf>URL</jsf>)
.retryable(180, 10000, RetryOn.<jsf>DEFAULT</jsf>)
.run();
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server"></a>
<h2 class='topic' onclick='toggle(this)'>10 - juneau-microservice-server</h2>
<div class='topic'>
<h5 class='figure'>Maven Dependency</h5>
<p class='bcode' style='width:500px;'>
<xt>&lt;dependency&gt;</xt>
<xt>&lt;groupId&gt;</xt>org.apache.juneau<xt>&lt;/groupId&gt;</xt>
<xt>&lt;artifactId&gt;</xt>juneau-microservice-server<xt>&lt;/artifactId&gt;</xt>
<xt>&lt;version&gt;</xt>7.0.0<xt>&lt;/version&gt;</xt>
<xt>&lt;/dependency&gt;</xt>
</p>
<h5 class='figure'>Java Library</h5>
<p class='bcode' style='width:500px;'>
juneau-microservice-server-7.0.0.jar
</p>
<h5 class='figure'>OSGi Module</h5>
<p class='bcode' style='width:500px;'>
org.apache.juneau.microservice.server_7.0.0.jar
</p>
<h5 class='figure'>Microservice Starter Project</h5>
<p class='bcode' style='width:500px;'>
my-microservice.zip
</p>
<p>
Juneau Microservice is an API for creating stand-alone executable jars that can be used to
start lightweight configurable REST interfaces with all the power of the Juneau REST server and client APIs.
</p>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.Introduction"></a>
<h3 class='topic' onclick='toggle(this)'>10.1 - Microservice Introduction</h3>
<div class='topic'>
<p>
The Microservice API consists of a combination of the Juneau Core, Server, and Client APIs and an embedded
Eclipse Jetty Servlet Container.
<br>It includes all libraries needed to execute in a Java 1.6+ environment.
</p>
<p>
Features include:
</p>
<ul class='spaced-list'>
<li>
An out-of-the-box zipped Eclipse project to get started quickly.
<li>
Packaged as a simple executable jar and configuration file.
<li>
All the power of the Juneau Cloud Tools for defining REST servlets and clients with the ability to
serialize and parse POJOs as HTML, JSON, XML, RDF, URL-Encoding, and others.
<li>
An extensible API that allows you to hook into various lifecycle events.
<li>
Simple-to-use APIs for accessing manifest file entries, command-line arguments, and external configuration
file properties.
<li>
Predefined REST resources for configuring microservice and accessing log files.
</ul>
<p>
The <code>juneau-microservice-server</code> library consists of the following classes:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.microservice.Microservice}
- Defines basic lifecycle methods for microservices in general.
<ul>
<li class='jc'>
{@link org.apache.juneau.microservice.RestMicroservice}
- Defines additional lifecycle methods for REST microservices.
<br>Starts up an externally-configured Jetty server, registers servlets, and sets up
other features such as logging.
</ul>
<li class='jc'>
{@link org.apache.juneau.microservice.Resource}
- A subclass of <code>RestServletDefault</code> with support for manfest-file and args variables
and configured to use the external INI file.
<li class='jc'>
{@link org.apache.juneau.microservice.ResourceGroup}
- A subclass of <code>RestServletGroupDefault</code> with support for manfest-file and args variables
and configured to use the external INI file.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.GettingStarted"></a>
<h3 class='topic' onclick='toggle(this)'>10.2 - Getting Started</h3>
<div class='topic'>
<p>
The <l>my-microservice.zip</l> file is a zipped eclipse project that includes everything you
need to create a REST microservice in an Eclipse workspace.
</p>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.Installing"></a>
<h4 class='topic' onclick='toggle(this)'>10.2.1 - Installing in Eclipse</h4>
<div class='topic'>
<p>
Follow these instructions to create a new template project in Eclipse.
</p>
<ol class='spaced-list'>
<li>
Download the latest microservice-project zip file (e.g. <l>my-microservice.zip</l>).
<li>
In your Eclipse workspace, go to <b>File -&gt; Import -&gt; General -&gt; Existing Projects into Workspace</b>
and select the zip file and click <b>Finish</b>.
<br><br>
<img class='bordered' src="doc-files/juneau-microservice-server.Installing.1.png" style='width:549px'>
<li>
In your workspace, you should now see the following project:
<br><br>
<img class='bordered' src="doc-files/juneau-microservice-server.Installing.2.png" style='width:299px'>
</ol>
<p>
The important elements in this project are:
</p>
<ul class='spaced-list'>
<li>
<l>RootResources.java</l> - The top-level REST resource.
<br>This class routes HTTP requests to child resources:
<br><br>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/"</js>,
title=<js>"My Microservice"</js>,
description=<js>"Top-level resources page"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
widgets={
ContentTypeMenuItem.<jk>class</jk>,
StyleMenuItem.<jk>class</jk>
},
navlinks={
<js>"options: servlet:/?method=OPTIONS"</js>
}
),
children={
HelloWorldResource.<jk>class</jk>,
ConfigResource.<jk>class</jk>,
LogsResource.<jk>class</jk>
}
)
<jk>public class</jk> RootResources <jk>extends</jk> ResourceGroup {
<jc>// No code</jc>
}
</p>
<li>
<l>my-microservice.cfg</l> - The external configuration file.
<br>Contains various useful settings.
<br>Can be used for your own resource configurations.
<br><br>
<p class='bcode'>
<cc>#=======================================================================================================================
# Basic configuration file for REST microservices
# Subprojects can use this as a starting point.
#=======================================================================================================================</cc>
<cc># What to do when the config file is saved.
# Possible values:
# NOTHING - Don't do anything. (default)
# RESTART_SERVER - Restart the Jetty server.
# RESTART_SERVICE - Shutdown and exit with code '3'.</cc>
<ck>saveConfigAction</ck> = <cv>RESTART_SERVER</cv>
<cc>#=======================================================================================================================
# Jetty settings
#=======================================================================================================================</cc>
<cs>[Jetty]</cs>
<cc># Path of the jetty.xml file used to configure the Jetty server.</cc>
<ck>config</ck> = <cv>jetty.xml</cv>
<cc># Resolve Juneau variables in the jetty.xml file.</cc>
<ck>resolveVars</ck> = <cv>true</cv>
<cc># Port to use for the jetty server.
# You can specify multiple ports. The first available will be used. '0' indicates to try a random port.
# The resulting available port gets set as the system property "availablePort" which can be referenced in the
# jetty.xml file as "$S{availablePort}" (assuming resolveVars is enabled).</cc>
<ck>port</ck> = <cv>10000,0,0,0</cv>
<cc>#=======================================================================================================================
# REST settings
#=======================================================================================================================</cc>
<cs>[REST]</cs>
<cc># Stylesheet to use for HTML views.
# The default options are:
# - servlet:/styles/juneau.css
# - servlet:/styles/devops.css
# Other stylesheets can be referenced relative to the servlet package or working directory.</cc>
<ck>stylesheet</ck> = <cv>servlet:/styles/devops.css</cv>
<cc>#=======================================================================================================================
# Console settings
#=======================================================================================================================</cc>
<cs>[Console]</cs>
<ck>enabled</ck> = <cv>true</cv>
<cc># List of available console commands.
# These are classes that implements ConsoleCommand that allow you to submit commands to the microservice via
# the console.
# When listed here, the implementations must provide a no-arg constructor.
# They can also be provided dynamically by overriding the Microservice.createConsoleCommands() method.</cc>
<ck>commands</ck> =
<cv>org.apache.juneau.microservice.console.ExitCommand,
org.apache.juneau.microservice.console.RestartCommand,
org.apache.juneau.microservice.console.HelpCommand</cv>
<cc>#=======================================================================================================================
# Logger settings
#-----------------------------------------------------------------------------------------------------------------------
# See FileHandler Java class for details.
#=======================================================================================================================</cc>
<cs>[Logging]</cs>
...
<cc>#=======================================================================================================================
# System properties
#-----------------------------------------------------------------------------------------------------------------------
# These are arbitrary system properties that are set during startup.
#=======================================================================================================================</cc>
<cs>[SystemProperties]</cs>
<cc># Configure Jetty for StdErrLog Logging
# org.eclipse.jetty.util.log.class = org.eclipse.jetty.util.log.StrErrLog</cc>
<cc># Configure Jetty to log using java-util logging</cc>
<ck>org.eclipse.jetty.util.log.class</ck> = <cv>org.apache.juneau.microservice.JettyLogger</cv>
<cc># Jetty logging level
# Possible values: ALL, DEBUG, INFO, WARN, OFF</cc>
<ck>org.eclipse.jetty.LEVEL</ck> = <cv>WARN
<ck>derby.stream.error.file</ck> = <cv>$C{Logging/logDir}/derby-errors.log</cv>
</p>
<li>
<l>jetty.xml</l> - The Jetty configuration file.
<br>A bare-bones config file that can be extended to use any Jetty features.
<br><br>
<p class='bcode'>
<xt>&lt;Configure</xt> <xa>id</xa>=<xs>"ExampleServer"</xs> <xa>class</xa>=<xs>"org.eclipse.jetty.server.Server"</xs>&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"connectors"</xs><xt>&gt;</xt>
<xt>&lt;Array</xt> <xa>type</xa>=<xs>"org.eclipse.jetty.server.Connector"</xs><xt>&gt;</xt>
<xt>&lt;Item&gt;</xt>
<xt>&lt;New</xt> <xa>class</xa>=<xs>"org.eclipse.jetty.server.ServerConnector"</xs><xt>&gt;</xt>
<xt>&lt;Arg&gt;</xt>
<xt>&lt;Ref</xt> <xa>refid</xa>=<xs>"ExampleServer"</xs><xt>/&gt;</xt>
<xt>&lt;/Arg&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"port"</xs><xt>&gt;</xt>$S{availablePort,8080}<xt>&lt;/Set&gt;</xt>
<xt>&lt;/New&gt;</xt>
<xt>&lt;/Item&gt;</xt>
<xt>&lt;/Array&gt;</xt>
<xt>&lt;/Set&gt;</xt>
<xt>&lt;New</xt> <xa>id</xa>=<xs>"context"</xs> <xa>class</xa>=<xs>"org.eclipse.jetty.servlet.ServletContextHandler"</xs><xt>&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"contextPath"</xs><xt>&gt;/&lt;/Set&gt;</xt>
<xt>&lt;Call</xt> <xa>name</xa>=<xs>"addServlet"</xs><xt>&gt;</xt>
<xt>&lt;Arg&gt;</xt>org.apache.juneau.microservice.sample.RootResources<xt>&lt;/Arg&gt;</xt>
<xt>&lt;Arg&gt;</xt>/*<xt>&lt;/Arg&gt;</xt>
<xt>&lt;/Call&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"sessionHandler"</xs><xt>&gt;</xt>
<xt>&lt;New</xt> <xa>class</xa>=<xs>"org.eclipse.jetty.server.session.SessionHandler"</xs><xt>/&gt;</xt>
<xt>&lt;/Set&gt;</xt>
<xt>&lt;/New&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"handler"</xs><xt>&gt;</xt>
<xt>&lt;New</xt> <xa>class</xa>=<xs>"org.eclipse.jetty.server.handler.HandlerCollection"</xs><xt>&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"handlers"</xs><xt>&gt;</xt>
<xt>&lt;Array</xt> <xa>type</xa>=<xs>"org.eclipse.jetty.server.Handler"</xs><xt>&gt;</xt>
<xt>&lt;Item&gt;</xt>
<xt>&lt;Ref</xt> <xa>refid</xa>=<xs>"context"</xs><xt>/&gt;</xt>
<xt>&lt;/Item&gt;</xt>
<xt>&lt;Item&gt;</xt>
<xt>&lt;New</xt> <xa>class</xa>=<xs>"org.eclipse.jetty.server.handler.DefaultHandler"</xs><xt>/&gt;</xt>
<xt>&lt;/Item&gt;</xt>
<xt>&lt;/Array&gt;</xt>
<xt>&lt;/Set&gt;</xt>
<xt>&lt;/New&gt;</xt>
<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"requestLog"</xs><xt>&gt;</xt>
<xt>&lt;New</xt> <xa>id</xa>=<xs>"RequestLogImpl"</xs> <xa>class</xa>=<xs>"org.eclipse.jetty.server.NCSARequestLog"</xs><xt>&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"filename"</xs><xt>&gt;&lt;Property</xt> <xa>name</xa>=<xs>"jetty.logs"</xs> <xa>default</xa>=<xs>"$C{Logging/logDir,logs}"</xs><xt>/&gt;</xt>/jetty-requests.log<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"filenameDateFormat</xs><xt>"&gt;</xt>yyyy_MM_dd<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"LogTimeZone"</xs><xt>&gt;</xt>GMT<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"retainDays"</xs><xt>&gt;</xt>90<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"append"</xs><xt>&gt;</xt>false<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"LogLatency"</xs><xt>&gt;</xt>true<xt>&lt;/Set&gt;</xt>
<xt>&lt;/New&gt;</xt>
<xt>&lt;/Set&gt;</xt>
<xt>&lt;Get</xt> <xa>name</xa>=<xs>"ThreadPool"</xs><xt>&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"minThreads"</xs> <xa>type</xa>=<xs>"int"</xs><xt>&gt;</xt>10<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"maxThreads"</xs> <xa>type</xa>=<xs>"int"</xs><xt>&gt;</xt>100<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"idleTimeout"</xs> <xa>type</xa>=<xs>"int"</xs><xt>&gt;</xt>60000<xt>&lt;/Set&gt;</xt>
<xt>&lt;Set</xt> <xa>name</xa>=<xs>"detailedDump"</xs><xt>&gt;</xt>true<xt>&lt;/Set&gt;</xt>
<xt>&lt;/Get&gt;</xt>
<xt>&lt;/Configure&gt;</xt>
</p>
</ul>
<p>
At this point, you're ready to start the microservice from your workspace.
</p>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.Running"></a>
<h4 class='topic' onclick='toggle(this)'>10.2.2 - Running in Eclipse</h4>
<div class='topic'>
<p>
The <l>my-microservice.launch</l> file is already provided to allow you to quickly start
your new microservice.
</p>
<p>
Go to <b>Run -&gt; Run Configurations -&gt; Java Application -&gt; my-microservice</b> and click <b>Run</b>.
<br>In your console view, you should see the following output:
</p>
<p class='bcode'>
Running class 'RestMicroservice' using config file 'my-microservice.cfg'.
Server started on port 10000
List of available commands:
exit -- Shut down service
restart -- Restarts service
help -- Commands help
>
</p>
<p>
Now open your browser and point to <l>http://localhost:10000</l>.
You should see the following:
</p>
<img class='bordered' src="doc-files/MicroserviceServer.Running.6.png" style='width:800px;'>
<p>
You have started a REST interface on port 10000.
<br>You can enter the command <code>exit</code> to shut it down.
</p>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.Building"></a>
<h4 class='topic' onclick='toggle(this)'>10.2.3 - Building and Running from Command-Line</h4>
<div class='topic'>
<p>
The <l>pom.xml</l> file is a basic Maven build script for creating your microservice
as an executable uber-jar.
</p>
<p>
The easiest way to build your microservice is to run the following from the project root.
</p>
<p class='bcode'>
mvn clean install
</p>
<p>
Your <code>target</code> directory should now contain the following files:
</p>
<ul>
<li><code>my-microservice-1.0.jar</code>
<li><code>my-microservice.cfg</code>
<li><code>jetty.xml</code>
</ul>
<p>
To start from a command line, run the following command from inside your <code>target</code> directory:
</p>
<p class='bcode'>
java -jar my-microservice-1.0.jar
</p>
<p>
You should see the following console output:
</p>
<p class='bcode'>
Running class 'RestMicroservice' using config file 'my-microservice.cfg'.
Server started on port 10000
List of available commands:
exit -- Shut down service
restart -- Restarts service
help -- Commands help
>
</p>
<p>
If you get this error message: <code class='snippet'>java.net.BindException: Address already in use</code>,
then this microservice is already running elsewhere and so it cannot bind to port 10000.
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.Manifest"></a>
<h3 class='topic' onclick='toggle(this)'>10.3 - Manifest File</h3>
<div class='topic'>
<p>
The generated <l>META-INF/MANIFEST.MF</l> file is used to describe the microservice.
<br>If you open it, you'll see the following:
</p>
<p class='bcode'>
<mk>Main-Class</mk>: <mv>org.apache.juneau.microservice.RestMicroservice</mv>
<mk>Main-ConfigFile</mk>: <mv>microservice.cfg</mv>
<p>
The <mk>Main-Class</mk> entry is the standard manifest entry describing the entry point for the executable jar.
<br>In most cases, this value will always be <l>org.apache.juneau.microservice.RestMicroservice</l>.
<br>However, it is possible to extend this class or implement your own microservice, in which case you'll need
to modify this value to point to the new class.
</p>
<p>
The <mk>Main-ConfigFile</mk> entry points to the location of an external configuration file for our microservice.
</p>
<p>
In addition to these predefined manifest entries, you can add your own particular entries to the manifest file
and access them through the Manifest API described next.
</p>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.ManifestApi"></a>
<h4 class='topic' onclick='toggle(this)'>10.3.1 - Manifest API</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.microservice.Microservice#getManifest()} method is a static method that
can be used to retrieve the manifest file as a {@link org.apache.juneau.utils.ManifestFile}.
</p>
<p class='bcode'>
<jc>// Get Main-Class from manifest file.</jc>
String mainClass = Microservice.<jsm>getInstance</jsm>().getManifest().getString(<js>"Main-Class"</js>, <js>"unknown"</js>);
<jc>// Get Rest-Resources from manifest file.</jc>
String[] restResources = Microservice.<jsm>getInstance</jsm>().getManifest().getStringArray(<js>"Rest-Resources"</js>);
</p>
<p>
The {@link org.apache.juneau.utils.ManifestFile} class extends {@link org.apache.juneau.ObjectMap}.
<br>That makes it possible to retrieve entries as a wide variety of object types such as java primitives, arrays, collections,
maps, or even POJOs serialized as JSON.
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.Config"></a>
<h3 class='topic' onclick='toggle(this)'>10.4 - Config</h3>
<div class='topic'>
<p>
The microservice config file is an external INI-style configuration file that is used to configure
your microservice.
</p>
<p>
If you open the <l>my-microservice.cfg</l> file, you'll see several predefined sections and settings.
<br>The contents were shown in the previous sections.
</p>
<p>
Although the config file looks deceptively simple, the config file API is a very powerful feature with many
capabilities, including:
</p>
<ul class='spaced-list'>
<li>
The ability to use variables to reference environment variables, system properties, other config file
entries, and a host of other types.
<li>
The ability to store and retrieve POJOs as JSON.
<li>
APIs for updating, modifying, and saving configuration files without losing comments or formatting.
<li>
Extensive listener APIs.
</ul>
<h5 class='figure'>Examples:</h5>
<p class='bcode'>
<cc>#--------------------------</cc>
<cc># My section</cc>
<cc>#--------------------------</cc>
<cs>[MySection]</cs>
<cc># An integer</cc>
<ck>anInt</ck> = <cv>1 </cv>
<cc># A boolean</cc>
<ck>aBoolean</ck> = <cv>true </cv>
<cc># An int array</cc>
<ck>anIntArray</ck> = <cv>1,2,3 </cv>
<cc># A POJO that can be converted from a String</cc>
<ck>aURL</ck> = <cv>http://foo </cv>
<cc># An encoded password</cc>
<ck>aPassword*</ck> = <cv>{HRAaRQoT}</cv>
<cc># A POJO that can be converted from JSON</cc>
<ck>aBean</ck> = <cv>{foo:'bar',baz:123}</cv>
<cc># A system property</cc>
<ck>locale</ck> = <cv>$S{java.locale, en_US}</cv>
<cc># An environment variable</cc>
<ck>path</ck> = <cv>$E{PATH, unknown}</cv>
<cc># A manifest file entry</cc>
<ck>mainClass</ck> = <cv>$MF{Main-Class}</cv>
<cc># Another value in this config file</cc>
<ck>sameAsAnInt</ck> = <cv>$C{MySection/anInt}</cv>
<cc># A command-line argument in the form "myarg=foo"</cc>
<ck>myArg</ck> = <cv>$ARG{myarg}</cv>
<cc># The first command-line argument</cc>
<ck>firstArg</ck> = <cv>$ARG{0}</cv>
<cc># Look for system property, or env var if that doesn't exist, or command-line arg if that doesn't exist.</cc>
<ck>nested</ck> = <cv>$S{mySystemProperty,$E{MY_ENV_VAR,$ARG{0}}}</cv>
<cc># A POJO with embedded variables</cc>
<ck>aBean2</ck> = <cv>{foo:'$ARG{0}',baz:$C{MySection/anInt}}</cv>
</p>
<p class='bcode'>
<jc>// Java code for accessing config entries above.</jc>
Config cf = Microservice.<jsm>getInstance</jsm>().getConfig();
<jk>int</jk> anInt = cf.getInt(<js>"MySection/anInt"</js>);
<jk>boolean</jk> aBoolean = cf.getBoolean(<js>"MySection/aBoolean"</js>);
<jk>int</jk>[] anIntArray = cf.getObject(<jk>int</jk>[].<jk>class</jk>, <js>"MySection/anIntArray"</js>);
URL aURL = cf.getObject(URL.<jk>class</jk>, <js>"MySection/aURL"</js>);
String aPassword = cf.getString(<js>"MySection/aPassword"</js>);
MyBean aBean = cf.getObject(MyBean.<jk>class</jk>, <js>"MySection/aBean"</js>);
Locale locale = cf.getObject(Locale.<jk>class</jk>, <js>"MySection/locale"</js>);
String path = cf.getString(<js>"MySection/path"</js>);
String mainClass = cf.getString(<js>"MySection/mainClass"</js>);
<jk>int</jk> sameAsAnInt = cf.getInt(<js>"MySection/sameAsAnInt"</js>);
String myArg = cf.getString(<js>"MySection/myArg"</js>);
String firstArg = cf.getString(<js>"MySection/firstArg"</js>);
</p>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.ConfigApi"></a>
<h4 class='topic' onclick='toggle(this)'>10.4.1 - Config File API</h4>
<div class='topic'>
<p>
There are 3 primary ways of getting access to the config file.
</p>
<ul class='doctree'>
<li class='jm'>{@link org.apache.juneau.microservice.Microservice#getConfig()}
<br>Any <a class='doclink' href='#DefaultRestSvlVariables'>initialization-time variables</a> and <l>$ARG</l> and <l>$MF</l> variables can be used.
<li class='jm'>{@link org.apache.juneau.rest.RestContext#getConfig()}
<br>Any <a class='doclink' href='#DefaultRestSvlVariables'>initialization-time variables</a> and <l>$ARG</l> and <l>$MF</l> variables can be used.
<h5 class='figure'>Example usage:</h5>
<p class='bcode'>
<cc>#-------------------------------</cc>
<cc># Properties for MyHelloResource </cc>
<cc>#-------------------------------</cc>
<cs>[MyHelloResource]</cs>
<ck>greeting</ck> = <cv>Hello world!</cv>
</p>
<p class='bcode'>
<ja>@RestResource</ja>(...)
<jk>public class</jk> MyHelloResource <jk>extends</jk> Resource {
<jc>// Access config file when initializing fields.</jc>
<jk>private</jk> String greeting = getConfig().getString(<js>"MyHelloResource/greeting"</js>);
<jc>// Or access config file in servlet init method.</jc>
<ja>@Override</ja> <jc>/* Servlet */</jc>
<jk>public void</jk> init() {
String greeting = getConfig().getString(<js>"MyHelloResource/greeting"</js>);
}
}
</p>
<p>
Additional user-defined variables can be defined at this level by adding a
{@link org.apache.juneau.rest.annotation.HookEvent#INIT} hook method
and using the {@link org.apache.juneau.rest.RestContextBuilder#vars(Class...)} method.
</p>
<li class='jm'>
{@link org.apache.juneau.rest.RestRequest#getConfig()}
- An instance method to access it from inside a REST method.
<br>Any <a class='doclink' href='#DefaultRestSvlVariables'>initialization-time or request-time variables</a> and <l>$ARG</l> and <l>$MF</l> variables can be used.
<h5 class='figure'>Example usage:</h5>
<p class='bcode'>
<cc>#-----------------------------</cc>
<cc># Contents of microservice.cfg </cc>
<cc>#-----------------------------</cc>
<cs>[MyHelloResource]</cs>
<ck>greeting</ck> = <cv>Hello $RP{person}!</cv>
<ck>localizedGreeting</ck> = <cv>$L{HelloMessage,$RP{person}}</cv>
</p>
<p class='bcode'>
<cc>#---------------------------------</cc>
<cc># Contents of MyHelloResource.java </cc>
<cc>#---------------------------------</cc>
<ja>@RestResource</ja>(
path=<js>"/hello"</js>,
messages=<js>"nls/Messages"</js>,
...
)
<jk>public class</jk> MyHelloResource <jk>extends</jk> Resource {
<jd>/** Standard hello message. */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/{person}"</js>)
<jk>public</jk> String sayHello(RestRequest req) {
<jk>return</jk> req.getConfig().getString(<js>"MyHelloResource/greeting"</js>);
}
<jd>/** Hello message in users language. */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/localized/{person}"</js>)
<jk>public</jk> String sayLocalizedHello(RestRequest req) {
<jk>return</jk> req.getConfig().getString(<js>"MyHelloResource/localizedGreeting"</js>);
}
}
</p>
<p class='bcode'>
<cc>#---------------------------------------</cc>
<cc># Contents of nls/Messages_en.properties </cc>
<cc>#---------------------------------------</cc>
<ck>MyHelloResource.HelloMessage</ck> = <cv>Hello {0}!</cv>
</p>
<p>
Additional user-defined variables can be defined at this level by overriding the
{@link org.apache.juneau.rest.RestContextBuilder#vars(Class...)} method.
</p>
</ul>
<p>
That <l>sayLocalizedHello()</l> example might need some explanation since there's a lot going on there.
<br>Here's what happens when an HTTP call is made to <l>GET /hello/localized/Bob</l>:
</p>
<ol class='spaced-list'>
<li>
The HTTP call matches the <l>/hello</l> path on the <l>MyHelloResource</l> class.
<li>
The HTTP call matches the <l>/localized/{person}</l> path on the <l>sayLocalizedHello()</l> method.
<li>
The request attribute <l>person</l> gets assigned the value <l>"Bob"</l>.
<li>
The call to <l>req.getConfig().getString("MyHelloResource/localizedGreeting")</l>
finds the value <l>"$L{HelloMessage,$RP{person}}"</l>.
<li>
The arguments in the <l>$L{}</l> variable get resolved, resulting in <l>"$L{HelloMessage,Bob}"</l>.
<li>
The <l>$L{}</l> variable gets resolved to the message <l>"Hello {0}!"</l> in the localized properties
file of the servlet based on the <l>Accept-Language</l> header on the request.
<li>
The arguments get replaced in the message resulting in <l>"Hello Bob!"</l>.
<li>
The resulting message <l>"Hello Bob!"</l> is returned as a POJO to be serialized to whatever content
type was specified on the <l>Accept</l> header on the request.
</ol>
<p>
This particular example is needlessly complex, but it gives an idea of how variables can be used
recursively to produce sophisticated results
</p>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.ResourceClasses"></a>
<h3 class='topic' onclick='toggle(this)'>10.5 - Resource Classes</h3>
<div class='topic'>
<p>
Now let's take a look at the resource classes themselves.
<br>The top-level page...
</p>
<img class='bordered' src='doc-files/MicroserviceServer.Running.6.png' style='width:800px;'>
<p>
...is generated by this class...
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/"</js>,
title=<js>"My Microservice"</js>,
description=<js>"Top-level resources page"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
widgets={
ContentTypeMenuItem.<jk>class</jk>,
StyleMenuItem.<jk>class</jk>
},
navlinks={
<js>"options: servlet:/?method=OPTIONS"</js>
}
),
children={
HelloWorldResource.<jk>class</jk>,
ConfigResource.<jk>class</jk>,
LogsResource.<jk>class</jk>
}
)
<jk>public class</jk> RootResources <jk>extends</jk> ResourceGroup {
<jc>// No code! </jc>
}
</p>
<ul class='spaced-list'>
<li>
The </l>title</l> and <l>description</l> annotations define the titles on the page.
<br>These can be globalized using <l>$L{...}</l> variables, or by defining specially-named properties in the
properties file for the resource.
<li>
In this case, the <l>path</l> annotation defines the context root of your application since it was
not specified in the manifest or config file.
<br>Therefore, this resource is mapped to <l>http://localhost:10000</l>.
<li>
The <l>children</l> annotation make up the list of child resources.
<br>These child resources can be anything that extends from <l>Servlet</l>, although usually
they will be subclasses of {@link org.apache.juneau.microservice.Resource} or other resource groups.
</ul>
<p>
If you click the <l>helloWorld</l> link in your application, you'll get a simple hello world message:
</p>
<img class='bordered' src='doc-files/juneau-microservice-server.ResourceClasses.1.png' style='width:800px;'>
<p>
...which is generated by this class...
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/helloWorld"</js>,
title=<js>"Hello World example"</js>,
description=<js>"Simplest possible REST resource"</js>
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> Resource {
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>)
<jk>public</jk> String sayHello() {
<jk>return</jk> <js>"Hello world!"</js>;
}
}
</p>
<p>
The {@link org.apache.juneau.microservice.Resource} and {@link org.apache.juneau.microservice.ResourceGroup}
classes are powerful servlets designed specifically for creating REST APIs using nothing more than serialized
and parsed POJOs.
</p>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.PredefinedResourceClasses"></a>
<h3 class='topic' onclick='toggle(this)'>10.6 - Predefined Resource Classes</h3>
<div class='topic'>
<p>
The following predefined resource classes are also provided for easy inclusion into your microservice:
</p>
<ul class='doctree'>
<li class='jc'>{@link org.apache.juneau.microservice.resources.ConfigResource}
- View and modify the external INI config file.
<li class='jc'>{@link org.apache.juneau.microservice.resources.DirectoryResource}
- View and modify file system directories.
<li class='jc'>{@link org.apache.juneau.microservice.resources.LogsResource}
- View and control generated log files.
<li class='jc'>{@link org.apache.juneau.microservice.resources.SampleRootResource}
- A sample root resource class to get started from.
<li class='jc'>{@link org.apache.juneau.microservice.resources.ShutdownResource}
- Shutdown and/or restart the JVM.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.RestMicroservice"></a>
<h3 class='topic' onclick='toggle(this)'>10.7 - RestMicroservice</h3>
<div class='topic'>
<p>
The {@link org.apache.juneau.microservice.RestMicroservice} class is the main application entry-point for REST
microservices.
</p>
<p>
The class hierarchy is:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.microservice.Microservice}
- Abstract class that defines simple start/stop methods and access to the manifest file, config file, and
arguments.
<ul>
<li class='jc'>
{@link org.apache.juneau.microservice.RestMicroservice}
- Specialized microservice for starting up REST interfaces using Jetty and specifying REST servlets
through the manifest file or config file.
</ul>
</li>
</ul>
<p>
Refer to the Javadocs for these class for more information.
</p>
<!-- =========================================================================================================== -->
<a id="juneau-microservice-server.ExtendingRestMicroservice"></a>
<h4 class='topic' onclick='toggle(this)'>10.7.1 - Extending RestMicroservice</h4>
<div class='topic'>
<p>
This example shows how the {@link org.apache.juneau.microservice.RestMicroservice} class
can be extended to implement lifecycle listener methods or override existing methods.
<br>We'll create a new class <l>com.foo.SampleCustomRestMicroservice</l>.
</p>
<p>
First, the manifest file needs to be modified to point to our new microservice:
</p>
<p class='bcode'>
<mk>Main-Class:</mk> com.foo.SampleCustomRestMicroservice
</p>
<p>
Then we define the following class:
</p>
<p class='bcode'>
<jd>/**
* Sample subclass of a RestMicroservice that provides customized behavior.
* This class must be specified in the Main-Class entry in the manifest file and optionally
* a Main-ConfigFile entry.
*/</jd>
<jk>public class</jk> SampleCustomRestMicroservice <jk>extends</jk> RestMicroservice {
<jd>/**
* Must implement a main method and call start()!
*/</jd>
<jk>public static void</jk> main(String[] args) <jk>throws</jk> Exception {
<jk>new</jk> SampleCustomRestMicroservice(args).start().join();
}
<jd>/**
* Must implement a constructor!
*
* <ja>@param</ja> args Command line arguments.
* <ja>@throws</ja> Exception
*/</jd>
<jk>public</jk> SampleCustomRestMicroservice(String[] args) <jk>throws</jk> Exception {
<jk>super</jk>(args);
}
</p>
<p>
The microservice APIs provide several useful methods that can be used or extended.
</p>
<h5 class='section'>See Also:</h5>
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.microservice.Microservice}
<li class='jc'>{@link org.apache.juneau.microservice.RestMicroservice}
</ul>
</div>
</div>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-examples-core"></a>
<h2 class='topic' onclick='toggle(this)'>11 - juneau-examples-core</h2>
<div class='topic'>
<h5 class='figure'>Archive File</h5>
<p class='bcode' style='width:500px;'>
juneau-examples-core-7.0.0.zip
</p>
<p>
The <code>juneau-examples-core</code> project contains various code examples for using the core APIs.
</p>
<p>
The project project can be loaded into your workspace by importing the
<code>juneau-examples-core-7.0.0.zip</code> file.
</p>
<h5 class='topic'>Instructions on how to install juneau-examples-core project</h5>
<p>
Download the <code>juneau-examples-core-7.0.0.zip</code> file from the downloads page
(located in the binaries) and import it into your workspace as an existing project:
</p>
<img class='bordered' src='doc-files/juneau-examples-core.1.png' style='width:512px'>
<p>
Select the archive file and import the project:
</p>
<img class='bordered' src='doc-files/juneau-examples-core.2.png' style='width:523px'>
<p>
Once loaded, you should see the following project structure:
</p>
<img class='bordered' src='doc-files/juneau-examples-core.3.png' style='width:459px'>
<p>
The Core library samples are currently a work-in-progress so there's not much here yet.
This section will be updated as new code is added.
</p>
</div>
<!-- =========================================================================================================== -->
<a id="juneau-examples-rest"></a>
<h2 class='topic' onclick='toggle(this)'>12 - juneau-examples-rest</h2>
<div class='topic'>
<h5 class='figure'>Archive File</h5>
<p class='bcode' style='width:500px;'>
juneau-examples-rest-7.0.0.zip
</p>
<p>
The <code>juneau-examples-rest</code> project includes everything you need to start the Samples REST
microservice in an Eclipse workspace.
</p>
<p>
This project is packaged as a Juneau Microservice project that allows REST resources to be started
using embedded Jetty.
</p>
<h5 class='topic'>Instructions on how to install juneau-examples-rest project</h5>
<p>
Download the <code>juneau-examples-rest-7.0.0.zip</code> file from the downloads page
(located in the binaries) and import it into your workspace as an existing project:
</p>
<img class='bordered' src='doc-files/juneau-examples-rest.1.png' style='width:524px'>
<p>
Select the archive file and import the project:
</p>
<img class='bordered' src='doc-files/juneau-examples-rest.2.png' style='width:523px'>
<p>
Once loaded, you should see the following project structure:
</p>
<img class='bordered' src='doc-files/juneau-examples-rest.3.png' style='width:412px'>
<p>
The microservice can be started from the <code>juneau-examples-rest.launch</code> file.
It will start up the microservice on port 10000 which you can then view through a browser:
</p>
<img class='bordered' src='doc-files/juneau-examples-rest.4.png' style='width:466px'>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.RootResources"></a>
<h4 class='topic' onclick='toggle(this)'>12.1 - RootResources</h4>
<div class='topic'>
<p>
The <l>RootResources</l> class is the main page for the REST microservice.
It serves as the jumping-off point for the other resources.
</p>
<p>
The class hierarchy for this class is:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.rest.RestServlet org.apache.juneau.rest.RestServlet}
<br>Contains all the REST servlet logic.
<ul>
<li class='jac'>
{@link org.apache.juneau.rest.RestServletDefault org.apache.juneau.rest.RestServletDefault}
<br>Defines default serializers and parsers, and OPTIONs page logic.
<ul>
<li class='jac'>
{@link org.apache.juneau.rest.RestServletGroupDefault org.apache.juneau.rest.RestServletGroupDefault}
<br>Specialized subclass for grouping other resources
<ul>
<li class='jac'>
{@link org.apache.juneau.microservice.ResourceGroup org.apache.juneau.microservice.ResourceGroup}
<br>Specialized subclass when using the Microservice API.
<ul>
<li class='jc'>
<code>org.apache.juneau.rest.samples.RootResources</code>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.Running.3.png'>
<p>
The <l>RootResources</l> class can also be defined as a servlet in a <l>web.xml</l> file:
</p>
<p class='bcode'>
<xt>&lt;web-app</xt> <xa>version</xa>=<xs>'2.3'</xs><xt>&gt;</xt>
<xt>&lt;servlet&gt;</xt>
<xt>&lt;servlet-name&gt;</xt>RootResources<xt>&lt;/servlet-name&gt;</xt>
<xt>&lt;servlet-class&gt;</xt>org.apache.juneau.rest.samples.RootResources<xt>&lt;/servlet-class&gt;</xt>
<xt>&lt;/servlet&gt;</xt>
<xt>&lt;servlet-mapping&gt;</xt>
<xt>&lt;servlet-name&gt;</xt>RootResources<xt>&lt;/servlet-name&gt;</xt>
<xt>&lt;url-pattern&gt;</xt>/*<xt>&lt;/url-pattern&gt;</xt>
<xt>&lt;/servlet-mapping&gt;</xt>
<xt>&lt;/web-app&gt;</xt>
</p>
<p>
The <l>RootResources</l> class consists entirely of annotations:
</p>
<h5 class='figure'>RootResources.java</h5>
<p class='bcode'>
<jd>/**
* Sample REST resource showing how to implement a "router" resource page.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/"</js>,
messages=<js>"nls/RootResources"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"options: ?method=OPTIONS"</js>
}
),
children={
HelloWorldResource.<jk>class</jk>,
MethodExampleResource.<jk>class</jk>,
RequestEchoResource.<jk>class</jk>,
TempDirResource.<jk>class</jk>,
AddressBookResource.<jk>class</jk>,
SampleRemoteableServlet.<jk>class</jk>,
PhotosResource.<jk>class</jk>,
AtomFeedResource.<jk>class</jk>,
JsonSchemaResource.<jk>class</jk>,
SqlQueryResource.<jk>class</jk>,
TumblrParserResource.<jk>class</jk>,
CodeFormatterResource.<jk>class</jk>,
UrlEncodedFormResource.<jk>class</jk>,
SourceResource.<jk>class</jk>,
ConfigResource.<jk>class</jk>,
LogsResource.<jk>class</jk>,
DockerRegistryResource.<jk>class</jk>,
ShutdownResource.<jk>class</jk>
}
)
<jk>public class</jk> RootResources <jk>extends</jk> ResourceGroup {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
}
</p>
<p>
The resource bundle contains the localized strings for the resource:
</p>
<h5 class='figure'>RootResources.properties</h5>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# RootResources labels
#--------------------------------------------------------------------------------</cc>
<ck>title</ck> = <cv>Root resources</cv>
<ck>description</ck> = <cv>This is an example of a router resource that is used to access other resources.</cv>
</p>
<p>
The <l>title</l> and <l>description</l> keys identify the localized values
return by the {@link org.apache.juneau.rest.RestRequest#getResourceTitle()} and
{@link org.apache.juneau.rest.RestRequest#getResourceDescription()} methods.
</p>
<p>
The <l>children</l> annotation defines the child resources of this router resource.
These are resources whose paths are relative to the parent resource.
</p>
<p>
Child resources must also be subclasses of {@link org.apache.juneau.rest.RestServlet}, and
must specify a {@link org.apache.juneau.rest.annotation.RestResource#path() @RestResource.path()} annotation to
identify the subpath of the child.
For example, the <l>HelloWorldResource</l> class is annotated as follows:
</p>
<h5 class='figure'>HelloWorldResource.java</h5>
<p class='bcode'>
<ja>@RestResource</ja>(messages=<js>"nls/HelloWorldResource"</js>, path=<js>"/helloWorld"</js>)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> Resource {
</p>
<p>
It should be noted that child resources do not need to be defined this way.
They could also be defined as servlets in the same way as the root resource.
The <l>children</l> annotation approach simply makes it easier to define them without having to touch the
<l>web.xml</l> file again.
Child resources can also be defined programmatically by using the
{@link org.apache.juneau.rest.RestContextBuilder#children(Class[])} method.
</p>
<p>
Note that these router pages can be arbitrarily nested deep.
You can define many levels of router pages for arbitrarily hierarchical REST interfaces.
</p>
<ul class='doctree'>
<li class='info'>
Let's step back and describe what's going on here:
<br>During servlet initialization of the <l>RootResources</l> object, the toolkit looks for the
<l>@RestResource.children()</l> annotation.
If it finds it, it instantiates instances of each class and recursively performs servlet initialization
on them.
It then associates the child resource with the parent by the name specified by the
<l>@RestResource.path()</l> annotation on the child class.
When a request for the child URL (<l>/helloWorld</l>) is received, the <l>RootResources</l> servlet
gets the request and sees that the URL remainder matches one of its child resources.
It then forwards the request to the child resource for processing.
The request passed to the child resource is the same as if the child resource had been deployed
independently (e.g. path-info, resource-URI, and so forth).
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.HelloWorldResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.2 - HelloWorldResource</h4>
<div class='topic'>
<p>
The <l>HelloWorldResource</l> class is a simple resource that prints a "Hello world!" message.
</p>
<h5 class='figure'>HelloWorldResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample REST resource that prints out a simple "Hello world!" message.
*/</jd>
<ja>@RestResource</ja>(
messages=<js>"nls/HelloWorldResource"</js>,
path=<js>"/helloWorld"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> HelloWorldResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jd>/** GET request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>)
<jk>public</jk> String sayHello() {
<jk>return</jk> <js>"Hello world!"</js>;
}
}
</p>
<h5 class='figure'>HelloWorldResource.properties</h5>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# HelloWorldResource labels
#--------------------------------------------------------------------------------</cc>
<ck>title</ck> = <cv>Hello World sample resource</cv>
<ck>description</ck> = <cv>Simplest possible resource</cv>
<ck>sayHello.summary</ck> = <cv>Responds with "Hello world!"</cv>
</p>
<p>
The class hierarchy for this class is:
</p>
<ul class='doctree'>
<li class='jac'>
{@link org.apache.juneau.rest.RestServlet org.apache.juneau.rest.RestServlet}
<br>Contains all the REST servlet logic.
<ul>
<li class='jac'>
{@link org.apache.juneau.rest.RestServletDefault org.apache.juneau.rest.RestServletDefault}
<br>Defines default serializers and parsers, and OPTIONs page logic.
<ul>
<li class='jac'>
{@link org.apache.juneau.microservice.Resource org.apache.juneau.microservice.Resource}
<br>Specialized subclass when using the Microservice API.
<ul>
<li class='jc'><code>org.apache.juneau.rest.samples.HelloWorldResource</code>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.HelloWorldResource.1.png'>
<p>
Using the special <l>&amp;Accept=text/json</l> and <l>&amp;plainText=true</l> parameters
allows us to see this page rendered as JSON:
</p>
<img class='bordered' src='doc-files/Samples.HelloWorldResource.2.png'>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.MethodExampleResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.3 - MethodExampleResource</h4>
<div class='topic'>
<p>
The <l>MethodExampleResource</l> class provides examples of the following:
</p>
<ul class='spaced-list'>
<li>
Using the {@link org.apache.juneau.rest.Redirect} object to perform redirections.
<li>
Using the various Java method parameter annotations to retrieve request attributes, parameters, etc.
<li>
Using the annotation programmatic equivalents on the {@link org.apache.juneau.rest.RestRequest} object.
<li>
Setting response POJOs by either returning them or using the
{@link org.apache.juneau.rest.RestResponse#setOutput(Object)} method.
</ul>
<p>
The resource is provided to show how various HTTP entities (e.g. parameters, headers) can be accessed
as either annotated Java parameters, or through methods on the <l>RestRequest</l> object.
</p>
<h5 class='figure'>MethodExampleResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample REST resource that shows how to define REST methods and OPTIONS pages
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/methodExample"</js>,
messages=<js>"nls/MethodExampleResource"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> MethodExampleResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jd>/** Example GET request that redirects to our example method */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> Redirect doExample() <jk>throws</jk> Exception {
<jk>return new</jk> Redirect(<js>"example1/xxx/123/{0}/xRemainder?q1=123&amp;q2=yyy"</js>,
UUID.<jsm>randomUUID</jsm>());
}
<jd>/**
* Methodology #1 - GET request using annotated attributes.
* This approach uses annotated parameters for retrieving input.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example1/{p1}/{p2}/{p3}/*"</js>)
<jk>public</jk> String example1(
<ja>@Method</ja> String method, <jc>// HTTP method.</jc>
<ja>@Path</ja> String p1, <jc>// Path variables.</jc>
<ja>@Path</ja> <jk>int</jk> p2,
<ja>@Path</ja> UUID p3,
<ja>@Query</ja>(<js>"q1"</js>) <jk>int</jk> q1, <jc>// Query parameters.</jc>
<ja>@Query</ja>(<js>"q2"</js>) String q2,
<ja>@Query</ja>(<js>"q3"</js>) UUID q3,
<ja>@PathRemainder</ja> String remainder, <jc>// Path remainder after pattern match.</jc>
<ja>@Header</ja>(<js>"Accept-Language"</js>) String lang, <jc>// Headers.</jc>
<ja>@Header</ja>(<js>"Accept"</js>) String accept,
<ja>@Header</ja>(<js>"DNT"</js>) <jk>int</jk> doNotTrack
) {
<jc>// Send back a simple String response</jc>
String output = String.<jsm>format</jsm>(
<js>"method=%s, p1=%s, p2=%d, p3=%s, remainder=%s, q1=%d, q2=%s, q3=%s, lang=%s, accept=%s, dnt=%d"</js>,
method, p1, p2, p3, remainder, q1, q2, q3, lang, accept, doNotTrack);
<jk>return</jk> output;
}
<jd>/**
* Methodology #2 - GET request using methods on RestRequest and RestResponse.
* This approach uses low-level request/response objects to perform the same as above.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example2/{p1}/{p2}/{p3}/*"</js>)
<jk>public</jk> String example2(
RestRequest req, <jc>// A direct subclass of HttpServletRequest.</jc>
RestResponse res <jc>// A direct subclass of HttpServletResponse.</jc>
) {
<jc>// HTTP method.</jc>
String method = req.getMethod();
<jc>// Path variables.</jc>
RequestPathMatch path = req.getPathMatch();
String p1 = path.get(<js>"p1"</js>, String.<jk>class</jk>);
<jk>int</jk> p2 = path.get(<js>"p2"</js>, <jk>int</jk>.<jk>class</jk>);
UUID p3 = path.get(<js>"p3"</js>, UUID.<jk>class</jk>);
<jc>// Query parameters.</jc>
RequestQuery query = req.getQuery();
<jk>int</jk> q1 = query.get(<js>"q1"</js>, 0, <jk>int</jk>.<jk>class</jk>);
String q2 = query.get(<js>"q2"</js>, String.<jk>class</jk>);
UUID q3 = query.get(<js>"q3"</js>, UUID.<jk>class</jk>);
<jc>// Path remainder after pattern match.</jc>
String remainder = req.getPathMatch().getRemainder();
<jc>// Headers.</jc>
String lang = req.getHeader(<js>"Accept-Language"</js>);
String accept = req.getHeader(<js>"Accept"</js>);
<jk>int</jk> doNotTrack = req.getHeaders().get(<js>"DNT"</js>, <jk>int</jk>.<jk>class</jk>);
<jc>// Send back a simple String response</jc>
String output = String.format(
<js>"method=%s, p1=%s, p2=%d, p3=%s, remainder=%s, q1=%d, q2=%s, q3=%s, lang=%s, accept=%s, dnt=%d"</js>,
method, p1, p2, p3, remainder, q1, q2, q3, lang, accept, doNotTrack);
res.setOutput(output); <jc>// Or use getWriter().</jc>
}
<jd>/**
* Methodology #3 - GET request using special objects.
* This approach uses intermediate-level APIs.
* The framework recognizes the parameter types and knows how to resolve them.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/example3/{p1}/{p2}/{p3}/*"</js>)
<jk>public</jk> String example3(
HttpMethod method, <jc>// HTTP method.</jc>
RequestPathMatch path, <jc>// Path variables.</jc>
RequestQuery query, <jc>// Query parameters.</jc>
RequestHeaders headers, <jc>// Headers.</jc>
AcceptLanguage lang, <jc>// Specific header classes.</jc>
Accept accept
) {
<jc>// Path variables.</jc>
String p1 = path.get(<js>"p1"</js>, String.<jk>class</jk>);
<jk>int</jk> p2 = path.get(<js>"p2"</js>, <jk>int</jk>.<jk>class</jk>);
UUID p3 = path.get(<js>"p3"</js>, UUID.<jk>class</jk>);
<jc>// Query parameters.</jc>
<jk>int</jk> q1 = query.get(<js>"q1"</js>, 0, <jk>int</jk>.<jk>class</jk>);
String q2 = query.get(<js>"q2"</js>, String.<jk>class</jk>);
UUID q3 = query.get(<js>"q3"</js>, UUID.<jk>class</jk>);
<jc>// Path remainder after pattern match.</jc>
String remainder = path.getRemainder();
<jc>// Headers.</jc>
int doNotTrack = headers.get(<js>"DNT"</js>, <jk>int</jk>.<jk>class</jk>);
<jc>// Send back a simple String response</jc>
String output = String.format(
<js>"method=%s, p1=%s, p2=%d, p3=%s, remainder=%s, q1=%d, q2=%s, q3=%s, lang=%s, accept=%s, dnt=%d"</js>,
method, p1, p2, p3, remainder, q1, q2, q3, lang, accept, doNotTrack);
res.setOutput(output);
}
}
</p>
<p>
The class consists of 4 methods:
</p>
<ul class='doctree'>
<li class='jm'>
<l>doExample()</l>
<br>The root page.
<br>Performs a simple redirection to the <l>doGetExample1()</l> method using a
{@link org.apache.juneau.rest.Redirect} object.
<li class='jm'>
<l>example1()</l>
<br>Shows how to use the following annotations:
<ul>
<li class='ja'>{@link org.apache.juneau.rest.annotation.Path @Path}
<li class='ja'>{@link org.apache.juneau.rest.annotation.Query @Query}
<li class='ja'>{@link org.apache.juneau.rest.annotation.Header @Header}
<li class='ja'>{@link org.apache.juneau.rest.annotation.Method @Method}
<li class='ja'>{@link org.apache.juneau.rest.annotation.PathRemainder @PathRemainder}
</ul>
Method returns a POJO to be serialized as the output.
<li class='jm'>
<l>example2()</l>
<br>Identical to <l>doGetExample1()</l> but shows how to use the
{@link org.apache.juneau.rest.RestRequest} and {@link org.apache.juneau.rest.RestResponse} objects:
<ul>
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getPathMatch()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getQuery()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getFormData()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getHeaders()}
<li class='jm'>{@link org.apache.juneau.rest.RestRequest#getMethod()}
<li class='jm'>{@link org.apache.juneau.rest.RequestPathMatch#getRemainder()}
</ul>
Method sets the POJO to be serialized using the {@link org.apache.juneau.rest.RestResponse#setOutput(Object)} method.
<li class='jm'>
<l>example3()</l>
<br>Identical to <l>doGetExample1()</l> but uses automatically resolved parameters based on class type.
<br>Juneau automatically recognizes specific class types such as common header types and automatically
resolves them to objects for you.
<br>See <a class='doclink' href='#juneau-rest-server.RestMethod'>@RestMethod</a> for the list of all automatically support parameter types, and
{@link org.apache.juneau.rest.annotation.RestResource#paramResolvers() @RestResource.paramResolvers()}
for defining your own custom parameter type resolvers.
</ul>
<p>
There's a lot going on in this method.
Notice how you're able to access URL attributes, parameters, headers, and content as parsed POJOs.
All the input parsing is already done by the toolkit.
You simply work with the resulting POJOs.
</p>
<p>
As you might notice, using annotations typically results in fewer lines of code and are therefore usually
preferred over the API approach, but both are equally valid.
</p>
<p>
When you visit this page through the router page, you can see the following (after the automatic
redirection occurs):
</p>
<img class='bordered' src="doc-files/Samples.MethodExampleResource.1.png">
<p>
Notice how the conversion to POJOs is automatically done for us, even for non-standard POJOs such as UUID.
</p>
<h5 class='topic'>Self-documenting design through Swagger OPTIONS pages</h5>
<p>
One of the main features of Juneau is that it produces OPTIONS pages for self-documenting design (i.e. REST
interfaces that document themselves).
</p>
<p>
Much of the information populated on the OPTIONS page is determined through reflection.
This basic information can be augmented with information defined through:
</p>
<ul class='spaced-list'>
<li>
Annotations - An example of this was shown in the <code>SystemPropertiesResource</code> example above.
<br>Localized strings can be pulled from resource bundles using the <code>$L</code> localization variable.
<li>
Resource bundle properties - Described in detail in this section.
<li>
Swagger JSON files with the same name and location as the resource class (e.g.
<code>MethodExampleResource.json</code>).
<br>Localized versions are defined by appending the locale to the file name (e.g.
<code>MethodExampleResource_ja_JP.json</code>);
</ul>
<p>
OPTIONS pages are simply serialized {@link org.apache.juneau.dto.swagger.Swagger} DTO beans.
Localized versions of these beans are retrieved using the
{@link org.apache.juneau.rest.RestRequest#getSwagger()} method.
</p>
<p>
To define an OPTIONS request handler, the {@link org.apache.juneau.rest.RestServletDefault} class defines
the following Java method:
</p>
<h5 class='figure'>RestServletDefault.java</h5>
<p class='bcode'>
<jd>/** OPTIONS request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>OPTIONS</jsf>, path=<js>"/*"</js>)
<jk>public</jk> Swagger getOptions(RestRequest req) {
<jk>return</jk> req.getSwagger();
}
</p>
<p>
The <l>OPTIONS</l> link that you see on the HTML version of the page is created
through a property defined by the {@link org.apache.juneau.html.HtmlDocSerializer} class
and specified on the resource class annotation:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
</p>
<p>
This simply creates a link that's the same URL as the resource URL appended with <l>"?method=OPTIONS"</l>,
which is a shorthand way that the framework provides of defining overloaded GET requests.
Links using relative or absolute URLs can be defined this way.
</p>
<p>
Metadata about the servlet class is combined with localized strings from a properties file associated
through a <code><ja>@RestResource</ja>(messages=<js>"nls/MethodExampleResources"</js>)</code> annotation.
The properties file contains localized descriptions for the resource, resource methods, and method
parameters.
</p>
<h5 class='figure'>MethodExampleResource.properties</h5>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# MethodExampleResource labels
#--------------------------------------------------------------------------------</cc>
<ck>title = <cv>A simple REST method example resource</cv>
<ck>doGetExample.summary</ck> = <cv>Sample GET method</cv>
<ck>doGetExample1.summary</ck> = <cv>Sample GET using annotations</cv>
<ck>doGetExample1.req.path.a1.description</ck> = <cv>Sample variable</cv>
<ck>doGetExample1.req.path.a2.description</ck> = <cv>Sample variable</cv>
<ck>doGetExample1.req.path.a3.description</ck> = <cv>Sample variable</cv>
<ck>doGetExample1.req.query.p1.description</ck> = <cv>Sample parameter</cv>
<ck>doGetExample1.req.query.p2.description</ck> = <cv>Sample parameter</cv>
<ck>doGetExample1.req.query.p3.description</ck> = <cv>Sample parameter</cv>
<ck>doGetExample1.req.header.Accept-Language.description</ck> = <cv>Sample header</cv>
<ck>doGetExample1.req.header.DNT.description</ck> = <cv>Sample header</cv>
<ck>doGetExample2.summary</ck> = <cv>Sample GET using Java APIs</cv>
<ck>doGetExample2.req.path.a1.description</ck> = <cv>Sample variable</cv>
<ck>doGetExample2.req.path.a2.description</ck> = <cv>Sample variable</cv>
<ck>doGetExample2.req.path.a3.description</ck> = <cv>Sample variable</cv>
<ck>doGetExample2.req.query.p1.description</ck> = <cv>Sample parameter</cv>
<ck>doGetExample2.req.query.p2.description</ck> = <cv>Sample parameter</cv>
<ck>doGetExample2.req.query.p3.description</ck> = <cv>Sample parameter</cv>
<ck>doGetExample2.req.header.Accept-Language.description</ck> = <cv>Sample header</cv>
<ck>doGetExample2.req.header.DNT.description</ck> = <cv>Sample header</cv>
<ck>getOptions.summary</ck> = <cv>View these options</cv>
</p>
<p>
Clicking the <l>options</l> link on the page presents you with information about how to use this resource:
</p>
<img class='bordered' src="doc-files/Samples.MethodExampleResource.2.png">
<p>
This page (like any other) can also be rendered in JSON or XML by using the <l>&amp;Accept</l> URL parameter.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.UrlEncodedFormResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.4 - UrlEncodedFormResource</h4>
<div class='topic'>
<p>
The <l>UrlEncodedFormResource</l> class provides examples of the following:
</p>
<ul class='spaced-list'>
<li>
How to use form entry beans to process form POSTs.
<li>
How to use the {@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String)} method to
serve up static files with embedded string variables.
</ul>
<p>
The class is shown below:
</p>
<h5 class='figure'>UrlEncodedFormResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample REST resource for loading URL-Encoded form posts into POJOs.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/urlEncodedForm"</js>,
messages=<js>"nls/UrlEncodedFormResource"</js>
)
<jk>public class</jk> UrlEncodedFormResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jd>/** GET request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> ReaderResource doGet(RestRequest req) <jk>throws</jk> IOException {
<jk>return</jk> req.getClasspathReaderResource(<js>"UrlEncodedForm.html"</js>, <jk>true</jk>);
}
<jd>/** POST request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>)
<jk>public</jk> Object doPost(<ja>@Body</ja> FormInputBean input) <jk>throws</jk> Exception {
<jc>// Just mirror back the request</jc>
<jk>return</jk> input;
}
<jk>public static class</jk> FormInputBean {
<jk>public</jk> String aString;
<jk>public int</jk> aNumber;
<ja>@BeanProperty</ja>(pojoSwaps=CalendarSwap.<jsf>ISO8601DT</jsf>.<jk>class</jk>)
<jk>public</jk> Calendar aDate;
}
}
</p>
<p>
The {@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String,boolean)} method pulls in the following
file located in the same package as the class:
</p>
<h5 class='figure'>UrlEncodedForm.html</h5>
<b>TODO - Needs update</b>
<p class='bcode'>
<xt>&lt;html&gt;</xt>
<xt>&lt;head&gt;</xt>
<xt>&lt;meta</xt> <xa>http-equiv</xa>=<xs>"Content-Type"</xs> <xa>content</xa>=<xs>"text/html;charset=UTF-8"</xs><xt>&gt;</xt>
<xt>&lt;style</xt> <xa>type</xa>=<xs>'text/css'</xs><xt>&gt;</xt>
<xt>@import</xt> <xs>'$R{servletURI}/style.css'</xs>;
<xt>&lt;/style&gt;</xt>
<xt>&lt;script</xt> <xa>type</xa>=<xs>"text/javascript"</xs><xt>&gt;</xt>
<jc>// Load results from IFrame into this document.</jc>
<jk>function</jk> loadResults(buff) {
<jk>var</jk> doc = buff.contentDocument || buff.contentWindow.document;
<jk>var</jk> buffBody = doc.getElementById(<js>'data'</js>);
document.getElementById(<js>'results'</js>).innerHTML = buffBody.innerHTML;
}
<xt>&lt;/script&gt;</xt>
<xt>&lt;/head&gt;</xt>
<xt>&lt;body&gt;</xt>
<xt>&lt;h1&gt;</xt>$R{resourceTitle}<xt>&lt;/h1&gt;</xt>
<xt>&lt;h2&gt;</xt>$R{resourceDescription}<xt>&lt;/h2&gt;</xt>
<xt>&lt;div</xt> <xa>class</xa>=<xs>'data'</xs><xt>&gt;</xt>
<xt>&lt;form</xt> <xa>id</xa>=<xs>'form'</xs> <xa>action</xa>=<xs>'$R{servletURI}'</xs> <xa>method</xa>=<xs>'POST'</xs> <xa>target</xa>=<xs>'buff'</xs><xt>&gt;</xt>
<xt>&lt;table&gt;</xt>
<xt>&lt;tr&gt;</xt>
<xt>&lt;th&gt;</xt>$L{aString}<xt>&lt;/th&gt;</xt>
<xt>&lt;td&gt;</xt><xt>&lt;input</xt> <xa>name</xa>=<xs>"aString"</xs> <xa>type</xa>=<xs>"text"</xs><xt>&gt;</xt><xt>&lt;/td&gt;</xt>
<xt>&lt;/tr&gt;</xt>
<xt>&lt;tr&gt;</xt>
<xt>&lt;th&gt;</xt>$L{aNumber}<xt>&lt;/th&gt;</xt>
<xt>&lt;td&gt;</xt><xt>&lt;input</xt> <xa>name</xa>=<xs>"aNumber"</xs> <xa>type</xa>=<xs>"number"</xs><xt>&gt;</xt><xt>&lt;/td&gt;</xt>
<xt>&lt;/tr&gt;</xt>
<xt>&lt;tr&gt;</xt>
<xt>&lt;th&gt;</xt>$L{aDate}<xt>&lt;/th&gt;</xt>
<xt>&lt;td&gt;</xt><xt>&lt;input</xt> <xa>name</xa>=<xs>"aDate"</xs> <xa>type</xa>=<xs>"datetime"</xs><xt>&gt;</xt> (ISO8601, e.g. "<xt>&lt;code&gt;</xt>2001-07-04T15:30:45Z<xt>&lt;/code&gt;</xt>")<xt>&lt;/td&gt;</xt>
<xt>&lt;/tr&gt;</xt>
<xt>&lt;tr&gt;</xt>
<xt>&lt;td</xt> <xa>colspan</xa>=<xs>'2'</xs> <xa>align</xa>=<xs>'right'</xs><xt>&gt;</xt><xt>&lt;button</xt> <xa>type</xa>=<xs>"submit"</xs><xt>&gt;</xt>$L{submit}<xt>&lt;/button&gt;</xt><xt>&lt;/td&gt;</xt>
<xt>&lt;/tr&gt;</xt>
<xt>&lt;/table&gt;</xt>
<xt>&lt;/form&gt;</xt>
<xt>&lt;br&gt;</xt>
<xt>&lt;div</xt> <xa>id</xa>=<xs>'results'</xs><xt>&gt;</xt>
<xt>&lt;/div&gt;</xt>
<xt>&lt;/div&gt;</xt>
<xt>&lt;iframe</xt> <xa>name</xa>=<xs>'buff'</xs> <xa>style</xa>=<xs>'display:none'</xs> <xa>onload</xa>=<xs>"parent.loadResults(this)"</xs><xt>&gt;</xt><xt>&lt;/iframe&gt;</xt>
<xt>&lt;/body&gt;</xt>
<xt>&lt;/html&gt;</xt>
</p>
<p>
The <l>$L</l> variables are string variable that pull in localized values from the resource bundle:
</p>
<h5 class='figure'>UrlEncodedFormResource.properties</h5>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# UrlEncodedFormResource labels
#--------------------------------------------------------------------------------</cc>
<ck>title</ck> = <cv>URL-Encoded Form Post Example</cv>
<ck>description</ck> = <cv>Shows how URL-Encoded form input can be loaded into POJOs. POJO is simply echoed back.</cv>
<ck>aString</ck> = <cv>A String:</cv>
<ck>aNumber</ck> = <cv>A Number:</cv>
<ck>aDate</ck> = <cv>A Date:</cv>
<ck>submit</ck> = <cv>submit</cv>
</p>
<p>
The <l>$R</l> variables are request string variables.
In this case, <l>$R{resourceTitle}</l> and <l>$R{resourceDescription}</l> resolve to the values returned by
{@link org.apache.juneau.rest.RestRequest#getResourceTitle()} and
{@link org.apache.juneau.rest.RestRequest#getResourceDescription()}.
</p>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.UrlEncodedFormResource.1.png'>
<p>
Entering some values and clicking <l>submit</l> causes the form bean to be populated
and returned back as a POJO response:
</p>
<img class='bordered' src='doc-files/Samples.UrlEncodedFormResource.2.png'>
<p>
Another option is to construct the HTML form in Java using <a class='doclink'
href='org/apache/juneau/dto/html5/package-summary.html#TOC'>HTML5 beans</a>.
This is arguably a better approach since it's typically cleaner with less code, and the headers/links
are already part of the page.
</p>
<p class='bcode'>
<jk>import static</jk> org.apache.juneau.dto.html5.HtmlBuilder.*;
<jd>/** GET request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> Div doGet(RestRequest req) {
<jk>return</jk> div(
script(<js>"text/javascript"</js>,
<js>"\n // Load results from IFrame into this document."</js>
+<js>"\n function loadResults(buff) {"</js>
+<js>"\n var doc = buff.contentDocument || buff.contentWindow.document;"</js>
+<js>"\n var buffBody = doc.getElementById('data');"</js>
+<js>"\n document.getElementById('results').innerHTML = buffBody.innerHTML;"</js>
+<js>"\n }"</js>
),
<jsf>form</jsf>().id(<js>"form"</js>).action(req.getServletURI()).method(<jsf>POST</jsf>).target(<js>"buff"</js>).children(
<jsf>table</jsf>(
<jsf>tr</jsf>(
<jsf>th</jsf>(req.getMessage(<js>"aString"</js>)),
<jsf>td</jsf>(<jsf>input</jsf>().name(<js>"aString"</js>).type(<js>"text"</js>))
),
<jsf>tr</jsf>(
<jsf>th</jsf>(req.getMessage(<js>"aNumber"</js>)),
<jsf>td</jsf>(<jsf>input</jsf>().name(<js>"aNumber"</js>).type(<js>"number"</js>))
),
<jsf>tr</jsf>(
<jsf>th</jsf>(req.getMessage(<js>"aDate"</js>)),
<jsf>td</jsf>(<jsf>input</jsf>().name(<js>"aDate"</js>).type(<js>"datetime"</js>), <js>" (ISO8601, e.g. "</js>, code(<js>"2001-07-04T15:30:45Z"</js>), <js>\" )"</js>)
),
<jsf>tr</jsf>(
<jsf>td</jsf>().colspan(2).style(<js>"text-align:right"</js>).children(
<jsf>button</jsf>(<js>"submit"</js>, req.getMessage(<js>"submit"</js>))
)
)
)
),
<jsf>br</jsf>(),
<jsf>div</jsf>().id(<js>"results"</js>),
<jsf>iframe</jsf>().name(<js>"buff"</js>).style(<js>"display:none"</js>).onload(<js>"parent.loadResults(this)"</js>)
);
}
</p>
<h5 class='toc'>Additional Information</h5>
<ul class='toc'>
<li class='jm'>
{@link org.apache.juneau.rest.RestContextBuilder#vars(Class[])}
- Servlet and request variables.
<li class='jm'>
{@link org.apache.juneau.rest.RestCallHandler#getSessionObjects(RestRequest)}
- Var resolver session objects.
</ul>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.RequestEchoResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.5 - RequestEchoResource</h4>
<div class='topic'>
<p>
The <l>RequestEchoResource</l> class shows how existing complex POJOs can be serialized to a variety of
content types.
The example simply takes the incoming <l>HttpServletRequest</l> object and serializes it.
</p>
<p>
It provides examples of the following:
</p>
<ul class='spaced-list'>
<li>
Using the {@link org.apache.juneau.rest.annotation.RestResource#properties() @RestResource.properties()}
annotation to set serializer properties.
<li>
Using the {@link org.apache.juneau.rest.annotation.RestResource#beanFilters() @RestResource.beanFilters()}
and {@link org.apache.juneau.rest.annotation.RestResource#pojoSwaps() @RestResource.pojoSwaps()}
annotations to set serializer transforms.
<li>
Simply passing in an {@link org.apache.juneau.ObjectMap} parameter on the Java method.
<br>This object map contains the modifiable properties on the request.
</ul>
<p>
The class is shown below:
</p>
<h5 class='figure'>RequestEchoResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample REST resource for echoing HttpServletRequests back to the browser
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/echo"</js>,
messages=<js>"nls/RequestEchoResource"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
),
properties={
<ja>@Property</ja>(name=<jsf>SERIALIZER_maxDepth</jsf>, value=<js>"10"</js>),
<ja>@Property</ja>(name=<jsf>SERIALIZER_detectRecursions</jsf>, value=<js>"true"</js>)
},
beanFilters={
<jc>// Interpret these as their parent classes, not subclasses</jc>
HttpServletRequest.<jk>class</jk>, HttpSession.<jk>class</jk>, ServletContext.<jk>class</jk>,
},
pojoSwaps={
<jc>// Add a special POJO swap for Enumerations</jc>
EnumerationSwap.<jk>class</jk>
}
)
<jk>public class</jk> RequestEchoResource <jk>extends</jk> Resource {
<jd>/** GET request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/*"</js>, converters={Queryable.<jk>class</jk>,Traversable.<jk>class</jk>})
<jk>public</jk> HttpServletRequest doGet(RestRequest req, RestResponse res, ObjectMap properties) {
<jc>// Set the HtmlDocSerializer title programmatically.</jc>
res.setPageTitle(req.getPathInfo());
<jc>// Just echo the request back as the response.</jc>
<jk>return</jk> req;
}
}
</p>
<p>
Again, there's a lot going on here that's new that requires some explanation.
The <l>HttpServletRequest</l> object is not a tree-shaped POJO model.
Instead, it contains lots of loops that can cause stack overflow errors if you were to try
to serialize it as-is.
Also, you want to look only at the properties defined on the <l>HttpServletRequest</l> class,
not implementation-specific (i.e. WAS or Jetty) fields which can get messy.
</p>
<p>
The {@link org.apache.juneau.rest.annotation.RestResource#properties() @RestResource.properties()},
{@link org.apache.juneau.rest.annotation.RestResource#beanFilters() @RestResopurce.beanFilters()}, and
{@link org.apache.juneau.rest.annotation.RestResource#pojoSwaps() @RestResopurce.pojoSwaps()}
annotations are used to set behavior properties on the resource's underlying bean context, serializers,
and parsers.
You're using them here to modify the behavior of serialization for all content types.
The annotations are functionally equivalent to using the {@link org.apache.juneau.rest.RestContextBuilder} class,
as follows:
</p>
<h5 class='figure'>Hypothetical RequestEchoResource.createSerializers() method</h5>
<p class='bcode'>
<jd>/** Override the default rest serializers to add some transforms through an INIT hook*/</jd>
<ja>@RestHook</ja>(<jsf>INIT</jsf>)
<jk>public void</jk> init(RestContextBuilder builder) throws Exception {
<jc>// Add bean filters for the HttpServletRequest, HttpSession, and ServletContext objects
// so that you don't show vendor-specific properties on subclasses.
// Add Enumeration POJO swap to be able to render the contents of Enumeration properties.
// The max depth and detect recursion options prevent any possible runaway serializations.
// This shouldn't happen, but future JEE APIs may introduce deep hierarchies or loops.</jc>
builder
.beanFilters(HttpServletRequest.<jk>class</jk>, HttpSession.<jk>class</jk>, ServletContext.<jk>class</jk>)
.pojoSwaps(EnumerationSwap.<jk>class</jk>)
.setProperty(<jsf>SERIALIZER_maxDepth</jsf>, 10)
.setProperty(<jsf>SERIALIZER_detectRecursions</jsf>, <jk>true</jk>)
.pageLinks(<js>"{...}"</js>);
}
</p>
<p>
Note how the annotations generally require fewer lines of code.
</p>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src="doc-files/Samples.RequestEchoResource.1.png">
<p>
This gives you an idea of what kinds of POJO models can be serialized, since you are serializing a regular
old <l>HttpServletRequest</l> object.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.6 - AddressBookResource</h4>
<div class='topic'>
<p>
The <l>AddressBookResource</l> class is a proof-of-concept class that shows a true RESTful API using the
Juneau REST toolkit.
It provides examples of the following:
</p>
<ul class='spaced-list'>
<li>
How to create RESTful interfaces using only POJOs.
<li>
How to use the {@link org.apache.juneau.xml.annotation.Xml @Xml} and
{@link org.apache.juneau.xml.annotation.XmlSchema @XmlSchema} annotations to provide XML namespaces
and alter how beans are handled by the XML serializer.
<li>
How to use the {@link org.apache.juneau.jena.annotation.Rdf @Rdf} and
{@link org.apache.juneau.xml.annotation.XmlSchema @RdfSchema} annotations to provide XML namespaces
and alter how beans are handled by the Jena serializers.
<li>
How to use the {@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotation
to alter how bean properties are handled by the serializers.
<li>
How to use the {@link org.apache.juneau.rest.annotation.RestMethod#name() RestMethod.name()} annotation
to create overloaded methods beyond the standard GET/PUT/POST/DELETE.
<li>
How to augment data in the OPTIONS page.
<li>
How to use the {@link org.apache.juneau.rest.client.RestClient} API to interact with the REST resource
using the same POJOs used to create the server-side API.
<li>
How to interact with the REST resource using only a browser.
<li>
Using the {@link org.apache.juneau.rest.converters.Traversable} converter to drill down into POJO models.
<li>
Using the {@link org.apache.juneau.rest.converters.Queryable} converter to provide search/view/sort
functionality against POJOs.
<li>
Using the {@link org.apache.juneau.rest.converters.Introspectable} converter to invoke methods on POJOs.
<li>
Using proxy interfaces.
</ul>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.AddressBookResource.1.png'>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.Classes"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.1 - Classes</h4>
<div class='topic'>
<p>
The code is straightforward, consisting of the following classes:
</p>
<ul class='spaced-list'>
<li>
<l>package-info.java</l> - Used to define XML namespaces for POJOs in this package.
<li>
<l>IAddressBook</l> - An interface describing the address book.
<li>
<l>AddressBook</l> - A data structure consisting of a list of <code>Persons</code>.
<li>
<l>Person, Address</l> - In-memory representations of people and addresses.
<li>
<l>CreatePerson, CreateAddress</l> - POJOs for creating and updating people and address through the
REST interface.
<li>
<l>AddressBookResource</l> - The REST resource class.
</ul>
<ul class='doctree'>
<li class='info'>
For the sake of brevity, bean properties are defined as public fields instead of the normal
getters/setters.
Also, the examples are not the most efficient design and are not thread safe.
</ul>
<p>
The <l>package-info.java</l> file is used to define XML and RDF namespaces on beans and properties in
this package.
Here you define a default XML and RDF namespaces and URL mappings for namespace short-names used
throughout this package.
It should be noted that these features are entirely optional, and there are often several ways of
defining these namespaces.
</p>
<h5 class='figure'>package-info.java</h5>
<p class='bcode'>
<jc>// XML and RDF namespaces used in this package</jc>
<ja>@Xml</ja>(ns=<js>"ab"</js>,
namespaces={
<ja>@XmlNs</ja>(name=<js>"ab"</js>, uri=<js>"http://www.apache.org/addressBook/"</js>),
<ja>@XmlNs</ja>(name=<js>"per"</js>, uri=<js>"http://www.apache.org/person/"</js>),
<ja>@XmlNs</ja>(name=<js>"addr"</js>, uri=<js>"http://www.apache.org/address/"</js>),
<ja>@XmlNs</ja>(name=<js>"mail"</js>, uri=<js>"http://www.apache.org/mail/"</js>)
}
)
<ja>@Rdf</ja>(ns=<js>"ab"</js>,
namespaces={
<ja>@RdfNs</ja>(name=<js>"ab"</js>, uri=<js>"http://www.apache.org/addressBook/"</js>),
<ja>@RdfNs</ja>(name=<js>"per"</js>, uri=<js>"http://www.apache.org/person/"</js>),
<ja>@RdfNs</ja>(name=<js>"addr"</js>, uri=<js>"http://www.apache.org/address/"</js>),
<ja>@RdfNs</ja>(name=<js>"mail"</js>, uri=<js>"http://www.apache.org/mail/"</js>)
}
)
<jk>package</jk> org.apache.juneau.examples.addressBook;
<jk>import</jk> org.apache.juneau.xml.annotation.*;
</p>
<p>
Our address book uses the following interface:
</p>
<h5 class='figure'>IAddressBook.java</h5>
<p class='bcode'>
<jd>/**
* Interface used to help illustrate proxy interfaces.
* See {<ja>@link</ja> SampleRemoteableServlet}.
*/</jd>
<jk>public interface</jk> IAddressBook {
<jd>/** Return all people in the address book */</jd>
List&lt;Person&gt; getPeople();
<jd>/** Return all addresses in the address book */</jd>
List&lt;Address&gt; getAddresses();
<jd>/** Create a person in this address book */</jd>
Person createPerson(CreatePerson cp) <jk>throws</jk> Exception;
<jd>/** Find a person by id */</jd>
Person findPerson(<jk>int</jk> id);
<jd>/** Find an address by id */</jd>
Address findAddress(<jk>int</jk> id);
<jd>/** Find a person by address id */</jd>
Person findPersonWithAddress(<jk>int</jk> id);
<jd>/** Remove a person by id */</jd>
Person removePerson(<jk>int</jk> id);
}
</p>
<h5 class='topic'>Notes</h5>
<ul class='spaced-list'>
<li>
You interface an interface for our address book so that you can later
use it to demonstrate the proxy interface support.
</ul>
<p>
The <l>AddressBook</l> class is our address book.
It maintains a list of <l>Person</l> objects with some additional convenience methods:
</p>
<h5 class='figure'>AddressBook.java</h5>
<p class='bcode'>
<jd>/** Address book bean */</jd>
<jk>public class</jk> AddressBook <jk>extends</jk> LinkedList&lt;Person&gt; <jk>implements</jk> IAddressBook {
<jc>// The URL of this resource</jc>
<jk>private</jk> URI <jf>uri</jf>;
<jd>/** Bean constructor - Needed for instantiating on client side */</jd>
<jk>public</jk> AddressBook () {}
<jd>/** Normal constructor - Needed for instantiating on server side */</jd>
<jk>public</jk> AddressBook (URI uri) {...}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> List&lt;Person&gt; getPeople() {
<jk>return</jk> <jk>this</jk>;
}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> Person createPerson(CreatePerson cp) <jk>throws</jk> Exception {
Person p = <jk>new</jk> Person(uri, cp);
add(p);
<jk>return</jk> p;
}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> Person findPerson(<jk>int</jk> id) {
<jk>for</jk> (Person p : <jk>this</jk>)
<jk>if</jk> (p.<jf>id</jf> == id)
<jk>return</jk> p;
<jk>return null</jk>;
}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> Address findAddress(<jk>int</jk> id) {
<jk>for</jk> (Person p : <jk>this</jk>)
<jk>for</jk> (Address a : p.<jf>addresses</jf>)
<jk>if</jk> (a.<jf>id</jf> == id)
<jk>return</jk> a;
<jk>return null</jk>;
}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> Person findPersonWithAddress(<jk>int</jk> id) {
<jk>for</jk> (Person p : <jk>this</jk>)
<jk>for</jk> (Address a : p.<jf>addresses</jf>)
<jk>if</jk> (a.<jf>id</jf> == id)
<jk>return</jk> p;
<jk>return null</jk>;
}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> List&lt;Address&gt; getAddresses() {
Set&lt;Address&gt; s = <jk>new</jk> LinkedHashSet&lt;Address&gt;();
<jk>for</jk> (Person p : <jk>this</jk>)
<jk>for</jk> (Address a : p.<jf>addresses</jf>)
s.add(a);
<jk>return new</jk> ArrayList&lt;Address&gt;(s);
}
<ja>@Override</ja> <jc>/* IAddressBook */</jc>
<jk>public</jk> Person removePerson(<jk>int</jk> id) {
Person p = findPerson(id);
<jk>if</jk> (p != <jk>null</jk>)
remove(p);
<jk>return</jk> p;
}
<jd>/** Utility method */</jd>
<jk>public static</jk> Calendar toCalendar(String birthDate) <jk>throws</jk> Exception {
Calendar c = <jk>new</jk> GregorianCalendar();
c.setTime(DateFormat.<jsm>getDateInstance</jsm>(DateFormat.<jsf>MEDIUM</jsf>,
Locale.<jsf>US</jsf>).parse(birthDate));
<jk>return</jk> c;
}
}
</p>
<h5 class='topic'>Notes</h5>
<ul class='spaced-list'>
<li>
The <code><ja>@Xml</ja>(elementName=<js>"addressBook"</js>)</code> annotation tells the toolkit that
when serialized as XML, the element name is <xt>&lt;addressBook&gt;</xt>.
Without this annotation, the element would revert to the generalized <xt>&lt;array&gt;</xt> tag.
<li>
The separate constructors are implementation specific and are needed because you're going to be
using this class in two ways, since you'll be demonstrating the client code as well as the server
code, and it eliminates having to define separate client-side and server-side POJOs:
<ol>
<li>The normal constructor is used to programmatically create this object in the REST servlet code.
<li>The no-arg constructor is used by the Juneau parsers to construct this object in our client
side code.
</ol>
</li>
</ul>
<p>
The <l>Person</l> bean is defined as follows:
</p>
<h5 class='figure'>Person.java</h5>
<p class='bcode'>
<jd>/** Person bean */</jd>
<ja>@Xml</ja>(ns=<js>"per"</js>)
<ja>@Rdf</ja>(prefix=<js>"per"</js>)
<ja>@Bean</ja>(typeName=<js>"person"</js>)
<jk>public class</jk> Person {
<jk>private static int</jk> <jsf>nextPersonId</jsf> = 1;
<jc>// Bean properties.</jc>
<ja>@Rdf</ja>(beanUri=<jk>true</jk>) public URI <jf>uri</jf>;
<jk>public</jk> URI <jf>addressBookUri</jf>;
<jk>public</jk> String <jf>id</jf>;
<jk>public</jk> String <jf>name</jf>;
<ja>@BeanProperty</ja>(swap=CalendarSwap.Medium.<jk>class</jk>) <jk>public</jk> Calendar <jf>birthDate</jf>;
<jk>public</jk> LinkedList&lt;Address&gt; <jf>addresses</jf> = new LinkedList&lt;Address&gt;();
<jd>/** Bean constructor - Needed for instantiating on server side */</jd>
<jk>public</jk> Person() {}
<jd>/** Normal constructor - Needed for instantiating on client side */</jd>
<jk>public</jk> Person(URI addressBookUri, CreatePerson cp) <jk>throws</jk> Exception {
<jk>this</jk>.<jf>id</jf> = <jsf>nextPersonId</jsf>++;
<jk>this</jk>.<jf>addressBookUri</jf> = addressBookUri;
<jk>if</jk> (addressBookUri != <jk>null</jk>)
<jk>this</jk>.<jf>uri</jf> = addressBookUri.resolve(<js>"people/"</js> + <jf>id</jf>);
<jk>this</jk>.<jf>name</jf> = cp.<jf>name</jf>;
<jk>this</jk>.<jf>birthDate</jf> = cp.<jf>birthDate</jf>;
<jk>for</jk> (CreateAddress ca : cp.<jf>addresses</jf>)
<jk>this</jk>.<jf>addresses</jf>.add(<jk>new</jk> Address(addressBookUri, <jf>uri</jf>, ca));
}
<jd>/** Extra read-only bean property */</jd>
<jk>public int</jk> getAge() {
<jk>return new</jk> GregorianCalendar().get(Calendar.<jsf>YEAR</jsf>) - birthDate.get(Calendar.<jsf>YEAR</jsf>);
}
<jd>/** Convenience method - Add an address for this person */</jd>
<jk>public</jk> Address createAddress(CreateAddress ca) <jk>throws</jk> Exception {
Address a = <jk>new</jk> Address(<jf>addressBookUri</jf>, <jf>uri</jf>, ca);
<jf>addresses</jf>.add(a);
<jk>return</jk> a;
}
<jd>/** Extra method (for method invocation example) */</jd>
<jk>public</jk> String sayHello(String toPerson, <jk>int</jk> age) {
<jk>return</jk> <jf>name</jf> + <js>" says hello to "</js> + toPerson + <js>" who is "</js>
+ age + <js>" years old"</js>;
}
}
</p>
<h5 class='topic'>Notes</h5>
<ul class='spaced-list'>
<li>
The <l>ns="per"</l> annotations override the default <l>"ab"</l> namespace defined on the package.
It applies to this class and all properties of this class.
<li>
The <code><ja>@Rdf</ja>(beanUri=<jk>true</jk>)</code> annotation identifies the <l>uri</l> property
as the resource URI for this resource.
This property has special meaning for the RDF serializer.
The RDF serializer uses this property for the value of the <l>rdf:resource</l> attribute.
<li>
The <code><ja>@BeanProperty</ja>(swap=CalendarSwap.Medium.<jk>class</jk>)</code> annotation causes
the date field to be serialized in the format <l>"MM dd, yyyy"</l>.
This could have also been specified globally on the resource level through the
{@link org.apache.juneau.rest.annotation.RestResource#properties} annotation.
</ul>
<p>
The <l>Address</l> bean is defined as follows:
</p>
<h5 class='figure'>Address.java</h5>
<p class='bcode'>
<jd>/**
* Address bean
*/</jd>
<ja>@Xml</ja>(prefix=<js>"addr"</js>)
<ja>@Rdf</ja>(prefix=<js>"addr"</js>)
<ja>@Bean</ja>(typeName=<js>"address"</js>)
<jk>public class</jk> Address {
<jk>private static int</jk> <jsf>nextAddressId</jsf> = 1;
<jc>// Bean properties</jc>
<ja>@Rdf</ja>(beanUri=<jk>true</jk>) <jk>public</jk> URI <jf>uri</jf>;
<jk>public</jk> URI <jf>personUri</jf>;
<jk>public int</jk> <jf>id</jf>;
<ja>@Xml</ja>(prefix=<js>"mail"</js>) <ja>@Rdf</ja>(prefix=<js>"mail"</js>)
<jk>public</jk> String <jf>street</jf>, <jf>city</jf>, <jf>state</jf>;
<ja>@Xml</ja>(prefix=<js>"mail"</js>) <ja>@Rdf</ja>(prefix=<js>"mail"</js>)
<jk>public int</jk> <jf>zip</jf>;
<jk>public boolean</jk> <jf>isCurrent</jf>;
<jd>/** Bean constructor - Needed for instantiating on client side */</jd>
<jk>public</jk> Address() {}
<jd>/** Normal constructor - Needed for instantiating on server side */</jd>
<jk>public</jk> Address(URI addressBookUri, URI personUri, CreateAddress ca) <jk>throws</jk> Exception {
<jk>this</jk>.<jf>id</jf> = <jsf>nextAddressId</jsf>++;
<jk>if</jk> (addressBookUri != <jk>null</jk>)
<jk>this</jk>.<jf>uri</jf> = addressBookUri.resolve(<js>"addresses/"</js> + <jf>id</jf>);
<jk>this</jk>.<jf>personUri</jf> = personUri</jf>;
<jk>this</jk>.<jf>street</jf> = ca.<jf>street</jf>;
<jk>this</jk>.<jf>city</jf> = ca.<jf>city</jf>;
<jk>this</jk>.<jf>state</jf> = ca.<jf>state</jf>;
<jk>this</jk>.<jf>zip</jf> = ca.<jf>zip</jf>;
<jk>this</jk>.<jf>isCurrent</jf> = ca.<jf>isCurrent</jf>;
}
}
</p>
<h5 class='topic'>Notes</h5>
<ul class='spaced-list'>
<li>
This class shows how the namespace can be overridden at the property level through the
<code><ja>@Xml</ja>(ns=<js>"mail"</js>)</code> annotation.
</ul>
<p>
The <l>CreatePerson</l> bean is used as the input data for creating a person.
</p>
<h5 class='figure'>CreatePerson.java</h5>
<p class='bcode'>
<jd>/** Bean for creating a new person */</jd>
<ja>@Xml</ja>(ns=<js>"per"</js>)
<ja>@Rdf</ja>(ns=<js>"addr"</js>)
<ja>@Bean</ja>(typeName=<js>"person"</js>)
<jk>public class</jk> CreatePerson {
<jc>// Bean properties</jc>
<jk>public</jk> String <jf>name</jf>;
<ja>@BeanProperty(</ja>swap=CalendarSwap.Medium.<jk>class</jk>) <jk>public</jk> Calendar <jf>birthDate</jf>;
<jk>public</jk> LinkedList&lt;CreateAddress&gt; <jf>addresses</jf>;
<jd>/** Bean constructor - Needed for instantiating on server side */</jd>
<jk>public</jk> CreatePerson() {}
<jd>/** Normal constructor - Needed for instantiating on client side */</jd>
<jk>public</jk> CreatePerson(String name, Calendar birthDate, CreateAddress...addresses) {...}
}
</p>
<p>
The <l>CreateAddress</l> bean is used as the input data for creating an address.
</p>
<h5 class='figure'>CreateAddress.java</h5>
<p class='bcode'>
<jd>/** Bean for creating a new address */</jd>
<ja>@Xml</ja>(ns=<js>"addr"</js>)
<ja>@Rdf</ja>(ns=<js>"addr"</js>)
<ja>@Bean</ja>(typeName=<js>"address"</js>)
<jk>public class</jk> CreateAddress {
<jc>// Bean properties</jc>
<ja>@Xml</ja>(ns=<js>"mail"</js>) <ja>@Rdf</ja>(ns=<js>"mail"</js>)
<jk>public</jk> String <jf>street</jf>, <jf>city</jf>, <jf>state</jf>;
<ja>@Xml</ja>(ns=<js>"mail"</js>) <ja>@Rdf</ja>(ns=<js>"mail"</js>)
<jk>public int</jk> <jf>zip</jf>;
<jk>public boolean</jk> <jf>isCurrent</jf>;
<jd>/** Bean constructor -Needed for instantiating on server side */</jd>
<jk>public</jk> CreateAddress() {}
<jd>/** Normal constructor - Needed for instantiating on client side */</jd>
<jk>public</jk> CreateAddress(String street, String city, String state, <jk>int</jk> zip,
<jk>boolean</jk> isCurrent) {...}
}
</p>
<p>
The <l>AddressBookResource</l> class is our REST resource class.
</p>
<h5 class='figure'>AddressBookResource.java</h5>
<p class='bcode'>
<jd>/**
* Proof-of-concept resource that shows off the capabilities of working with POJO resources.
* Consists of an in-memory address book repository.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/addressBook"</js>,
messages=<js>"nls/AddressBookResource"</js>,
<jc>// Links on the HTML rendition page.
// "request:/..." URIs are relative to the request URI.
// "servlet:/..." URIs are relative to the servlet URI.
// "$C{...}" variables are pulled from the config file.</jc>
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>,
<js>"source: $C{Source/gitHub}/org/apache/juneau/examples/rest/addressbook/AddressBookResource.java"</js>
}
),
<jc>// Allow INIT as a method parameter.</jc>
allowedMethodParams=<js>"*"</js>,
<jc>// Properties that get applied to all serializers and parsers.</jc>
properties={
<jc>// Use single quotes.</jc>
<ja>@Property</ja>(name=<jsf>SERIALIZER_quoteChar</jsf>, value=<js>"'"</js>),
<jc>// Make RDF/XML readable.</jc>
<ja>@Property</ja>(name=<jsf>RDF_rdfxml_tab</jsf>, value=<js>"5"</js>),
<jc>// Make RDF parsable by adding a root node.</jc>
<ja>@Property</ja>(name=<jsf>RDF_addRootProperty</jsf>, value=<js>"true"</js>),
<jc>// Make URIs absolute so that we can easily reference them on the client side.</jc>
<ja>@Property</ja>(name=<jsf>SERIALIZER_uriResolution</jsf>, value=<js>"ABSOLUTE"</js>)
<jc>// Make the anchor text on URLs be just the path relative to the servlet.</jc>
<ja>@Property</ja>(name=<jsf>HTML_uriAnchorText</jsf>, value=<js>"SERVLET_RELATIVE"</js>)
},
<jc>// Our stylesheet for the HTML rendition.</jc>
stylesheet=<js>"styles/devops.css"</js>,
<jc>// Support GZIP encoding on Accept-Encoding header.</jc>
encoders=GzipEncoder.<jk>class</jk>,
<jc>// Swagger info.</jc>
contact=<js>"{name:'John Smith',email:'john@smith.com'}"</js>,
license=<js>"{name:'Apache 2.0',url:'http://www.apache.org/licenses/LICENSE-2.0.html'}"</js>,
version=<js>"2.0"</js>,
termsOfService=<js>"You're on your own."</js>,
tags=<js>"[{name:'Java',description:'Java utility',externalDocs:{description:'Home page',
url:'http://juneau.apache.org'}}]"</js>,
externalDocs=<js>"{description:'Home page',url:'http://juneau.apache.org'}"</js>
)
<jk>public class</jk> AddressBookResource <jk>extends</jk> ResourceJena {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jc>// The in-memory address book</jc>
<jk>private</jk> AddressBook <jf>addressBook</jf>;
<ja>@Override</ja> /* Servlet */
<jk>public void</jk> init() {
<jk>try</jk> {
<jc>// Create the address book</jc>
<jf>addressBook</jf> = <jk>new</jk> AddressBook(java.net.URI.create(<js>"servlet:/"</js>));
<jc>// Add some people to our address book by default</jc>
<jf>addressBook</jf>.createPerson(
<jk>new</jk> CreatePerson(
<js>"Barack Obama"</js>,
<jsm>toCalendar</jsm>(<js>"Aug 4, 1961"</js>),
<jk>new</jk> CreateAddress(<js>"1600 Pennsylvania Ave"</js>, <js>"Washington"</js>,
<js>"DC"</js>, 20500, <jk>true</jk>),
<jk>new</jk> CreateAddress(<js>"5046 S Greenwood Ave"</js>, <js>"Chicago"</js>,
<js>"IL"</js>, 60615, <jk>false</jk>)
)
);
<jf>addressBook</jf>.createPerson(
<jk>new</jk> CreatePerson(
<js>"George Walker Bush"</js>,
<jsm>toCalendar</jsm>(<js>"Jul 6, 1946"</js>),
<jk>new</jk> CreateAddress(<js>"43 Prairie Chapel Rd"</js>, <js>"Crawford"</js>,
<js>"TX"</js>, 76638, <jk>true</jk>),
<jk>new</jk> CreateAddress(<js>"1600 Pennsylvania Ave"</js>, <js>"Washington"</js>,
<js>"DC"</js>, 20500, <jk>false</jk>)
)
);
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RuntimeException(e);
}
}
<jd>/**
* [GET /]
* Get root page.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>,
converters=Queryable.<jk>class</jk>
)
<jk>public</jk> Link[] getRoot() <jk>throws</jk> Exception {
<jk>return new</jk> Link[] {
<jk>new</jk> Link(<js>"people"</js>, <js>"people"</js>),
<jk>new</jk> Link(<js>"addresses"</js>, <js>"addresses"</js>)
};
}
<jd>/**
* [GET /people/*]
* Get all people in the address book.
* Traversable transforming enabled to allow nodes in returned POJO tree to be addressed.
* Introspectable transforming enabled to allow public methods on the returned object to be invoked.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/people/*"</js>,
converters={Traversable.<jk>class</jk>,Queryable.<jk>class</jk>,Introspectable.<jk>class</jk>}
)
<jk>public</jk> AddressBook getAllPeople() <jk>throws</jk> Exception {
<jk>return</jk> <jf>addressBook</jf>;
}
<jd>/**
* [GET /people/{id}/*]
* Get a single person by ID.
* Traversable transforming enabled to allow nodes in returned POJO tree to be addressed.
* Introspectable transforming enabled to allow public methods on the returned object to be invoked.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/people/{id}/*"</js>,
converters={Traversable.<jk>class</jk>,Queryable.<jk>class</jk>,Introspectable.<jk>class</jk>}
)
<jk>public</jk> Person getPerson(<ja>@Path</ja> <jk>int</jk> id) <jk>throws</jk> Exception {
<jk>return</jk> findPerson(id);
}
<jd>/**
* [GET /addresses/*]
* Get all addresses in the address book.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/addresses/*"</js>,
converters={Traversable.<jk>class</jk>,Queryable.<jk>class</jk>}
)
<jk>public</jk> List&lt;Address&gt; getAllAddresses() <jk>throws</jk> Exception {
<jk>return</jk> <jf>addressBook</jf>.getAddresses();
}
<jd>/**
* [GET /addresses/{id}/*]
* Get a single address by ID.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/addresses/{id}/*"</js>,
converters={Traversable.<jk>class</jk>,Queryable.<jk>class</jk>}
)
<jk>public</jk> Address getAddress(<ja>@Path</ja> <jk>int</jk> id) <jk>throws</jk> Exception {
<jk>return</jk> findAddress(id);
}
<jd>/**
* [POST /people]
* Create a new Person bean.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/people"</js>,
guards=AdminGuard.<jk>class</jk>
)
<jk>public</jk> Redirect createPerson(<ja>@Body</ja> CreatePerson cp) <jk>throws</jk> Exception {
Person p = <jf>addressBook</jf>.createPerson(cp);
<jk>return new</jk> Redirect(<js>"people/{0}"</js>, p.id);
}
<jd>/**
* [POST /people/{id}/addresses]
* Create a new Address bean.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/people/{id}/addresses"</js>,
guards=AdminGuard.<jk>class</jk>
)
<jk>public</jk> Redirect createAddress(<ja>@Path</ja> <jk>int</jk> id, <ja>@Body</ja> CreateAddress ca) <jk>throws</jk> Exception {
Person p = findPerson(id);
Address a = p.createAddress(ca);
<jk>return new</jk> Redirect(<js>"addresses/{0}"</js>, a.id);
}
<jd>/**
* [DELETE /people/{id}]
* Delete a Person bean.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>DELETE</jsf>, path=<js>"/people/{id}"</js>,
guards=AdminGuard.<jk>class</jk>,
)
<jk>public</jk> String deletePerson(<ja>@Path</ja> <jk>int</jk> id) <jk>throws</jk> Exception {
<jf>addressBook</jf>.removePerson(id);
<jk>return</jk> <js>"DELETE successful"</js>;
}
<jd>/**
* [DELETE /addresses/{id}]
* Delete an Address bean.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>DELETE</jsf>, path=<js>"/addresses/{id}"</js>,
guards=AdminGuard.<jk>class</jk>
)
<jk>public</jk> String deleteAddress(<ja>@Path</ja> <jk>int</jk> addressId) <jk>throws</jk> Exception {
Person p = <jf>addressBook</jf>.findPersonWithAddress(addressId);
<jk>if</jk> (p == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Person not found"</js>);
Address a = findAddress(addressId);
p.addresses.remove(a);
<jk>return</jk> <js>"DELETE successful"</js>;
}
<jd>/**
* [PUT /people/{id}/*]
* Change property on Person bean.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/people/{id}/*"</js>,
guards=AdminGuard.<jk>class</jk>
)
<jk>public</jk> String updatePerson(RestRequest req, <ja>@Path</ja> <jk>int</jk> id, <ja>@PathRemainder</ja>
String remainder) <jk>throws</jk> Exception {
<jk>try</jk> {
Person p = findPerson(id);
PojoRest r = <jk>new</jk> PojoRest(p);
ClassMeta&lt;?&gt; cm = r.getClassMeta(remainder);
Object in = req.getBody().asType(cm);
r.put(remainder, in);
<jk>return</jk> <js>"PUT successful"</js>;
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RestException(<jsf>SC_BAD_REQUEST</jsf>, <js>"PUT unsuccessful"</js>).initCause(e);
}
}
<jd>/**
* [PUT /addresses/{id}/*]
* Change property on Address bean.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/addresses/{id}/*"</js>,
guards=AdminGuard.<jk>class</jk>
)
<jk>public</jk> String updateAddress(RestRequest req, <ja>@Path</ja> <jk>int</jk> id,
<ja>@PathRemainder</ja> String remainder) <jk>throws</jk> Exception {
<jk>try</jk> {
Address a = findAddress(id);
PojoRest r = <jk>new</jk> PojoRest(a);
ClassMeta&lt;?&gt; cm = r.getClassMeta(remainder);
Object in = req.getBody().asType(cm);
r.put(remainder, in);
<jk>return</jk> <js>"PUT successful"</js>;
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RestException(<jsf>SC_BAD_REQUEST</jsf>, <js>"PUT unsuccessful"</js>).initCause(e);
}
}
<jd>/**
* [INIT /]
* Reinitialize this resource.
*/</jd>
<ja>@RestMethod</ja>(name=<js>"INIT"</js>, path=<js>"/"</js>,
guards=AdminGuard.<jk>class</jk>
)
<jk>public</jk> String doInit() <jk>throws</jk> Exception {
init();
<jk>return</jk> <js>"OK"</js>;
}
<jd>/**
* [GET /cognos]
* Get data in Cognos/XML format
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/cognos"</js>)
<jk>public</jk> DataSet getCognosData() <jk>throws</jk> Exception {
<jc>// The Cognos metadata</jc>
Column[] items = {
<jk>new</jk> Column(<js>"name"</js>, <js>"xs:String"</js>, 255),
<jk>new</jk> Column(<js>"age"</js>, <js>"xs:int"</js>),
<jk>new</jk> Column(<js>"numAddresses"</js>, <js>"xs:int"</js>)
.addPojoSwap(
<jk>new</jk> PojoSwap&lt;Person,Integer&gt;() {
<ja>@Override</ja> /* PojoSwap */
<jk>public</jk> Integer swap(BeanSession session, Person p) {
<jk>return</jk> p.addresses.size();
}
}
)
};
<jk>return new</jk> DataSet(items, <jf>addressBook</jf>, <jk>this</jk>.getBeanContext());
}
<jd>/**
* [OPTIONS /*]
* View resource options
*/</jd>
<ja>@Override</ja> <jc>/* RestServletDefault */</jc>
<ja>@RestMethod</ja>(name=<jsf>OPTIONS</jsf>, path=<js>"/*"</js>)
<jk>public</jk> Swagger getOptions(RestRequest req) {
<jk>return</jk> req.getSwagger();
}
<jd>/** Convenience method - Find a person by ID */</jd>
<jk>private</jk> Person findPerson(<jk>int</jk> id) <jk>throws</jk> RestException {
Person p = <jf>addressBook</jf>.findPerson(id);
<jk>if</jk> (p == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Person not found"</js>);
<jk>return</jk> p;
}
<jd>/** Convenience method - Find an address by ID */</jd>
<jk>private</jk> Address findAddress(<jk>int</jk> id) <jk>throws</jk> RestException {
Address a = <jf>addressBook</jf>.findAddress(id);
<jk>if</jk> (a == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Address not found"</js>);
<jk>return</jk> a;
}
}
</p>
<h5 class='topic'>Notes</h5>
<ul class='spaced-list'>
<li>
The <l>@RestResource.messages()</l> annotation identifies
<l>org/apache/juneau/samples/addressbook/nls/AddressBookResource.properties</l> as the resource
bundle for localized message for this class.
<li>
You are setting <l>XML_enableNamespaces</l> to <l>true</l> to enable XML namespaces.
By default, XML namespace support is disabled per
{@link org.apache.juneau.xml.XmlSerializer#XML_enableNamespaces}, so you have to explicitly
enable it on our serializers.
<li>
The <l>XML_autoDetectNamespaces</l> setting is needed to get the XML serializer to add <l>xmlns</l>
attributes to the root elements.
This causes the XML serializer to scan the POJO objects for namespaces in order to populate the
root element.
There are other ways to do this, such as explicitly specifying the <l>XML_defaultNamespaceUris</l>
setting at either the resource or method level, which might be preferred in high-performance
environments.
However, <l>XML_autoDetectNamespaces</l> produces the simplest code for our example.
<li>
The <l>updatePerson()</l> and <l>updateAddress()</l> methods use a guard to only allow
administrators access.
For the sample code, the guard does nothing. It's up to the implementer to decide how to restrict
access.
<li>
The <l>updatePerson()</l> and <l>updateAddress()</l> methods use the
{@link org.apache.juneau.utils.PojoRest} class
to locate and update individual nodes in a POJO tree using the path remainder on the request.
<li>
The <l>doInit()</l> method shows an example of an overloaded method using the
<l>@RestMethod(name=<jsf>INIT</jsf>)</l> annotation.
<li>
The <l>getOptions()</l> method shows the default OPTIONS page augmented with some additional
information.
</ul>
<p>
The OPTIONS page uses the servlet resource bundle to specify the labels so that they're globalizable.
</p>
<h5 class='figure'>AddressBookResource.properties</h5>
<p class='bcode'>
<ck>title</ck> = <cv>AddressBook sample resource</cv>
<ck>description</ck> = <cv>Proof-of-concept resource that shows off the capabilities of working with POJO resources</cv>
<ck>getRoot.summary</ck> = <cv>Get root page</cv>
<ck>getRoot.description</ck> = <cv>Jumping off page for top-level Person and Address beans.</cv>
<ck>doInit.summary</ck> = <cv>Reinitialize this resource</cv>
<ck>doInit.description</ck> = <cv>Resets the address book to the original contents.</cv>
<ck>doInit.res.200.description</ck> = <cv>Returns the string "OK"</cv>
<ck>getAllPeople.summary</ck> = <cv>Get all people in the address book</cv>
<ck>getAllPeople.res.200.description</ck> = <cv>Returns a serialized List&lt;Person&gt;</cv>
<ck>getAllPeople.res.200.examples</ck> = <cv>{'text/json':"[\n\t{\n\t\turi:'http://hostname/addressBook/person/1',\n\t\taddressBookUri:'http://localhost/addressBook',\n\t\tid:1,\n\t\tname:'John Smith',\n\t\tbirthDate:'Jan 1, 2000',\n\t\taddresses:[\n\t\t\t{\n\t\t\t\turi:'http://localhost/addressBook/addresses/1',\n\t\t\t\tpersonUri:'http://localhost/addressBook/people/1',\n\t\t\t\tid:1,\n\t\t\t\tstreet:'101 Main St',\n\t\t\t\tcity:'Anywhere',\n\t\t\t\tstate:'NY',\n\t\t\t\tzip:12345,\n\t\t\t\tisCurrent:true\n\t\t\t}\n\t\t]\n\t}\n]"}</cv>
<ck>getPerson.summary</ck> = <cv>Get a single person by ID</cv>
<ck>getPerson.req.path.id.description</ck> = <cv>Person ID</cv>
<ck>getPerson.req.path.id.type</ck> = <cv>integer</cv>
<ck>getPerson.res.200.description</ck> = <cv>Returns a serialized Person bean</cv>
<ck>getPerson.res.200.examples</ck> = <cv>{'text/json':"{\n\turi:'http://hostname/addressBook/person/1',\n\taddressBookUri:'http://localhost/addressBook',\n\tid:1,\n\tname:'John Smith',\n\tbirthDate:'Jan 1, 2000',\n\taddresses:[\n\t\t{\n\t\t\turi:'http://localhost/addressBook/addresses/1',\n\t\t\tpersonUri:'http://localhost/addressBook/people/1',\n\t\t\tid:1,\n\t\t\tstreet:'101 Main St',\n\t\t\tcity:'Anywhere',\n\t\t\tstate:'NY',\n\t\t\tzip:12345,\n\t\t\tisCurrent:true\n\t\t}\n\t]\n\}"}</cv>
<ck>getPerson.res.404.description</ck> = <cv>Person ID not found</cv>
<ck>getAllAddresses.summary</ck> = <cv>Get all addresses in the address book</cv>
<ck>getAllAddresses.res.200.description</ck> = <cv>Returns a serialized List&lt;Address&gt;</cv>
<ck>getAllAddresses.res.200.examples</ck> = <cv>{'text/json':"[\n\t{\n\t\turi:'http://localhost/addressBook/addresses/1',\n\t\tpersonUri:'http://localhost/addressBook/people/1',\n\t\tid:1,\n\t\tstreet:'101 Main St',\n\t\tcity:'Anywhere',\n\t\tstate:'NY',\n\t\tzip:12345,\n\t\tisCurrent:true\n\t}\n]"}</cv>
<ck>getAddress.summary</ck> = <cv>Get a single address by ID</cv>
<ck>getAddress.req.path.id.description</ck> = <cv>Address ID</cv>
<ck>getAddress.req.path.id.type</ck> = <cv>integer</cv>
<ck>getAddress.res.200.description</ck> = <cv>Returns a serialized Address bean</cv>
<ck>getAddress.res.200.examples</ck> = <cv>{'text/json':"{\n\turi:'http://localhost/addressBook/addresses/1',\n\tpersonUri:'http://localhost/addressBook/people/1',\n\tid:1,\n\tstreet:'101 Main St',\n\tcity:'Anywhere',\n\tstate:'NY',\n\tzip:12345,\n\tisCurrent:true\n}"}</cv>
<ck>getAddress.res.404.description</ck> = <cv>Address ID not found</cv>
<ck>createPerson.summary</ck> = <cv>Create a new Person bean </cv>
<ck>createPerson.req.body.description</ck> = <cv>Serialized CreatePerson bean</cv>
<ck>createPerson.req.body.schema</ck> = <cv>{example:"{\n\tname:'John Smith',\n\tbirthDate:'Jan 1, 2000',\n\taddresses:[\n\t\t{\n\t\t\tstreet:'101 Main St',\n\t\t\tcity:'Anywhere',\n\t\t\tstate:'NY',\n\t\t\tzip:12345,\n\t\t\tisCurrent:true\n\t\t}\n\t]\n\}"}</cv>
<ck>createPerson.res.307.header.Location.description</ck> = <cv>URL of new person</cv>
<ck>createAddress.summary</ck> = <cv>Create a new Address bean</cv>
<ck>createAddress.req.path.id.description</ck> = <cv>Person ID</cv>
<ck>createAddress.req.path.id.type</ck> = <cv>integer</cv>
<ck>createAddress.req.body.schema</ck> = <cv>{example:"{\n\tstreet:'101 Main St',\n\tcity:'Anywhere',\n\tstate:'NY',\n\tzip:12345,\n\tisCurrent:true\n}"}</cv>
<ck>createAddress.res.307.header.Location.description</ck> = <cv>URL of new address</cv>
<ck>deletePerson.summary</ck> = <cv>Delete a Person bean</cv>
<ck>deletePerson.req.path.id.description</ck> = <cv>Person ID</cv>
<ck>deletePerson.req.path.id.type</ck> = <cv>integer</cv>
<ck>deletePerson.res.200.description</ck> = <cv>Returns the string "DELETE successful"</cv>
<ck>deletePerson.res.404.description</ck> = <cv>Person ID not found</cv>
<ck>deleteAddress.summary</ck> = <cv>Delete an Address bean</cv>
<ck>deleteAddress.req.path.id.description</ck> = <cv>Address ID</cv>
<ck>deleteAddress.res.200.description</ck> = <cv>Returns the string "DELETE successful"</cv>
<ck>deleteAddress.res.404.description</ck> = <cv>Address ID not found</cv>
<ck>updatePerson.summary</ck> = <cv>Change property on Person bean</cv>
<ck>updatePerson.req.path.id.description</ck> = <cv>Person ID</cv>
<ck>updatePerson.req.path.id.type</ck> = <cv>integer</cv>
<ck>updatePerson.req.body.description</ck> = <cv>Any object matching the field</cv>
<ck>updatePerson.res.200.description</ck> = <cv>Returns the string "PUT successful"</cv>
<ck>updatePerson.res.400.description</ck> = <cv>Invalid object type used</cv>
<ck>updatePerson.res.404.description</ck> = <cv>Person ID not found</cv>
<ck>updateAddress.summary</ck> = <cv>Change property on Address bean</cv>
<ck>updateAddress.req.path.id.description</ck> = <cv>Address ID</cv>
<ck>updateAddress.req.path.id.type</ck> = <cv>integer</cv>
<ck>updateAddress.req.body.description</ck> = <cv>Any object matching the field</cv>
<ck>updateAddress.res.200.description</ck> = <cv>Returns the string "PUT successful"</cv>
<ck>updateAddress.res.400.description</ck> = <cv>Invalid object type used</cv>
<ck>updateAddress.res.404.description</ck> = <cv>Address ID not foundv
<ck>getOptions.summary</ck> = <cv>View resource options</cv>
<ck>getCognosData.summary</ck> = <cv>Get data in Cognos/XML format</cv>
<ck>getCognosData.res.200.description</ck> = <cv>Returns a serialized DataSet</cv>
<ck>otherNotes</ck> = <cv>GZip support enabled. Public methods can be invoked by using the &amp;Method URL parameter. 'text/cognos+xml' support available under root resource only</cv>
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.Demo"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.2 - Demo</h4>
<div class='topic'>
<p>
Pointing a browser to the resource shows the results of running the <l>getRoot()</l> method:
</p>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.1.png">
<p>
Clicking the <l>people</l> link shows you the result of running the <l>getAllPeople()</l> method:
</p>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.2.png">
<p>
Notice how the <l>URI</l> properties automatically became hyperlinks.
</p>
<p>
Also notice how the dates are formatted as readable strings.
This was from the transform you added to the <l>Calendar</l> property.
</p>
<p>
Let's see what the output looks like in other formats:
</p>
<h5 class='figure'>JSON</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.3.png">
<h5 class='figure'>Lax JSON</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.4.png">
<h5 class='figure'>XML</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.5.png">
<p>
Notice how our <l>XML_enableNamespaces</l> and <l>XML_autoDetectNamespaces</l> settings result
in namespaces being used.
</p>
<p>
Also notice how the <code><ja>@BeanProperty</ja>(uri=<jk>true</jk>)</code> annotations caused the
<l>uri</l> properties to become XML attributes instead of elements.
</p>
<h5 class='figure'>RDF/XML</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.6.png">
<p>
Notice how the <code><ja>@BeanProperty</ja>(uri=<jk>true</jk>)</code> annotations are used to identify
values for <l>rdf:about</l> values.
</p>
<p>
Also notice how <l>URI</l> properties are serialized as <l>rdf:resource</l> attributes.
</p>
<p>
Now lets look at the schema outputs that can be rendered that show information about the POJO classes
themselves.
</p>
<h5 class='figure'>HTML Schema</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.7.png">
<h5 class='figure'>JSON Schema</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.8.png">
<h5 class='figure'>XML Schema</h5>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.9.png">
<p>
Now let's see what else you can do.
</p>
<p>
Clicking on the first <l>personUri</l> link executes the <l>getPerson()</l> method, which renders a
serialized <l>Person</l> object:
</p>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Demo.10.png">
<p>
Clicking on the OPTIONS link on the page shows you the Swagger doc generated from our annotations and
resource bundle properties:
</p>
<img class='bordered' src="doc-files/Samples.AddressBookResource.Options.png">
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.Traversable"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.3 - Traversable</h4>
<div class='topic'>
<p>
Because you added the <l>Traversable</l> converter to the <l>getPerson</l> method, you can also address
child nodes in the POJO model through path remainders:
</p>
<img class="bordered" src="doc-files/Samples.AddressBookResource.Traversable.1.png">
<br><br>
<img class="bordered" src="doc-files/Samples.AddressBookResource.Traversable.2.png">
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.Queryable"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.4 - Queryable</h4>
<div class='topic'>
<p>
The <l>Queryable</l> converter on the <l>getAllPeople()</l> method allows us to perform search/view/sort
functions against the data structure before serialization:
</p>
<h5 class='figure'>Show only the name and addresses columns</h5>
<img class="bordered" src="doc-files/Samples.AddressBookResource.Queryable.1.png">
<h5 class='figure'>Show only names that start with 'B*'</h5>
<img class="bordered" src="doc-files/Samples.AddressBookResource.Queryable.2.png">
<h5 class='figure'>Show only entries with age greater than 60</h5>
<img class="bordered" src="doc-files/Samples.AddressBookResource.Queryable.3.png">
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.Introspectable"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.5 - Introspectable</h4>
<div class='topic'>
<p>
The <l>Introspectable</l> converter on the <l>getPerson</l> method allows us to invoke public methods
on the addressed POJO (in this case, public methods on the <l>String</l> class):
</p>
<img class="bordered" src="doc-files/Samples.AddressBookResource.Introspectable.1.png">
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.RestClient"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.6 - ClientTest</h4>
<div class='topic'>
<p>
The <l>ClientTest</l> class is provided to demonstrate how POJOs can be serialized and parsed
through the REST interface using the <l>RestClient</l> class.
</p>
<p>
You'll notice that the class is a stand-alone executable that can be invoked as a plain Java process.
</p>
<h5 class='figure'>ClientTest.java</h5>
<p class='bcode'>
<jd>/**
* Sample client code for interacting with AddressBookResource
*/</jd>
<jk>public class</jk> ClientTest {
<jk>public static void</jk> main(String[] args) {
<jk>try</jk> {
System.<jsf>out</jsf>.println(<js>"Running client test..."</js>);
<jc>// Create a client to handle XML requests and responses.</jc>
RestClient client = RestClient.<jsm>create</jsm>().build();
RestClient xmlClient = RestClient.<jsm>create</jsm>().serializer(XmlSerializer.<jsf>DEFAULT</jsf>)
.parser(XmlParser.<jsf>DEFAULT</jsf>).build();
String root = <js>"http://localhost:10000/addressBook"</js>;
<jc>// Get the current contents of the address book</jc>
AddressBook ab = client.doGet(root + <js>"/people"</js>).getResponse(AddressBook.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Number of entries = "</js> + ab.getPeople().size());
<jc>// Same, but use XML as the protocol both ways</jc>
ab = xmlClient.doGet(root + <js>"/people"</js>).getResponse(AddressBook.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Number of entries = "</js> + ab.getPeople().size());
<jc>// Delete the existing entries</jc>
<jk>for</jk> (Person p : ab.getPeople()) {
String r = client.doDelete(p.<jf>uri</jf>).getResponse(String.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Deleted person "</js> + p.<jf>name</jf> + <js>", response = "</js> + r);
}
<jc>// Make sure they're gone</jc>
ab = client.doGet(root + <js>"/people"</js>).getResponse(AddressBook.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Number of entries = "</js> + ab.getPeople().size());
<jc>// Add 1st person again</jc>
CreatePerson cp = <jk>new</jk> CreatePerson(
<js>"Barack Obama"</js>,
<jsm>toCalendar</jsm>(<js>"Aug 4, 1961"</js>),
<jk>new</jk> CreateAddress(<js>"1600 Pennsylvania Ave"</js>, <js>"Washington"</js>, <js>"DC"</js>, 20500, <jk>true</jk>),
<jk>new</jk> CreateAddress(<js>"5046 S Greenwood Ave"</js>, <js>"Chicago"</js>, <js>"IL"</js>, 60615, <jk>false</jk>)
);
Person p = client.doPost(root + <js>"/people"</js>, cp).getResponse(Person.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Created person "</js> + p.<jf>name</jf> + <js>", uri = "</js> + p.<jf>uri</jf>);
<jc>// Add 2nd person again, but add addresses separately</jc>
cp = <jk>new</jk> CreatePerson(
<js>"George Walker Bush"</js>,
<jsm>toCalendar</jsm>(<js>"Jul 6, 1946"</js>)
);
p = client.doPost(root + <js>"/people"</js>, cp).getResponse(Person.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Created person "</js> + p.<jf>name</jf> + <js>", uri = "</js> + p.<jf>uri</jf>);
<jc>// Add addresses to 2nd person</jc>
CreateAddress ca = <jk>new</jk> CreateAddress(<js>"43 Prairie Chapel Rd"</js>, <js>"Crawford"</js>, <js>"TX"</js>, 76638, <jk>true</jk>);
Address a = client.doPost(p.uri + <js>"/addresses"</js>, ca).getResponse(Address.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Created address "</js> + a.<jf>uri</jf>);
ca = <jk>new</jk> CreateAddress(<js>"1600 Pennsylvania Ave"</js>, <js>"Washington"</js>, <js>"DC"</js>, 20500, <jk>false</jk>);
a = client.doPost(p.uri + <js>"/addresses"</js>, ca).getResponse(Address.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Created address "</js> + a.<jf>uri</jf>);
<jc>// Find 1st person, and change name</jc>
Person[] pp = client.doGet(root + <js>"/people?q=(name='Barack+Obama')"</js>).getResponse(Person[].<jk>class</jk>);
String r = client.doPut(pp[0].uri + <js>"/name"</js>, <js>"Barack Hussein Obama"</js>).getResponse(String.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"Changed name, response = "</js> + r);
p = client.doGet(pp[0].<jf>uri</jf>).getResponse(Person.<jk>class</jk>);
System.<jsf>out</jsf>.println(<js>"New name = "</js> + p.<jf>name</jf>);
} <jk>catch</jk> (Exception e) {
e.printStackTrace();
}
}
<jc>// Utility method</jc>
<jk>public static</jk> Calendar toCalendar(String birthDate) <jk>throws</jk> Exception {
Calendar c = <jk>new</jk> GregorianCalendar();
c.setTime(DateFormat.getDateInstance(DateFormat.<jsf>MEDIUM</jsf>).parse(birthDate));
<jk>return</jk> c;
}
}
</p>
<p>
The output from running this code is the following:
</p>
<p class='bcode'>
Running client test...
Number of entries = 2
Deleted person Barack Obama, response = DELETE successful
Deleted person George Walker Bush, response = DELETE successful
Number of entries = 0
Created person Barack Obama, uri = http://localhost:9081/sample/addressBook/people/3
Created person George Walker Bush, uri = http://localhost:9081/sample/addressBook/people/4
Created address http://localhost:9081/sample/addressBook/addresses/7
Created address http://localhost:9081/sample/addressBook/addresses/8
Changed name, response = PUT successful
New name = Barack Hussein Obama
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AddressBookResource.Browser"></a>
<h4 class='topic' onclick='toggle(this)'>12.6.7 - Browser Tips</h4>
<div class='topic'>
<p>
The Juneau architecture is designed to make it easy to debug REST resources using nothing more than a
browser.
The same actions done programmatically in the last section can also be done using URLs.
By default, you can override the HTTP Method and Content through GET parameters, as shown below:
</p>
<p class='bcode'>
<jc>// Delete the existing entries</jc>
http://localhost:10000/addressBook/people/1?method=DELETE
http://localhost:10000/addressBook/people/2?method=DELETE
<jc>// Add 1st person again</jc>
http://localhost:10000/addressBook/people?method=POST&amp;content={name:'Barack Obama',birthDate:'Aug 4, 1961',addresses:[{street:'1600 Pennsylvania Ave',city:'Washington',state:'DC',zip:20500,isCurrent:true},{street:'5046 S Greenwood Ave',city:'Chicago',state:'IL',zip:60615,isCurrent:false}]}
<jc>// Add 2nd person again</jc>
http://localhost:10000/addressBook/people?method=POST&amp;content={name:'George Walker Bush',birthDate:'Jul 6, 1946'}
http://localhost:10000/addressBook/people/4/addresses?method=POST&amp;content={street:'43 Prairie Chapel Rd',city:'Crawford',state:'TX',zip:76638,isCurrent:true}
http://localhost:10000/addressBook/people/4/addresses?method=POST&amp;content={street:'1600 Pennsylvania Ave',city:'Washington',state:'DC',zip:20500,isCurrent:false}
<jc>// Change name of 1st person</jc>
http://localhost:10000/addressBook/people/3/name?method=PUT&amp;content="'Barack Hussein Obama'"
</p>
<p>
The ability to overload methods is enabled through the
<code><del>RestResource.allowMethodParam()</del></code> setting.
</p>
</div>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.SampleRemoteableServlet"></a>
<h4 class='topic' onclick='toggle(this)'>12.7 - SampleRemoteableServlet</h4>
<div class='topic'>
<p>
The <l>SampleRemoteableServlet</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Extending the {@link org.apache.juneau.rest.remoteable.RemoteableServlet} class to create a proxy
service.
<li>
Using the {@link org.apache.juneau.rest.client.RestClient} class to create remoteable proxy interfaces.
</ul>
<p>
The <l>RemoteableServlet</l> class has a single abstract method,
{@link org.apache.juneau.rest.remoteable.RemoteableServlet#getServiceMap()}, that defines interface
keys and POJO values.
</p>
<p>
The <l>SampleRemoteableServlet</l> exposes the <l>AddressBook</l> bean from the previous example as a
service.
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/remoteable"</js>,
messages=<js>"nls/SampleRemoteableServlet"</js>,
title=<js>"Remoteable Service Proxy API"</js>,
description=<js>"Sample class showing how to use remoteable proxies. The list below are exposed services that
can be retrieved using RestClient.getProxyInterface(Class)."</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
),
<jc>// Allow us to use method=POST from a browser.</jc>
allowedMethodParams=<js>"*"</js>
)
<jk>public class</jk> SampleRemoteableServlet <jk>extends</jk> RemoteableServlet {
AddressBook <jf>addressBook</jf> = <jk>new</jk> AddressBook();
<ja>@Override</ja> <jc>/* RemoteableServlet */</jc>
<jk>protected</jk> Map&lt;Class&lt;?&gt;,Object&gt; getServiceMap() <jk>throws</jk> Exception {
Map&lt;Class&lt;?&gt;,Object&gt; m = <jk>new</jk> LinkedHashMap&lt;Class&lt;?&gt;,Object&gt;();
<jc>// In this simplified example, you expose the same POJO service under two different interfaces.</jc>
<jc>// One is IAddressBook which only exposes methods defined on that interface, and</jc>
<jc>// the other is AddressBook itself which exposes all methods defined on the class itself.</jc>
m.put(IAddressBook.<jk>class</jk>, <jf>addressBook</jf>);
m.put(AddressBook.<jk>class</jk>, <jf>addressBook</jf>);
<jk>return</jk> m;
}
}
</p>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.SampleRemoteableServlet.1.png'>
<p>
Clicking the hyperlinks on each shows you the list of methods that can be invoked on that service.
Note that the <l>IAddressBook</l> link shows that you can only invoke methods defined on that
interface, whereas the <l>AddressBook</l> link shows ALL public methods defined on that class.
Since <l>AddressBook</l> extends from <l>LinkedList</l>, you may notice familiar collections
framework methods listed.
</p>
<img class='bordered' src='doc-files/Samples.SampleRemoteableServlet.2.png'>
<br><br>
<img class='bordered' src='doc-files/Samples.SampleRemoteableServlet.3.png'>
<ul class='doctree'>
<li class='info'>
As good practice, you'll want to use interfaces to prevent all public methods from being exposed.
</ul>
<p>
Proxy interfaces are then retrieved using the {@link org.apache.juneau.rest.client.RestClient#getRemoteableProxy(Class)} method.
</p>
<p>
The client side code for invoking this method is shown below:
</p>
<p class='bcode'>
<jc>// Create a RestClient using JSON for serialization, and point to the server-side remoteable servlet.</jc>
RestClient client = RestClient.<jsm>create</jsm>()
.rootUrl(<js>"http://localhost:10000/remoteable"</js>)
.build();
<jc>// Create a proxy interface.</jc>
IAddressBook ab = client.getRemoteableProxy(IAddressBook.<jk>class</jk>);
<jc>// Invoke a method on the server side and get the returned result.</jc>
Person p = ab.createPerson(
<jk>new</jk> CreatePerson(<js>"Test Person"</js>,
AddressBook.<jsm>toCalendar</jsm>(<js>"Aug 1, 1999"</js>),
<jk>new</jk> CreateAddress(<js>"Test street"</js>, <js>"Test city"</js>, <js>"Test state"</js>, 12345, <jk>true</jk>))
);
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.TempDirResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.8 - TempDirResource</h4>
<div class='topic'>
<p>
The <l>TempDirResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Extending the {@link org.apache.juneau.microservice.resources.DirectoryResource} class.
<li>
Using the Apache <l>ServletFileUpload</l> class to handle multi-part form posts.
<li>
Using a system property string variable.
<li>
Using {@link org.apache.juneau.rest.RestMatcher RestMatchers}.
</ul>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.TempDirResource.1.png'>
<p>
Pointing a browser to the <l>upload</l> link shows a form entry page:
</p>
<img class='bordered' src='doc-files/Samples.TempDirResource.2.png'>
<h5 class='figure'>TempDirResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample resource that extends DirectoryResource to open up the temp directory as a REST resource.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/tempDir"</js>,
messages=<js>"nls/TempDirResource"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>,
<js>"upload: servlet:/upload"</js>
}
),
properties={
<ja>@Property</ja>(name=<js>"DirectoryResource.rootDir"</js>, value=<js>"$S{java.io.tmpdir}"</js>),
<ja>@Property</ja>(name=<js>"DirectoryResource.allowViews"</js>, value=<js>"true"</js>),
<ja>@Property</ja>(name=<js>"DirectoryResource.allowDeletes"</js>, value=<js>"true"</js>),
<ja>@Property</ja>(name=<js>"DirectoryResource.allowPuts"</js>, value=<js>"false"</js>)
},
stylesheet=<js>"styles/devops.css"</js>
)
<jk>public class</jk> TempDirResource <jk>extends</jk> DirectoryResource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jd>/**
* [GET /upload] - Display the form entry page for uploading a file to the temp directory.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/upload"</js>)
<jk>public</jk> ReaderResource getUploadPage(RestRequest req) <jk>throws</jk> IOException {
<jk>return</jk> req.getClasspathReaderResource(<js>"TempDirUploadPage.html"</js>, <jk>true</jk>);
}
<jd>/**
* [POST /upload] - Upload a file as a multipart form post.
* Shows how to use the Apache Commons ServletFileUpload class for handling multi-part form posts.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/upload"</js>,
matchers=TempDirResource.MultipartFormDataMatcher.<jk>class</jk>)
<jk>public</jk> Redirect uploadFile(RestRequest req) <jk>throws</jk> Exception {
ServletFileUpload upload = <jk>new</jk> ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(req);
<jk>while</jk> (iter.hasNext()) {
FileItemStream item = iter.next();
<jk>if</jk> (item.getFieldName().equals(<js>"contents"</js>)) {
File f = <jk>new</jk> File(getRootDir(), item.getName());
IOPipe.<jsm>create</jsm>(item.openStream(), <jk>new</jk> FileOutputStream(f)).closeOut().run();
}
}
<jk>return new</jk> Redirect(); <jc>// Redirect to the servlet root.</jc>
}
<jd>/** Causes a 404 if POST isn't multipart/form-data */</jd>
<jk>public static class</jk> MultipartFormDataMatcher <jk>extends</jk> RestMatcher {
<ja>@Override</ja> <jc>/* RestMatcher */</jc>
<jk>public boolean</jk> matches(RestRequest req) {
String contentType = req.getContentType();
<jk>return</jk> contentType != <jk>null</jk> &amp;&amp; contentType.startsWith(<js>"multipart/form-data"</js>);
}
}
}
</p>
<h5 class='figure'>TempDirResource.properties</h5>
<p class='bcode'>
<cc>#--------------------------------------------------------------------------------
# TempDirResource labels
#--------------------------------------------------------------------------------</cc>
<ck>title</ck> = <cv>Temp Directory View Service</cv>
<ck>description</ck> = <cv>View and download files in the '$S{java.io.tmpdir}' directory.</cv>
</p>
<p>
Note how a system property variable can be defined in the properties file.
</p>
<h5 class='figure'>TempDirUploadPage.html</h5>
<b>TODO - Needs update</b>
<p class='bcode'>
<xt>&lt;html&gt;</xt>
<xt>&lt;head&gt;</xt>
<xt>&lt;meta</xt> <xa>http-equiv</xa>=<xs>"Content-Type"</xs> <xa>content</xa>=<xs>"text/html; <xa>charset</xa>=UTF-8"</xs><xt>&gt;</xt>
<xt>&lt;style</xt> <xa>type</xa>=<xs>'text/css'</xs><xt>&gt;</xt>
<xt>@import</xt> <xs>'$R{servletURI}/style.css'</xs>;
<xt>&lt;/style&gt;</xt>
<xt>&lt;/head&gt;</xt>
<xt>&lt;body&gt;</xt>
<xt>&lt;h1&gt;</xt>$R{resourceTitle}<xt>&lt;/h1&gt;</xt>
<xt>&lt;h2&gt;</xt>$R{resourceDescription}<xt>&lt;/h2&gt;</xt>
<xt>&lt;div</xt> <xa>class</xa>=<xs>'data'</xs><xt>&gt;</xt>
<xt>&lt;form</xt> <xa>id</xa>=<xs>'form'</xs> <xa>action</xa>=<xs>'$R{servletURI}/upload'</xs> <xa>method</xa>=<xs>'POST'</xs> <xa>target</xa>=<xs>'buff'</xs> <xa>enctype</xa>=<xs>"multipart/form-data"</xs><xt>&gt;</xt>
<xt>&lt;input</xt> <xa>name</xa>=<xs>"contents"</xs> <xa>type</xa>=<xs>"file"</xs><xt>&gt;</xt><xt>&lt;button</xt> <xa>type</xa>=<xs>"submit"</xs><xt>&gt;</xt>Submit<xt>&lt;/button&gt;</xt>
<xt>&lt;/form&gt;</xt>
<xt>&lt;/div&gt;</xt>
<xt>&lt;/body&gt;</xt>
<xt>&lt;/html&gt;</xt>
</p>
<p>
Note how the HTML file contains localized variables for the servlet label and description.
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.AtomFeedResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.9 - AtomFeedResource</h4>
<div class='topic'>
<p>
The <l>AtomFeedResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Using the <a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#TOC'>ATOM Feed DTO</a> API.
</ul>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.AtomFeedResource.1.png'>
<p>
True ATOM feeds require using an <l>Accept:text/xml</l> header:
</p>
<img class='bordered' src='doc-files/Samples.AtomFeedResource.2.png'>
<p>
Other languages, such as JSON are also supported:
</p>
<img class='bordered' src='doc-files/Samples.AtomFeedResource.3.png'>
<h5 class='figure'>AtomFeedResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample resource that shows how to generate ATOM feeds.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/atom"</js>,
messages=<js>"nls/AtomFeedResource"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
),
properties={
<ja>@Property</ja>(name=<jsf>SERIALIZER_quoteChar</jsf>, value=<js>"'"</js>),
<ja>@Property</ja>(name=<jsf>RDF_rdfxml_tab</jsf>, value=<js>"5"</js>),
<ja>@Property</ja>(name=<jsf>RDF_addRootProperty</jsf>, value=<js>"true"</js>)
},
encoders=GzipEncoder.<jk>class</jk>
)
<jk>public class</jk> AtomFeedResource <jk>extends</jk> ResourceJena {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jk>private</jk> Feed <jf>feed</jf>; <jc>// The root resource object</jc>
<ja>@Override</ja> <jc>/* Servlet */</jc>
<jk>public void</jk> init() {
<jk>try</jk> {
<jf>feed</jf> = <jk>new</jk> Feed()
.setTitle(<jk>new</jk> Text(<js>"text"</js>, <js>"Juneau ATOM specification"</js>))
.setSubTitle(<jk>new</jk> Text(<js>"html"</js>, <js>"Decribes &lt;em&gt;stuff&lt;/em&gt; about Juneau"</js>))
.setUpdated(<jsm>parseDateTime</jsm>(<js>"2016-01-02T03:04:05Z"</js>))
.setId(<jk>new</jk> Id(<js>"tag:juneau.apache.org"</js>))
.addLinks(
<jk>new</jk> Link(<js>"alternate"</js>, <js>"text/html"</js>, <js>"http://juneau.apache.org/"</js>).setHreflang(<js>"en"</js>),
<jk>new</jk> Link(<js>"self"</js>, <js>"application/atom+xml"</js>, <js>"http://juneau.apache.org/feed.atom"</js>)
)
.setRights(<jk>new</jk> Text(<js>"Copyright (c) ..."</js>))
.setGenerator(<jk>new</jk> Generator(<js>"Juneau"</js>).setUri(<jk>new</jk> URI(<js>"http://juneau.apache.org/"</js>)).setVersion(<js>"1.0"</js>))
.addEntries(
<jk>new</jk> Entry()
.setTitle(<jk>new</jk> Text(<js>"Juneau ATOM specification snapshot"</js>))
.addLinks(
<jk>new</jk> Link(<js>"alternate"</js>, <js>"text/html"</js>, <js>"http://juneau.apache.org/juneau.atom"</js>),
<jk>new</jk> Link(<js>"enclosure"</js>, <js>"audio/mpeg"</js>, <js>"http://juneau.apache.org/audio/juneau_podcast.mp3"</js>).setLength(12345)
)
.setId(<jk>new</jk> Id(<js>"tag:juneau.apache.org"</js>))
.setUpdated(<jsm>parseDateTime</jsm>(<js>"2016-01-02T03:04:05Z"</js>))
.setPublished(<jsm>parseDateTime</jsm>(<js>"2016-01-02T03:04:05Z"</js>))
.addAuthors(<jk>new</jk> Person(<js>"James Bognar"</js>).setUri(<jk>new</jk> URI(<js>"http://juneau.apache.org/"</js>)).setEmail(<js>"james.bognar@apache.org"</js>))
.addContributors(
<jk>new</jk> Person(<js>"Barry M. Caceres"</js>)
)
.setContent(
<jk>new</jk> Content()
.setLang(<js>"en"</js>)
.setBase(<jk>new</jk> URI(<js>"http://www.apache.org/"</js>))
.setType(<js>"xhtml"</js>)
.setText(<js>"&lt;div xmlns=\"http://www.w3.org/1999/xhtml\"&gt;&lt;p&gt;&lt;i&gt;[Update: Juneau supports ATOM.]&lt;/i&gt;&lt;/p&gt;&lt;/div&gt;"</js>)
)
);
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RuntimeException(e);
}
}
<jd>/**
* GET request handler
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> Feed getFeed() <jk>throws</jk> Exception {
<jk>return</jk> <jf>feed</jf>;
}
<jd>/**
* PUT request handler.
* Replaces the feed with the specified content, and then mirrors it as the response.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/"</js>)
<jk>public</jk> Feed setFeed(<ja>@org.apache.juneau.rest.annotation.Content</ja> Feed feed) <jk>throws</jk> Exception {
<jk>this</jk>.<jf>feed</jf> = feed;
<jk>return</jk> feed;
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.DockerRegistryResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.10 - DockerRegistryResource</h4>
<div class='topic'>
<p>
The <l>DockerRegistryResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Accessing a docker registry REST API as POJOs using {@link org.apache.juneau.rest.client.RestClient}.
<li>
Using the {@link org.apache.juneau.rest.labels.ResourceDescription} class to implement a top-level
'router' page.
<li>
Using the {@link org.apache.juneau.rest.RestContext#getConfig()} method to access external
configuration file values.
</ul>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.DockerRegistryResource.1.png'>
<p>
Clicking the <l>search</l> link provides you with the search results against the Docker registry:
</p>
<img class='bordered' src='doc-files/Samples.DockerRegistryResource.2.png'>
<h5 class='figure'>DockerRegistryResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample resource that shows how to mirror query results from a Docker registry.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/docker"</js>,
title=<js>"Sample Docker resource"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> DockerRegistryResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jc>// Get registry URL from examples.cfg file.</jc>
<jk>private</jk> String <jf>registryUrl</jf> = getConfig().getString(<js>"DockerRegistry/url"</js>);
RestClient <jf>rc</jf> = RestClient.<jsm>create</jsm>().build();
<jd>/** [GET /] - Show child resources. */</jd>
<ja>@SuppressWarnings</ja>(<js>"nls"</js>)
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> ResourceDescription[] getChildren(RestRequest req) {
<jk>return new</jk> ResourceDescription[] {
<jk>new</jk> ResourceDescription(req, <js>"search"</js>, <js>"Search Registry"</js>)
};
}
<jd>/**
* PUT request handler.
* Replaces the feed with the specified content, and then mirrors it as the response.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/search"</js>)
<jk>public</jk> QueryResults query(<ja>@Query</ja>(<js>"q"</js>) String q) <jk>throws</jk> Exception {
String url = <jf>registryUrl</jf> + <js>"/search"</js> + (q == <jk>null</jk> ? <js>""</js> : <js>"?q="</js> + q);
<jk>return</jk> <jf>rc</jf>.doGet(url).getResponse(QueryResults.<jk>class</jk>);
}
<jk>public static class</jk> QueryResults {
<jk>public int</jk> <jf>num_results</jf>;
<jk>public</jk> String <jf>query</jf>;
<jk>public</jk> List&lt;DockerImage&gt; <jf>results</jf>;
}
<jk>public static class</jk> DockerImage {
<jk>public</jk> String <jf>name</jf>, <jf>description</jf>;
}
}
</p>
<p>
The Docker registry URL is specified in the <l>examples.cfg</l> file:
</p>
<h5 class='figure'>examples.cfg</h5>
<p class='bcode'>
<cc>#================================================================================
# DockerRegistryResource properties
#================================================================================</cc>
<cs>[DockerRegistry]</cs>
<ck>url</ck> = <cv>http://clmdocker02.ratl.swg.usma.apache.org:5000/v1</cv>
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.TumblrParserResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.11 - TumblrParserResource</h4>
<div class='topic'>
<p>
The <l>TumblrParserResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Using {@link org.apache.juneau.rest.client.RestClient} to retrieve information from other REST resources.
<li>
Using {@link org.apache.juneau.ObjectMap} and {@link org.apache.juneau.ObjectList} to produce
generalized POJO models.
</ul>
<p>
Pointing a browser at a Tumblr blog name, such as <l>ibmblr</l> causes a REST call to be make to the Tumblr
blog and the results to be parsed:
</p>
<img class='bordered' src='doc-files/Samples.TumblrParserResource.1.png'>
<h5 class='figure'>TumblrParserResource.java</h5>
<p class='bcode'>
<ja>@RestResource</ja>(
path=<js>"/tumblrParser"</js>,
messages=<js>"nls/TumblrParserResource"</js>,
title=<js>"Tumblr parser service"</js>,
description=<js>"Specify a URL to a Tumblr blog and parse the results."</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> TumblrParserResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> String getInstructions() <jk>throws</jk> Exception {
<jk>return</jk> <js>"Append the Tumblr blog name to the URL above (e.g. /tumblrParser/mytumblrblog)"</js>;
}
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/{blogName}"</js>)
<jk>public</jk> ObjectList parseBlog(<ja>@Path</ja> String blogName) <jk>throws</jk> Exception {
ObjectList l = <jk>new</jk> ObjectList();
RestClient rc = RestClient.<jsm>create</jsm>().build();
String site = <js>"http:<jc>//"</js> + blogName + <js>".tumblr.com/api/read/json"</js>;</jc>
ObjectMap m = rc.doGet(site).getResponse(ObjectMap.<jk>class</jk>);
<jk>int</jk> postsTotal = m.getInt(<js>"posts-total"</js>);
<jk>for</jk> (<jk>int</jk> i = 0; i &lt; postsTotal; i += 20) {
m = rc.doGet(site + <js>"?start="</js> + i + <js>"&amp;num=20&amp;transform=text"</js>).getResponse(ObjectMap.<jk>class</jk>);
ObjectList ol = m.getObjectList(<js>"posts"</js>);
<jk>for</jk> (<jk>int</jk> j = 0; j &lt; ol.size(); j++) {
ObjectMap om = ol.getObjectMap(j);
String type = om.getString(<js>"type"</js>);
Entry e = <jk>new</jk> Entry();
e.date = om.getString(<js>"date"</js>);
<jk>if</jk> (type.equals(<js>"link"</js>))
e.entry = <jk>new</jk> Link(om.getString(<js>"link-text"</js>), om.getString(<js>"link-url"</js>));
<jk>else if</jk> (type.equals(<js>"audio"</js>))
e.entry = <jk>new</jk> ObjectMap().append(<js>"type"</js>,<js>"audio"</js>).append(<js>"audio-caption"</js>, om.getString(<js>"audio-caption"</js>));
<jk>else if</jk> (type.equals(<js>"video"</js>))
e.entry = <jk>new</jk> ObjectMap().append(<js>"type"</js>,<js>"video"</js>).append(<js>"video-caption"</js>, om.getString(<js>"video-caption"</js>));
<jk>else if</jk> (type.equals(<js>"quote"</js>))
e.entry = <jk>new</jk> ObjectMap().append(<js>"type"</js>,<js>"quote"</js>).append(<js>"quote-source"</js>, om.getString(<js>"quote-source"</js>)).append(<js>"quote-text"</js>, om.getString(<js>"quote-text"</js>));
<jk>else if</jk> (type.equals(<js>"regular"</js>))
e.entry = om.getString(<js>"regular-body"</js>);
<jk>else if</jk> (type.equals(<js>"photo"</js>))
e.entry = <jk>new</jk> Img(om.getString(<js>"photo-url-250"</js>));
<jk>else</jk>
e.entry = <jk>new</jk> ObjectMap().append(<js>"type"</js>, type);
l.add(e);
}
}
<jk>return</jk> l;
}
<jk>public static class</jk> Entry {
<jk>public</jk> String <jf>date</jf>;
<jk>public</jk> Object <jf>entry</jf>;
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.PhotosResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.12 - PhotosResource</h4>
<div class='topic'>
<p>
The <l>PhotosResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
How to define custom serializers and parsers at the method level.
In this case, you define a serializer and parser to handle images.
</ul>
<p>
The resource consists of a simple registry of images with integer IDs.
</p>
<img class='bordered' src='doc-files/Samples.PhotosResource.1.png'>
<p>
It is initialized with a single entry, which can be accessed through a GET request.
</p>
<img class='bordered' src='doc-files/Samples.PhotosResource.2.png'>
<h5 class='figure'>PhotosResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample resource that allows images to be uploaded and retrieved.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/photos"</js>,
messages=<js>"nls/PhotosResource"</js>,
title=<js>"Photo REST service"</js>,
description=<js>"Use a tool like Poster to upload and retrieve jpeg and png images."</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> PhotosResource <jk>extends</jk> RestServletDefault {
<jc>// Our cache of photos</jc>
<jk>private</jk> Map&lt;Integer,Photo&gt; photos = <jk>new</jk> TreeMap&lt;Integer,Photo&gt;();
<ja>@Override</ja> <jc>/* Servlet */</jc>
<jk>public void</jk> init() {
<jk>try</jk> {
<jc>// Preload an image.</jc>
InputStream is = getClass().getResourceAsStream(<js>"averycutedog.jpg"</js>);
BufferedImage image = ImageIO.<jsm>read</jsm>(is);
Photo photo = <jk>new</jk> Photo(0, image);
<jf>photos</jf>.put(photo.<jf>id</jf>, photo);
} <jk>catch</jk> (IOException e) {
<jk>throw new</jk> RuntimeException(e);
}
}
<jd>/** Bean class for storing photos */</jd>
<jk>public static class</jk> Photo {
<jk>private int</jk> <jf>id</jf>;
BufferedImage <jf>image</jf>;
Photo(int id, BufferedImage image) {
<jk>this</jk>.<jf>id</jf> = id;
<jk>this</jk>.<jf>image</jf> = image;
}
<jk>public</jk> URI getURI() <jk>throws</jk> URISyntaxException {
<jk>return new</jk> URI(<js>"photos/"</js>+<jf>id</jf>);
}
<jk>public int</jk> getID() {
<jk>return</jk> <jf>id</jf>;
}
}
<jd>/** GET request handler for list of all photos */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> Collection&lt;Photo&gt; getAllPhotos(RestRequest req, RestResponse res) <jk>throws</jk> Exception {
res.setPageTitle(<js>"Photo REST service"</js>);
res.setPageText(<js>"Use a tool like Poster to upload and retrieve jpeg and png images."</js>);
<jk>return</jk> photos.values();
}
<jd>/** GET request handler for single photo */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/{id}"</js>, serializers=ImageSerializer.<jk>class</jk>)
<jk>public</jk> BufferedImage getPhoto(RestRequest req, <ja>@Path</ja> int id) <jk>throws</jk> Exception {
Photo p = photos.get(id);
if (p == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Photo not found"</js>);
<jk>return</jk> p.image;
}
<jd>/** PUT request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/{id}"</js>, parsers=ImageParser.<jk>class</jk>)
<jk>public</jk> String addPhoto(RestRequest req, <ja>@Path</ja> <jk>int</jk> id, <ja>@Body</ja> BufferedImage image) <jk>throws</jk> Exception {
photos.put(id, <jk>new</jk> Photo(id, image));
<jk>return</jk> <js>"OK"</js>;
}
<jd>/** POST request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>, parsers=ImageParser.<jk>class</jk>)
<jk>public</jk> Photo setPhoto(RestRequest req, <ja>@Body</ja> BufferedImage image) <jk>throws</jk> Exception {
<jk>int</jk> id = photos.size();
Photo p = <jk>new</jk> Photo(id, image);
photos.put(id, p);
<jk>return</jk> p;
}
<jd>/** DELETE request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>DELETE</jsf>, path=<js>"/{id}"</js>)
<jk>public</jk> String deletePhoto(RestRequest req, <ja>@Path</ja> <jk>int</jk> id) <jk>throws</jk> Exception {
Photo p = photos.remove(id);
if (p == <jk>null</jk>)
<jk>throw new</jk> RestException(<jsf>SC_NOT_FOUND</jsf>, <js>"Photo not found"</js>);
<jk>return</jk> <js>"OK"</js>;
}
<jd>/** OPTIONS request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>OPTIONS</jsf>, path=<js>"/*"</js>)
<jk>public</jk> Swagger getOptions(RestRequest req) {
<jk>return</jk> req.getSwagger();
}
<jd>/** Serializer for converting images to byte streams */</jd>
<ja>@Produces</ja>(<js>"image/png,image/jpeg"</js>)
<jk>public static class</jk> ImageSerializer <jk>extends</jk> OutputStreamSerializer {
<ja>@Override</ja> <jc>/* Serializer */</jc>
<jk>public void</jk> serialize(Object o, OutputStream out, SerializerSession session) <jk>throws</jk> IOException, SerializeException {
RenderedImage image = (RenderedImage)o;
String mediaType = ctx.getMediaType();
ImageIO.<jsm>write</jsm>(image, mediaType.substring(mediaType.indexOf(<js>'/'</js>)+1), out);
}
}
<jd>/** Parser for converting byte streams to images */</jd>
<ja>@Consumes</ja>(<js>"image/png,image/jpeg"</js>)
<jk>public static class</jk> ImageParser <jk>extends</jk> InputStreamParser {
<ja>@Override</ja> <jc>/* Parser */</jc>
<jk>public</jk> &lt;T&gt; T parse(InputStream in, ClassMeta&lt;T&gt; type, ParserSession session) <jk>throws</jk> ParseException, IOException {
BufferedImage image = ImageIO.<jsm>read</jsm>(in);
<jk>return</jk> (T)image;
}
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.JsonSchemaResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.13 - JsonSchemaResource</h4>
<div class='topic'>
<p>
The <l>JsonSchemaResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Using the <a class='doclink'
href='org/apache/juneau/dto/jsonschema/package-summary.html#TOC'>JSON Schema DTO</a> API.
</ul>
<p>
The resource consists of a pre-initialized {@link org.apache.juneau.dto.jsonschema.Schema} object.
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.JsonSchemaResource.1.png'>
<p>
For true JSON-Schema, you need to specify the header <l>Accept: text/json</l>:
</p>
<img class='bordered' src='doc-files/Samples.JsonSchemaResource.2.png'>
<h5 class='figure'>JsonSchemaResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample resource that shows how to serialize JSON-Schema documents.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/jsonSchema"</js>,
messages=<js>"nls/JsonSchemaResource"</js>,
title=<js>"Sample JSON-Schema document"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> JsonSchemaResource <jk>extends</jk> ResourceJena {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jk>private</jk> Schema schema; <jc>// The schema document</jc>
<ja>@Override</ja> /* Servlet */
<jk>public void</jk> init() {
<jk>try</jk> {
<jf>schema</jf> = <jk>new</jk> Schema()
.setId(<js>"http://example.com/sample-schema#"</js>)
.setSchemaVersionUri(<js>"http://json-schema.org/draft-04/schema#"</js>)
.setTitle(<js>"Example Schema"</js>)
.setType(JsonType.<jsf>OBJECT</jsf>)
.addProperties(
<jk>new</jk> SchemaProperty(<js>"firstName"</js>, JsonType.<jsf>STRING</jsf>),
<jk>new</jk> SchemaProperty(<js>"lastName"</js>, JsonType.<jsf>STRING</jsf>),
<jk>new</jk> SchemaProperty(<js>"age"</js>, JsonType.<jsf>INTEGER</jsf>)
.setDescription(<js>"Age in years"</js>)
.setMinimum(0)
)
.addRequired(<js>"firstName"</js>, <js>"lastName"</js>);
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RuntimeException(e);
}
}
<jd>/** GET request handler */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> Schema getSchema() <jk>throws</jk> Exception {
<jk>return</jk> <jf>schema</jf>;
}
<jd>/**
* PUT request handler.
* Replaces the schema document with the specified content, and then mirrors it as the response.
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/"</js>)
<jk>public</jk> Schema setSchema(<ja>@Body</ja> Schema schema) <jk>throws</jk> Exception {
<jk>this</jk>.<jf>schema</jf> = schema;
<jk>return</jk> schema;
}
}
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.SqlQueryResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.14 - SqlQueryResource</h4>
<div class='topic'>
<p>
The <l>SqlQueryResource</l> class shows examples of the following:
</p>
<ul class='spaced-list'>
<li>
Using the {@link org.apache.juneau.dto.ResultSetList} to serialize database result sets.
<li>
Using {@link org.apache.juneau.rest.RestContext#getConfig()} to access config properties.
<li>
Using form entry beans.
</ul>
<p>
The example uses embedded Derby to create a database whose name is defined in the external configuration
files.
</p>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.SqlQueryResource.1.png'>
<p>
Running a query results in the following output:
</p>
<img class='bordered' src='doc-files/Samples.SqlQueryResource.2.png'>
<h5 class='figure'>SqlQueryResource.java</h5>
<p class='bcode'>
<jd>/**
* Sample resource that shows how Juneau can serialize ResultSets.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/sqlQuery"</js>,
messages=<js>"nls/SqlQueryResource"</js>,
title=<js>"SQL query service"</js>,
description=<js>"Executes queries against the local derby '$C{SqlQueryResource/connectionUrl}' database"</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
}
)
)
<jk>public class</jk> SqlQueryResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jk>private</jk> Config <jf>cf</jf> = getConfig();
<jk>private</jk> String <jf>driver</jf> = cf.getString(<js>"SqlQueryResource/driver"</js>);
<jk>private</jk> String <jf>connectionUrl</jf> = cf.getString(<js>"SqlQueryResource/connectionUrl"</js>);
<jk>private boolean</jk>
<jf>allowUpdates</jf> = cf.getBoolean(<js>"SqlQueryResource/allowUpdates"</js>, <jk>false</jk>),
<jf>allowTempUpdates</jf> = cf.getBoolean(<js>"SqlQueryResource/allowTempUpdates"</js>, <jk>false</jk>),
<jf>includeRowNums</jf> = cf.getBoolean(<js>"SqlQueryResource/includeRowNums"</js>, <jk>false</jk>);
<ja>@Override</ja> <jc>/* Servlet */</jc>
<jk>public void</jk> init() {
<jk>try</jk> {
Class.<jsm>forName</jsm>(driver).newInstance();
} <jk>catch</jk> (Exception e) {
<jk>throw new</jk> RuntimeException(e);
}
}
<jd>/** GET request handler - Display the query entry page. */</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>)
<jk>public</jk> ReaderResource doGet(RestRequest req) <jk>throws</jk> IOException {
<jk>return</jk> req.getClasspathReaderResource(<js>"SqlQueryResource.html"</js>, <jk>true</jk>);
}
<jd>/** POST request handler - Execute the query. */</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>)
<jk>public</jk> List&lt;Object&gt; doPost(<ja>@Body</ja> PostInput in) <jk>throws</jk> Exception {
List&lt;Object&gt; results = <jk>new</jk> LinkedList&lt;Object&gt;();
<jc>// Don't try to submit empty input.</jc>
<jk>if</jk> (StringUtils.<jsm>isEmpty</jsm>(in.<jf>sql</jf>))
<jk>return</jk> results;
<jk>if</jk> (in.<jf>pos</jf> &lt; 1 || in.<jf>pos</jf> &gt; 10000)
<jk>throw new</jk> RestException(<jsf>SC_BAD_REQUEST</jsf>, <js>"Invalid value for position. Must be between 1-10000"</js>);
<jk>if</jk> (in.<jf>limit</jf> &lt; 1 || in.<jf>limit</jf> &gt; 10000)
<jk>throw new</jk> RestException(<jsf>SC_BAD_REQUEST</jsf>, <js>"Invalid value for limit. Must be between 1-10000"</js>);
<jc>// Create a connection and statement.</jc>
<jc>// If these fails, let the exception transform up as a 500 error.</jc>
Connection c = DriverManager.getConnection(<jf>connectionUrl</jf>);
c.setAutoCommit(<jk>false</jk>);
Statement st = c.createStatement();
String sql = <jk>null</jk>;
<jk>try</jk> {
<jk>for</jk> (String s : in.<jf>sql</jf>.split(<js>";"</js>)) {
sql = s.trim();
<jk>if</jk> (! sql.isEmpty()) {
Object o = <jk>null</jk>;
<jk>if</jk> (<jf>allowUpdates</jf> || (<jf>allowTempUpdates</jf> &amp;&amp; ! sql.matches(<js>"(?:i)commit.*"</js>))) {
<jk>if</jk> (st.execute(sql)) {
ResultSet rs = st.getResultSet();
o = <jk>new</jk> ResultSetList(rs, in.<jf>pos</jf>, in.<jf>limit</jf>, <jf>includeRowNums</jf>);
} <jk>else</jk> {
o = st.getUpdateCount();
}
} <jk>else</jk> {
ResultSet rs = st.executeQuery(sql);
o = <jk>new</jk> ResultSetList(rs, in.<jf>pos</jf>, in.<jf>limit</jf>, <jf>includeRowNums</jf>);
}
results.add(o);
}
}
<jk>if</jk> (<jf>allowUpdates</jf>)
c.commit();
<jk>else if</jk> (<jf>allowTempUpdates</jf>)
c.rollback();
} <jk>catch</jk> (SQLException e) {
c.rollback();
<jk>throw new</jk> RestException(<jsf>SC_BAD_REQUEST</jsf>, <js>"Invalid query: {0}"</js>, sql).initCause(e);
} <jk>finally</jk> {
c.close();
}
<jk>return</jk> results;
}
<jd>/** The parsed form post */</jd>
<jk>public static class</jk> PostInput {
<jk>public</jk> String <jf>sql</jf>;
<jk>public int</jk> <jf>pos</jf> = 1, <jf>limit</jf> = 100;
}
}
</p>
<h5 class='figure'>SqlQueryResource.html</h5>
<b>TODO - Needs update</b>
<p class='bcode'>
<xt>&lt;html&gt;</xt>
<xt>&lt;head&gt;</xt>
<xt>&lt;style</xt> <xa>type</xa>=<xs>'text/css'</xs><xt>&gt;</xt>
<xt>@import</xt> <xs>'$R{servletURI}/style.css'</xs>;
<xt>&lt;/style&gt;</xt>
<xt>&lt;script&gt;</xt>
<jc>// Quick and dirty function to allow tabs in textarea.</jc>
<jk>function</jk> checkTab(e) {
<jk>if</jk> (e.keyCode == 9) {
<jk>var</jk> t = e.target;
<jk>var</jk> ss = t.selectionStart, se = t.selectionEnd;
t.value = t.value.slice(0,ss).concat(<js>'\t'</js>).concat(t.value.slice(ss,t.value.length));
e.preventDefault();
}
}
<jc>// Load results from IFrame into this document.</jc>
<jk>function</jk> loadResults(b) {
<jk>var</jk> doc = b.contentDocument || b.contentWindow.document;
<jk>var</jk> data = doc.getElementById(<js>'data'</js>) || doc.getElementsByTagName(<js>'body'</js>)[0];
document.getElementById(<js>'results'</js>).innerHTML = data.innerHTML;
}
<xt>&lt;/script&gt;</xt>
<xt>&lt;/head&gt;</xt>
<xt>&lt;body&gt;</xt>
<xt>&lt;h1&gt;</xt>SQL Query API<xt>&lt;/h1&gt;</xt>
<xt>&lt;div</xt> <xa>class</xa>=<xs>'data'</xs><xt>&gt;</xt>
<xt>&lt;form</xt> <xa>action</xa>=<xs>'sqlQuery'</xs> <xa>method</xa>=<xs>'POST'</xs> <xa>target</xa>=<xs>'buf'</xs><xt>&gt;</xt>
<xt>&lt;table&gt;</xt>
<xt>&lt;tr&gt;</xt>
<xt>&lt;th&gt;</xt>Position (1-10000):<xt>&lt;/th&gt;</xt>
<xt>&lt;td&gt;</xt><xt>&lt;input</xt> <xa>name</xa>=<xs>'pos'</xs> <xa>type</xa>=<xs>'number'</xs> <xa>value</xa>=<xs>'1'</xs><xt>&gt;</xt><xt>&lt;/td&gt;</xt>
<xt>&lt;th&gt;</xt>Limit (1-10000):<xt>&lt;/th&gt;</xt>
<xt>&lt;td&gt;</xt><xt>&lt;input</xt> <xa>name</xa>=<xs>'limit'</xs> <xa>type</xa>=<xs>'number'</xs> <xa>value</xa>=<xs>'100'</xs><xt>&gt;</xt><xt>&lt;/td&gt;</xt>
<xt>&lt;td&gt;</xt><xt>&lt;button</xt> <xa>type</xa>=<xs>'submit'</xs><xt>&gt;</xt>Submit<xt>&lt;/button&gt;</xt><xt>&lt;button</xt> <xa>type</xa>=<xs>'reset'</xs><xt>&gt;</xt>Reset<xt>&lt;/button&gt;</xt><xt>&lt;/td&gt;</xt>
<xt>&lt;/tr&gt;</xt>
<xt>&lt;tr&gt;</xt>
<xt>&lt;td</xt> <xa>colspan</xa>=<xs>"5"</xs><xt>&gt;</xt>
<xt>&lt;textarea</xt> <xa>name</xa>=<xs>'sql'</xs> <xa>style</xa>=<xs>'width:100%;height:200px;font-family:Courier;font-size:9pt;'</xs> <xa>onkeydown</xa>=<xs>'checkTab(event)'</xs><xt>&gt;</xt><xt>&lt;/textarea&gt;</xt>
<xt>&lt;/td&gt;</xt>
<xt>&lt;/tr&gt;</xt>
<xt>&lt;/table&gt;</xt>
<xt>&lt;/form&gt;</xt>
<xt>&lt;br&gt;</xt>
<xt>&lt;div</xt> <xa>id</xa>=<xs>'results'</xs><xt>&gt;</xt>
<xt>&lt;/div&gt;</xt>
<xt>&lt;/div&gt;</xt>
<xt>&lt;iframe</xt> <xa>name</xa>=<xs>'buf'</xs> <xa>style</xa>=<xs>'display:none'</xs> <xa>onload</xa>=<xs>"parent.loadResults(this)"</xs><xt>&gt;</xt><xt>&lt;/iframe&gt;</xt>
<xt>&lt;/body&gt;</xt>
<xt>&lt;/html&gt;</xt>
</p>
<h5 class='figure'>samples.cfg</h5>
<p class='bcode'>
<cc>#================================================================================
# SqlQueryResource properties
#================================================================================</cc>
<cs>[SqlQueryResource]</cs>
<ck>driver</ck> = <cv>org.apache.derby.jdbc.EmbeddedDriver</cv>
<ck>connectionUrl</ck> = <cv>jdbc:derby:C:/testDB;create=true</cv>
<ck>allowTempUpdates</ck> = <cv>true</cv>
<ck>includeRowNums</ck> = <cv>true</cv>
</p>
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.ConfigResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.15 - ConfigResource</h4>
<div class='topic'>
<!--p>
The {@link org.apache.juneau.microservice.resources.ConfigResource} class is a predefined reusable resource.
<br>It provides a REST interface for reading and altering the microservice config file.
</p>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.ConfigResource.1.png'>
<p>
An edit page is provided for altering the raw config file:
</p>
<img class='bordered' src='doc-files/Samples.ConfigResource.3.png'>
<p>
The {@link org.apache.juneau.config.Config} class is a serializable POJO, which makes the resource
relatively straightforward to implement.
</p>
<h5 class='figure'>ConfigResource.java</h5>
<p class='bcode'>
<jd>/**
* Shows contents of the microservice configuration file.
*/</jd>
<ja>@RestResource</ja>(
path=<js>"/config"</js>,
title=<js>"Configuration"</js>,
description=<js>"Contents of configuration file."</js>,
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>,
<js>"edit: servlet:/edit"</js>
}
)
)
<jk>public class</jk> ConfigResource <jk>extends</jk> Resource {
<jk>private static final long</jk> <jsf>serialVersionUID</jsf> = 1L;
<jd>/**
* [GET /] - Show contents of config file.
*
* <ja>@return</ja> The config file.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/"</js>, description=<js>"Show contents of config file."</js>)
<jk>public</jk> Config getConfigContents() <jk>throws</jk> Exception {
<jk>return</jk> getConfig();
}
<jd>/**
* [GET /edit] - Show config file edit page.
*
* <ja>@param</ja> req The HTTP request.
* <ja>@return</ja> The config file as a reader resource.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/edit"</js>, description=<js>"Show config file edit page."</js>)
<jk>public</jk> ReaderResource getConfigEditPage(RestRequest req) <jk>throws</jk> Exception {
<jc>// Note that you don't want variables in the config file to be resolved,</jc>
<jc>// so you need to escape any $ characters that you see.</jc>
req.setAttribute(<js>"contents"</js>, getConfig().toString().replaceAll(<js>"\\$"</js>, <js>"\\\\\\$"</js>));
<jk>return</jk> req.getClasspathReaderResource(<js>"ConfigEdit.html"</js>, <jk>true</jk>);
}
<jd>/**
* [GET /{section}] - Show config file section.
*
* <ja>@param</ja> section The section name.
* <ja>@return</ja> The config file section.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/{section}"</js>,
description=<js>"Show config file section."</js>,
parameters={
<ja>@Parameter</ja>(in=<js>"path"</js>, name=<js>"section"</js>, description=<js>"Section name."</js>)
}
)
<jk>public</jk> ObjectMap getConfigSection(<ja>@Path</ja>(<js>"section"</js>) String section) <jk>throws</jk> Exception {
<jk>return</jk> getSection(section);
}
<jd>/**
* [GET /{section}/{key}] - Show config file entry.
*
* <ja>@param</ja> section The section name.
* <ja>@param</ja> key The section key.
* <ja>@return</ja> The value of the config file entry.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>GET</jsf>, path=<js>"/{section}/{key}"</js>,
description=<js>"Show config file entry."</js>,
parameters={
<ja>@Parameter</ja>(in=<js>"path"</js>, name=<js>"section"</js>, description=<js>"Section name."</js>),
<ja>@Parameter</ja>(in=<js>"path"</js>, name=<js>"key"</js>, description=<js>"Entry name."</js>)
}
)
<jk>public</jk> String getConfigEntry(<ja>@Path</ja>(<js>"section"</js>) String section, <ja>@Path</ja>(<js>"key"</js>) String key) <jk>throws</jk> Exception {
<jk>return</jk> getSection(section).getString(key);
}
<jd>/**
* [POST /] - Sets contents of config file from a FORM post.
*
* <ja>@param</ja> contents The new contents of the config file.
* <ja>@return</ja> The new config file contents.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>POST</jsf>, path=<js>"/"</js>,
description=<js>"Sets contents of config file from a FORM post."</js>,
parameters={
<ja>@Parameter</ja>(in=<js>"formData"</js>, name=<js>"contents"</js>, description=<js>"New contents in INI file format."</js>)
}
)
<jk>public</jk> Config setConfigContentsFormPost(<ja>@FormData</ja>(<js>"contents"</js>) String contents) <jk>throws</jk> Exception {
<jk>return</jk> setConfigContents(<jk>new</jk> StringReader(contents));
}
<jd>/**
* [PUT /] - Sets contents of config file.
*
* <ja>@param</ja> contents The new contents of the config file.
* <ja>@return</ja> The new config file contents.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/"</js>,
description=<js>"Sets contents of config file."</js>,
parameters={
<ja>@Parameter</ja>(in=<js>"body"</js>, description=<js>"New contents in INI file format."</js>)
}
)
<jk>public</jk> Config setConfigContents(<ja>@Body</ja> Reader contents) <jk>throws</jk> Exception {
Config cf2 = Config.<jsm>create</jsm>().build().load(contents);
<jk>return</jk> getConfig().merge(cf2).save();
}
<jd>/**
* [PUT /{section}] - Add or overwrite a config file section.
*
* <ja>@param</ja> section The section name.
* <ja>@param</ja> contents The new contents of the config file section.
* <ja>@return</ja> The new section.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/{section}"</js>,
description=<js>"Add or overwrite a config file section."</js>,
parameters={
<ja>@Parameter</ja>(in=<js>"path"</js>, name=<js>"section"</js>, description=<js>"Section name."</js>),
<ja>@Parameter</ja>(in=<js>"body"</js>, description=<js>"New contents for section as a simple map with string keys and values."</js>)
}
)
<jk>public</jk> ObjectMap setConfigSection(<ja>@Path</ja>(<js>"section"</js>) String section, <ja>@Body</ja> Map&lt;String,String&gt; contents) <jk>throws</jk> Exception {
getConfig().setSection(section, contents);
<jk>return</jk> getSection(section);
}
<jd>/**
* [PUT /{section}/{key}] - Add or overwrite a config file entry.
*
* <ja>@param</ja> section The section name.
* <ja>@param</ja> key The section key.
* <ja>@param</ja> value The new value.
* <ja>@return</ja> The new value.
* <ja>@throws</ja> Exception
*/</jd>
<ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/{section}/{key}"</js>,
description=<js>"Add or overwrite a config file entry."</js>,
parameters={
<ja>@Parameter</ja>(in=<js>"path"</js>, name=<js>"section"</js>, description=<js>"Section name."</js>),
<ja>@Parameter</ja>(in=<js>"path"</js>, name=<js>"key"</js>, description=<js>"Entry name."</js>),
<ja>@Parameter</ja>(in=<js>"body"</js>, description=<js>"New value as a string."</js>)
}
)
<jk>public</jk> String setConfigSection(<ja>@Path</ja>(<js>"section"</js>) String section, <ja>@Path</ja>(<js>"key"</js>) String key, <ja>@Body</ja> String value) <jk>throws</jk> Exception {
getConfig().put(section, key, value, <jk>false</jk>);
<jk>return</jk> getSection(section).getString(key);
}
<jk>private</jk> ObjectMap getSection(String name) {
ObjectMap m = getConfig().getSectionMap(name);
<jk>if</jk> (m == <jk>null</jk>)
<jk>throw new</jk> RestException(SC_NOT_FOUND, <js>"Section not found."</js>);
<jk>return</jk> m;
}
}
</p>
<h5 class='figure'>ConfigEdit.html</h5>
<b>TODO - Needs update</b>
<p class='bcode'>
<xt>&lt;html&gt;</xt>
<xt>&lt;head&gt;</xt>
<xt>&lt;meta</xt> <xa>http-equiv</xa>=<xs>'Content-Type'</xs> <xa>content</xa>=<xs>'text/html; <xa>charset</xa>=UTF-8'</xs><xt>&gt;</xt>
<xt>&lt;style</xt> <xa>type</xa>=<xs>'text/css'</xs><xt>&gt;</xt>
<xt>@import</xt> <xs>'$R{servletURI}/style.css'</xs>;
<xt>&lt;/style&gt;</xt>
<xt>&lt;/head&gt;</xt>
<xt>&lt;body&gt;</xt>
<xt>&lt;h1&gt;</xt>$R{resourceTitle}<xt>&lt;/h1&gt;</xt>
<xt>&lt;h2&gt;</xt>Edit config file<xt>&lt;/h2&gt;</xt>
<xt>&lt;p</xt> <xa>class</xa>=<xs>'links'</xs><xt>&gt;</xt><xt>&lt;a</xt> <xa>href</xa>=<xs>'$R{requestParentURI}'</xs><xt>&gt;</xt>up<xt>&lt;/a&gt;</xt> - <xt>&lt;a</xt> <xa>href=<xs>'$R{servletURI}?method</xa>=OPTIONS'</xs><xt>&gt;</xt>options<xt>&lt;/a&gt;</xt><xt>&lt;/p&gt;</xt>
<xt>&lt;form</xt> <xa>id</xa>=<xs>'form'</xs> <xa>action</xa>=<xs>'$R{servletURI}'</xs> <xa>method</xa>=<xs>'POST'</xs> <xa>enctype</xa>=<xs>'application/x-www-form-urlencoded'</xs><xt>&gt;</xt>
<xt>&lt;div</xt> <xa>class</xa>=<xs>'data'</xs><xt>&gt;</xt>
<xt>&lt;table&gt;</xt>
<xt>&lt;tr&gt;</xt><xt>&lt;td</xt> <xa>colspan</xa>=<xs>'2'</xs> <xa>align</xa>=<xs>'right'</xs><xt>&gt;</xt><xt>&lt;button</xt> <xa>type</xa>=<xs>'submit'</xs><xt>&gt;</xt>Submit<xt>&lt;/button&gt;</xt><xt>&lt;button</xt> <xa>type</xa>=<xs>'reset'</xs><xt>&gt;</xt>Reset<xt>&lt;/button&gt;</xt><xt>&lt;/td&gt;</xt><xt>&lt;/tr&gt;</xt>
<xt>&lt;tr&gt;</xt><xt>&lt;th</xt> <xa>colspan</xa>=<xs>'2'</xs><xt>&gt;</xt>Contents<xt>&lt;/th&gt;</xt><xt>&lt;/tr&gt;</xt>
<xt>&lt;tr&gt;</xt><xt>&lt;td</xt> <xa>colspan</xa>=<xs>'2'</xs><xt>&gt;</xt><xt>&lt;textarea</xt> <xa>name</xa>=<xs>'contents'</xs> <xa>rows</xa>=<xs>'40'</xs> <xa>cols</xa>=<xs>'120'</xs> <xa>style</xa>=<xs>'white-space: pre; word-wrap: normal; overflow-x: scroll;'</xs><xt>&gt;</xt>$SA{contents}<xt>&lt;/textarea&gt;</xt><xt>&lt;/td&gt;</xt><xt>&lt;/tr&gt;</xt>
<xt>&lt;/table&gt;</xt>
<xt>&lt;/div&gt;</xt>
<xt>&lt;/form&gt;</xt>
<xt>&lt;/body&gt;</xt>
<xt>&lt;/html&gt;</xt>
</p-->
</div>
<!-- ======================================================================================================= -->
<a id="juneau-examples-rest.LogsResource"></a>
<h4 class='topic' onclick='toggle(this)'>12.16 - LogsResource</h4>
<div class='topic'>
<p>
The {@link org.apache.juneau.microservice.resources.LogsResource} class is a reusable predefined resource.
<br>It provides a REST interface for the log files generated by the microservice.
</p>
<p>
Pointing a browser to the resource shows the following:
</p>
<img class='bordered' src='doc-files/Samples.LogsResource.1.png'>
<p>
The <l>highlighted</l> links show the contents of the log file with color highlighting:
</p>
<img class='bordered' src='doc-files/Samples.LogsResource.2.png'>
<p>
The <l>parsed</l> links parse the log file and return the entries as serialized POJOs:
</p>
<img class='bordered' src='doc-files/Samples.LogsResource.3.png'>
</div>
</div>
<!-- =============================================================================================================== -->
<a id="Security"></a>
<h2 class='topic' onclick='toggle(this)'>13 - Security Best-Practices</h2>
<div class='topic'>
<p>
Security is always an ongoing concern in any library.
If you discover any security vulnerabilities in this code, please refer to the instructions found here:
</p>
<ul class='spaced-list'>
<li class='extlink'><a class='doclink' href='http://www.apache.org/security'>SECURITY</a>
</ul>
<!-- =========================================================================================================== -->
<a id="Security.juneau-marshall"></a>
<h3 class='topic' onclick='toggle(this)'>13.1 - juneau-marshall</h3>
<div class='topic'>
<h5 class='topic'>Demarshalling vulnerabilities</h5>
<p>
One common security vulnerability is the ability to create arbitrary Java object instances through crafted
user input. For example, support for constructing POJOs based on an input attribute defining a
fully-qualified class name like <js>"{class:'com.foo.MyBean',...}"</js>
</p>
<p>
Fortunately, Juneau does not support an open-ended <js>"class</js> attribute.
As a rule, it should not be possible to create arbitrary POJOs by any of the parsers.
The demarshalled object types are inferred via reflection of the class objects passed in through the parser
method (e.g. <code>JsonParser.<jsf>DEFAULT</jsf>.parse(input, MyBean.<jk>class</jk>)</code>).
As long as the <code>Class</code> object passed into this method is not constructed from user-generated input,
it should be free from demarshalling vulnerabilities.
</p>
<p>
The following example shows a potential vector that circumvents the restriction above:
</p>
<p class='bcode'>
<jc>// Don't do this!</jc>
Class c = Class.<jsf>forName</jsf>(someUserInputString);
JsonParser.<jsf>DEFAULT</jsf>.parse(input, c); <jc>// Oops! Security hole!</jc>
</p>
<p>
Juneau does support something similar to a <js>"class"</js> attribute that allows you to define the
POJO type at runtime.
This is the <js>"type"</js> attribute.
The difference is that it's not possible to specify fully-qualified class names in <js>"type"</js> attributes,
and instead can only specify type keys defined through bean dictionaries.
Instead of serializing the fully-qualified class names in the output, we instead serialize type
names that represent those POJO types.
<br>i.e. instead of <js>"class='com.foo.MyBean'"</js>, we instead serialize <js>"type='MyBeanIdentifier'"</js>.
<br>Since bean types are defined at compile time, it's impossible to instantiate arbitrary POJOs.
</p>
<p>
POJO types of generalized input are also inferred through swaps.
Again, since the POJO types are hardcoded at compile time, these should not be subject to demarshalling
vulnerabilities. However, it is possible to circumvent this through your swap implementation as shown
below:
</p>
<p class='bcode'>
<jc>// Don't do this!</jc>
<jk>public class</jk> MyInsecureSwap <jk>extends</jk> PojoSwap&lt;ObjectMap,Object&gt; {
<jk>public</jk> Object swap(BeanSession session, ObjectMap input) <jk>throws</jk> Exception {
<jc>// Security hole!</jc>
<jk>return</jk> Class.<jsf>forName</jsf>(input.getString(<js>"class"</js>)).newInstance();
}
}
</p>
<p>
Note that the {@link org.apache.juneau.jso.JsoParser}, a thin layer of the Juneau Parser API written on
top of plain-old Java Object Serialization which itself is vulnerable to demarshalling issues.
Due to this, the JSO parser is not included in any of the default REST servlet implementations.
Be especially careful when using this parser, particularly if you want to use it for handing
<code>application/x-java-serialized-object</code> input through REST servlets.
</p>
<p>
All other parsers (JSON, URL-Encoding, MessagePack, etc...) work the same way in determining POJO types, so
should be safe from demarshalling vulnerabilities.
</p>
<h5 class='topic'>Dependent libraries</h5>
<p>
When accessing security vulnerabilities of any library, dependent libraries must also be taken into account:
</p>
<ul>
<li>The JSON, HTML, MsgPack, URL-Encoding, and UON parsers are written from scratch and do not rely on
any other parsing technologies.
<li>The XML and HTML parsers uses the built-in Java StAX parser.
This *should* be free from vulnerabilities.
<li>The RDF parsers rely on Apache Jena 2.7.1.
As of <code>7.0.1</code>, no known security vulnerabilities exist that affect Juneau at this time.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="Security.juneau-svl"></a>
<h3 class='topic' onclick='toggle(this)'>13.2 - juneau-svl</h3>
<div class='topic'>
<p>
Care must be used when defining new {@link org.apache.juneau.svl.Var Vars} using the SVL API since mistakes
could potentially expose system properties, environment variables, or even file system files.
</p>
<p>
For recap, the SVL support allows you to embed variables of the form <js>"$X{key}"</js> inside strings that
get resolved to other strings. The resolved strings themselves can also contain variables that also
get recursively resolved.
</p>
<p>
An example of a potential security hole is shown below that could potentially expose any file on a file
system through a REST request:
</p>
<p class='bcode'>
<jk>public</jk> String doUnsafeGet(RestRequest req) {
<jc>// Security hole!</jc>
<jk>return</jk> req.getVarResolver().resolve(<js>"$RQ{foo}"</js>);
}
</p>
<p>
This code is simply echoing the value of the <code>foo</code> query parameter.
Now say for example that a bad actor passes in the query string <js>"foo=$F{/some/file/on/file/system}"</js>.
The <code>$F</code> variable allows you to resolve the contents of files using SVL, and is provided
by default using the built-in variable resolver returned by the <code>RestRequest</code> object.
You've potentially just exposed the contents of that file through your REST interface.
</p>
<p>
In reality, the above security hole does not exist because of the following restrictions:
</p>
<ul class='spaced-list'>
<li>
<code>Vars</code> have two methods {@link org.apache.juneau.svl.Var#allowNested()} and
{@link org.apache.juneau.svl.Var#allowRecurse()} that can be overridden to prevent recursive processing
of string variables. These are both <jk>false</jk> for the <code>$R</code> variable, so the <code>$F</code>
variable in the result will never get processed and instead be treated as plain text.
<li>
The <code>$F</code> variable only allows you to retrieve files within the JVM starting directory.
</ul>
<p>
Even though the built-in Juneau variables are safe, special care is needed when defining your own custom
variables. If your variable resolves user input in any way, it's HIGHLY recommended that you override the
{@link org.apache.juneau.svl.Var#allowNested()} and {@link org.apache.juneau.svl.Var#allowRecurse()}
methods to prevent recursive handling of variables.
</p>
</div>
<!-- =========================================================================================================== -->
<a id="Security.juneau-rest-server"></a>
<h3 class='topic' onclick='toggle(this)'>13.3 - juneau-rest-server</h3>
<div class='topic'>
<p>
Denial of service attacks can be alleviated through the {@link org.apache.juneau.rest.annotation.RestResource#maxInput() maxInput()}
setting. Arbitrarily-large input will trigger an exception before causing out-of-memory errors.
The default value for this setting is 100MB.
</p>
<p>
Since the parsers do not use intermediate DOMs and instead parse directly into Java objects,
deeply nested data structures will almost always trigger stack overflow errors long before memory consumption
becomes an issue. However, this is NOT true of the RDF parsers that use an intermediate DOM. If parsing
RDF, you may want to consider lowering the max-input value above.
</p>
</div>
</div>
<!-- =============================================================================================================== -->
<a id="ReleaseNotes"></a>
<h2 class='topic' onclick='toggle(this)'>14 - Release Notes</h2>
<div class='topic'>
<h5 class='toc'>What's new in each release</h5>
<ul class='toc'>
<li><p><a class='doclink' href='#7.1.0'>7.1.0 (TBD)</a></p>
<li><p><a class='doclink' href='#7.0.1'>7.0.1 (Dec 24, 2017)</a></p>
<li><p><a class='doclink' href='#7.0.0'>7.0.0 (Oct 25, 2017)</a></p>
<li><p><a class='doclink' href='#6.4.0'>6.4.0 (Oct 5, 2017)</a></p>
<li><p><a class='doclink' href='#6.3.1'>6.3.1 (Aug 1, 2017)</a></p>
<li><p><a class='doclink' href='#6.3.0'>6.3.0 (Jun 30, 2017)</a></p>
<li><p><a class='doclink' href='#6.2.0'>6.2.0 (Apr 28, 2017)</a></p>
<li><p><a class='doclink' href='#6.1.0'>6.1.0 (Feb 25, 2017)</a></p>
<li><p><a class='doclink' href='#6.0.1'>6.0.1 (Jan 3, 2017)</a></p>
<li><p><a class='doclink' href='#6.0.0'>6.0.0 (Oct 3, 2016)</a></p>
<li><p><a class='doclink' href='#5.2.0.1'>5.2.0.1 (Mar 23, 2016)</a></p>
<li><p><a class='doclink' href='#5.2.0.0'>5.2.0.0 (Dec 30, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.20'>5.1.0.20 (Sept 5, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.19'>5.1.0.19 (Aug 15, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.18'>5.1.0.18 (Aug 5, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.17'>5.1.0.17 (Aug 3, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.16'>5.1.0.16 (June 28, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.15'>5.1.0.15 (May 24, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.14'>5.1.0.14 (May 10, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.13'>5.1.0.13 (Apr 24, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.12'>5.1.0.12 (Mar 28, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.11'>5.1.0.11 (Feb 14, 2015)</a></p>
<li><p><a class='doclink' href='#5.1.0.10'>5.1.0.10 (Dec 23, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.9'>5.1.0.9 (Dec 1, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.8'>5.1.0.8 (Oct 25, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.7'>5.1.0.7 (Oct 5, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.6'>5.1.0.6 (Sept 21, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.5'>5.1.0.5 (Sept 1, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.4'>5.1.0.4 (Aug 25, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.3'>5.1.0.3 (Jun 28, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.2'>5.1.0.2 (Apr 27, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.1'>5.1.0.1 (Jan 25, 2014)</a></p>
<li><p><a class='doclink' href='#5.1.0.0'>5.1.0.0 (Jan 18, 2014)</a></p>
<li><p><a class='doclink' href='#5.0.0.36'>5.0.0.36 (Dec 18, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.35'>5.0.0.35 (Nov 26, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.34'>5.0.0.34 (Nov 10, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.33'>5.0.0.33 (Oct 20, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.32'>5.0.0.32 (Oct 5, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.31'>5.0.0.31 (Aug 9, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.30'>5.0.0.30 (Aug 8, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.29'>5.0.0.29 (Aug 2, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.28'>5.0.0.28 (July 9, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.27'>5.0.0.27 (July 7, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.26'>5.0.0.26 (Jun 5, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.25'>5.0.0.25 (May 11, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.24'>5.0.0.24 (May 9, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.23'>5.0.0.23 (Apr 14, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.22'>5.0.0.22 (Apr 12, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.21'>5.0.0.21 (Apr 9, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.20'>5.0.0.20 (Apr 7, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.19'>5.0.0.19 (Apr 1, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.18'>5.0.0.18 (Mar 27, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.17'>5.0.0.17 (Mar 25, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.16'>5.0.0.16 (Mar 25, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.15'>5.0.0.15 (Mar 24, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.14'>5.0.0.14 (Mar 23, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.13'>5.0.0.13 (Mar 14, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.12'>5.0.0.12 (Mar 10, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.11'>5.0.0.11 (Mar 8, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.10'>5.0.0.10 (Mar 7, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.9'>5.0.0.9 (Feb 26, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.8'>5.0.0.8 (Jan 30, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.7'>5.0.0.7 (Jan 20, 2013)</a></p>
<li><p><a class='doclink' href='#5.0.0.6'>5.0.0.6 (Oct 30, 2012)</a></p>
<li><p><a class='doclink' href='#5.0.0.5'>5.0.0.5 (Oct 29, 2012)</a></p>
<li><p><a class='doclink' href='#5.0.0.4'>5.0.0.4 (Oct 7, 2012)</a></p>
<li><p><a class='doclink' href='#5.0.0.3'>5.0.0.3 (Oct 3, 2012)</a></p>
<li><p><a class='doclink' href='#5.0.0.2'>5.0.0.2 (Sept 28, 2012)</a></p>
<li><p><a class='doclink' href='#5.0.0.1'>5.0.0.1 (Jun 14, 2012)</a></p>
<li><p><a class='doclink' href='#5.0.0.0'>5.0.0.0 (Jun 11, 2012)</a></p>
</ul>
<!-- =========================================================================================================== -->
<a id="7.1.0"></a>
<h3 class='topic' onclick='toggle(this)'>7.1.0 (TBD)</h3>
<div class='topic'>
<p>
</p>
<h5 class='topic'>juneau-marshall</h5>
<ul class='spaced-list'>
<li>
Significant improvements made to the internals of the Serializer and Parser classes.
<ul>
<li>
Caching improvements on serializers and parsers have reduced execution time of the core
JUnits by approximately 1/3.
<br>The 17000+ JUnit tests now execute in less than 10 seconds and have a cache-reuse hit rate
of 98% (164104 serializers/parsers/bean-contexts retrieved, but only 1801 created from scratch).
<li>
All the various separate <code>Context</code> classes (e.g. <code>JsonSerializerContext</code>) have been folded into
their respective serializer or parser classes (e.g. <code>JsonSerializer</code>).
<br>Additionally, these classes are their own bean contexts.
<br>For example, the class hierarchy of <code>JsonSerializer</code> is now:
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.Context}
<ul>
<li class='jc'>{@link org.apache.juneau.BeanContext}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.Serializer}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.WriterSerializer}
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonSerializer}
</ul>
</ul>
</ul>
</ul>
</ul>
All <code>Context</code> objects are thread-safe and read-only.
<li>
Session objects also now have a consistent class hierarchy.
<br>For example, the class hierarchy of <code>JsonSerializerSession</code> is now:
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.Session}
<ul>
<li class='jc'>{@link org.apache.juneau.BeanSession}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.SerializerSession}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.WriterSerializerSession}
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonSerializerSession}
</ul>
</ul>
</ul>
</ul>
</ul>
Session objects are transient objects that live for the duration of a single parse.
<li>
Builder objects also now have a consistent class hierarchy.
<br>For example, the class hierarchy of <code>JsonSerializerBuilder</code> is now:
<ul class='doctree'>
<li class='jac'>{@link org.apache.juneau.ContextBuilder}
<ul>
<li class='jc'>{@link org.apache.juneau.BeanContextBuilder}
<ul>
<li class='jac'>{@link org.apache.juneau.serializer.SerializerBuilder}
<ul>
<li class='jc'>{@link org.apache.juneau.json.JsonSerializerBuilder}
</ul>
</ul>
</ul>
</ul>
Builder objects are used for building up and creating <code>Context</code> objects.
<li>
The {@link org.apache.juneau.PropertyStore} class has been completely rewritten.
It is now a read-only configuration store build using the {@link org.apache.juneau.PropertyStoreBuilder}
class.
<br>The previous <code>PropertyStore</code> class was overly-complicated with many read/write
locks to ensure thread-safety.
<br>The new design shifts to a builder-based model with read-only <code>PropertyStore</code> objects
that can be used as hash keys.
</ul>
<li>
New SVL variables:
<ul>
<li>{@link org.apache.juneau.svl.vars.CoalesceVar}
<li>{@link org.apache.juneau.svl.vars.CoalesceAndRecurseVar}
</ul>
<li>
Improvements to the HTTP-Part APIs.
<br>The existing <code>PartSerializer</code>/<code>PartParser</code> classes
have been replaced with the following all located in the new <code>org.apache.juneau.httppart</code> package:
<ul class='doctree'>
<li class='jp'>{@link org.apache.juneau.httppart}
<ul>
<li class='jc'>{@link org.apache.juneau.httppart.HttpPartType}
<li class='jic'>{@link org.apache.juneau.httppart.HttpPartSerializer}
<ul>
<li class='jc'>{@link org.apache.juneau.httppart.UonPartSerializer}
<li class='jc'>{@link org.apache.juneau.httppart.SimpleUonPartSerializer}
<li class='jc'>{@link org.apache.juneau.httppart.SimplePartSerializer}
</ul>
<li class='jic'>{@link org.apache.juneau.httppart.HttpPartParser}
<ul>
<li class='jc'>{@link org.apache.juneau.httppart.UonPartParser}
<li class='jc'>{@link org.apache.juneau.httppart.SimplePartParser}
</ul>
</ul>
</ul>
Code for marshalling of parts have been removed from the URL-Encoding serializers and parsers.
<li>
<code>ContextBuilder.property(String,Object)</code> renamed to {@link org.apache.juneau.ContextBuilder#set(String,Object)}.
<li>
<code>ResourceFinder</code> class has been replaced with the following:
<ul>
<li>{@link org.apache.juneau.utils.ClasspathResourceFinder}
<li>{@link org.apache.juneau.utils.ClasspathResourceFinderSimple}
<li>{@link org.apache.juneau.utils.ClasspathResourceFinderBasic}
<li>{@link org.apache.juneau.utils.ClasspathResourceFinderRecursive}
<li>{@link org.apache.juneau.utils.ClasspathResourceManager}
</ul>
<li>
New methods on {@link org.apache.juneau.serializer.SerializerSession}:
<ul>
<li>{@link org.apache.juneau.serializer.SerializerSession#getListener() getListener()}
<li>{@link org.apache.juneau.serializer.SerializerSession#getListener(Class) getListener(Class)}
</ul>
<li>
New methods on {@link org.apache.juneau.parser.ParserSession}:
<ul>
<li>{@link org.apache.juneau.parser.ParserSession#getListener() getListener()}
<li>{@link org.apache.juneau.parser.ParserSession#getListener(Class) getListener(Class)}
</ul>
<li>
New {@link org.apache.juneau.parser.Parser#PARSER_unbuffered} setting allows you to disable internal
buffering on the JSON and UON parsers so that they can be used to read continous streams of objects.
<li>
New {@link org.apache.juneau.json.JsonParser#JSON_validateEnd} and {@link org.apache.juneau.uon.UonParser#UON_validateEnd}
settings allow you to control whether we validate that there is no garbage at the end of the parsed input.
<li>
New {@link org.apache.juneau.parser.Parser#PARSER_autoCloseStreams} setting allows input streams and
readers passed into parsers to be automatically closed after parsing.
<li>
Syntax changed on unswap method on {@link org.apache.juneau.transform.Surrogate} classes.
<br>It's now a regular method instead of a static method.
<li>
{@link org.apache.juneau.annotation.Swap @Swap} annotation can now be used with
{@link org.apache.juneau.transform.Surrogate} classes.
<li>
New support for <a class='doclink' href='#juneau-marshall.PojoBuilders'>POJO Builders</a>.
</ul>
<h5 class='topic'>juneau-config</h5>
<ul class='spaced-list'>
<li>
The Config API has been completely revamped.
<br>New features include:
<ul>
<li>Support for pluggable storage.
<li>File-system watcher integration support.
<br>Changes made to file system files now automatically reflected in configurations
and interface proxies.
<li>New builder-based design.
</ul>
</ul>
<h5 class='topic'>juneau-dto</h5>
<ul class='spaced-list'>
<li>
Enhancements to Swagger DTO:
<ul>
<li>New methods for setting and retrieving properties via name:
<ul>
<li>{@link org.apache.juneau.dto.swagger.SwaggerElement#get(String,Class)}
<li>{@link org.apache.juneau.dto.swagger.SwaggerElement#set(String,Object)}
</ul>
<li>
Support for setting non-standard fields such as <js>"$ref"</js> via getter and setter
above.
<li>
Setter methods that take in beans and collections of beans can now take in
JSON strings.
</ul>
</ul>
<h5 class='topic'>juneau-rest-server</h5>
<ul class='spaced-list'>
<li>
The <js>"$R{...}"</js> variable has been split into the following:
<ul>
<li><js>"$RA{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RequestAttributeVar}, first non-null value returned by <code>HttpServletRequest.getAttribute(String)</code>.
<li><js>"$RF{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RequestFormDataVar}, first non-null value returned by {@link org.apache.juneau.rest.RestRequest#getFormData(String)}.
<li><js>"$RH{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RequestHeaderVar}, first non-null value returned by {@link org.apache.juneau.rest.RestRequest#getHeader(String)}.
<li><js>"$RI{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RestInfoVar}, first non-null value returned by {@link org.apache.juneau.rest.RestRequest#getInfoProvider()}.
<br>The possible values are:
<ul>
<li><js>"contact"</js> - Value returned by {@link org.apache.juneau.dto.swagger.Info#getContact()}
<li><js>"description"</js> - Value returned by {@link org.apache.juneau.rest.RestInfoProvider#getDescription(RestRequest)}
<li><js>"externalDocs"</js> - Value returned by {@link org.apache.juneau.dto.swagger.Swagger#getExternalDocs()}
<li><js>"license"</js> - Value returned by {@link org.apache.juneau.dto.swagger.Info#getLicense()}
<li><js>"methodDescription"</js> - Value returned by {@link org.apache.juneau.rest.RestInfoProvider#getMethodDescription(Method,RestRequest)}
<li><js>"methodSummary"</js> - Value returned by {@link org.apache.juneau.rest.RestInfoProvider#getMethodSummary(Method,RestRequest)}
<li><js>"siteName"</js> - Value returned by {@link org.apache.juneau.rest.RestInfoProvider#getSiteName(RestRequest)}
<li><js>"tags"</js> - Value returned by {@link org.apache.juneau.dto.swagger.Swagger#getTags()}
<li><js>"termsOfService"</js> - Value returned by {@link org.apache.juneau.dto.swagger.Info#getTermsOfService()}
<li><js>"title"</js> - See {@link org.apache.juneau.rest.RestInfoProvider#getTitle(RestRequest)}
<li><js>"version"</js> - See {@link org.apache.juneau.dto.swagger.Info#getVersion()}
</ul>
<li><js>"$RP{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RequestPathVar}, first non-null value returned by {@link org.apache.juneau.rest.RestRequest#getPath(String)}.
<li><js>"$RQ{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RequestQueryVar}, first non-null value returned by {@link org.apache.juneau.rest.RestRequest#getQuery(String)}
<li><js>"$R{key1[,key2...]}"</js> - {@link org.apache.juneau.rest.vars.RequestVar}, first non-null other request variable.
<br>The possible values are:
<ul>
<li><js>"contextPath"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getContextPath()}
<li><js>"method"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getMethod()}
<li><js>"methodDescription"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getMethodDescription()}
<li><js>"methodSummary"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getMethodSummary()}
<li><js>"pathInfo"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getPathInfo()}
<li><js>"requestParentURI"</js> - Value returned by {@link org.apache.juneau.UriContext#getRootRelativePathInfoParent()}
<li><js>"requestURI"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getRequestURI()}
<li><js>"resourceDescription"</js> - Value returned by {@link org.apache.juneau.rest.RestRequest#getResourceDescription()}
<li><js>"resourceTitle"</js> - See {@link org.apache.juneau.rest.RestRequest#getResourceTitle()}
<li><js>"servletParentURI"</js> - Value returned by {@link org.apache.juneau.UriContext#getRootRelativeServletPathParent()}
<li><js>"servletPath"</js> - See {@link org.apache.juneau.rest.RestRequest#getServletPath()}
<li><js>"servletURI"</js> - See {@link org.apache.juneau.UriContext#getRootRelativeServletPath()}
<li><js>"siteName"</js> - See {@link org.apache.juneau.rest.RestRequest#getSiteName()}
</ul>
</ul>
<li>
Refactored the <code>RestConfig</code> class into {@link org.apache.juneau.rest.RestContextBuilder}.
<br>Settings on {@link org.apache.juneau.rest.RestContext} objects can now be set declaratively through the
following new properties:
<ul>
<li>{@link org.apache.juneau.rest.RestContext#REST_allowHeaderParams REST_allowHeaderParams}
<li>{@link org.apache.juneau.rest.RestContext#REST_allowBodyParam REST_allowBodyParam}
<li>{@link org.apache.juneau.rest.RestContext#REST_allowedMethodParams REST_allowedMethodParams}
<li>{@link org.apache.juneau.rest.RestContext#REST_renderResponseStackTraces REST_renderResponseStackTraces}
<li>{@link org.apache.juneau.rest.RestContext#REST_useStackTraceHashes REST_useStackTraceHashes}
<li>{@link org.apache.juneau.rest.RestContext#REST_defaultCharset REST_defaultCharset}
<li>{@link org.apache.juneau.rest.RestContext#REST_maxInput REST_maxInput}
<li>{@link org.apache.juneau.rest.RestContext#REST_paramResolvers REST_paramResolvers}
<li>{@link org.apache.juneau.rest.RestContext#REST_converters REST_converters}
<li>{@link org.apache.juneau.rest.RestContext#REST_guards REST_guards}
<li>{@link org.apache.juneau.rest.RestContext#REST_responseHandlers REST_responseHandlers}
<li>{@link org.apache.juneau.rest.RestContext#REST_defaultRequestHeaders REST_defaultRequestHeaders}
<li>{@link org.apache.juneau.rest.RestContext#REST_defaultResponseHeaders REST_defaultResponseHeaders}
<li>{@link org.apache.juneau.rest.RestContext#REST_produces REST_produces}
<li>{@link org.apache.juneau.rest.RestContext#REST_consumes REST_consumes}
<li>{@link org.apache.juneau.rest.RestContext#REST_clientVersionHeader REST_clientVersionHeader}
<li>{@link org.apache.juneau.rest.RestContext#REST_resourceResolver REST_resourceResolver}
<li>{@link org.apache.juneau.rest.RestContext#REST_logger REST_logger}
<li>{@link org.apache.juneau.rest.RestContext#REST_callHandler REST_callHandler}
<li>{@link org.apache.juneau.rest.RestContext#REST_infoProvider REST_infoProvider}
<li>{@link org.apache.juneau.rest.RestContext#REST_path REST_path}
<li>{@link org.apache.juneau.rest.RestContext#REST_contextPath REST_contextPath}
<li>{@link org.apache.juneau.rest.RestContext#REST_staticFiles REST_staticFiles}
<li>{@link org.apache.juneau.rest.RestContext#REST_staticFileResponseHeaders REST_staticFileResponseHeaders}
<li>{@link org.apache.juneau.rest.RestContext#REST_classpathResourceFinder REST_classpathResourceFinder}
<li>{@link org.apache.juneau.rest.RestContext#REST_useClasspathResourceCaching REST_useClasspathResourceCaching}
<li>{@link org.apache.juneau.rest.RestContext#REST_widgets REST_widgets}
<li>{@link org.apache.juneau.rest.RestContext#REST_mimeTypes REST_mimeTypes}
</ul>
<li>
Support for static files has been simplified and improved.
<ul>
<li>Syntax on {@link org.apache.juneau.rest.annotation.RestResource#staticFiles() @RestResource.staticFiles()} has been simplified, and
now allows you to specify response headers in the strings.
<li>Response headers for static files can also be configured through
{@link org.apache.juneau.rest.RestContext#REST_staticFileResponseHeaders REST_staticFileResponseHeaders}.
<li>Static file in-memory caching now configurable through
{@link org.apache.juneau.rest.RestContext#REST_useClasspathResourceCaching REST_useClasspathResourceCaching}.
<li>Static file retrieval can be customized through
{@link org.apache.juneau.rest.RestContext#REST_classpathResourceFinder REST_classpathResourceFinder}
</ul>
<li>
Eliminated the <code>RestMatcherReflecting</code> class.
<br>You can now simply create a {@link org.apache.juneau.rest.RestMatcher} that has a public constructor that
takes in the server and method arguments.
<li>
<code>@RestResource.allowMethodParam</code> renamed to {@link org.apache.juneau.rest.annotation.RestResource#allowedMethodParams}.
<li>
<code>@RestMethod.serializersInherit</code> and <code>@RestMethod.parsersInherit</code> replaced with
simplified {@link org.apache.juneau.rest.annotation.RestMethod#inherit() @RestMethod.inherit()}.
<li>
Changes to {@link org.apache.juneau.rest.RequestFormData}:
<ul>
<li>{@link org.apache.juneau.rest.RequestFormData#addDefault(Map) addDefault(Map)} takes in a
<code>Map&lt;String,Object&gt;</code> instead of <code>Map&lt;String,String&gt;</code>.
</ul>
<li>
Changes to {@link org.apache.juneau.rest.RequestHeaders}:
<ul>
<li>{@link org.apache.juneau.rest.RequestHeaders#addDefault(Map) addDefault(Map)} takes in a
<code>Map&lt;String,Object&gt;</code> instead of <code>Map&lt;String,String&gt;</code>.
</ul>
<li>
Changes to {@link org.apache.juneau.rest.RequestQuery}:
<ul>
<li>{@link org.apache.juneau.rest.RequestQuery#addDefault(Map) addDefault(Map)} takes in a
<code>Map&lt;String,Object&gt;</code> instead of <code>Map&lt;String,String&gt;</code>.
</ul>
<li>
Changes to {@link org.apache.juneau.rest.RestContext}:
<ul>
<li><code>getResource(String,Locale)</code> renamed to {@link org.apache.juneau.rest.RestContext#getClasspathResource(String,Locale) getClasspathResource(String,Locale)}
<li><code>getResourceAsString(String,Locale)</code> renamed to {@link org.apache.juneau.rest.RestContext#getClasspathResourceAsString(String,Locale) getClasspathResourceAsString(String,Locale)}
<li><code>getResource(Class,MediaType,String,Locale)</code> renamed to {@link org.apache.juneau.rest.RestContext#getClasspathResource(Class,MediaType,String,Locale) getClasspathResourceAsString(Class,MediaType,String,Locale)}
<li>New method {@link org.apache.juneau.rest.RestContext#getClasspathResource(Class,String,Locale) getClasspathResource(Class,String,Locale)}.
<li>New method {@link org.apache.juneau.rest.RestContext#getClasspathResourceAsString(Class,String,Locale) getClasspathResourceAsString(Class,String,Locale)}.
<li>New method {@link org.apache.juneau.rest.RestContext#getClasspathResource(Class,Class,MediaType,String,Locale) getClasspathResource(Class,Class,MediaType,String,Locale)}.
<li>{@link org.apache.juneau.rest.RestContext#getDefaultRequestHeaders() getDefaultRequestHeaders} returns a
<code>Map&lt;String,Object&gt;</code> instead of <code>Map&lt;String,String&gt;</code>.
<li>{@link org.apache.juneau.rest.RestContext#getDefaultResponseHeaders() getDefaultRequestHeaders} returns a
<code>Map&lt;String,Object&gt;</code> instead of <code>Map&lt;String,String&gt;</code>.
</ul>
<li>
Changes to {@link org.apache.juneau.rest.RestRequest}:
<ul>
<li><code>getSupportedMediaTypes()</code> replaced with
{@link org.apache.juneau.rest.RestRequest#getConsumes() getConsumes()} and
{@link org.apache.juneau.rest.RestRequest#getProduces() getProduces()}.
<li><code>getReaderResource(String,boolean,MediaType)</code> renamed to
{@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String,boolean,MediaType) getClasspathReaderResource(String,boolean,MediaType)}
<li><code>getReaderResource(String,boolean)</code> renamed to
{@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String,boolean) getClasspathReaderResource(String,boolean)}
<li><code>getReaderResource(String)</code> renamed to
{@link org.apache.juneau.rest.RestRequest#getClasspathReaderResource(String) getClasspathReaderResource(String)}
</ul>
<li>
Changes to {@link org.apache.juneau.rest.annotation.RestResource @RestResource}:
<ul>
<li>New {@link org.apache.juneau.rest.annotation.RestResource#mimeTypes() mimeTypes()} annotation.
</ul>
<li>
Changes to {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod}:
<ul>
<li>New {@link org.apache.juneau.rest.annotation.RestMethod#consumes() consumes()} and
{@link org.apache.juneau.rest.annotation.RestMethod#produces() produces()}
for overriding the supported media types inferred from the serializers and parsers.
</ul>
<li>
<code>RestCallHandler</code> split up into {@link org.apache.juneau.rest.RestCallHandler} and
{@link org.apache.juneau.rest.RestCallHandlerDefault}
<li>
<code>RestInfoProvider</code> split up into {@link org.apache.juneau.rest.RestInfoProvider} and
{@link org.apache.juneau.rest.RestInfoProviderDefault}
<li>
<code>RestLogger</code> split up into {@link org.apache.juneau.rest.RestLogger},
{@link org.apache.juneau.rest.RestLoggerDefault} and {@link org.apache.juneau.rest.RestLoggerNoOp}
<li>
<code>RestResourceResolverSimple</code> renamed to {@link org.apache.juneau.rest.RestResourceResolverDefault}
<li>
Introduced the following classes that helps make the code more understandable:
<ul>
<li>{@link org.apache.juneau.rest.RestContextProperties}
<li>{@link org.apache.juneau.rest.RestMethodProperties}
<li>{@link org.apache.juneau.rest.RequestProperties}
</ul>
<li>
Eliminated the <code>@Messages</code> and <code>@Properties</code> REST java method parameter
annotations.
<br>These aren't needed anymore since you can just pass in <code>MessageBundle</code> and
<code>RestRequestProperties</code> as unannotated parameters.
<li>
Revamped the {@link org.apache.juneau.rest.RestInfoProvider} class.
<li>
New builder classes:
<ul>
<li>{@link org.apache.juneau.rest.ReaderResourceBuilder}
<li>{@link org.apache.juneau.rest.StreamResourceBuilder}
</ul>
<li>
{@link org.apache.juneau.rest.RestResponse#getNegotiatedOutputStream()} now returns a
{@link org.apache.juneau.rest.FinishableServletOutputStream} and {@link org.apache.juneau.rest.RestResponse#getNegotiatedWriter()}
now returns a {@link org.apache.juneau.rest.FinishablePrintWriter} that allows you to finish the output
without closing the stream.
<br>The {@link org.apache.juneau.rest.response.DefaultHandler} class now calls <code>finish()</code>
instead of <code>close()</code> on the stream.
<li>
Added the following annotations to the {@link org.apache.juneau.rest.RestServletDefault} class
(which were previously defined on the {@link org.apache.juneau.microservice.Resource} class):
<p class='bcode'>
<ja>@RestResource</ja>(
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>
},
stylesheet=<js>"$C{REST/stylesheet,servlet:/styles/devops.css}"</js>
),
<jc>// Optional external configuration file.</jc>
config=<js>"$S{juneau.configFile}"</js>
)
</p>
</ul>
<h5 class='topic'>juneau-rest-client</h5>
<ul class='spaced-list'>
<li>
New configuration property {@link org.apache.juneau.rest.client.RestClient#RESTCLIENT_query} and
builder method {@link org.apache.juneau.rest.client.RestClientBuilder#query(String,Object)}.
<li>
API changes to replace <code>PartSerializer</code> with {@link org.apache.juneau.httppart.HttpPartSerializer}.
<br>The default value is now {@link org.apache.juneau.httppart.SimpleUonPartSerializer} which will
serialize strings as plain-text and collections/arrays as comma-delimited lists.
<br>We decided to change the default behavior in favor of practicality over purity.
<li>
New methods on {@link org.apache.juneau.rest.client.RestCall} class:
<ul>
<li>{@link org.apache.juneau.rest.client.RestCall#getResponseHeader(String) getResponseHeader(String)}
<li>{@link org.apache.juneau.rest.client.RestCall#getResponseCode() getResponseCode()}
</ul>
<li>
{@link org.apache.juneau.rest.client.RestCall} and {@link org.apache.juneau.rest.client.RestClient}
now implement the <code>Closeable</code> interface.
</ul>
<h5 class='topic'>Documentation</h5>
<ul class='spaced-list'>
<li>
New and updated sections in overview document:
<ul>
<li><p><a class='doclink' href='#juneau-marshall.PojoSwaps'>PojoSwaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.PerMediaTypePojoSwaps'>Per-media-type PojoSwaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.OneWayPojoSwaps'>One-way PojoSwaps</a></p>
<li><p><a class='doclink' href='#juneau-marshall.SwapAnnotation'>@Swap Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.SwapMethods'>Swap Methods</a></p>
<li><p><a class='doclink' href='#juneau-marshall.SurrogateClasses'>Surrogate Classes</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanAnnotation'>@Bean Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanPropertyAnnotation'>@BeanProperty Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanConstructorAnnotation'>@BeanConstructor Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanIgnoreAnnotation'>@BeanIgnore Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.NamePropertyAnnotation'>@NameProperty Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.ParentPropertyAnnotation'>@ParentProperty Annotation</a></p>
<li><p><a class='doclink' href='#juneau-marshall.URIs'>URIs</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BeanFilters'>BeanFilters</a></p>
<li><p><a class='doclink' href='#juneau-marshall.StopClasses'>Stop Classes</a></p>
<li><p><a class='doclink' href='#juneau-marshall.BypassSerialization'>Bypass Serialization</a></p>
</ul>
<li>
Updated javadocs:
<ul>
<li>{@link org.apache.juneau.BeanContext}
<li>{@link org.apache.juneau.BeanContextBuilder}
<li>{@link org.apache.juneau.rest.RestContext}
<li>{@link org.apache.juneau.rest.RestContextBuilder}
<li>Swagger DTOs.
</ul>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="7.0.1"></a>
<h3 class='topic' onclick='toggle(this)'>7.0.1 (Dec 24, 2017)</h3>
<div class='topic'>
<p>
This release is a minor update.
It includes the following prereq updates:
</p>
<ul class='spaced-list'>
<li>Apache HttpClient: 4.5.3 to 4.5.4
<li>Eclipse Jetty: 9.4.6.v20170531 to 9.4.8.v20171121
</ul>
<h5 class='topic'>juneau-marshall</h5>
<ul class='spaced-list'>
<li>New static <code>create()</code> methods for builders on serializers and parsers.
<br>This simplifies the syntax of creation of serializers and parsers by scratch.
<p class='bcode'>
<jc>// Old way</jc>
JsonSerializer s1 = <jk>new</jk> JsonSerializerBuilder().ws().build();
<jc>// New way</jc>
JsonSerializer s2 = JsonSerializer.<jsm>create</jsm>().ws().build();
</p>
<br>The same static create methods have also been added to the following classes:
<ul>
<li>{@link org.apache.juneau.serializer.SerializerGroup#create()}
<li>{@link org.apache.juneau.parser.ParserGroup#create()}
<li>{@link org.apache.juneau.encoders.EncoderGroup#create()}
<li>{@link org.apache.juneau.rest.client.RestClient#create()}
<li><code><del>ConfigFile.create()</del></code>
</ul>
<li>
The order of the parameters in {@link org.apache.juneau.serializer.SerializerSession#serialize(Object,Object)}
has been change to match {@link org.apache.juneau.serializer.Serializer#serialize(Object,Object)}.
<li>
Fixed some bugs in the XML parser related to whitespace and comments.
</ul>
<h5 class='topic'>juneau-svl</h5>
<ul class='spaced-list'>
<li>New methods on {@link org.apache.juneau.svl.Var} class to restrict when nested and embedded variables
are resolved.
<ul>
<li>{@link org.apache.juneau.svl.Var#allowNested()}
<li>{@link org.apache.juneau.svl.Var#allowRecurse()}
</ul>
</ul>
<h5 class='topic'>juneau-rest-server</h5>
<ul class='spaced-list'>
<li>
New {@link org.apache.juneau.rest.annotation.RestResource#maxInput() @RestResource.maxInput()} and
{@link org.apache.juneau.rest.annotation.RestMethod#maxInput() @RestMethod.maxInput()} for alleviating
potential DoS attacks.
</ul>
<h5 class='topic'>juneau-microservice-server</h5>
<ul class='spaced-list'>
<li>
New pluggable console commands.
<br>When you start up the microservice, you'll now see the following:
<p class='bcode'>
Running class 'RestMicroservice' using config file 'examples.cfg'.
Server started on port 10000
List of available commands:
exit -- Shut down service
restart -- Restarts service
help -- Commands help
echo -- Echo command
&gt; <span style='color:green'>help help</span>
NAME
help -- Commands help
SYNOPSIS
help [command]
DESCRIPTION
When called without arguments, prints the descriptions of all available commands.
Can also be called with one or more arguments to get detailed information on a command.
EXAMPLES
List all commands:
&gt; help
List help on the help command:
&gt; help help
&gt;
</p>
<p>
Commands are pluggable and extensible through the config file.
<p class='bcode'>
<cc>#=======================================================================================================================
# Console settings
#=======================================================================================================================</cc>
<cs>[Console]</cs>
<ck>enabled</ck> = <cv>true</cv>
<cc># List of available console commands.
# These are classes that implements ConsoleCommand that allow you to submit commands to the microservice via
# the console.
# When listed here, the implementations must provide a no-arg constructor.
# They can also be provided dynamically by overriding the Microservice.createConsoleCommands() method.</cc>
<ck>commands</ck> =
<cv>org.apache.juneau.microservice.console.ExitCommand,
org.apache.juneau.microservice.console.RestartCommand,
org.apache.juneau.microservice.console.HelpCommand</cv>
</p>
<ul>
<li>New classes:
<ul>
<li>{@link org.apache.juneau.microservice.console.ConsoleCommand}
<li>{@link org.apache.juneau.microservice.console.ExitCommand}
<li>{@link org.apache.juneau.microservice.console.RestartCommand}
<li>{@link org.apache.juneau.microservice.console.HelpCommand}
</ul>
<li>New methods on {@link org.apache.juneau.microservice.Microservice}
<ul>
<li>{@link org.apache.juneau.microservice.Microservice#startConsole() startConsole()}
<li>{@link org.apache.juneau.microservice.Microservice#createConsoleCommands() createConsoleCommands()}
<li>{@link org.apache.juneau.microservice.Microservice#getConsoleReader() getConsoleReader()}
<li>{@link org.apache.juneau.microservice.Microservice#getConsoleWriter() getConsoleWriter()}
</ul>
</ul>
<li>
Console input reader and output writer can now be overridden.
<li>
Console strings are now internationalized.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="7.0.0"></a>
<h3 class='topic' onclick='toggle(this)'>7.0.0 (Oct 25, 2017)</h3>
<div class='topic'>
<p>
This release ups the Java prerequisite to Java 7.
</p>
<h5 class='topic'>juneau-marshall</h5>
<ul class='spaced-list'>
<li>
New class {@link org.apache.juneau.http.HttpMethodName} with valid static string HTTP method names.
</ul>
<h5 class='topic'>juneau-dto</h5>
<ul class='spaced-list'>
<li>
Class <code>org.apache.juneau.dto.Link</code> renamed to {@link org.apache.juneau.dto.LinkString}.
Helps avoid confusion since there are other Link classes in the library.
</ul>
<h5 class='topic'>juneau-rest-server</h5>
<ul class='spaced-list'>
<li>
Annotation <code><ja>@HtmlDoc</ja>(links)</code> renamed to {@link org.apache.juneau.rest.annotation.HtmlDoc#navlinks() navlinks}.
<li>
New annotation {@link org.apache.juneau.rest.annotation.HtmlDoc#head() @HtmlDoc.head()}.
<br>Allows you to specify arbitrary HTML content in the <xt>&lt;head&gt;</xt> section of the page.
<li>
Removed annotation <code><ja>@HtmlDoc</ja>(favIcon)</code>.
<br>This was a discouraged way of defining fav-icons anyway, and with the addition of
<code><ja>@HtmlDoc</ja>(head)</code>, you can define them using:
<p class='bcode'>
head={
<js>"&lt;link rel='icon' href='$U{servlet:/htdocs/juneau.png}'/&gt;"</js>
}
</p>
<li>
Removed several of the HTMLDOC-related methods from the <code>RestResponse/RestConfig/RestContext</code>
classes and moved it into the new {@link org.apache.juneau.rest.HtmlDocBuilder} class.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.4.0"></a>
<h3 class='topic' onclick='toggle(this)'>6.4.0 (Oct 5, 2017)</h3>
<div class='topic'>
<p>
The major change in this release is the project structure.
</p>
<p>
The library now consists of the following artifacts found in the Maven group <code>"org.apache.juneau"</code>:
</p>
<table class='styled' style='min-width:800px;'>
<tr>
<th>Category</th><th>Maven Artifacts</th><th>Description</th><th>Prereqs</th>
</tr>
<tr class='dark bb'>
<td rowspan="5" style='text-align:center;font-weight:bold;padding:20px;'>Juneau Core</td>
<td class='code'>juneau-marshall</td>
<td>Serializers and parsers for:
<ul style='margin:0px 10px;'>
<li>JSON
<li>XML
<li>HTML
<li>UON
<li>URL-Encoding
<li>MessagePack
<li>SOAP/XML
<li>CSV
<li>BSON (coming soon)
<li>YAML (coming soon)
<li>Protobuf (coming soon)
</ul>
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
</ul>
</td>
</tr>
<tr class='dark bb'>
<td class='code'>juneau-marshall-rdf</td>
<td>
Serializers and parsers for:
<ul style='margin:0px 10px;'>
<li>RDF/XML
<li>RDF/XML-Abbrev
<li>N-Triple
<li>Turtle
<li>N3
</ul>
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Apache Jena 2.7.1
</ul>
</td>
</tr>
<tr class='dark bb'>
<td class='code'>juneau-dto</td>
<td>
Data Transfer Objects for:
<ul style='margin:0px 10px;'>
<li>HTML5
<li>Atom
<li>Cognos
<li>JSON-Schema
<li>Swagger 2.0
</ul>
</td>
<td><ul style='margin:0px 10px;'><li>Java 6</li></ul></td>
</tr>
<tr class='dark bb'>
<td class='code'>juneau-svl</td>
<td>
Simple Variable Language API
</td>
<td><ul style='margin:0px 10px;'><li>Java 6</li></ul></td>
</tr>
<tr class='dark bb'>
<td class='code'>juneau-config</td>
<td>
Configuration file API
</td>
<td><ul style='margin:0px 10px;'><li>Java 6</li></ul></td>
</tr>
<tr class='light bb'>
<td rowspan="3" style='text-align:center;font-weight:bold;padding:20px;'>Juneau REST</td>
<td class='code'>juneau-rest-server</td>
<td>
REST Servlet API
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Servlet 3.1
</ul>
</td>
</tr>
<tr class='light bb'>
<td class='code'>juneau-rest-server-jaxrs</td>
<td>
Optional JAX-RS support
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>JAX-RS 2.0
</ul>
</td>
</tr>
<tr class='light bb'>
<td class='code'>juneau-rest-client</td>
<td>
REST Client API
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Apache HttpClient 4.5
</ul>
</td>
</tr>
<tr class='dark bb'>
<td rowspan="2" style='text-align:center;font-weight:bold;padding:20px;'>Juneau Microservice</td>
<td class='code'>juneau-microservice-server</td>
<td>
REST Microservice Server API
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 8
<li>Eclipse Jetty 9.4.3
</ul>
</td>
</tr>
<tr class='dark bb'>
<td class='code'>juneau-microservice-template</td>
<td>
Developer template project
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 8
<li>Eclipse Jetty 9.4.3
</ul>
</td>
</tr>
<tr class='light bb'>
<td rowspan="2" style='text-align:center;font-weight:bold;padding:20px;'>Examples</td>
<td class='code'><code>juneau-examples-core</code></td>
<td>
Core code examples
</td>
<td></td>
</tr>
<tr class='light bb'>
<td class='code'><code>juneau-examples-rest</code></td>
<td>
REST code examples
</td>
<td></td>
</tr>
<tr class='dark bb'>
<td rowspan="1" style='text-align:center;font-weight:bold;padding:20px;'>Juneau All</td>
<td class='code'><code>juneau-all</code></td>
<td>
Combination of the following:
<ul style='margin:0px 10px;'>
<li>juneau-marshall
<li>juneau-dto
<li>juneau-svl
<li>juneau-config
<li>juneau-rest-server
<li>juneau-rest-client
</ul>
</td>
<td>
<ul style='margin:0px 10px;'>
<li>Java 6
<li>Servlet 3.1
<li>Apache HttpClient 4.5
</ul>
</td>
</tr>
</table>
<h5 class='topic'>juneau-marshall</h5>
<ul class='spaced-list'>
<li>
Improvements to swap support.
<ul>
<li>New {@link org.apache.juneau.annotation.Swap @Swap} annotation.
<br>Replaces the <code>@Pojo</code> and <code>@BeanProperty.swap()</code> annotations.
<li>Support for per-media-type swaps.
<br>Programmatic example:
<p class='bcode'>
<ja>@Swap</ja>(MyJsonOnlySwap.<jk>class</jk>)
<jk>public class</jk> MyPojo {}
<jk>public class</jk> MyJsonOnlySwap <jk>extends</jk> PojoSwap&lt;MyPojo,String&gt; {
<jk>public</jk> MediaType[] forMediaTypes() {
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/json"</js>);
}
<jk>public</jk> String swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
<jk>return</jk> <js>"It's JSON!"</js>;
}
</p>
<br>Annotated example:
<p class='bcode'>
<ja>@Swap</ja>(impl=ToStringSwap.<jk>class</jk>, mediaTypes=<js>"&#42;/json"</js>)
<jk>public class</jk> MyBean { ... }
<jk>public class</jk> ToStringSwap <jk>extends</jk> PojoSwap&lt;Object,String&gt; {
<jk>public</jk> String swap(BeanSession session, Object o) <jk>throws</jk> Exception {
<jk>return</jk> o.toString();
}
}
</p>
<li>Support for templated swaps which provide additional context information for a swap.
<br>The following is an example of a templated swap class used to serialize POJOs to HTML using FreeMarker:
<p class='bcode'>
<jc>// Our abstracted templated swap class.</jc>
<jk>public abstract class</jk> FreeMarkerSwap <jk>extends</jk> PojoSwap&lt;Object,Reader&gt; {
<jk>public</jk> MediaType[] forMediaTypes() {
<jk>return</jk> MediaType.<jsm>forStrings</jsm>(<js>"&#42;/html"</js>);
}
<jk>public</jk> Reader swap(BeanSession session, Object o, String template) <jk>throws</jk> Exception {
<jk>return</jk> getFreeMarkerReader(template, o); <jc>// Some method that creates raw HTML.</jc>
}
}
</p>
<p class='bcode'>
<ja>@Swap</ja>(impl=FreeMarkerSwap.<jk>class</jk>, template=<js>"MyPojo.div.ftl"</js>)
<jk>public class</jk> MyPojo {}
</p>
<li>New {@link org.apache.juneau.annotation.Swaps @Swaps} annotation for defining multiple swaps
against the same POJO when they're differentiated by media types:
<p class='bcode'>
<ja>@Swaps</ja>(
{
<ja>@Swap</ja>(MyJsonSwap.<jk>class</jk>),
<ja>@Swap</ja>(MyXmlSwap.<jk>class</jk>),
<ja>@Swap</ja>(MyOtherSwap.<jk>class</jk>)
}
)
<jk>public class</jk> MyPojo {}
</p>
</ul>
<li>
New {@link org.apache.juneau.transform.Surrogate} interface for identifying surrogate classes.
<li>
Serializers can now serialize to {@link java.util.StringBuilder StringBuilders}.
<li>
Serializers now serialize the contents of {@link java.io.Reader Readers} and {@link java.io.InputStream InputStreams}
directly to the output stream or writer.
<br>When used with conjunction with <code>PojoSwaps</code>, this can be used to provide customized
output for specific content types.
<p class='bcode'>
<ja>@Pojo</ja>(swap=MyBeanSwap.<jk>class</jk>)
<jk>public class</jk> MyBean {...}
<jk>public class</jk> MyBeanSwap <jk>extends</jk> PojoSwap&lt;MyBean,Object&gt; {
<jk>public</jk> Object swap(BeanSession session, MyPojo o) <jk>throws</jk> Exception {
MediaType mt = session.getMediaType();
<jk>if</jk> (mt.hasSubType(<js>"json"</js>))
<jk>return new</jk> StringReader(<js>"{foo:'bar'}"</js>); <jc>// Custom JSON output</jc>
<jk>return</jk> o; <jc>// Otherwise treat as normal bean</jc>
}
}
<jc>// Produces "{foo:'bar'}"</jc>
String json = JsonSerializer.<jsf>DEFAULT_LAX</jsf>.toString(<jk>new</jk> MyBean());
</p>
<br>This feature helps with the implementation of language-agnostic template support such as for
using FreeMaker to serialize POJOs to HTML.
<li>
{@link org.apache.juneau.serializer.SerializerSession} and {@link org.apache.juneau.parser.ParserSession}
objects are now reusable if used within the same thread.
<p class='bcode'>
<jc>// Old way (still works)</jc>
JsonSerializer.<jsf>DEFAULT</jsf>.serialize(writer1, pojo1);
JsonSerializer.<jsf>DEFAULT</jsf>.serialize(writer2, pojo2);
<jc>// Same, but using a session object</jc>
SerializerSession session = JsonSerializer.<jsf>DEFAULT</jsf>.createSession();
<jk>try</jk> {
session.serialize(writer1, pojo1);
session.serialize(writer2, pojo2);
} <jk>finally</jk> {
session.close();
}
</p>
This is mostly an internal change and doesn't affect the existing APIs.
<li>
{@link org.apache.juneau.transform.PojoSwap#swap(BeanSession,Object)} and {@link org.apache.juneau.transform.PojoSwap#unswap(BeanSession,Object,ClassMeta)}
can now throw arbitrary exceptions instead of having to wrap them in <code>SerializeException</code>/<code>ParseException</code>.
<li>
New {@link org.apache.juneau.utils.CalendarUtils} class that encapsulates serialization/parsing logic from {@link org.apache.juneau.transforms.CalendarSwap} and
{@link org.apache.juneau.transforms.DateSwap}.
<li>
New annotation {@link org.apache.juneau.html.annotation.Html#anchorText}.
<li>
New methods on {@link org.apache.juneau.ObjectList}:
<ul>
<li>{@link org.apache.juneau.ObjectList#get(int,Class) get(int,Class)}
<li>{@link org.apache.juneau.ObjectList#get(int,Type,Type...) get(int,Type,Type...)}
<li>{@link org.apache.juneau.ObjectList#getMap(int,Class,Class) getMap(int,Class,Class)}
<li>{@link org.apache.juneau.ObjectList#getList(int,Class) getList(int,Class)}
</ul>
<li>
New methods on {@link org.apache.juneau.ObjectMap}:
<ul>
<li>{@link org.apache.juneau.ObjectMap#get(String,Class) get(String,Class)}
<li>{@link org.apache.juneau.ObjectMap#get(String,Type,Type...) get(String,Type,Type...)}
<li>{@link org.apache.juneau.ObjectMap#getWithDefault(String,Object) getWithDefault(String,Object)}
<li>{@link org.apache.juneau.ObjectMap#getWithDefault(String,Object,Class) getWithDefault(String,Object,Class)}
<li>{@link org.apache.juneau.ObjectMap#getWithDefault(String,Object,Type,Type...) getWithDefault(String,Object,Type,Type...)}
<li>{@link org.apache.juneau.ObjectMap#getSwapped(String,PojoSwap) getSwapped(String,PojoSwap)}
<li>{@link org.apache.juneau.ObjectMap#getAt(String,Class) getAt(String,Class)}
<li>{@link org.apache.juneau.ObjectMap#getAt(String,Type,Type...) getAt(String,Type,Type...)}
<li>{@link org.apache.juneau.ObjectMap#getMap(String,Class,Class,Map) getMap(String,Class,Class,Map)}
<li>{@link org.apache.juneau.ObjectMap#getList(String,Class,List) getList(String,Class,List)}
</ul>
<li>
New methods on {@link org.apache.juneau.utils.PojoRest}:
<ul>
<li>{@link org.apache.juneau.utils.PojoRest#get(String,Class) get(String,Class)}
<li>{@link org.apache.juneau.utils.PojoRest#get(String,Type,Type...) get(String,Type,Type...)}
<li>{@link org.apache.juneau.utils.PojoRest#getWithDefault(String,Object) getWithDefault(String,Object)}
<li>{@link org.apache.juneau.utils.PojoRest#getWithDefault(String,Object,Class) getWithDefault(String,Object,Class)}
<li>{@link org.apache.juneau.utils.PojoRest#getWithDefault(String,Object,Type,Type...) getWithDefault(String,Object,Type,Type...)}
</ul>
<li>
Fixed bug where {@link org.apache.juneau.BeanSession#getMediaType()} wasn't returning a value.
<li>
Eliminated the <ja>@Consumes</ja> and <ja>@Produces</ja> annotations.
<br>The supported media types are now passed in through the constructors.
<br>This was changed to eliminate a performance issue where a field could not be set as final because
the call to <code>getClass()</code> to retrieve the annotation value could not be called before calling
the <code><jk>super</jk>()</code> method.
<li>
New class: {@link org.apache.juneau.utils.PojoMerge}
<li>
New doc: <del>2.6.2 - @Pojo annotation</del>
<li>
New doc: <del>2.6.5 - Serializing Readers and InputStreams</del>
</ul>
<h5 class='topic'>juneau-dto</h5>
<ul class='spaced-list'>
<li>
{@link org.apache.juneau.dto.html5.HtmlElementMixed#children(Object...)} can now take in collections
of objects.
<li>
The DTO beans can now be serialized to strings of their typical language by calling the <code>toString()</code> method.
<br>For example, <code>Swagger.toString()</code> produces JSON and the HTML5 <code>Form.toString()</code>
produces HTML.
</ul>
<h5 class='topic'>juneau-rest-server</h5>
<ul class='spaced-list'>
<li>
Revamped and simplified servlet and REST-call lifecycle handling through new
{@link org.apache.juneau.rest.annotation.RestHook @RestHook} annotation.
<ul>
<li>The {@link org.apache.juneau.rest.RestServlet#init(ServletConfig)} method is now final and can
no longer be extended.
<br>Instead, use {@link org.apache.juneau.rest.annotation.HookEvent#INIT} or
{@link org.apache.juneau.rest.annotation.HookEvent#POST_INIT} for initialization.
<li>The following methods on {@link org.apache.juneau.rest.RestServlet} have been removed:
<ul>
<li><code>init(RestConfig)</code>
- Use {@link org.apache.juneau.rest.annotation.HookEvent#INIT} instead.
<li><code>onSuccess(RestRequest, RestResponse, long)</code>
- Use {@link org.apache.juneau.rest.annotation.HookEvent#END_CALL} instead.
<li><code>onPreCall(RestRequest)</code>
- Use {@link org.apache.juneau.rest.annotation.HookEvent#PRE_CALL} instead.
<li><code>onPostCall(RestRequest, RestResponse)</code>
- Use {@link org.apache.juneau.rest.annotation.HookEvent#POST_CALL} instead.
</ul>
</ul>
<li>
Simplified {@link org.apache.juneau.rest.widget.MenuItemWidget}.
<br>Exposes an abstract method {@link org.apache.juneau.rest.widget.MenuItemWidget#getContent(RestRequest)} that
can return raw HTML via readers or char-sequences, or any other object (such as HTML5 beans) that will
get converted to HTML using {@link org.apache.juneau.html.HtmlSerializer#DEFAULT}.
<li>
{@link org.apache.juneau.rest.RestResourceResolver} instances are now inherited from parent resources to child resources
unless explicitly overridden at the child level.
<br>It's also been changed to an interface.
<li>New annotations on {@link org.apache.juneau.rest.annotation.RestResource @RestResource}:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestResource#resourceResolver() resourceResolver()}
<br>Allows you to specify a resource resolver on the servlet context to make it easier to work with
dependency injection frameworks.
<li>{@link org.apache.juneau.rest.annotation.RestResource#contextPath() contextPath()} -
<br>Allows you to override the context path value inherited from the servlet container.
<li>{@link org.apache.juneau.rest.annotation.RestResource#allowHeaderParams() allowHeaderParams()} -
<br>Replaces the <code>RestContext.REST_allowHeaderParams</code> setting.
<li><code><del>RestResource.allowMethodParam()</del></code> -
<br>Replaces the <code>RestContext.REST_allowMethodParam</code> setting.
<li>{@link org.apache.juneau.rest.annotation.RestResource#allowBodyParam() allowBodyParam()} -
<br>Replaces the <code>RestContext.REST_allowBodyParam</code> setting.
<li>{@link org.apache.juneau.rest.annotation.RestResource#renderResponseStackTraces() renderResponseStackTraces()} -
<br>Replaces the <code>RestContext.REST_xxx</code> setting.
<li>{@link org.apache.juneau.rest.annotation.RestResource#useStackTraceHashes() useStackTraceHashes()} -
<br>Replaces the <code>RestContext.REST_useStackTraceHashes</code> setting.
<li>{@link org.apache.juneau.rest.annotation.RestResource#defaultCharset() defaultCharset()} -
<br>Replaces the <code>RestContext.REST_defaultCharset</code> setting.
<li><code><del>RestResource.paramFormat()</del></code> -
<br>Replaces the <code>RestContext.REST_paramFormat</code> setting.
</ul>
<li>New annotations on {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod}:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#defaultCharset() defaultCharset()} -
<br>Replaces the <code>RestContext.REST_defaultCharset</code> setting.
<li><code><del>RestMethod.paramFormat()</del></code> -
<br>Replaces the <code>RestContext.REST_paramFormat</code> setting.
</ul>
<li>
The following implementation classes can now be defined as non-static inner classes of servlets/resources:
<ul>
<li>{@link org.apache.juneau.rest.widget.Widget}
<li>{@link org.apache.juneau.rest.RestConverter}
<li>{@link org.apache.juneau.rest.RestGuard}
<li>{@link org.apache.juneau.rest.ResponseHandler}
<li>{@link org.apache.juneau.rest.RestCallHandler}
<li>{@link org.apache.juneau.rest.RestInfoProvider}
<li>{@link org.apache.juneau.rest.RestResourceResolver}
<li>{@link org.apache.juneau.rest.RestLogger}
<li>{@link org.apache.juneau.html.HtmlDocTemplate}
</ul>
<li>
New tooltip template: {@link org.apache.juneau.rest.widget.Tooltip}
<li>
New dark theme:
<br><img src='doc-files/ReleaseNotes.632.DarkStyle.png'>
<li>
Stylesheet selection now stored in HTTP session when passed in via <code>?stylesheet</code> query parameter.
<li>
New doc: <del>Lifecycle Hooks</del>
<li>
Eliminated the <code>RestServletJenaDefault</code> class to remove the Jena dependency class on
the <code>juneau-rest-server</code> artifact.
<br>It's simple enough to simply extend <code>RestServletDefault</code> and add the RDF serializers and
parsers.
</ul>
<h5 class='topic'>juneau-microservice</h5>
<ul class='spaced-list'>
<li>
The microservice has been significantly modified to be configured via a <code>jetty.xml</code> file
for maximum flexibility instead of the hodge-podge of support in the config file.
<br>Top-level servlets should now be defined in the provided <code>jetty.xml</code> file.
<li>
New methods on {@link org.apache.juneau.microservice.RestMicroservice}:
<ul>
<li>{@link org.apache.juneau.microservice.RestMicroservice#addServlet(Servlet,String) addServlet(Servlet,String)}
<li>{@link org.apache.juneau.microservice.RestMicroservice#addServletAttribute(String,Object) addServletAttribute(String,Object)}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getServer() getServer()}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getInstance() getInstance()}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getPort() getPort()}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getContextPath() getContextPath()}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getProtocol() getProtocol()}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getHostName() getHostName()}
</ul>
<li>
New methods on {@link org.apache.juneau.microservice.Microservice}:
<ul>
<li>{@link org.apache.juneau.microservice.Microservice#getInstance() getInstance()}
</ul>
<li>
New class {@link org.apache.juneau.microservice.JettyLogger} for directing Jetty logging to the
java.util.logging framework.
<li>
New class {@link org.apache.juneau.microservice.resources.DebugResource} for viewing and generating
Jetty thread dumps through REST calls.
</ul>
<h5 class='topic'>org.apache.juneau.rest.examples</h5>
<ul class='spaced-list'>
<li>
New example of adding a menu-item widget to the Pet Store resource (including tooltips):
<br><img src='doc-files/ReleaseNotes.632.PetStoreAdd.png'>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.3.1"></a>
<h3 class='topic' onclick='toggle(this)'>6.3.1 (Aug 1, 2017)</h3>
<div class='topic'>
<p>
Juneau 6.3.1 is a minor release.
</p>
<h5 class='topic'>org.apache.juneau</h5>
<ul class='spaced-list'>
<li>
{@link org.apache.juneau.utils.PojoQuery} improvements.
<li>
New {@link org.apache.juneau.remoteable.RemoteMethod#returns()} annotation.
<br>Allows you to specify whether the remote method returns the HTTP body or status code.
<li>
Fixed bugs with {@link org.apache.juneau.BeanContext#BEAN_includeProperties} and {@link org.apache.juneau.BeanContext#BEAN_excludeProperties} settings.
<li>
New/modified settings in <code><del>HtmlDocSerializerContext</del></code>:
<ul>
<li><code><del>HTMLDOC_script</del></code>
<li><code><del>HTMLDOC_style</del></code> - Was <jsf>HTMLDOC_css</jsf>.
<li><code><del>HTMLDOC_stylesheet</del></code> - Was <jsf>HTMLDOC_cssUrl</jsf>. Now an array.
</ul>
<li>
New <code><del>ResourceFinder</del></code> utility class.
Allows you to search for resources up the parent hierarchy chain.
Also allows you to search for localized resources.
<li>
Eliminated the following properties from <code><del>HtmlDocSerializerContext</del></code>:
<jsf>HTMLDOC_title</jsf>, <jsf>HTMLDOC_description</jsf>, <jsf>HTMLDOC_description</jsf>
<br>See below on changes to simplify HTML headers.
<li>
{@link org.apache.juneau.svl.Var} implementations can now throw exceptions and will be converted to
<js>""{exceptionMessage}"</js> values.
</ul>
<h5 class='topic'>org.apache.juneau.rest</h5>
<ul class='spaced-list'>
<li>
New 'light' stylesheet:
<br><img src='doc-files/ReleaseNotes.631.LightStyle.png'>
<br>Compared with previous 'devops':
<br><img src='doc-files/ReleaseNotes.631.DevopsStyle.png'>
<br>For those nolstalgic for old times, there's also 'original':
<br><img src='doc-files/ReleaseNotes.631.OriginalStyle.png'>
<li>
Simplified the stylesheets and HTML code.
<br>For example, the nav links are now an ordered list of elements which makes rendering as as side-bar
(for example) easier to do in CSS.
<li>
Modifications to the following <ja>@HtmlDoc</ja> annotations:
<ul>
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#navlinks() navlinks()} - Now an array of strings instead of a JSON object. Simplified syntax.
<br>For example:
<p class='bcode'>
<jc>// Old syntax</jc>
htmldoc=<ja>@HtmlDoc</ja>(
links=<js>"{"</js>
+ <js>"up:'request:/..',"</js>
+ <js>"options:'servlet:/?method=OPTIONS',"</js>
+ <js>"contentTypes:'$W{ContentTypeMenuItem}',"</js>
+ <js>"styles:'$W{StyleMenuItem}',"</js>
+ <js>"source:'$C{Source/gitHub}/org/apache/juneau/examples/rest/PetStoreResource.java'"</js>
+ <js>"}"</js>
)
<jc>// New syntax</jc>
htmldoc=<ja>@HtmlDoc</ja>(
navlinks={
<js>"up: request:/.."</js>,
<js>"options: servlet:/?method=OPTIONS"</js>,
<js>"$W{ContentTypeMenuItem}"</js>,
<js>"$W{StyleMenuItem}"</js>,
<js>"source: $C{Source/gitHub}/org/apache/juneau/examples/rest/PetStoreResource.java"</js>
}
)
</p>
Previous syntax will still work, but you're encouraged to use the simplified syntax.
<li>Several annotations are now arrays of strings instead of simple strings.
Values are simply concatenated with newlines which makes multi-line values cleaner.
<ul>
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#header() header()}
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#nav() nav()}
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#aside() aside()}
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#footer() footer()}
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#script() script()}
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#style() style()}
</ul>
Additionally, the <js>"INHERIT"</js> string literal can be used to combine the value with
the value defined on the servlet or parent class. Links can also be inserted at specific
index positions.
</ul>
<li>
Improvements made to the {@link org.apache.juneau.rest.widget.Widget} API.
<ul>
<li>
You can now add arbitrary CSS and Javascript along with your widgets through new methods:
<ul>
<li>{@link org.apache.juneau.rest.widget.Widget#getHtml(RestRequest)}
<li>{@link org.apache.juneau.rest.widget.Widget#getScript(RestRequest)}
<li>{@link org.apache.juneau.rest.widget.Widget#getStyle(RestRequest)}
</ul>
</li>
<li>
Declaration of widgets moved to {@link org.apache.juneau.rest.annotation.HtmlDoc#widgets() @HtmlDoc.widgets()}
instead of separately on <ja>@RestResource</ja> and <ja>@RestMethod</ja> annotations.
<li>
{@link org.apache.juneau.rest.widget.Widget#getName()} now defaults to the simple class name.
<br>So now you can just refer to the class name: <js>"$W{ContentTypeMenuItem}"</js>.
<li>
Renamed widgets:
<ul>
<li><code>PoweredByApacheWidget</code> -&gt; <code>PoweredByApache</code>
<li><code>PoweredByJuneauWidget</code> -&gt; <code>PoweredByJuneau</code>
</ul>
<li>
New {@link org.apache.juneau.rest.widget.MenuItemWidget} can be used as a starting point for creatint pull-down menu items.
<li>
New {@link org.apache.juneau.rest.widget.ContentTypeMenuItem} widget that provides a pull-down menu
with hyperlinks for all supported languages for that page:
<br><img src='doc-files/ReleaseNotes.631.ContentTypeMenuItem.png'>
<li>
Improved {@link org.apache.juneau.rest.widget.QueryMenuItem} widget that provides a pull-down menu
of a search/view/order-by/page form:
<br><img src='doc-files/ReleaseNotes.631.QueryMenuItem.png'>
<br>Fields are now pre-filled with current query parameters.
<li>
New {@link org.apache.juneau.rest.widget.StyleMenuItem} widget that provides a pull-down menu
with hyperlinks to show the content in the default stylesheets:
<br><img src='doc-files/ReleaseNotes.631.StyleMenuItem.png'>
</ul>
<li>
New/modified annotations on {@link org.apache.juneau.rest.annotation.HtmlDoc @HtmlDoc}:
<ul>
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#style() style()} - Renamed from <code>css()</code>.
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#stylesheet() stylesheet()} - Renamed from <code>cssUrl()</code>.
<br>Can now be a comma-delimited list of URLs.
<li>{@link org.apache.juneau.rest.annotation.HtmlDoc#script() script()} - Add arbitrary Javascript to page header.
</ul>
<li>
Bug fix with {@link org.apache.juneau.rest.annotation.HtmlDoc#nowrap() @HtmlDoc.nowrap()} so that the setting only applies
to the data contents, not the whole page.
<li>
Two convenience methods added to {@link org.apache.juneau.rest.RestRequest}:
<ul>
<li>{@link org.apache.juneau.rest.RestRequest#attr(String,Object) attr(String,Object)}
<li>{@link org.apache.juneau.rest.RestRequest#prop(String,Object) prop(String,Object)}
</ul>
</li>
<li>
Annotations added:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestResource#siteName() @RestResource.siteName()}
<li>{@link org.apache.juneau.rest.annotation.RestResource#flags() @RestResource.flags()}
<li>{@link org.apache.juneau.rest.annotation.RestMethod#flags() @RestMethod.flags()}
</ul>
</li>
<li>
Eliminated the <code>@RestResource.stylesheet()</code> annotation.
It's no longer needed now that you can easily specify styles via <ja>@Htmldoc</ja>.
<li>
Eliminated the following annotations since they are now redundant with {@link org.apache.juneau.rest.annotation.HtmlDoc#header() @HtmlDoc.header()}:
<ul>
<li><code>title()</code>
<li><code>description()</code>
<li><code>branding()</code>
</ul>
Instead, the {@link org.apache.juneau.rest.RestServletDefault} class defines the following default header
that can be easily overridden:
<p class='bcode'>
htmldoc=<ja>@HtmlDoc</ja>(
header={
<js>"&lt;h1&gt;$R{resourceTitle}&lt;/h1&gt;"</js>,
<js>"&lt;h2&gt;$R{methodSummary,resourceDescription}&lt;/h2&gt;"</js>,
<js>"&lt;a href='http://juneau.apache.org'&gt;&lt;img src='$U{servlet:/htdocs/juneau.png}' style='position:absolute;top:5;right:5;background-color:transparent;height:30px'/&gt;&lt;/a&gt;"</js>
}
)
</p>
Note that the subtitle first tries using the method summary and then the servlet description.
<li>
New {@link org.apache.juneau.rest.vars.FileVar $F} variable resolver for resolving the contents of
files in the classpath.
<br>The <code>DockerRegistryResource</code> examples shows how it can be used to pull in a localized
file from the classpath to populate the aside section of a page.
<p class='bcode'>
htmldoc=<ja>@HtmlDoc</ja>(
<jc>// Pull in aside contents from file.</jc>
aside=<js>"$F{resources/DockerRegistryResourceAside.html}"</js>
)
</p>
<li>
New {@link org.apache.juneau.rest.ReaderResource#toCommentStrippedString()} method.
<li>
The <code>bpIncludes()</code> and <code>bpExcludes()</code> annotations on <ja>@RestMethod</ja>
has been replaced with the following:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#bpi() bpi()} - Now an array of simplified values instead of LAX JSON.
<li>{@link org.apache.juneau.rest.annotation.RestMethod#bpx() bpx()} - Now an array of simplified values instead of LAX JSON.
</ul>
<li>
Two new variables added to <code>$R</code> variable: <js>"$R{servletClass}"</js>, <js>"$R{servletClassSimple}"</js>
</ul>
<h5 class='topic'>org.apache.juneau.rest.examples</h5>
<ul class='spaced-list'>
<li>
Added CONTENT-TYPE and STYLES menu items to most pages.
<li>
Added improved QUERY menu item to PetStore page.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.3.0"></a>
<h3 class='topic' onclick='toggle(this)'>6.3.0 (Jun 30, 2017)</h3>
<div class='topic'>
<p>
Juneau 6.3.0 is a major update with significant new functionality for defining proxy interfaces against
arbitrary 3rd-party REST interfaces.
</p>
<h5 class='topic'>org.apache.juneau</h5>
<ul class='spaced-list'>
<li>
New package: {@link org.apache.juneau.http}.
<li>
Support for dynamic beans. See {@link org.apache.juneau.annotation.BeanProperty#name() @BeanProperty.name()}.
<li>
New doc: <code><del>2.8 - Virtual Beans</del></code>
<li>
New doc: <code><del>2.13 - Comparison with Jackson</del></code>
<li>
All parsers now allow for numeric types with <js>'K'</js>/<js>'M'</js>/<js>'G'</js> suffixes to represent
kilobytes, megabytes, and gigabytes.
<p class='bcode'>
<jc>// Example</jc>
<jk>int</jk> i = JsonParser.<jsf>DEFAULT</jsf>.parse(<js>"123M"</js>); <jc>// 123MB</jc>
</p>
<li>New/modified methods on <code><del>ConfigFile</del></code>:
<ul>
<li><code><del>ConfigFile.put(String,String,String,boolean)</del></code>
<li><code><del>ConfigFile.put(String,String,Object,Serializer,boolean,boolean)</del></code>
<li><code><del>ConfigFile.getObject(String,Type,Type...)</del></code>
<li><code><del>ConfigFile.getObject(String,Parser,Type,Type...)</del></code>
<li><code><del>ConfigFile.getObject(String,Class)</del></code>
<li><code><del>ConfigFile.getObject(String,Parser,Class)</del></code>
<li><code><del>ConfigFile.getObject(String,String,Type,Type...)</del></code>
<li><code><del>ConfigFile.getObject(String,String,Parser,Type,Type...)</del></code>
<li><code><del>ConfigFile.getObject(String,String,Class)</del></code>
<li><code><del>ConfigFile.getObject(String,String,Parser,Class)</del></code>
<li><code><del>ConfigFile.getObjectWithDefault(String,Object,Type,Type...)</del></code>
<li><code><del>ConfigFile.getObjectWithDefault(String,Parser,Object,Type,Type...)</del></code>
<li><code><del>ConfigFile.getObjectWithDefault(String,Object,Class)</del></code>
<li><code><del>ConfigFile.getObjectWithDefault(String,Parser,Object,Class)</del></code>
</ul>
<li>New ability to interact with config file sections with proxy interfaces with new method <code><del>ConfigFile.getSectionAsInterface(String,Class)</del></code>.
<li>{@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotation can now be applied to getters
and setters defined on interfaces.
<li>New methods on {@link org.apache.juneau.serializer.SerializerSession} and {@link org.apache.juneau.parser.ParserSession}
for retrieving context and runtime-override properties:
<ul>
<li><code><del>Session.getProperty(String)</del></code>
<li><code><del>Session.getProperty(String,String)</del></code>
<li><code><del>Session.getProperty(Class,String)</del></code>
<li><code><del>Session.getProperty(Class,String,Object)</del></code>
</ul>
<li>New <code><del>org.apache.juneau.serializer.PartSerializer</del></code> interface particularly tailored to HTTP
headers, query parameters, form-data parameters, and path variables.
<br>Allows easy user-defined serialization of these objects.
<br>The interface can be used in the following locations:
<ul>
<li>{@link org.apache.juneau.rest.client.RestClientBuilder#partSerializer(Class)}
<li>{@link org.apache.juneau.remoteable.Path#serializer}
<li>{@link org.apache.juneau.remoteable.Query#serializer}
<li>{@link org.apache.juneau.remoteable.QueryIfNE#serializer}
<li>{@link org.apache.juneau.remoteable.FormData#serializer}
<li>{@link org.apache.juneau.remoteable.FormDataIfNE#serializer}
<li>{@link org.apache.juneau.remoteable.Header#serializer}
<li>{@link org.apache.juneau.remoteable.HeaderIfNE#serializer}
</ul>
<li>Across-the-board improvements to the URI-resolution support (i.e. how URIs get serialized).
<ul>
<li>New support for resolving URIs with the following newly-recognized protocols:
<ul>
<li><js>"context:/..."</js> - Relative to context-root of the application.
<li><js>"servlet:/..."</js> - Relative to the servlet URI.
<li><js>"request:/..."</js> - Relative to the request URI.
</ul>
For example, currently we define HTML page links using variables and servlet-relative URIs...
<p class='bcode'>
pages=<js>"{up:'$R{requestParentURI}', options:'?method=OPTIONS', upload:'upload'}"</js>
</p>
With these new protocols, we can define them like so:
<p class='bcode'>
links=<js>"{top:'context:/', up:'request:/..' ,options:'servlet:/?method=OPTIONS', upload:'servlet:/upload'}"</js>
</p>
The old method of using variables and servlet-relative URIs will still be supported, but using
these new protocols should (hopefully) be easier to understand.
<br>
These protocols work on all serialized URL and URI objects, as well as classes and properties
annotated with {@link org.apache.juneau.annotation.URI @URI}.
<li>New classes:
<ul>
<li>{@link org.apache.juneau.UriContext}
<li>{@link org.apache.juneau.UriRelativity}
<li>{@link org.apache.juneau.UriResolution}
<li>{@link org.apache.juneau.UriResolver}
</ul>
<li>New configuration properties:
<li><code><del>SerializerContext.SERIALIZER_uriContext</del></code>
<li><code><del>SerializerContext.SERIALIZER_uriRelativity</del></code>
<li><code><del>SerializerContext.SERIALIZER_uriResolution</del></code>
<li><code><del>SerializerContext.SERIALIZER_maxIndent</del></code>
</ul>
<li>New annotation property: {@link org.apache.juneau.annotation.BeanProperty#value() @BeanProperty.value()}.
<br>The following two annotations are considered equivalent:
<p class='bcode'>
<ja>@BeanProperty</ja>(name=<js>"foo"</js>)
<ja>@BeanProperty</ja>(<js>"foo"</js>)
</p>
<li>Fixed a race condition in ClassMeta.
<li><jsf>URLENC_paramFormat</jsf> has been moved to <code><del>UonSerializer.UON_paramFormat</del></code>,
and the UON/URL-Encoding serializers will now always serialize all values as plain text.
<br>This means that arrays and maps are converted to simple comma-delimited lists.
<li>Listener APIs added to serializers and parsers:
<ul>
<li>{@link org.apache.juneau.serializer.SerializerListener}
<li>{@link org.apache.juneau.serializer.SerializerBuilder#listener(Class)}
<li>{@link org.apache.juneau.rest.annotation.RestResource#serializerListener() @RestResource.serializerListener()}
<li><code><del>RestConfig.serializerListener(Class)</del></code>
<li>{@link org.apache.juneau.parser.ParserListener}
<li>{@link org.apache.juneau.parser.ParserBuilder#listener(Class)}
<li>{@link org.apache.juneau.rest.annotation.RestResource#parserListener() @RestResource.parserListener()}
<li><code><del>RestConfig.parserListener(Class)</del></code>
<li><code><del>RestClientBuilder.listeners(Class,Class)</del></code>
</ul>juneau-examples-core.import1.pngjuneau-examples-core.import1.png
<li>The {@link org.apache.juneau.BeanContext#BEAN_debug} flag will now capture parser input and make it
available through the <code><del>ParserSession.getInputAsString()</del></code> method so that it can be used
in the listeners.
<li>Significant new functionality introduced to the HTML serializer.
<br>Lots of new options for customizing the HTML output.
<ul>
<li>New {@link org.apache.juneau.html.annotation.Html#render() @Html.render()} annotation and {@link org.apache.juneau.html.HtmlRender} class that allows you
to customize the HTML output and CSS style on bean properties:
<br><img class='bordered' src='doc-files/ReleaseNotes.630.1.png'>
<br>Annotation can be applied to POJO classes and bean properties.
<li>Several new properties for customizing parts of the HTML page:
<ul>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_title</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_description</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_branding</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_header</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_nav</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_aside</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_footer</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_noResultsMessage</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_cssUrl</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_css</del></code>
<li><code><del>HtmlDocSerializerContext.HTMLDOC_template</del></code>
</ul>
<li>New interface {@link org.apache.juneau.html.HtmlDocTemplate} that allows full control over rendering
of HTML produced by {@link org.apache.juneau.html.HtmlDocSerializer}.
</ul>
<li>{@link org.apache.juneau.annotation.NameProperty @NameProperty} and {@link org.apache.juneau.annotation.ParentProperty @ParentProperty}
can now be applied to fields.
<li>New properties on {@link org.apache.juneau.BeanContext}:
<ul>
<li>{@link org.apache.juneau.BeanContext#BEAN_includeProperties BEAN_includeProperties}
<li>{@link org.apache.juneau.BeanContext#BEAN_excludeProperties BEAN_excludeProperties}
</ul>
<li>New annotation property: {@link org.apache.juneau.annotation.BeanProperty#format() @BeanProperty.format()}.
</ul>
<h5 class='topic'>org.apache.juneau.rest</h5>
<ul class='spaced-list'>
<li>
MAJOR enhancements made to the REST API.
<li>
The {@link org.apache.juneau.rest.RestRequest} class functionality has been broken up into the following
functional pieces to reduce its complexity:
<ul>
<li>{@link org.apache.juneau.rest.RestRequest#getBody()} - The request body.
<li>{@link org.apache.juneau.rest.RestRequest#getHeaders()} - The request headers.
<li>{@link org.apache.juneau.rest.RestRequest#getQuery()} - The request query parameters.
<li>{@link org.apache.juneau.rest.RestRequest#getFormData()} - The request form data parameters.
<li>{@link org.apache.juneau.rest.RestRequest#getPathMatch()} - The path variables and remainder.
</ul>
The following classes have been introduced:
<ul>
<li>{@link org.apache.juneau.rest.RequestBody}
<li>{@link org.apache.juneau.rest.RequestHeaders}
<li>{@link org.apache.juneau.rest.RequestQuery}
<li>{@link org.apache.juneau.rest.RequestFormData}
<li>{@link org.apache.juneau.rest.RequestPathMatch}
</ul>
<li>
The un-annotated parameter types that can be passed in through REST Java methods has been significantly expanded.
<br>For reference, the previous supported types were:
<ul>
<li>{@link org.apache.juneau.rest.RestRequest} - The request object.
<li>{@link javax.servlet.http.HttpServletRequest} - The superclass of <code>RestRequest</code>.
<li>{@link org.apache.juneau.rest.RestResponse} - The response object.
<li>{@link javax.servlet.http.HttpServletResponse} - The superclass of <code>RestResponse</code>.
</ul>
The new supported types are:
<ul>
<li>{@link org.apache.juneau.http.Accept}
<li>{@link org.apache.juneau.http.AcceptCharset}
<li>{@link org.apache.juneau.http.AcceptEncoding}
<li>{@link org.apache.juneau.http.AcceptLanguage}
<li>{@link org.apache.juneau.http.Authorization}
<li>{@link org.apache.juneau.http.CacheControl}
<li>{@link org.apache.juneau.http.Connection}
<li>{@link org.apache.juneau.http.ContentLength}
<li>{@link org.apache.juneau.http.ContentType}
<li>{@link org.apache.juneau.http.Date}
<li>{@link org.apache.juneau.http.Expect}
<li>{@link org.apache.juneau.http.From}
<li>{@link org.apache.juneau.http.Host}
<li>{@link org.apache.juneau.http.IfMatch}
<li>{@link org.apache.juneau.http.IfModifiedSince}
<li>{@link org.apache.juneau.http.IfNoneMatch}
<li>{@link org.apache.juneau.http.IfRange}
<li>{@link org.apache.juneau.http.IfUnmodifiedSince}
<li>{@link org.apache.juneau.http.MaxForwards}
<li>{@link org.apache.juneau.http.Pragma}
<li>{@link org.apache.juneau.http.ProxyAuthorization}
<li>{@link org.apache.juneau.http.Range}
<li>{@link org.apache.juneau.http.Referer}
<li>{@link org.apache.juneau.http.TE}
<li>{@link org.apache.juneau.http.UserAgent}
<li>{@link org.apache.juneau.http.Upgrade}
<li>{@link org.apache.juneau.http.Via}
<li>{@link org.apache.juneau.http.Warning}
<li>{@link java.util.TimeZone}
<li>{@link java.io.InputStream}
<li>{@link javax.servlet.ServletInputStream}
<li>{@link java.io.Reader}
<li>{@link java.io.OutputStream}
<li>{@link javax.servlet.ServletOutputStream}
<li>{@link java.io.Writer}
<li>{@link java.util.ResourceBundle} - Client-localized resource bundle.
<li>{@link org.apache.juneau.utils.MessageBundle} - A resource bundle with additional features.
<li>{@link java.util.Locale} - Client locale.
<li>{@link org.apache.juneau.rest.RequestHeaders} - API for accessing request headers.
<li>{@link org.apache.juneau.rest.RequestQuery} - API for accessing request query parameters.
<li>{@link org.apache.juneau.rest.RequestFormData} - API for accessing request form data.
<li>{@link org.apache.juneau.rest.RequestPathMatch} - API for accessing path variables.
<li>{@link org.apache.juneau.rest.RequestBody} - API for accessing request body.
<li>{@link org.apache.juneau.http.HttpMethod} - The method name matched (when using <code><ja>@RestMethod</ja>(name=<js>"*"</js>)</code>)
<li>{@link java.util.logging.Logger} - The logger to use for logging.
<li>{@link org.apache.juneau.internal.JuneauLogger} - Logger with additional features.
<li>{@link org.apache.juneau.rest.RestContext} - The resource read-only context.
<li>{@link org.apache.juneau.parser.Parser} - The parser matching the request content type.
<li>{@link org.apache.juneau.dto.swagger.Swagger} - The auto-generated Swagger doc.
<li><code><del>ConfigFile</del></code> - The external config file for the resource.
</ul>
So, for example...
<p class='bcode'>
<jd>/** Old way */</jd>
<ja>@RestMethod</ja>(name=<js>"*"</js>, path=<js>"/example1/{a1}/{a2}/{a3}/*"</js>)
<jk>public</jk> String example1(
<ja>@Method</ja> String method,
<ja>@Path</ja> String a1,
<ja>@Path</ja> <jk>int</jk> a2,
<ja>@Path</ja> UUID a3,
<ja>@Query</ja>(<js>"p1"</js>) <jk>int</jk> p1,
<ja>@Query</ja>(<js>"p2"</js>) String p2,
<ja>@Query</ja>(<js>"p3"</js>) UUID p3,
<ja>@Header</ja>(<js>"Accept-Language"</js>) String lang,
<ja>@Header</ja>(<js>"Accept"</js>) String accept
)
<jd>/** New way */</jd>
<ja>@RestMethod</ja>(name=<js>"*"</js>, path=<js>"/example2/{a1}/{a2}/{a3}/*"</js>)
<jk>public</jk> String example2(
HttpMethod httpMethod,
RequestPathParams pathParams,
RequestQuery query,
AcceptLanguage acceptLanguage,
Accept accept
)
</p>
<li>
A new annotation {@link org.apache.juneau.rest.annotation.RestResource#paramResolvers() @RestResource.paramResolvers()}
that allows you to define your own custom Java method parameter resolvers.
<li>
Fixed bug where Writer returned by {@link org.apache.juneau.rest.RestResponse#getWriter()} was not being flushed automatically
at the end of the HTTP call.
<li>
New annotations added to {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod}:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#defaultQuery() defaultQuery()}
<li>{@link org.apache.juneau.rest.annotation.RestMethod#defaultFormData() defaultFormData()}
<li><code><del>bpIncludes()</del></code>
<li><code><del>bpExcludes()</del></code>
</ul>
<li>
Default values on header, query, and form-data annotations:
<ul>
<li>{@link org.apache.juneau.rest.annotation.Header#def @Header.def()} - Default header value.
<li>{@link org.apache.juneau.rest.annotation.Query#def @Query.def()} - Default query parameter value.
<li>{@link org.apache.juneau.rest.annotation.FormData#def @FormData.def()} - Default form data parameter value.
</ul>
<li>
New attributes on {@link org.apache.juneau.rest.annotation.RestResource @RestResource}:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestResource#serializerListener() serializerListener()}
<li>{@link org.apache.juneau.rest.annotation.RestResource#parserListener() parserListener()}
<li><code><del>widgets()</del></code>
<li>{@link org.apache.juneau.rest.annotation.RestResource#swagger() swagger()}
<li>{@link org.apache.juneau.rest.annotation.RestResource#htmldoc() htmldoc()}
</ul>
<li>
New attributes on {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod}:
<ul>
<li><code><del>widgets()</del></code>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#swagger() swagger()}
<li>{@link org.apache.juneau.rest.annotation.RestMethod#htmldoc() htmldoc()}
</ul>
<li>
New string vars:
<ul>
<li>{@link org.apache.juneau.rest.vars.UrlVar} - Resolve <js>"$U{...}"</js> variables to URLs.
<li>{@link org.apache.juneau.rest.vars.WidgetVar} - Resolve <js>"$W{...}"</js> variables to widget contents.
</ul>
<li>
New methods on <code><del>RestConfig</del></code>:
<ul>
<li><code><del>setHtmlTitle(String)</del></code>
<li><code><del>setHtmlDescription(String)</del></code>
<li><code><del>setHtmlBranding(String)</del></code>
<li><code><del>setHtmlHeader(String)</del></code>
<li><code><del>setHtmlLinks(String)</del></code>
<li><code><del>setHtmlNav(String)</del></code>
<li><code><del>setHtmlAside(String)</del></code>
<li><code><del>setHtmlFooter(String)</del></code>
<li><code><del>setHtmlCss(String)</del></code>
<li><code><del>setHtmlCssUrl(String)</del></code>
<li><code><del>setHtmlNoWrap(boolean)</del></code>
<li><code><del>setHtmlNoResultsMessage(String)</del></code>
<li><code><del>setHtmlTemplate(Class)</del></code>
<li><code><del>setHtmlTemplate(HtmlDocTemplate)</del></code>
<li><code><del>addWidget(Class)</del></code>
</ul>
<li>
New methods on {@link org.apache.juneau.rest.RestResponse}:
<ul>
<li><code><del>setHtmlTitle(Object)</del></code>
<li><code><del>setHtmlDescription(Object)</del></code>
<li><code><del>setHtmlBranding(Object)</del></code>
<li><code><del>setHtmlHeader(Object)</del></code>
<li><code><del>setHtmlLinks(Object)</del></code>
<li><code><del>setHtmlNav(Object)</del></code>
<li><code><del>setHtmlAside(Object)</del></code>
<li><code><del>setHtmlFooter(Object)</del></code>
<li><code><del>setHtmlCss(Object)</del></code>
<li><code><del>setHtmlCssUrl(Object)</del></code>
<li><code><del>setHtmlNoWrap(boolean)</del></code>
<li><code><del>setHtmlNoResultsMessage(Object)</del></code>
<li><code><del>setHtmlTemplate(Class)</del></code>
<li><code><del>setHtmlTemplate(HtmlDocTemplate)</del></code>
</ul>
<li>
<code>&amp;plainText=true</code> parameter now works on byte-based serializers by converting the output to hex.
<li>
New classes for widget support:
<ul>
<li>{@link org.apache.juneau.rest.widget.Widget}
<li><code><del>PoweredByJuneauWidget</del></code>
<li><code><del>ContentTypeLinksColumnWidget</del></code>
<li><code><del>ContentTypeLinksRowWidget</del></code>
<li><code><del>QueryWidget</del></code>
</ul>
<li>
<code>devops.css</code> cleaned up.
<li>
Removed a bunch of URL-related methods from {@link org.apache.juneau.rest.RestRequest}.
These all have equivalents in {@link org.apache.juneau.rest.RestRequest#getUriContext()}.
<li>
New annotation attributes:
<ul>
<li>{@link org.apache.juneau.rest.annotation.Query#name() @Query.name()}
<li>{@link org.apache.juneau.rest.annotation.FormData#name() @FormData.name()}
<li>{@link org.apache.juneau.rest.annotation.Header#name() @Header.name()}
<li>{@link org.apache.juneau.rest.annotation.Path#name() @Path.name()}
<li>{@link org.apache.juneau.rest.annotation.HasQuery#name() @HasQuery.name()}
<li>{@link org.apache.juneau.rest.annotation.HasFormData#name() @HasFormData.name()}
</ul>
</li>
</ul>
<h5 class='topic'>org.apache.juneau.rest.client</h5>
<ul class='spaced-list'>
<li>
New {@link org.apache.juneau.remoteable.Path @Path} annotation for specifying path variables on remoteable interfaces.
<li>
New {@link org.apache.juneau.remoteable.RequestBean @RequestBean} annotation for specifying beans with remoteable annotations
defined on properties.
<li>
The following annotations (and related methods on RestCall) can now take <code>NameValuePairs</code> and beans as input
when using <js>"*"</js> as the name.
<br>{@link org.apache.juneau.remoteable.FormData @FormData},{@link org.apache.juneau.remoteable.FormDataIfNE @FormDataIfNE},
{@link org.apache.juneau.remoteable.Query @Query},{@link org.apache.juneau.remoteable.QueryIfNE @QueryIfNE},
{@link org.apache.juneau.remoteable.Header @Header},{@link org.apache.juneau.remoteable.HeaderIfNE @HeaderIfNE},
</ul>
<h5 class='topic'>org.apache.juneau.microservice</h5>
<ul class='spaced-list'>
</ul>
<h5 class='topic'>org.apache.juneau.examples.rest</h5>
<ul class='spaced-list'>
<li>
Many code enhancements make to examples to reflect new functionality.
<li>All pages now render aside comments to help explain what feature they're trying to explain using the
new features that allow you to customize various elements of the page.
<br>
<img class='bordered' width="50%" src='doc-files/ReleaseNotes.630.2.png'>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.2.0"></a>
<h3 class='topic' onclick='toggle(this)'>6.2.0 (Apr 28, 2017)</h3>
<div class='topic'>
<p>
Juneau 6.2.0 is a major update.
</p>
<h5 class='topic'>org.apache.juneau</h5>
<ul class='spaced-list'>
<li>
Revamped the serializer, parser classes to use builders for creation.
Serializers and parsers are now unmodifiable objects once they are created.
This is a breaking code change that will require adoption.
<p class='bcode'>
<jc>/* Creating a new serializer or parser */ </jc>
<jc>// Old way</jc>
WriterSerializer s = <jk>new</jk> JsonSerializer().setUseWhitespace(<jk>true</jk>).pojoSwaps(BSwap.<jk>class</jk>).lock();
<jc>// New way</jc>
WriterSerializer s = JsonSerializer.<jsm>create</jsm>().ws().pojoSwaps(BSwap.<jk>class</jk>).build();
<jc>/* Cloning an existing serializer or parser */ </jc>
<jc>// Old way</jc>
WriterSerializer s = JsonSerializer.<jsf>DEFAULT_LAX</jsf>.clone().setUseWhitespace(<jk>true</jk>).pojoSwaps(BSwap.<jk>class</jk>).lock();
<jc>// New way</jc>
WriterSerializer s = JsonSerializer.<jsf>DEFAULT_LAX</jsf>.builder().ws().pojoSwaps(BSwap.<jk>class</jk>).build();
</p>
<li>Also introduced the following builder classes and related architecture changes to make the built objects unmodifiable:
<ul>
<li>{@link org.apache.juneau.serializer.SerializerGroupBuilder}
<li>{@link org.apache.juneau.parser.ParserGroupBuilder}
<li>{@link org.apache.juneau.encoders.EncoderGroupBuilder}
</ul>
<li>Revamped the config file API to use a build: <code><del>ConfigFileBuilder</del></code>.
<li>Removed the <code><del>Lockable</del></code> interface.
<li>New <code>addBeanTypeProperties</code> setting added to serializers to override the
<code><del>SerializerContext.SERIALIZER_addBeanTypeProperties</del></code> setting
for individual serializers in a serializer group:
<ul>
<li><code><del>HtmlSerializerContext.HTML_addBeanTypeProperties</del></code>
<li><code><del>JsonSerializerContext.JSON_addBeanTypeProperties</del></code>
<li><code><del>MsgPackSerializerContext.MSGPACK_addBeanTypeProperties</del></code>
<li><code><del>UonSerializerContext.UON_addBeanTypeProperties</del></code>
<li><code><del>XmlSerializerContext.#XML_addBeanTypeProperties</del></code>
<li><code><del>RdfSerializerContext.RDF_addBeanTypeProperties</del></code>
</ul>
<li>UON notation serializers and parsers moved into the new <code>org.apache.juneau.uon</code> package.
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#VOID} format to identify HTML void elements.
<li>Tweaks to HTML5 support.
<ul>
<li>Fixed handling of empty non-void elements in HTML serializer.
<li>Added <code>style()</code> override methods to all elements.
</ul>
<li>Improvements to Swagger support.
<ul>
<li>New {@link org.apache.juneau.dto.swagger.SwaggerBuilder} class.
<li>Fluent-style setters added to the Swagger beans.
<li>Added Swagger examples <code><del>here</del></code> and in the <del>org.apache.juneau.dto.swagger</del> javadocs.
</ul>
<li>Improvements to {@link org.apache.juneau.svl.VarResolver}.
<ul>
<li>New {@link org.apache.juneau.svl.vars.IfVar $IF} variable for if-else block logic.
<li><code><del>$SWITCH</del></code> variable for switch block logic.
<li>Whitespace wasn't being ignored in some cases.
</ul>
<li>{@link org.apache.juneau.html.HtmlParser} can now parse full body contents generated by {@link org.apache.juneau.html.HtmlDocSerializer}.
<li>Parse-args supported added to {@link org.apache.juneau.msgpack.MsgPackParser} to allow it to be used in remoteable proxies.
<li>Added some convenience classes for constructing collections using a fluent interface:
<ul>
<li>{@link org.apache.juneau.utils.AList}
<li>{@link org.apache.juneau.utils.ASet}
<li>{@link org.apache.juneau.utils.AMap}
</ul>
<li>New {@link org.apache.juneau.annotation.Bean#typePropertyName @Bean.typePropertyName()} annotation allows you to
specify the name of the <js>"_type"</js> property at the class level.
<li>New methods added to HTML5 container beans:
<ul>
<li>{@link org.apache.juneau.dto.html5.HtmlElementContainer#getChild(int...)}
<li>{@link org.apache.juneau.dto.html5.HtmlElementMixed#getChild(int...)}
</ul>
<li>New common serializer setting: <code><del>SerializerContext.SERIALIZER_abridged</del></code>.
<li>Support for defining interface proxies against 3rd-party REST interfaces.
<br>New package {@link org.apache.juneau.remoteable} for all remoteable proxy interface annotations.
<br><ja>@Remoteable</ja> annotation has been moved to this package.
<li>Updated doc: <code><del>6 - Remoteable Services</del></code>
<li>New doc: <code><del>6.1 - Interface proxies against 3rd-party REST interfaces</del></code>
<li>New URL-encoding serializer setting: <code><del>UrlEncodingSerializerContext.URLENC_paramFormat</del></code>.
<li>New methods on {@link org.apache.juneau.urlencoding.UrlEncodingSerializerBuilder}:
<ul>
<li><code><del>UrlEncodingSerializerBuilder.paramFormat(String)</del></code>
<li><code><del>UrlEncodingSerializerBuilder.plainTextParams()</del></code>
</ul>
</ul>
<h5 class='topic'>org.apache.juneau.rest</h5>
<ul class='spaced-list'>
<li>{@link org.apache.juneau.rest.annotation.RestResource @RestResource} annotation can now be applied to
any class! You're no longer restricted to subclassing your resources from {@link org.apache.juneau.rest.RestServlet}.
<br>This is a major enhancement in the API. Anything you could do by subclassing from <code>RestServlet</code>
should have an equivalent for non-<code>RestServlet</code> classes.
<br>The only restriction is that the top-level resource must subclass from <code>RestServlet</code>.
Child resources do not.
<br><br>
The majority of code has been split up into two separate classes:
<ul>
<li><code><del>RestConfig</del></code> - A modifiable configuration of a resource. Subclasses from {@link javax.servlet.ServletConfig}.
<li>{@link org.apache.juneau.rest.RestContext} - A read-only configuration that's the result of a snapshot of the config.
</ul>
<br><br>
The {@link org.apache.juneau.rest.RestServlet} class now has the following initialization method that allows you to override
the config settings define via annotations:
<ul>
<li><code><del>RestServlet.init(RestConfig)</del></code> - A modifiable configuration of a resource.
</ul>
Non-<code>RestServlet</code> classes must have one of the following to allow it to be instantiated:
<ul>
<li>A <code><jk>public</jk> T(RestConfig)</code> constructor.
<li>A <code><jk>public</jk> T()</code> constructor.
<li>The parent resource must have a customized {@link org.apache.juneau.rest.RestResourceResolver} for instantiating it.
</ul>
<br>
Non-<code>RestServlet</code> classes can optionally include the following init methods to gain access to the config and context:
<ul>
<li><code><del><jk>public</jk> init(RestConfig)</del></code>
<li><code><del><jk>public</jk> init(RestContext)</del></code>
</ul>
<li>New annotations added to {@link org.apache.juneau.rest.annotation.RestResource @RestResource} to allow non-<code>RestServlet</code>
resources to do the same as subclassing directly from <code>RestServlet</code>:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestResource#resourceResolver() resourceResolver()}
- Specify a {@link org.apache.juneau.rest.RestResourceResolver} class for resolving child resources.
<li>{@link org.apache.juneau.rest.annotation.RestResource#callHandler() callHandler()}
- Specify a {@link org.apache.juneau.rest.RestCallHandler} class for handling the lifecycle of a REST call.
<li>{@link org.apache.juneau.rest.annotation.RestResource#infoProvider() infoProvider()}
- Specify a {@link org.apache.juneau.rest.RestInfoProvider} class for customizing title/description/Swagger information on a REST resource.
<li>{@link org.apache.juneau.rest.annotation.RestResource#logger() logger()}
- Specify a {@link org.apache.juneau.rest.RestLogger} class for handling logging.
</ul>
<li>New annotations added to {@link org.apache.juneau.rest.annotation.RestResource @RestResource} and {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod}
to simplify defining page title, text, and links on HTML views:
<ul>
<li><code><del>@RestResource.pageTitle()</del></code>
<li><code><del>@RestMethod.pageTitle()</del></code>
<li><code><del>@RestResource.pageText()</del></code>
<li><code><del>@RestMethod.pageText()</del></code>
<li><code><del>@RestResource.pageLinks()</del></code>
<li><code><del>@RestMethod.pageLinks()</del></code>
</ul>
<p class='bcode'>
<jc>// Old method</jc>
<ja>@RestResource</ja>(
properties={
<ja>@Property</ja>(name=<jsf>HTMLDOC_title</jsf>, value=<js>"System properties resource"</js>),
<ja>@Property</ja>(name=<jsf>HTMLDOC_description</jsf>, value=<js>"REST interface for performing CRUD operations on system properties."</js>),
<ja>@Property</ja>(name=<jsf>HTMLDOC_navlinks</jsf>, value=<js>"{up:'$R{requestParentURI}',options:'?method=OPTIONS'}"</js>)
}
)
<jc>// New method</jc>
<ja>@RestResource</ja>(
pageTitle=<js>"System properties resource"</js>,
pageDescription=<js>"REST interface for performing CRUD operations on system properties."</js>,
pageLinks=<js>"{up:'$R{requestParentURI}',options:'?method=OPTIONS'}"</js>
)
</p>
<p>
Typically you're going to simply want to use the <code>title</code> and <code>description</code> annotations
which apply to both the page title/text and the swagger doc:
</p>
<p class='bcode'>
<ja>@RestResource</ja>(
title=<js>"System properties resource"</js>,
description=<js>"REST interface for performing CRUD operations on system properties."</js>,
pageLinks=<js>"{up:'$R{requestParentURI}',options:'?method=OPTIONS'}"</js>
)
</p>
<li><code><del>RestResource.stylesheet()</del></code> can now take in a comma-delimited list of stylesheet paths.
<li>{@link org.apache.juneau.rest.StreamResource} can now contain multiple sources from a variety of source types (e.g. <code><jk>byte</jk>[]</code> arrays, <code>InputStreams</code>, <code>Files</code>, etc...)
and is now immutable. It also includes a new {@link org.apache.juneau.rest.StreamResourceBuilder} class.
<li>Simplified remoteable proxies using the <code><ja>@RestMethod</ja>(name=<js>"PROXY"</js>)</code> annotation on REST methods.
Used to expose interface proxies without the need for {@link org.apache.juneau.rest.remoteable.RemoteableServlet}.
<p class='bcode'>
<jc>// Server side</jc>
<ja>@RestMethod</ja>(name=<js>"PROXY"</js>, path=<js>"/myproxy/*"</js>)
<jk>public</jk> IAddressBook getProxy() {
<jk>return</jk> <jf>addressBook</jf>;
}
<jc>// Client side</jc>
RestClient client = RestClient.<jsm>create</jsm>().rootUrl(<jf>samplesUrl</jf>).build();
IAddressBook ab = client.getRemoteableProxy(IAddressBook.<jk>class</jk>, <js>"/addressBook/myproxy"</js>);
</p>
See {@link org.apache.juneau.rest.annotation.RestMethod#name() @RestMethod.name()} for more information.
<li>{@link org.apache.juneau.rest.RestRequest#toString()} can be called at any time to view the headers and content of the request
without affecting functionality. Very useful for debugging.
<li>You can now use numeric values in path annotations.
<br>When using numeric variable names, you don't need to specify the variable name in the <ja>@Path</ja> annoation:
<p class='bcode'>
<ja>@RestMethod</ja>(name=<js>"GET"</js>, path=<js>"/myurl/{0}/{1}/{2}/*"</js>)
<jk>public void</jk> doGet(RestRequest req, RestResponse res,
<ja>@Path</ja> String foo, <ja>@Path</ja> <jk>int</jk> bar, <ja>@Path</ja> UUID baz) {
...
}
</p>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#name() @RestMethod.name()} annotation is now optional. Defaults to <js>"GET"</js>.
</ul>
<h5 class='topic'>org.apache.juneau.rest.client</h5>
<ul class='spaced-list'>
<li>Revamped the client API to use builders.
<li>New doc: <del>1.5 - Debugging</del>
<li>The <code>RestClient</code> class <code>doX(Object url)</code> methods now handle HttpClient <code>URIBuilder</code> instances.
<li>New methods added/updated to {@link org.apache.juneau.rest.client.RestClient}:
<ul>
<li>{@link org.apache.juneau.rest.client.RestClient#getRemoteableProxy(Class,Object) getRemoteableProxy(Class,Object)} - For interface proxies defined using <code><ja>@RestMethod</ja>(name=<js>"PROXY"</js>)</code>.
<li>{@link org.apache.juneau.rest.client.RestClient#getRemoteableProxy(Class,Object,Serializer,Parser) getRemoteableProxy(Class,Object,Serializer,Parser)} - Same as above, but overrides the serializer and parser defined on the client.
<li>{@link org.apache.juneau.rest.client.RestClient#doPost(Object) doPost(Object)}
<li>{@link org.apache.juneau.rest.client.RestClient#doCall(HttpMethod,Object,Object) doCall(HttpMethod,Object,Object)} - Can now pass in instances of {@link org.apache.juneau.rest.client.NameValuePairs} for easy form posts.
<br>This extends to all methods that take in the input.
</ul>
<li>New methods on {@link org.apache.juneau.rest.client.RestCall}:
<ul>
<li>{@link org.apache.juneau.rest.client.RestCall#uri(Object) uri(Object)}
<li><code><del>query(String,Object,boolean,PartSerializer)</del></code>
<li>{@link org.apache.juneau.rest.client.RestCall#query(String,Object) query(String,Object)}
<li>{@link org.apache.juneau.rest.client.RestCall#queryIfNE(String,Object) queryIfNE(String,Object)}
<li>{@link org.apache.juneau.rest.client.RestCall#query(Map) query(Map)}
<li>{@link org.apache.juneau.rest.client.RestCall#queryIfNE(Map) queryIfNE(Map)}
<li>{@link org.apache.juneau.rest.client.RestCall#query(String) query(String)}
<li><code><del>formData(String,Object,boolean,PartSerializer)</del></code>
<li>{@link org.apache.juneau.rest.client.RestCall#formData(String,Object) formData(String,Object)}
<li>{@link org.apache.juneau.rest.client.RestCall#formDataIfNE(String,Object) formDataIfNE(String,Object)}
<li>{@link org.apache.juneau.rest.client.RestCall#formData(Map) formData(Map)}
<li>{@link org.apache.juneau.rest.client.RestCall#formDataIfNE(Map) formDataIfNE(Map)}
<li><code><del>header(String,Object,boolean,PartSerializer)</del></code>
<li>{@link org.apache.juneau.rest.client.RestCall#header(String,Object) header(String,Object)}
<li>{@link org.apache.juneau.rest.client.RestCall#headerIfNE(String,Object) headerIfNE(String,Object)}
<li>{@link org.apache.juneau.rest.client.RestCall#headers(Map) headers(Map)}
<li>{@link org.apache.juneau.rest.client.RestCall#headersIfNE(Map) headersIfNE(Map)}
<li>{@link org.apache.juneau.rest.client.RestCall#host(String) host(String)}
<li>{@link org.apache.juneau.rest.client.RestCall#port(int) port(int)}
<li>{@link org.apache.juneau.rest.client.RestCall#userInfo(String,String) userInfo(String,String)}
<li>{@link org.apache.juneau.rest.client.RestCall#userInfo(String) userInfo(String)}
<li>{@link org.apache.juneau.rest.client.RestCall#scheme(String) scheme(String)}
</ul>
<li>New methods added to {@link org.apache.juneau.rest.client.RestClientBuilder}:
<ul>
<li>{@link org.apache.juneau.rest.client.RestClientBuilder#executorService(ExecutorService,boolean) executorService(ExecutorService,boolean)}
<li>{@link org.apache.juneau.rest.client.RestClientBuilder#paramFormat(String) paramFormat(ExecutorService,boolean)}
<li><code><del>RestClientBuilder.plainTextParams()</del></code>
<li>{@link org.apache.juneau.rest.client.RestClientBuilder#noTrace() noTrace()} - Adds a <code>No-Trace: true</code> header on all requests to prevent
the servlet from logging errors.
<br>Useful for testing scenarios when you don't want the console to end up showing errors done on purpose.
<li>{@link org.apache.juneau.rest.client.RestClientBuilder#debug() debug()} now adds a <code>Debug: true</code> header on all requests.
</ul>
<li>New methods added/updated to {@link org.apache.juneau.rest.client.RestCall}:
<ul>
<li>{@link org.apache.juneau.rest.client.RestCall#runFuture() runFuture()}
<li>{@link org.apache.juneau.rest.client.RestCall#getResponseFuture(Class) getResponseFuture(Class)}
<li>{@link org.apache.juneau.rest.client.RestCall#getResponseFuture(Type,Type...) getResponseFuture(Type,Type...)}
<li>{@link org.apache.juneau.rest.client.RestCall#getResponseAsStringFuture() getResponseAsStringFuture()}
<li>{@link org.apache.juneau.rest.client.RestCall#serializer(Serializer) serializer(Serializer)} - Override the serializer defined on the client for a single call.
<li>{@link org.apache.juneau.rest.client.RestCall#parser(Parser) parser(Parser)} - Override the parser defined on the client for a single call.
<li>{@link org.apache.juneau.rest.client.RestCall#input(Object) input(Object)} - Now accepts instances of {@link org.apache.juneau.rest.client.NameValuePairs}.
<li>{@link org.apache.juneau.rest.client.RestCall#getResponse(Class) getResponse(Class)} - Can now pass in any of the following:
<ul>
<li>{@link org.apache.http.HttpResponse} - Returns the raw <code>HttpResponse</code> returned by the inner <code>HttpClient</code>.
<li>{@link java.io.Reader} - Returns access to the raw reader of the response.
<li>{@link java.io.InputStream} - Returns access to the raw input stream of the response.
</ul>
</ul>
<li>New methods added to {@link org.apache.juneau.rest.client.NameValuePairs}:
<ul>
<li>{@link org.apache.juneau.rest.client.NameValuePairs#append(String,Object) append(String,Object)}
<li><code><del>append(String,Object,PartSerializer)</del></code>
</ul>
<li>{@link org.apache.juneau.rest.client.RetryOn} is now an abstract class with an additional method:
<ul>
<li>{@link org.apache.juneau.rest.client.RetryOn#onResponse(HttpResponse) onResponse(HttpResponse)}
</ul>
</ul>
<h5 class='topic'>org.apache.juneau.microservice</h5>
<ul class='spaced-list'>
<li><js>"REST/port"</js> configuration setting can now be a comma-limited list of port numbers to try.
<br>You can also specify one or more <code>0</code>s to try a random port.
<li>Methods added to {@link org.apache.juneau.microservice.RestMicroservice} class:
<ul>
<li>{@link org.apache.juneau.microservice.RestMicroservice#getPort()}
<li>{@link org.apache.juneau.microservice.RestMicroservice#getURI()}
<li>Override methods added from {@link org.apache.juneau.microservice.Microservice} class for easier method chaining.
</ul>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.1.0"></a>
<h3 class='topic' onclick='toggle(this)'>6.1.0 (Feb 25, 2017)</h3>
<div class='topic'>
<p>
Juneau 6.1.0 is a major update.
</p>
<p>
In particular, this release cleans up the {@link org.apache.juneau.BeanContext} API to match
the {@link org.apache.juneau.PropertyStore}/{@link org.apache.juneau.Context}/{@link org.apache.juneau.Session} paradigm
previously used in the serializer and parser APIs.
It also makes several improvements to the HTML and XML serialization support and introduces HTML5 DTO beans.
</p>
<h5 class='topic'>org.apache.juneau</h5>
<ul class='spaced-list'>
<li>Improvements to XML serialization support.
<ul>
<li>New supported XML formats:
<ul>
<li>{@link org.apache.juneau.xml.annotation.XmlFormat#ATTRS} format can now be applied to bean classes to have all bean properties serialized
as attributes instead of elements by default.
<li>{@link org.apache.juneau.xml.annotation.XmlFormat#ELEMENT} format can now be applied to bean properties to override the {@link org.apache.juneau.xml.annotation.XmlFormat#ATTRS}
setting above on specific bean properties.
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#ELEMENTS} format can be applied to a bean property of type array/Collection to represent the child elements.
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#MIXED} format can be applied to a bean property of type array/Collection to represent mixed content (text + child elements).
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#MIXED_PWS} format. Identical to <jsf>MIXED</jsf> except preserves whitespace.
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#TEXT} format can be applied to a bean property of a single object to represent a text node as a child.
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#TEXT_PWS} format. Identical to <jsf>TEXT</jsf> except preserves whitespace.
<li>New {@link org.apache.juneau.xml.annotation.XmlFormat#XMLTEXT} format that's identical to {@link org.apache.juneau.xml.annotation.XmlFormat#TEXT} except
XML content is not escaped and serialized directly as the child content. The parser will reconvert this to the original XML text during parsing.
</ul>
<li>New support methodology and other improvements to <a class='doclink' href='org/apache/juneau/xml/package-summary.html#TOC'>org.apache.juneau.xml</a> documentation.
<li>Eliminated unnecessary <xt>&lt;string&gt;</xt> elements.
<li>Eliminated <code><del>XmlContentHandler</del></code> class.
<li>Parser efficiency improvements through reuse of string builders.
<li>Reworked and simplified the default XML serializers. The {@link org.apache.juneau.xml.XmlSerializer#DEFAULT} serializer now has namespaces disabled,
and {@link org.apache.juneau.xml.XmlSerializer#DEFAULT_NS} has namespaces enabled. The 'XML-JSON' serializers have been eliminated.
<li>Eliminated the <code>addJsonTypeAttrs</code> and <code>addJsonStringTypeAttrs</code> settings.
<li>Namespace support is now disabled by default.
</ul>
<li>Significant modifications and improvements to HTML serialization support.
<ul>
<li>Parser converted from <code>XMLEventReader</code>-based to <code>XMLStreamReader</code>.
<li>Eliminated many unnecessary type tags and <xt>&lt;string&gt;</xt> elements and improved the readable layout.
The new format is much leaner.
<li>New exhaustive support methodology section added to <a class='doclink' href='org/apache/juneau/html/package-summary.html#TOC'>org.apache.juneau.html</a> documentation.
</ul>
<li>New HTML5 DTO support: <a class='doclink' href='org/apache/juneau/dto/html5/package-summary.html#TOC'>org.apache.juneau.dto.html5</a>.
<li>{@link org.apache.juneau.BeanContext} class split into separate {@link org.apache.juneau.BeanContext} and {@link org.apache.juneau.BeanSession} classes.
<ul>
<li>Session object meant to be single-use that can be discarded after use and contains session-level object cache and overridable Locale and TimeZone.
</ul>
<li><code><del>SerializerContext</del></code> and <code><del>ParserContext</del></code>
now extend directly from {@link org.apache.juneau.BeanContext}.
<li>{@link org.apache.juneau.serializer.SerializerSession} and {@link org.apache.juneau.parser.ParserSession}
now extend directly from {@link org.apache.juneau.BeanSession}.
<li>New settings in {@link org.apache.juneau.BeanContext}:
<ul>
<li>{@link org.apache.juneau.BeanContext#BEAN_debug} - Debug setting. Replaces individual debug properties in the serializer and parser contexts.
<li>{@link org.apache.juneau.BeanContext#BEAN_locale} - Specifies a default locale at the context level.
<li>{@link org.apache.juneau.BeanContext#BEAN_timeZone} - Specifies a default timezone at the context level.
<li>{@link org.apache.juneau.BeanContext#BEAN_mediaType} - Specifies a default media type at the context level.
</ul>
<li>Improvements to Parser class:
<ul>
<li>Simplified the parse methods (e.g. <code>parseMap()</code>, <code>parseCollection()</code>)
by replacing them with two simple methods:
<ul>
<li>{@link org.apache.juneau.parser.Parser#parse(Object,Class)} - Normal method.
<li>{@link org.apache.juneau.parser.Parser#parse(Object,Type,Type...)} - Method for parsing into parameterized maps and collections.
</ul>
Using these methods, you can construct arbitrarily complex objects consisting of maps and collections.
You could do this before, but it required constructing a <code>ClassMeta</code> object.
<br>For example:
<p class='bcode'>
<jc>// Old way:</jc>
ClassMeta&lt;?&gt; cm = parser.getMapClassMeta(
HashMap.<jk>class</jk>,
String.<jk>class</jk>,
parser.getCollectionClassMeta(
LinkedList.<jk>class</jk>,
MyBean.<jk>class</jk>
)
);
Map&lt;String,List&lt;MyBean&gt;&gt; map = (Map&lt;String,List&lt;MyBean&gt;&gt;)parser.parse(input, cm);
<jc>// New way:</jc>
Map&lt;String,List&lt;MyBean&gt;&gt; map = parser.parse(input, HashMap.<jk>class</jk>, String.<jk>class</jk>, LinkedList.<jk>class</jk>, MyBean.<jk>class</jk>);
</p>
<li>Arbitrarily-complex parameterized maps and collections can now be parsed without the need for creating intermediate <code>ClassMeta</code> objects.
<li>No need for casting anymore if you were using the old <code>parseMap()</code> and <code>parseCollection()</code> methods!
<li>Changes allow me to eliminate <code>BeanContext.normalizeClassMeta()</code> method.
<li>Convenience methods added for setting parser properties:
<p class='bcode'>
<jc>// Old way:</jc>
<jk>new</jk> JsonParser().setProperty(<jsf>PARSER_strict</jsf>, <jk>true</jk>).setProperty(<jsf>BEAN_locale</jsf>, mylocale);
<jc>// New way:</jc>
<jk>new</jk> JsonParser().setStrict(<jk>true</jk>).setLocale(mylocale);
</p>
</ul>
<li>Improvements to Serializer class:
<ul>
<li>Convenience methods added for setting serializer properties:
<p class='bcode'>
<jc>// Old way:</jc>
<jk>new</jk> JsonSerializer().setProperty(<jsf>JSON_simpleMode</jsf>, <jk>true</jk>).setProperty(<jsf>SERIALIZER_quoteChar</jsf>, <js>'"'</js>);
<jc>// New way:</jc>
<jk>new</jk> JsonSerializer().setSimpleMode(<jk>true</jk>).setQuoteChar(<js>'"'</js>);
</p>
</ul>
<li>Simplified {@link org.apache.juneau.transform.PojoSwap} class. Now just two methods:
<ul>
<li>{@link org.apache.juneau.transform.PojoSwap#swap(BeanSession,Object)}
<li>{@link org.apache.juneau.transform.PojoSwap#unswap(BeanSession,Object,ClassMeta)}
</ul>
<li>General code improvements made to {@link org.apache.juneau.ClassMeta} class.
<ul>
<li>All fields are now final which should improve overall performance.
<li>Replaced support for <code>toObjectMap()</code> and <code>fromObjectMap()/T(ObjectMap)</code> methods with
generalized <code>swap(BeanSession)</code>/<code>unswap(BeanSession,X)</code>/<code>T(BeanSession,X)</code> methods.<br>
See new section <code><del>Swap methods</del></code> for information.
</ul>
<li>Session-level media type now available through {@link org.apache.juneau.BeanSession#getMediaType()} method.
Allows for swaps and serializer/parser behavior to be tailored to individual media types.
<li>Several new {@link java.util.Calendar} and {@link java.util.Date} swaps:
<ul>
<li>{@link org.apache.juneau.transforms.CalendarSwap.ToString},{@link org.apache.juneau.transforms.DateSwap.ToString} - To {@link java.lang.String Strings} using the {@code Date.toString()} method.
<li>{@link org.apache.juneau.transforms.CalendarSwap.ISO8601DT},{@link org.apache.juneau.transforms.DateSwap.ISO8601DT} - To ISO8601 date-time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.ISO8601DTZ},{@link org.apache.juneau.transforms.DateSwap.ISO8601DTZ} - Same as <jsf>ISO8601DT</jsf>, except always serializes in GMT.
<li>{@link org.apache.juneau.transforms.CalendarSwap.ISO8601DTP},{@link org.apache.juneau.transforms.DateSwap.ISO8601DTP} - Same as <jsf>ISO8601DT</jsf> except with millisecond precision.
<li>{@link org.apache.juneau.transforms.CalendarSwap.ISO8601DTPZ},{@link org.apache.juneau.transforms.DateSwap.ISO8601DTPZ} - Same as <jsf>ISO8601DTZ</jsf> except with millisecond precision.
<li>{@link org.apache.juneau.transforms.CalendarSwap.RFC2822DT},{@link org.apache.juneau.transforms.DateSwap.RFC2822DT} - To RFC2822 date-time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.RFC2822DTZ},{@link org.apache.juneau.transforms.DateSwap.RFC2822DTZ} - Same as <jsf>RFC2822DT</jsf>, except always serializes in GMT.
<li>{@link org.apache.juneau.transforms.CalendarSwap.RFC2822D},{@link org.apache.juneau.transforms.DateSwap.RFC2822D} - To RFC2822 date strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateTimeSimple},{@link org.apache.juneau.transforms.DateSwap.DateTimeSimple} - To simple <js>"yyyy/MM/dd HH:mm:ss"</js> date-time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateSimple},{@link org.apache.juneau.transforms.DateSwap.DateSimple} - To simple <js>"yyyy/MM/dd"</js> date strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.TimeSimple},{@link org.apache.juneau.transforms.DateSwap.TimeSimple} - To simple <js>"HH:mm:ss"</js> time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateFull},{@link org.apache.juneau.transforms.DateSwap.DateFull} - To {@link java.text.DateFormat#FULL} date strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateLong},{@link org.apache.juneau.transforms.DateSwap.DateLong} - To {@link java.text.DateFormat#LONG} date strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateMedium},{@link org.apache.juneau.transforms.DateSwap.DateMedium} - To {@link java.text.DateFormat#MEDIUM} date strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateShort},{@link org.apache.juneau.transforms.DateSwap.DateShort} - To {@link java.text.DateFormat#SHORT} date strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.TimeFull},{@link org.apache.juneau.transforms.DateSwap.TimeFull} - To {@link java.text.DateFormat#FULL} time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.TimeLong},{@link org.apache.juneau.transforms.DateSwap.TimeLong} - To {@link java.text.DateFormat#LONG} time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.TimeMedium},{@link org.apache.juneau.transforms.DateSwap.TimeMedium} - To {@link java.text.DateFormat#MEDIUM} time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.TimeShort},{@link org.apache.juneau.transforms.DateSwap.TimeShort} - To {@link java.text.DateFormat#SHORT} time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateTimeFull},{@link org.apache.juneau.transforms.DateSwap.DateTimeFull} - To {@link java.text.DateFormat#FULL} date-time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateTimeLong},{@link org.apache.juneau.transforms.DateSwap.DateTimeLong} - To {@link java.text.DateFormat#LONG} date-time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateTimeMedium},{@link org.apache.juneau.transforms.DateSwap.DateTimeMedium} - To {@link java.text.DateFormat#MEDIUM} date-time strings.
<li>{@link org.apache.juneau.transforms.CalendarSwap.DateTimeShort},{@link org.apache.juneau.transforms.DateSwap.DateTimeShort} - To {@link java.text.DateFormat#SHORT} date-time strings.
</ul>
<li>New method {@link org.apache.juneau.serializer.SerializerGroup#getSerializerMatch(String)} that returns the matched serializer and media type.
<li>New method {@link org.apache.juneau.parser.ParserGroup#getParserMatch(String)} that returns the matched parser and media type.
<li>New method {@link org.apache.juneau.encoders.EncoderGroup#getEncoderMatch(String)} that returns the matched encoder and encoding.
<li>General improvements to Bean Dictionary support.
<ul>
<li>New {@link org.apache.juneau.BeanDictionaryList} class can be used for defining reusable sets of bean dictionaries consisting
of classes annotated with {@link org.apache.juneau.annotation.Bean#typeName() @Bean.typeName()}.
<li>New {@link org.apache.juneau.BeanDictionaryMap} class can be used for defining reusable sets of bean dictionaries consisting
of classes not annotated with {@link org.apache.juneau.annotation.Bean#typeName() @Bean.typeName()}.
<li>New {@link org.apache.juneau.annotation.Bean#beanDictionary() @Bean.beanDictionary()} annotation.
</ul>
<li>Removed restriction on getters and setters to be prefixed with "getX/setX/isX" if a {@link org.apache.juneau.annotation.BeanProperty#name() @BeanProperty.name()} annotation is used.
<li>Improvements to ATOM DTO:
<ul>
<li>New {@link org.apache.juneau.dto.atom.AtomBuilder} class.
<li>New setter method names for a better fluent design.
<li>Updated <a class='doclink' href='org/apache/juneau/dto/atom/package-summary.html#TOC'>org.apache.juneau.dto.atom</a> documentation.
</ul>
<li>New {@link org.apache.juneau.transform.MapSwap} and {@link org.apache.juneau.transform.StringSwap} classes.
<li>New {@link org.apache.juneau.serializer.WriterSerializer#println(Object)} method. Useful for debugging purposes.
<li>New {@link org.apache.juneau.BeanContext#getClassMeta(Type,Type...)} and {@link org.apache.juneau.BeanSession#getClassMeta(Type,Type...)}
methods for retrieving Map and Collection class metas.
Replaces the various <code>getMapClassMeta()</code>/<code>getCollectionClassMeta()</code> methods.
<li>New section added to this document: <code><del>Juneau Data Transfer Objects (org.apache.juneau.dto)</del></code>
<li>Modified the UON specification to work with mixed content.
<ul>
<li>The new specification is considerably cleaner and eliminates the need for separate normal/simple modes.
<br>It also allows for arbitrary whitespace to be added to the output without any confusion.
<li>Eliminated the <code>UonParser.<jsf>DEFAULT_WS_AWARE</jsf></code> and <code>UrlEncodingParser.<jsf>DEFAULT_WS_AWARE</jsf></code> parsers.
<br>The normal {@link org.apache.juneau.uon.UonParser#DEFAULT} and {@link org.apache.juneau.urlencoding.UrlEncodingParser#DEFAULT} parsers will now handle whitespace.
<li>Eliminated the <code>UonParserContext.<jsf>UON_whitespaceAware</jsf></code> configuration setting.
<li>Eliminated the <code>UonSerializer.<jsf>DEFAULT_SIMPLE</jsf></code>, <code>UonSerializer.<jsf>DEFAULT_SIMPLE_ENCODING</jsf></code>
and <code>UrlEncodingSerializer.<jsf>DEFAULT_SIMPLE</jsf></code>
serializers since there is no separate simple mode anymore.
<li>Eliminated the <code>UonParserContext.<jsf>UON_simpleMode</jsf></code> configuration setting.
</ul>
<li>Added new {@link org.apache.juneau.serializer.OutputStreamSerializer#serializeToHex(Object)} method.
<br>Useful mostly for testing purposes.
<br>Equivalently, the {@link org.apache.juneau.parser.InputStreamParser#parse(Object,Class)} method can now
read the output from this method.
<li>Eliminated the <code><ja>@Bean</ja>(subTypeProperty)</code> and <code><ja>@Bean</ja>(subTypes)</code> annotations
and replaced them with the ability to define subtypes using the existing {@link org.apache.juneau.annotation.Bean#beanDictionary() @Bean.beanDictionary()}
annotation on parent classes and interfaces.
<br>This has the added benefit of simplifying the overall code.
<li>The <code><del>SerializerContext.SERIALIZER_addBeanTypeProperties</del></code> setting is now enabled by default.
<li>Combined the <code>SERIALIZER_addIndentation</code>/<code>JSON_addWhitespace</code>/<code>UON_addWhitespace</code>
properties into a single <code><del>SerializerContext.SERIALIZER_useWhitespace</del></code> setting.
</ul>
<h5 class='topic'>org.apache.juneau.rest</h5>
<ul class='spaced-list'>
<li>{@link org.apache.juneau.rest.RestRequest} now passes locale and timezone to serializers/parsers/transforms.
<li><code><del>RestRequest.getTimeZone()</del></code> method.
<li>Standardized the following methods in {@link org.apache.juneau.rest.RestRequest} to remove dependency on <code>ClassMeta</code>
objects and eliminate the need for casts:
<ul>
<li><code><del>RestRequest.getHeader(String,Class)</del></code>
<li><code><del>RestRequest.getHeader(String,Object,Class)</del></code>
<li><code><del>RestRequest.getHeader(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Class)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Object,Class)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Object,Type,Type...)</del></code>
<li><code><del>RestRequest.getQueryParameters(String,Class)</del></code>
<li><code><del>RestRequest.getQueryParameters(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getFormDataParameter(String,Class)</del></code>
<li><code><del>RestRequest.getFormDataParameter(String,Object,Class)</del></code>
<li><code><del>RestRequest.getFormDataParameters(String,Class)</del></code>
<li><code><del>RestRequest.getFormDataParameter(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getFormDataParameters(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getPathParameter(String,Class)</del></code>
<li><code><del>RestRequest.getPathParameter(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getBody(Class)</del></code>
<li><code><del>RestRequest.getBody(Type,Type...)</del></code>
</ul>
<li>New methods on {@link org.apache.juneau.rest.client.NameValuePairs}
<li>Fixed issue where whitespace was not added to UON/URL-Encoding output when <code>&amp;plainText=true</code> specified.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.0.1"></a>
<h3 class='topic' onclick='toggle(this)'>6.0.1 (Jan 3, 2017)</h3>
<div class='topic'>
<p>
Juneau 6.0.1 is a minor update.
</p>
<h5 class='topic'>org.apache.juneau</h5>
<ul class='spaced-list'>
<li>General improvements to JSON parser.
<ul>
<li>Several fixes to handle obscure edge cases.
</ul>
<li>New properties in <code><del>ParserContext</del></code>.
<ul>
<li><code><del>ParserContext.PARSER_strict</del></code>
<li><code><del>ParserContext.PARSER_inputStreamCharset</del></code>
<li><code><del>ParserContext.PARSER_fileCharset</del></code>
</ul>
<li>Removed <code>JsonParserContext.JSON_strictMode</code>. Replaced by <code>PARSER_strict</code>.
<li><code><jk>byte[]</jk></code> arrays can now be passed to {@link org.apache.juneau.parser.Parser#parse(Object,Class)} for reader-based parsers.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="6.0.0"></a>
<h3 class='topic' onclick='toggle(this)'>6.0.0 (Oct 3, 2016)</h3>
<div class='topic'>
<p>
Juneau 6.0.0 is a major update.
</p>
<p>
The major change is rebranding from "Juno" to "Juneau" in preparation for donation to the Apache Foundation.
</p>
<h5 class='topic'>org.apache.juneau</h5>
<ul class='spaced-list'>
<li>Major changes around how serializer and parser class properties are defined to improve performance
and concurrency.
<ul>
<li>New {@link org.apache.juneau.PropertyStore} class - Used for creating context objects.
<li>New {@link org.apache.juneau.Context} class - Read-only configurations for serializers and parsers.
<li>New {@link org.apache.juneau.Session} class - One-time use objects used by serializers and parsers.
<li>All context context properties can now also be specified via system properties.
</ul>
</li>
<li>Refactored serializer and parser APIs for more consistency between stream-based and character-based serializers
and parsers.
<ul>
<li>More consistent handling of exceptions.
<li>More consistent method declarations.
</ul>
<li>Refactored var resolver API and added them to a new package - <code>org.apache.juneau.svl</code>.
<ul>
<li>Support for stream-based variables - {@link org.apache.juneau.svl.StreamedVar}.
<li>Added support for context and session objects.
</ul>
<li>Eliminated <js>"_class"</js> properties and replaced them with <js>"_type"</js> properties.
The class properties were a little-used feature where we would serialize fully-qualified class names when the class type could not be inferred through reflection.
It's been replaced with bean type names and bean dictionaries.
Instead of class names, we serialize <js>"_type"</js> properties whose name is the type name defined on the bean being serialized.
The parsers use a 'dictionary' of bean classes to resolve those names to actual bean classes.
The following features were added to enable this support:
<ul>
<li>{@link org.apache.juneau.annotation.Bean#typeName() @Bean.typeName()} - Annotation that defines an identifying name for a bean class.
<li>{@link org.apache.juneau.transform.BeanFilterBuilder#typeName(String)} - Programmatic equivalent to annotation above.
<li>{@link org.apache.juneau.BeanContext#BEAN_beanDictionary} - List of bean classes that make up the bean dictionary for lookup
during parsing.
<li>{@link org.apache.juneau.BeanContext#BEAN_beanTypePropertyName} - The overridable type property name. Default is <js>"_type"</js>.
<li>{@link org.apache.juneau.annotation.BeanProperty#beanDictionary() @BeanProperty.beanDictionary()} - Define a type dictionary
for a particular bean property value. This overrides the value specified using {@link org.apache.juneau.BeanContext#BEAN_beanDictionary}.
<li><code><del>SerializerContext.SERIALIZER_addBeanTypeProperties</del></code> - Controls whether type properties are serialized.
</ul>
In addition, the {@link org.apache.juneau.annotation.Bean#typeName() @Bean.typeName()} value replaces the <code>@Xml.name()</code> annotation, and the
<js>"type"</js> and <js>"_class"</js> attributes in the XML and HTML serializers have been standardized on a single <js>"_type"</js> attribute.
<li>Refactor bean filter support to use {@link org.apache.juneau.transform.BeanFilterBuilder} class.
Allows the <code>BeanFilter</code> class to use final fields.
<li>{@link org.apache.juneau.msgpack MessagePack} support.
<li>Serializers can now serialize directly to {@link java.io.File Files}.
See {@link org.apache.juneau.serializer.Serializer#serialize(Object,Object)}
<li>Parsers can now parse directly from {@link java.io.File Files} and other types.
See {@link org.apache.juneau.parser.Parser#parse(Object,ClassMeta)}
<li>Parsers will automatically covert numeric input to POJOs that have numeric constructors (e.g. <code>java.util.Date</code>).
<li>Renamed 'Filters' to 'BeanFilters' and 'PojoSwaps'. Filters is just too overloaded a term.
<li>Internal utility classes moved to a new <code>org.apache.juneau.internal</code> package.
These internal utility classes are not meant for consumption outside the Juneau codebase.
<li>New methods on {@link org.apache.juneau.parser.Parser}:
<ul>
<li><code>org.apache.juneau.parser.Parser.createSession(ObjectMap,Method,Object)</code>
<li><code><del>Parser.getMediaRanges()</del></code>
</ul>
</li>
<li>New methods on {@link org.apache.juneau.serializer.Serializer}:
<ul>
<li><code>org.apache.juneau.serializer.Serializer.createSession(ObjectMap,Method)</code>
<li><code><del>Serializer.getMediaRanges()</del></code>
</ul>
</li>
<li>New {@link org.apache.juneau.annotation.Bean#sort() @Bean.sort()} annotation.
<li>Added <ja>@Bean.properties</ja> annotations on various DTO beans to make the ordering consistent
between IBM and Oracle JVMs.<br>
IBM JVMs maintain the order of methods in a class, whereas Oracle JVMs do not.
<li>Serializers and parsers now automatically convert {@link java.lang.Class} objects to readable names via {@link org.apache.juneau.internal.ClassUtils#getReadableClassName(Class)}.
<li>Eliminated the <code>ClassFilter</code> class since it's no longer needed.
<li>Code and concurrency improvements to {@link org.apache.juneau.serializer.SerializerGroup} and {@link org.apache.juneau.parser.ParserGroup}.
<li>Various enhancements to <code><del>BeanContext.convertToType(Object,Class)</del></code>.
<li>New properties on {@link org.apache.juneau.html.HtmlSerializer}:
<ul>
<li><code><del>HtmlSerializerContext.HTML_detectLinksInStrings</del></code> - Automatically detect hyperlinks in strings.
<li><code><del>HtmlSerializerContext.HTML_lookForLabelParameters</del></code> - Specify anchor text by appending <code>&amp;label=MyLabel</code> to URL.
<li><code><del>HtmlSerializerContext.HTML_labelParameter</del></code> - Specify what URL parameter to use as the anchor text label.
<li><code><del>HtmlSerializerContext.URI_ANCHOR</del></code> option for <code><del>HtmlSerializerContext.HTML_uriAnchorText</del></code>.
</ul>
</li>
<li>Removed generics from {@link org.apache.juneau.BeanPropertyMeta}.
<li>Introduced new classes to eliminate the references to language-specific metadata in the core metadata classes:
<ul>
<li>{@link org.apache.juneau.ClassMetaExtended} / {@link org.apache.juneau.ClassMeta#getExtendedMeta(Class)}
<li>{@link org.apache.juneau.BeanMetaExtended} / {@link org.apache.juneau.BeanMeta#getExtendedMeta(Class)}
<li>{@link org.apache.juneau.BeanPropertyMetaExtended} / {@link org.apache.juneau.BeanPropertyMeta#getExtendedMeta(Class)}
</ul>
</li>
<li>Renamed <code>@Transform</code> annotation to <code><del>@Pojo</del></code> so that it can be used for various POJO-related behavior, not just associating transforms.
<li>Introduced {@link org.apache.juneau.dto.swagger Swagger DTOs}.
</ul>
<h5 class='topic'>org.apache.juneau.rest</h5>
<ul class='spaced-list'>
<li>OPTIONS pages replaced with Swagger documents.
Lots of changes related to supporting Swagger.
<ul>
<li>Annotation name changes to conform to Swagger specs: <ja>@Attr</ja>-&gt;<ja>@Path</ja>, <ja>@QParam</ja>-&gt;<ja>@Query</ja>, <ja>@Param</ja>-&gt;<ja>@FormData</ja>, <ja>@Content</ja>-&gt;<ja>@Body</ja>
<li>Eliminated <code>ResourceOptions</code> and related code.
<li>New annotations and related methods:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestResource#title() @RestResource.title()} / {@link org.apache.juneau.rest.RestInfoProvider#getTitle(RestRequest)}
<li>{@link org.apache.juneau.rest.annotation.RestResource#description() @RestResource.description()} / {@link org.apache.juneau.rest.RestInfoProvider#getDescription(RestRequest)}
<li><code><del>@RestResource.termsOfService()</del></code> / <code><del>RestInfoProvider.getTermsOfService(RestRequest)</del></code>
<li><code><del>@RestResource.contact()</del></code> / <code><del>RestInfoProvider.getContact(RestRequest)</del></code>
<li><code><del>@RestResource.license()</del></code> / <code><del>RestInfoProvider.getLicense(RestRequest)</del></code>
<li><code><del>@RestResource.version()</del></code> / <code><del>RestInfoProvider.getVersion(RestRequest)</del></code>
<li><code><del>@RestResource.tags()</del></code> / <code><del>RestInfoProvider.getTags(RestRequest)</del></code>
<li><code><del>@RestResource.externalDocs()</del></code> / <code><del>RestInfoProvidergetExternalDocs(RestRequest)</del></code>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#summary() @RestMethod.summary()} / <code><del>RestInfoProvider.getMethodSummary(String,RestRequest)</del></code>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#description() @RestMethod.description()} /<code><del>RestInfoProvider.getMethodDescription(String,RestRequest)</del></code>
<li><code><del>@RestMethod.externalDocs()</del></code>
<li><code><del>@RestMethod.tags()</del></code>
<li><code><del>@RestMethod.deprecated()</del></code>
<li><code><del>@RestMethod.parameters()</del></code>
<li><code><del>@RestMethod.responses()</del></code>
</ul>
</li>
</ul>
<li>New <code><del>RestServletContext.paramFormat</del></code> context property.
<li>New/updated methods on {@link org.apache.juneau.rest.RestServlet}:
<ul>
<li><code><del>RestServlet.createProperties()</del></code>
<li><code><del>RestServlet.createBeanContext(ObjectMap,Class[],Class[])</del></code>
<li><code><del>RestServlet.createBeanFilters()</del></code>
<li><code><del>RestServlet.createPojoSwaps()</del></code>
<li><code><del>RestServlet.createParsers(ObjectMap,Class[],Class[])</del></code>
<li><code><del>RestServlet.createUrlEncodingSerializer(ObjectMap,Class[],Class[])</del></code>
<li><code><del>RestServlet.createUrlEncodingParser(ObjectMap,Class[],Class[])</del></code>
<li><code><del>RestServlet.createConverters(ObjectMap)</del></code>
<li><code><del>RestServlet.createDefaultRequestHeaders(ObjectMap)</del></code>
<li><code><del>RestServlet.createDefaultResponseHeaders(ObjectMap)</del></code>
<li><code><del>RestServlet.createEncoders(ObjectMap)</del></code>
<li><code><del>RestServlet.createGuards(ObjectMap)</del></code>
<li><code><del>RestServlet.createMimetypesFileTypeMap(ObjectMap)</del></code>
<li><code><del>RestServlet.createResponseHandlers(ObjectMap)</del></code>
</ul>
</li>
<li>New client-version annotations:
<ul>
<li>{@link org.apache.juneau.rest.annotation.RestResource#clientVersionHeader} - The name of the header used to identify the client version.
<li>{@link org.apache.juneau.rest.annotation.RestMethod#clientVersion} - The client version range applied to a Java method.
</ul>
</li>
</ul>
<h5 class='topic'>org.apache.juneau.rest.client</h5>
<ul class='spaced-list'>
<li>Removed the <code>JazzRestClient</code> class.
<li>New method <code><del>RestClient.setClientVersion(String)</del></code>.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.2.0.1"></a>
<h3 class='topic' onclick='toggle(this)'>5.2.0.1 (Mar 23, 2016)</h3>
<div class='topic'>
<p>
Juno 5.2.0.1 is a moderate update.
</p>
<h5 class='topic'>com.ibm.team.juno</h5>
<ul class='spaced-list'>
<li>Improved support for multi-line values in config files.
Any line that begins with whitespace is interpreted as a continuation of the previous line.
<li>Support for <js>'\uXXXX'</js> character sequences in config files.
<li>Fixed issue in {@link org.apache.juneau.xml.XmlSerializer} where <js>'\r'</js> and <js>'\n'</js> characters were not being handled per XML specs.
<li>New methods on {@link org.apache.juneau.ObjectList}:
<ul>
<li><code><del>ObjectList.getAt(Class,String)</del></code>
<li>{@link org.apache.juneau.ObjectList#putAt(String,Object)}
<li>{@link org.apache.juneau.ObjectList#postAt(String,Object)}
<li>{@link org.apache.juneau.ObjectList#deleteAt(String)}
</ul>
<li>New methods on {@link org.apache.juneau.ObjectMap}:
<ul>
<li><code><del>ObjectMap.getAt(Class,String)</del></code>
<li>{@link org.apache.juneau.ObjectMap#putAt(String,Object)}
<li>{@link org.apache.juneau.ObjectMap#postAt(String,Object)}
<li>{@link org.apache.juneau.ObjectMap#deleteAt(String)}
</ul>
<li><code><del>@ThreadSafe</del></code> annotation.
<li>New <code>ClassFilter</code> class.
<li><del><code>ConfigFile.getResolving(StringVarResolver,boolean)</code></del> method.
<li><del><code>ConfigFile.getStringVar()</code></del> method.
<li>New <code><del>ParserContext.PARSER_trimStrings</del></code> property.
<li>New <code><del>SerializerContext.SERIALIZER_trimStrings</del></code> property.
<li><del><code>Args.getStringVar()}</code></del> method.
<li>New {@link org.apache.juneau.utils.ManifestFile} class
<li>New {@link org.apache.juneau.utils.MessageBundle} class. Replaces <l>SafeResourceBundle</l>/<l>SafeResourceMultiBundle</l>/<l>RestNls</l>.
<li>New <del><code>StringMapVar</code></del> class.
<li>New <del><code>StringVars</code></del> class with reusable common <del><code>StringVar</code></del> instances.
<li>New {@link org.apache.juneau.internal.JuneauLogger} class.
<li>Default value for <code><del>XmlParserContext.XML_trimWhitespace</del></code> changed to <jk>true</jk>.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>New methods on {@link org.apache.juneau.rest.RestContext}:
<ul>
<li>{@link org.apache.juneau.rest.RestContext#getMessages()}
</ul>
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>Fixed potential issue in {@link org.apache.juneau.rest.client.RestClient} where the HTTP connection pool could end up exhausted if an error occurred.
<li>Improved thread safety on {@link org.apache.juneau.rest.client.RestClient}.
<li>New warning message is logged if a {@link org.apache.juneau.rest.client.RestClient} is garbage collected without being closed:
<js>"WARNING: RestClient garbage collected before it was finalized."</js>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.2.0.0"></a>
<h3 class='topic' onclick='toggle(this)'>5.2.0.0 (Dec 30, 2015)</h3>
<div class='topic'>
<p>
Juno 5.2.0.0 is a major update.
Major changes have been made to the microservice architecture and config INI file APIs.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Significant changes and enhancements to the <code>org.apache.juneau.config</code> API.
<ul>
<li>More consistent handling of comma-delimited lists of objects.
<li>New methods in <code><del>ConfigFile</del></code>:
<ul>
<li><code><del>ConfigFile.getStringArray(String)</del></code>,<code><del>ConfigFile.getStringArray(String,String[])</del></code>
<li><code><del>ConfigFile.getSectionAsBean(String,Class)</del></code> - Instantiate a new bean with property values in the specified section..
<li><code><del>ConfigFile.writeProperties(String,Object,boolean,Class[])</del></code> - Copy the properties in a config file section into properties on an existing bean or POJO.
<li><code><del>ConfigFile.getSectionMap(String)</del></code> - Get all the resolved values in a section.
<li><code><del>ConfigFile.containsNonEmptyValue(String)</del></code>
<li><code><del>ConfigFile.isEncoded(String)</del></code>
<li><code><del>ConfigFile.addListener(ConfigFileListener)</del></code> - Listen for modification events on the config file.
<li><code><del>ConfigFile.merge(ConfigFile)} - Merge the contents of another config file into this config file.
<li><code><del>ConfigFile.getResolving()}, <del><code>ConfigFile.getResolving(StringVarResolver)</code></del> - Return an instance of the config file that resolves string variables.
Much more efficient than the previous design since the same underlying config file object is shared.
<li><code><del>ConfigFile.toWritable()</del></code> - Wraps the config file in a {@link org.apache.juneau.Writable} interface so that it can be serialized by the REST interface as a plain-text INI file instead of as a serialized POJO.
<li><code><del>ConfigFile.getInt(String)</del></code> - Now supports <js>"M"</js> and <js>"K"</js> to identify millions and thousands.
</ul>
<li>New methods in <code><del>ConfigMgr</del></code>:
<ul>
<li><code><del>ConfigMgr.create()</del></code>, <code><del>ConfigMgr.create(Reader)</del></code>, <code><del>ConfigMgr.create(File)</del></code>
<li><code><del>ConfigMgr.deleteAll()</del></code>
</ul>
<li>New methods in <code><del>Section</del></code>:
<ul>
<li><code><del>Section.setParent(ConfigFileImpl)</del></code> - Used by parsers to set the config file for this section.
<li><code><del>Section.setName(String)</del></code> - Used by parsers to set the name for this section.
</ul>
<li>New interfaces:
<ul>
<li><code><del>org.apache.juneau.config.ConfigFileListener</del></code>
<li><code><del>org.apache.juneau.config.SectionListener</del></code>
<li><code><del>org.apache.juneau.config.EntryListener</del></code>
</ul>
<li><code><del>org.apache.juneau.config.Encoder</del></code> methods have access to field names to use them as salt values.
<li>The name of the default section is now <js>"default"</js>. Before it was just <jk>null</jk>.
<li><code><del>org.apache.juneau.config.XorEncoder</del></code> XOR key can be overridden through the <js>"org.apache.juneau.config.XorEncoder.key"</js> system property.
</ul>
<li>Support for converting Strings to POJOs if the POJO class has any of the following static methods:
<ul>
<li><code>fromString(String)</code>
<li><code>valueOf(String)</code> (e.g. enums)
<li><code>parse(String)</code> (e.g. logging <code>Level</code> class)
<li><code>parseString(String)</code>
<li><code>forName(String)</code> (e.g. <code>Class</code> and <code>Charset</code> classes)
</ul>
<li>Support for parsing into objects with unbound type variables.
For example, if you have a class <code>Pair&lt;S,T&gt;</code> and you try to parse into this
class (e.g. <code>parser.parse(in, Pair.<jk>class</jk>)</code>), the unbound type variables
is interpreted as <code>Object</code> instead of throwing an exception.
<li>Support for serializing/parsing the following new types:
<ul>
<li><code>AtomicInteger</code>
<li><code>AtomicLong</code>
<li><code>BigInteger</code>
<li><code>BigDecimal</code>
</ul>
<li>Parsers have been enhanced to allow parent POJOs and field names to be passed into child POJOs.
New {@link org.apache.juneau.annotation.NameProperty @NameProperty} and {@link org.apache.juneau.annotation.ParentProperty @ParentProperty}
annotations are provided for identifying methods for setting names and parent POJOs on child POJOs.
For example, the config file <code><del>Section</del></code> class represents a section
in a config file. It needs to know it's own name and have a link to the <code><del>ConfigFile</del></code>
that it belongs to. With these new annotations, config files can be reconstructed using any of the parsers.
<li>New classes and interfaces:
<ul>
<li>{@link org.apache.juneau.Streamable} interface for identifying objects that can be serialized directly to an output stream.
<li>{@link org.apache.juneau.Writable} interface for identifying objects that can be serialized directly to a writer.
<li><code><del>StringObject</del></code> class that can be used for delayed object serialization.
<li>{@link org.apache.juneau.internal.ByteArrayCache}
<li>{@link org.apache.juneau.internal.ByteArrayInOutStream}
<li>{@link org.apache.juneau.internal.FileUtils}
<li>{@link org.apache.juneau.internal.ThrowableUtils}
<li><del><code>StringVarMultipart</code></del>
<li><del><code>StringVarWithDefault</code></del>
</ul>
<li>New fields on {@link org.apache.juneau.ObjectList}:
<ul>
<li>{@link org.apache.juneau.ObjectList#EMPTY_LIST}
</ul>
<li>New fields and methods on {@link org.apache.juneau.ObjectMap}:
<ul>
<li>{@link org.apache.juneau.ObjectMap#EMPTY_MAP}
<li>{@link org.apache.juneau.ObjectMap#getStringArray(String)}
<li>{@link org.apache.juneau.ObjectMap#getStringArray(String,String[])}
<li>{@link org.apache.juneau.ObjectMap#putIfNull(String,Object)}
<li>{@link org.apache.juneau.ObjectMap#putIfEmpty(String,Object)}
</ul>
<li>New methods in {@link org.apache.juneau.internal.ArrayUtils}:
<ul>
<li>{@link org.apache.juneau.internal.ArrayUtils#contains(Object,Object[])}
<li>{@link org.apache.juneau.internal.ArrayUtils#indexOf(Object,Object[])}
<li>{@link org.apache.juneau.internal.ArrayUtils#toPrimitiveArray(Object)}
</ul>
<li>New methods in {@link org.apache.juneau.internal.IOUtils}:
<ul>
<li>{@link org.apache.juneau.internal.IOUtils#pipe(Reader,Writer)}
<li>{@link org.apache.juneau.internal.IOUtils#read(File)}
<li>{@link org.apache.juneau.internal.IOUtils#readFile(String)}
<li>{@link org.apache.juneau.internal.IOUtils#write(File,Reader)}
</ul>
<li>New methods on {@link org.apache.juneau.utils.PojoRest}:
<ul>
<li><code><del>PojoRest.get(Class,String,Object)</del></code>
<li>{@link org.apache.juneau.utils.PojoRest#getString(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getString(String,String)}
<li>{@link org.apache.juneau.utils.PojoRest#getInt(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getInt(String,Integer)}
<li>{@link org.apache.juneau.utils.PojoRest#getLong(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getLong(String,Long)}
<li>{@link org.apache.juneau.utils.PojoRest#getBoolean(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getBoolean(String,Boolean)}
<li>{@link org.apache.juneau.utils.PojoRest#getMap(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getMap(String,Map)}
<li>{@link org.apache.juneau.utils.PojoRest#getList(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getList(String,List)}
<li>{@link org.apache.juneau.utils.PojoRest#getObjectMap(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getObjectMap(String,ObjectMap)}
<li>{@link org.apache.juneau.utils.PojoRest#getObjectList(String)}
<li>{@link org.apache.juneau.utils.PojoRest#getObjectList(String,ObjectList)}
</ul>
<li>New methods on {@link org.apache.juneau.utils.ProcBuilder}:
<ul>
<li>{@link org.apache.juneau.utils.ProcBuilder#pipeTo(Writer,boolean)}
<li>{@link org.apache.juneau.utils.ProcBuilder#pipeTo(Writer)}
<li>{@link org.apache.juneau.utils.ProcBuilder#logTo(Writer,boolean)}
<li>{@link org.apache.juneau.utils.ProcBuilder#logTo(Writer)}
<li>{@link org.apache.juneau.utils.ProcBuilder#logTo(Level,Logger)}
<li>{@link org.apache.juneau.utils.ProcBuilder#maxExitStatus(int)}
</ul>
<li>New methods on {@link org.apache.juneau.internal.StringUtils}:
<ul>
<li>{@link org.apache.juneau.internal.StringUtils#isEmpty(Object)}
<li>{@link org.apache.juneau.internal.StringUtils#nullIfEmpty(String)}
<li>{@link org.apache.juneau.internal.StringUtils#base64EncodeToString(String)}
<li>{@link org.apache.juneau.internal.StringUtils#base64Encode(byte[])}
<li>{@link org.apache.juneau.internal.StringUtils#base64DecodeToString(String)}
<li>{@link org.apache.juneau.internal.StringUtils#base64Decode(String)}
<li>{@link org.apache.juneau.internal.StringUtils#generateUUID(int)}
<li>{@link org.apache.juneau.internal.StringUtils#trim(String)}
<li>{@link org.apache.juneau.internal.StringUtils#parseISO8601Date(String)}
<li>{@link org.apache.juneau.internal.StringUtils#replaceVars(String,Map)}
<li>{@link org.apache.juneau.internal.StringUtils#pathStartsWith(String,String)}
<li>{@link org.apache.juneau.internal.StringUtils#pathStartsWith(String,String[])}
</ul>
<li>New <del><code>StringVar.doResolve(String)</code></del> method.
<li>New <del><code>StringVarResolver.DEFAULT</code></del> field.
<li>Eliminated dependency on <code>javax.mail.internet.MimeUtility</code> by implementing our own {@link org.apache.juneau.internal.StringUtils#base64Encode(byte[])} method.
<li>{@link org.apache.juneau.transforms.CalendarSwap} and {@link org.apache.juneau.transforms.DateSwap} classes now handle blank input better. Returns <jk>null</jk> instead of throwing an exception.
<li>{@link org.apache.juneau.html.HtmlDocSerializer} specifies the default CSS location as <code>/servletPath/style.css</code> instead of <code>/servletPath/htdocs/juneau.css</code>.
This coincides with enhancements made in the server code for specifying styles.
<li>{@link org.apache.juneau.html.HtmlDocSerializer} wraps output in two div tags instead of one (e.g. <code>&lt;div class='outerdata'&gt;&lt;div class='data' id='data'&gt;...&lt;/div&gt;&lt;/div&gt;</code>).
Needed for supporting the new devops look-and-feel.
<li>Fixed indentation inconsistencies in {@link org.apache.juneau.html.HtmlDocSerializer}.
<li>Renamed <del>HtmlSchemaSerializer</del> to {@link org.apache.juneau.html.HtmlSchemaDocSerializer}.
<li>RDF serializers and parsers now support <code>RdfProperties.RDF_looseCollection</code> loose collections.
<li>RDF parser handles case where resources point to themselves (an unfortunate behavior in JFS RDF documents).
<li>JSON parser with throw an exception in strict mode if it encounters numbers that are valid in Java but invalid in JSON (e.g. octal, hexadecimal numbers).
<li>{@link org.apache.juneau.parser.Parser} methods now check for <jk>null</jk> input.
<li>{@link org.apache.juneau.serializer.SerializerGroup} and {@link org.apache.juneau.parser.ParserGroup} ignores serializers and parsers if they throw <code>NoClassDefFoundErrors</code>.
<li>{@link org.apache.juneau.urlencoding.UrlEncodingParser} creates lists if the same attribute name is encountered more than once. Before it would just replace the previous value with the new value.
<li>New <code><del>UrlEncodingSerializer.DEFAULT_SIMPLE_EXPANDED</del></code> serializer.
<li>Changes to {@link org.apache.juneau.utils.Args}:
<ul>
<li><code>getMainArg(int)</code> changed to {@link org.apache.juneau.utils.Args#getArg(int)}.
Non-existent arguments are returned as <jk>null</jk> instead of blank strings.
This is more inline with the behavior of the rest of the library.
<li>New {@link org.apache.juneau.utils.Args#hasArg(int)} method.
</ul>
<li>Removed <code>org.apache.juneau.utils.CharsetUtils</code> class.
<li>Removed <code>org.apache.juneau.utils.ConcurrentIdentityList</code> class.
<li>Fixed bug in {@link org.apache.juneau.internal.MultiIterable} class.
<li>{@link org.apache.juneau.utils.PojoIntrospector} must now be instantiated with a <code>ReaderParser</code>.
Simplifies the API on the class.
<li>{@link org.apache.juneau.utils.PojoRest} must now be instantiated with a <code>ReaderParser</code>.
Simplifies the API on the class.
<li>{@link org.apache.juneau.utils.MessageBundle} and <code>SafeResourceMultiBundle</code> moved from server component.
<li>Several bug fixes and performance improvements in <del><code>StringVarResolver</code></del>.
<li>Various enhancements to {@link org.apache.juneau.internal.TeeWriter} and {@link org.apache.juneau.internal.TeeOutputStream}.
<li>Renamed <del>CharSet</del> to {@link org.apache.juneau.internal.AsciiSet}.
<li>{@link org.apache.juneau.serializer.SerializerGroup} and {@link org.apache.juneau.parser.ParserGroup} now ignores <code>NoClassDefFoundErrors</code>
so that resources that include Jena support can continue to operate even if the Jena libraries are not present.
<li>New {@link org.apache.juneau.internal.FileUtils#createTempFile(String)} method.
<li>New {@link org.apache.juneau.utils.PojoQuery} modified to handle bean getters that throw exceptions.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>Upgraded to use Apache HttpClient 4.5.
<li>New classes:
<ul>
<li>{@link org.apache.juneau.rest.client.AllowAllRedirects}
<li>{@link org.apache.juneau.rest.client.HttpMethod}
<li>{@link org.apache.juneau.rest.client.ResponsePattern}
<li>{@link org.apache.juneau.rest.client.SimpleX509TrustManager}
<li>{@link org.apache.juneau.rest.client.SSLOpts}
</ul>
<li>Removed <code>org.apache.juneau.rest.client.LaxRedirectStrategy</code>. Use HTTP Client equivalent.
<li>New methods on {@link org.apache.juneau.rest.client.RestCall}:
<ul>
<li><code><del>RestCall#addInterceptor(RestCallInterceptor)</del></code>
<li>{@link org.apache.juneau.rest.client.RestCall#pipeTo(Writer)}
<li>{@link org.apache.juneau.rest.client.RestCall#pipeTo(Writer,boolean)}
<li>{@link org.apache.juneau.rest.client.RestCall#pipeTo(String,Writer,boolean)}
<li>{@link org.apache.juneau.rest.client.RestCall#getWriter(String)}
<li>{@link org.apache.juneau.rest.client.RestCall#pipeTo(OutputStream)}
<li>{@link org.apache.juneau.rest.client.RestCall#pipeTo(OutputStream,boolean)}
<li>{@link org.apache.juneau.rest.client.RestCall#pipeTo(String,OutputStream,boolean)}
<li>{@link org.apache.juneau.rest.client.RestCall#getOutputStream(String)}
<li>{@link org.apache.juneau.rest.client.RestCall#byLines()}
<li>{@link org.apache.juneau.rest.client.RestCall#captureResponse()}
<li>{@link org.apache.juneau.rest.client.RestCall#successPattern(String)}
<li>{@link org.apache.juneau.rest.client.RestCall#failurePattern(String)}
<li><code><del>RestCall#addResponsePattern(ResponsePattern)</del></code>
<li>{@link org.apache.juneau.rest.client.RestCall#run()} - Renamed from <code>execute()</code>.
<li>{@link org.apache.juneau.rest.client.RestCall#getCapturedResponse()}
<li>{@link org.apache.juneau.rest.client.RestCall#getResponsePojoRest(Class)}
<li>{@link org.apache.juneau.rest.client.RestCall#getResponsePojoRest()}
<li>{@link org.apache.juneau.rest.client.RestCall#logTo(Level,Logger)}
<li>{@link org.apache.juneau.rest.client.RestCall#setConfig(RequestConfig)}
</ul>
<li>New lifecycle listener methods on {@link org.apache.juneau.rest.client.RestCallInterceptor}:
<ul>
<li>{@link org.apache.juneau.rest.client.RestCallInterceptor#onInit(RestCall)}
<li>{@link org.apache.juneau.rest.client.RestCallInterceptor#onClose(RestCall)}
</ul>
<li>New methods on {@link org.apache.juneau.rest.client.RestClient}:
<ul>
<li><code><del>RestClient.setBasicAuth(String,int,String,String)</del></code>
<li><code><del>RestClient.logTo(Level,Logger)</del></code>
<li><code><del>RestClient.setRootUrl(String)</del></code>
<li><code><del>RestClient.enableSSL(SSLOpts)</del></code>
<li><code><del>RestClient.enableLaxSSL()</del></code>
<li>{@link org.apache.juneau.rest.client.RestClient#doCall(HttpMethod,Object,Object)}
<li><code><del>RestClient.createHttpClientBuilder()</del></code>
</ul>
<li>New passthrough methods on {@link org.apache.juneau.rest.client.RestClient} defined on <code>HttpClientBuilder</code>:
<ul>
<li><code><del>RestClient.setRedirectStrategy(RedirectStrategy)</del></code>
<li><code><del>RestClient.setDefaultCookieSpecRegistry(Lookup)</del></code>
<li><code><del>RestClient.setRequestExecutor(HttpRequestExecutor)</del></code>
<li><code><del>RestClient.setSSLHostnameVerifier(HostnameVerifier)</del></code>
<li><code><del>RestClient.setPublicSuffixMatcher(PublicSuffixMatcher)</del></code>
<li><code><del>RestClient.setSSLContext(SSLContext)</del></code>
<li><code><del>RestClient.setSSLSocketFactory(LayeredConnectionSocketFactory)</del></code>
<li><code><del>RestClient.setMaxConnTotal(int)</del></code>
<li><code><del>RestClient.setMaxConnPerRoute(int)</del></code>
<li><code><del>RestClient.setDefaultSocketConfig(SocketConfig)</del></code>
<li><code><del>RestClient.setDefaultConnectionConfig(ConnectionConfig)</del></code>
<li><code><del>RestClient.setConnectionTimeToLive(long,TimeUnit)</del></code>
<li><code><del>RestClient.setConnectionManager(HttpClientConnectionManager)</del></code>
<li><code><del>RestClient.setConnectionManagerShared(boolean)</del></code>
<li><code><del>RestClient.setConnectionReuseStrategy(ConnectionReuseStrategy)</del></code>
<li><code><del>RestClient.setKeepAliveStrategy(ConnectionKeepAliveStrategy)</del></code>
<li><code><del>RestClient.setTargetAuthenticationStrategy(AuthenticationStrategy)</del></code>
<li><code><del>RestClient.setProxyAuthenticationStrategy(AuthenticationStrategy)</del></code>
<li><code><del>RestClient.setUserTokenHandler(UserTokenHandler)</del></code>
<li><code><del>RestClient.disableConnectionState()</del></code>
<li><code><del>RestClient.setSchemePortResolver(SchemePortResolver)</del></code>
<li><code><del>RestClient.setUserAgent(String userAgent)</del></code>
<li><code><del>RestClient.setDefaultHeaders(Collection)</del></code>
<li><code><del>RestClient.addInterceptorFirst(HttpResponseInterceptor)</del></code>
<li><code><del>RestClient.addInterceptorLast(HttpResponseInterceptor)</del></code>
<li><code><del>RestClient.addInterceptorFirst(HttpRequestInterceptor)</del></code>
<li><code><del>RestClient.addInterceptorLast(HttpRequestInterceptor)</del></code>
<li><code><del>RestClient.disableCookieManagement()</del></code>
<li><code><del>RestClient.disableContentCompression()</del></code>
<li><code><del>RestClient.disableAuthCaching()</del></code>
<li><code><del>RestClient.setHttpProcessor(HttpProcessor)</del></code>
<li><code><del>RestClient.setRetryHandler(HttpRequestRetryHandler)</del></code>
<li><code><del>RestClient.disableAutomaticRetries()</del></code>
<li><code><del>RestClient.setProxy(HttpHost)</del></code>
<li><code><del>RestClient.setRoutePlanner(HttpRoutePlanner)</del></code>
<li><code><del>RestClient.disableRedirectHandling()</del></code>
<li><code><del>RestClient.setConnectionBackoffStrategy(ConnectionBackoffStrategy)</del></code>
<li><code><del>RestClient.setBackoffManager(BackoffManager)</del></code>
<li><code><del>RestClient.setServiceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy)</del></code>
<li><code><del>RestClient.setDefaultCookieStore(CookieStore)</del></code>
<li><code><del>RestClient.setDefaultCredentialsProvider(CredentialsProvider)</del></code>
<li><code><del>RestClient.setDefaultAuthSchemeRegistry(Lookup)</del></code>
<li><code><del>RestClient.setContentDecoderRegistry(Map)</del></code>
<li><code><del>RestClient.setDefaultRequestConfig(RequestConfig)</del></code>
<li><code><del>RestClient.useSystemProperties()</del></code>
<li><code><del>RestClient.evictExpiredConnections()</del></code>
<li><code><del>RestClient.evictIdleConnections(long,TimeUnit)</del></code>
</ul>
<li><code>JazzRestClient</code> now supports OIDC authentication.
<li>These classes are now deprecated and will be removed in a future release:
<ul>
<li><code>org.apache.juneau.rest.client.jazz.CertificateStore</code>
<li><code>org.apache.juneau.rest.client.jazz.ICertificateValidator</code>
<li><code>org.apache.juneau.rest.client.jazz.ITrustStoreProvider</code>
<li><code>org.apache.juneau.rest.client.jazz.LenientCertificateValidator</code>
<li><code>org.apache.juneau.rest.client.jazz.SharedTrustStoreProvider</code>
<li><code>org.apache.juneau.rest.client.jazz.ValidatingX509TrustManager</code>
</ul>
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.rest.ReaderResource} class.
Represents the contents of a text file with convenience methods for resolving
<del><code>StringVar</code></del> variables and adding HTTP response headers.
REST Java methods can return instances of these to serialize <code>Readers</code>
containing text with <del><code>StringVarResolver</code></del> variables in them.
<li>New {@link org.apache.juneau.rest.StreamResource} class.
REST Java methods can return instances of these to serialize <code>OutputStreams</code>.
<li>Fixed a bug in the stack trace hash algorithm in {@link org.apache.juneau.rest.RestException}.
<li>New methods in {@link org.apache.juneau.rest.RestRequest}:
<ul>
<li><code><del>RestRequest.getReaderResource(String)</del></code> - Replaces <code>getVarResource(String)</code>.
<li><code><del>RestRequest.getReaderResource(String,boolean)</del></code>
<li><code><del>RestRequest.getReaderResource(String,boolean,String)</del></code>
</ul>
<li>Changes in {@link org.apache.juneau.rest.RestResponse}:
<ul>
<li>Don't set <code>Content-Encoding: identity</code> when no encoding is used. Some clients don't interpret it correctly.
</ul>
<li>New methods in {@link org.apache.juneau.rest.RestServlet}:
<ul>
<li><code><del>RestServlet.getChildClasses()</del></code> - Programmatic equivalent to {@link org.apache.juneau.rest.annotation.RestResource#children() @RestResource.children()} annotation.
<li><code><del>RestServlet.shouldLog(HttpServletRequest,HttpServletResponse,RestException)</del></code>
<li><code><del>RestServlet.shouldLogStackTrace(HttpServletRequest,HttpServletResponse,RestException)</del></code>
<li><code><del>RestServlet.logObjects(Level,String,Object[])</del></code>
<li><code><del>RestServlet.resolveStaticFile(String)</del></code>
<li><code><del>RestServlet.createStyleSheet()</del></code>
<li><code><del>RestServlet.createFavIcon()</del></code>
<li><code><del>RestServlet.createStaticFilesMap()</del></code>
<li><code><del>RestServlet.getConfigMgr()</del></code>
</ul>
<li>Removed {@link org.apache.juneau.jso.JsoParser}
from {@link org.apache.juneau.rest.RestServletDefault} and <code><del>RestServletJenaDefault</del></code>.
These may represent a security risk if not handled correctly, so removed
them as a precaution.
<li>Removed <code>RestServletProperties.REST_htDocsFolder</code>. Replaced with {@link org.apache.juneau.rest.annotation.RestResource#staticFiles() @RestResource.staticFiles()}.
<li>New annotations on {@link org.apache.juneau.rest.annotation.RestResource @RestResource}.
<ul>
<li><code><del>RestResource.stylesheet()</del></code>
<li><code><del>RestResource.favicon()</del></code>
<li>{@link org.apache.juneau.rest.annotation.RestResource#staticFiles() @RestResource.staticFiles()}
</ul>
<li>Eliminated <code>org.apache.juneau.rest.jaxrs.JsonProvider</code> class.
Some JAX-RS implementations use code scanning to find providers, so if you were using <code>DefaultJenaProvider</code>, it would
pick up <code>JsonProvider</code> as well. It's easy enough to create your own implementation if needed.
<li>OPTIONS pages now specify <code>consumes</code> and <code>produces</code> fields instead of <code>accept</code> and <code>contentType</code> which was confusing.
<li>Eliminated <code>properties</code> from OPTIONS pages.
<li>New <code><del>ResourceLink.ResourceLink(String,RestRequest,String,Object[])</del></code> constructor.
<li>New response handlers:
<ul>
<li>{@link org.apache.juneau.rest.response.StreamableHandler} - Allows REST Java methods to return instances of {@link org.apache.juneau.Streamable}.
<li>{@link org.apache.juneau.rest.response.WritableHandler} - Allows REST Java methods to return instances of {@link org.apache.juneau.Writable}.
</ul>
<li>New DevOps stylesheet.
<li>Servlet initialization and HTTP requests are now logged at <JSF>FINE</JSF> level.
<li>Added <jk>abstract</jk> modifier on various <l>RestServlet</l> subclasses to indicate that they're meant to be subclassed.
<li>New {@link org.apache.juneau.rest.RestUtils#trimPathInfo(StringBuffer,String,String)} method.
</ul>
<h5 class='topic'>Microservice</h5>
<ul class='spaced-list'>
<li>Completely revamped API.
<li>New {@link org.apache.juneau.microservice.Microservice} class that serves as a generic
interface for microservices and their lifecycles.
<li>New {@link org.apache.juneau.microservice.RestMicroservice} class that implements a microservice
consisting of a REST interface.
<ul>
<li>REST resources and configuration settings can be defined through either manifest files
or config files.
<li>Enhanced logging support.
<li>Easy-to-configure SSL support.
<li>BASIC auth support.
<li>Automatic restartability if the config file changes.
</ul>
<li>Eliminated <code>org.apache.juneau.microservice.Main</code> class. This is replaced by
the microservice classes defined above.
<li>{@link org.apache.juneau.microservice.Resource} and {@link org.apache.juneau.microservice.ResourceGroup}
classes now support the following new string variables:
<ul>
<li><js>"$ARG{key,default}""</js> - Command line arguments.
<li><js>"$MF{key,default}""</js> - Manifest file entries.
</ul>
<li>CSS stylesheet now configurable through config file entry <js>"REST/stylesheet"</js>.
<li>New {@link org.apache.juneau.microservice.ResourceJena} class if you want your REST interface to support RDF.
<li>Eliminated the following classes:
<ul>
<li><code>org.apache.juneau.microservice.RootResource</code>
<li><code>org.apache.juneau.microservice.SampleResource</code>
</ul>
<li>New predefined reusable resources:
<ul>
<li>{@link org.apache.juneau.microservice.resources.ConfigResource} - REST resource for viewing and editing microservice config file.
<li>{@link org.apache.juneau.microservice.resources.LogsResource} - REST resource for viewing log files.
<li>{@link org.apache.juneau.microservice.resources.SampleRootResource} - Sample REST resource that contains the config and logs resource as children.
<li>{@link org.apache.juneau.microservice.resources.ShutdownResource} - REST resource for stopping the microservice JVM. Useful for testing purposes.
</ul>
</ul>
<h5 class='topic'>Samples</h5>
<ul class='spaced-list'>
<li>Converted to a REST microservice.
<li>Look-and-feel changed to IBM DevOps.
</ul>
<h5 class='topic'>Documentation Updates</h5>
<ul class='spaced-list'>
<li><del>org.apache.juneau.microservice</del> - New package-level javadoc.
<li><del>org.apache.juneau.config</del> - New package-level javadoc.
<li><del><code>StringVarResolver</code></del> - New documentation.
<li><del>org.apache.juneau.rest.client</del> - New package-level javadoc.
<li><code><del>Overview / Samples</del></code> - New section.
<li><del>org.apache.juneau.transform / Stop Classes</del> - New section.
<li><del>org.apache.juneau.rest</del> - Extensive updates.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.20"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.20 (Sept 5, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.20 is a moderate update.
The biggest improvement is the ability to associate external INI config files with REST servlets using the <code><del>ConfigFile</del></code> functionality.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Significant API changes to <code>org.apache.juneau.config</code> API.
<ul>
<li><code><del>ConfigFile</del></code> is now thread safe and can be shared across multiple threads.
<li>New <code><del>ConfigMgr</del></code> class for managing configuration files.
<li>Serializers and parsers can be associated with config files for storing and retrieving POJOs.
Default support provided for JSON.
</ul>
</li>
<li>New {@link org.apache.juneau.html.SimpleHtmlWriter} class.
Can be used for simple HTML DOM construction.
<li>New {@link org.apache.juneau.utils.ProcBuilder} class for calling external processes.
<li>New <code><del>ObjectMap.remove(Class,String,Object)</del></code> method.
<li><js>"class='link'"</js> added to links generated by {@link org.apache.juneau.html.HtmlDocSerializer}.
<li>New <code><del>EncoderGroup#append(EncoderGroup)</del></code> method.
<li>New <code>HtmlDocSerializerContext.HTMLDOC_addLinks</code> configuration property.
<li>Modified the <code>Parser.createContext(ObjectMap,Method,Object)</code> method.
Outer context objects can be passed in to create instances of non-static inner classes.
<li>Fixed bug in {@link org.apache.juneau.html.HtmlStrippedDocSerializer} where exception was thrown when trying to serialize primitive arrays.
<li>{@link org.apache.juneau.json.JsonParser} now handles parsing JSON boolean/numeric values as strings to bean properties of type boolean or number.
<li>{@link org.apache.juneau.urlencoding.UrlEncodingSerializer} and {@link org.apache.juneau.urlencoding.UrlEncodingParser} now
represent arrays and collections as key-value pairs where the keys are numbers (e.g. <js>"?0=foo&amp;1=bar"</js>).
<li>Various internal improvements to {@link org.apache.juneau.utils.IOPipe}.
<li>New {@link org.apache.juneau.internal.ReflectionUtils#getResource(Class,String)} method.
<li>{@link org.apache.juneau.internal.StringUtils#parseNumber(String,Class)} now returns zero for empty strings.
This affects the way most parsers handle blank values.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>You can now parse into non-static inner classes of a servlet for parameters/attributes/content.
Useful if you like to define your marshaller beans inside your servlet.
<li>Changes to {@link org.apache.juneau.rest.RestServlet}:
<ul>
<li>New methods for accessing external INI config files:<br>
<code><del>RestServlet.getConfig()</del></code><br>
<code><del>RestServlet.createConfigFile()</del></code>
<li>New <js>"$C{...}"</js> variable that resolve to INI config file values.
<li>New <js>"$UE{...}"</js> variable that URL-encodes the value inside the variable.
<li>New convenience methods for retrieving classpath resource files:<br>
<del><code>RestServlet.getResource(String)</code></del><br>
<del><code>RestServlet.getResourceAsString(String)</code></del><br>
<del><code>RestServlet.getResource(Class,String,String)</code></del>.
Useful if you want to load predefined POJOs from JSON files in your classpath.
<li>New <code><del>RestServlet.handleNotFound(int,RestRequest,RestResponse)</del></code> method for customized handling
of when a resource or method was not found.
</ul>
<li>{@link org.apache.juneau.rest.RestServletDefault} now automatically processes <js>"/favicon.ico"</js> requests by
overriding the new <code><del>RestServlet.handleNotFound(int,RestRequest,RestResponse)</del></code> method.
<li>New {@link org.apache.juneau.rest.RestRequest} methods:
<ul>
<li><code><del>RestRequest.resolveVars(String)</del></code>
<li><code>RestRequest.getVarResource(String)</code>
<li><code><del>RestRequest.getConfig()</del></code>
</ul>
<li>New {@link org.apache.juneau.rest.RestResponse} methods:
<ul>
<li>{@link org.apache.juneau.rest.RestResponse#getDirectWriter(String)}.
<li>{@link org.apache.juneau.rest.RestResponse#getNegotiatedWriter()}.
<code>getWriter()</code> now returns an unnegotiated writer.
<code>getUnbufferedWriter()</code> has been removed.
</ul>
<li>New {@link org.apache.juneau.rest.annotation.RestMethod#encoders() @RestMethod.encoders()} and
<code><del>RestMethod.inheritEncoders()</del></code> annotations.
Allows encoders to be fine-tuned at the method level.
<li>New {@link org.apache.juneau.rest.annotation.RestResource#config() @RestResource.config()} annotation for associating external <code><del>ConfigFile</del></code> config files with servlets.
<li><code><del>ResourceLink</del></code>.
<li>New <code>org.apache.juneau.rest.matchers</code> package for commonly-used {@link org.apache.juneau.rest.RestMatcher RestMatchers}:
<ul>
<li>{@link org.apache.juneau.rest.matchers#MultipartFormDataMatcher}
<li>{@link org.apache.juneau.rest.matchers#UrlEncodedFormMatcher}
</ul>
</ul>
<h5 class='topic'>Microservice</h5>
<ul class='spaced-list'>
<li>New juneau-microservice.jar file that encapsulates all 3 juneau jars with code necessary for creating fast and efficent jetty-powered REST microservices.<br>
Contains the following:
<ul>
<li>Jetty 8.0
<li>Apache HttpClient 4.3.5
<li>Apache Commons FileUpload 1.3.1
</ul>
<li>Microservice now supports Java 6 (previously required Java 7)
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.19"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.19 (Aug 15, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.19 is a minor update in terms of core functionality.
But it introduces a <code><del>Microservices</del></code> project for building REST microservices and docker containers.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Beans can now be serialized to and parsed from {@link org.apache.juneau.ObjectMap ObjectMaps}.
See <del>Serializing to ObjectMaps</del> for details.
<li>New {@link org.apache.juneau.ObjectMap#include(String[])} and {@link org.apache.juneau.ObjectMap#exclude(String[])} methods.
<li>{@link org.apache.juneau.html.annotation.Html @Html} annotations can now be applied to bean properties.
<li>New {@link org.apache.juneau.utils.IOPipe} utility class.
<li>Behavior change on <del><code>StringVarResolver</code></del>. <jk>null</jk> input now results in blank strings instead of <jk>null</jk>.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.rest.client.RestClient#doCallback(String)} method.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.rest.RestRequest#getHeaders()} method.
<li>New <code>RestResponse.getUnbufferedWriter()</code> method.
<li>Fixed bug that was preventing <code>x-response-headers</code> parameter from working correctly.
<li>Added {@link org.apache.juneau.annotation.Bean#properties() @Bean.properties} annotations to the various
classes in <code>org.apache.juneau.rest.labels</code> so that the order of the bean properties are consistent
on all JVMs. On IBM JVMs this is unnecessary because the order of the properties as defined in the class
are stored in the bytecode. Other JVMs such as OpenJRE do not implement this feature causing the bean
properties to be in random order.
<li>New <code><del>ResourceDescription.ResourceDescription(RestRequest,String,String)</del></code> constructor.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.18"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.18 (Aug 5, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.18 is a minor update affecting the server component only.
</p>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>Fixed bug where localized strings weren't resolving when using chained resource bundles.
<li>Servlet and method labels and descriptions can now contain embedded string variables.
<li>New <del><code>RestMethod.input()</code></del> and <code><del>RestMethod.responses()</del></code>
annotations.
These replace the various <code>description</code> annotations added 2 days ago with a simpler design.
<li>New methods on {@link org.apache.juneau.rest.RestServlet}:
<ul>
<li><code><del>RestServlet.getMethodDescription(String,RestRequest)</del></code> so that subclasses
can override the method description in the OPTIONS page.
<li><del><code>RestServlet.createRequestVarResolver(RestRequest)</code></del> so that subclasses
can override and augment the variable resolver.
<li><code><del>RestServlet.resolveChild(Class)</del></code> and <code><del>RestServlet.replaceChild(RestServlet)</del></code>
classes that allows customized resolution of servlet instances (e.g. if services are defined in OSGi).
</ul>
<li>Reverted the <del><code>MethodDescription</code></del> back to 5.1.0.16 since it was being used by someone.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.17"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.17 (Aug 3, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.17 is a major update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>{@link org.apache.juneau.BeanMap#get(Object)} and {@link org.apache.juneau.BeanMap#put(String,Object)} now
automatically performs filtering if filters are defined on the bean property or bean property class.
<ul>
<li>Deleted the following methods which are now unnecessary:
<ul>
<li><code>BeanMap.getFiltered(String)</code>
<li><code>BeanMap.putFiltered(String,Object)</code>
<li><code>BeanMapEntry.getFiltered(String)</code>
<li><code>BeanMapEntry.putFiltered(String,Object)</code>
<li><code>BeanMapEntry.putFiltered(String,Object)</code>
<li><code>BeanPropertyMeta.getFiltered()</code>
<li><code>BeanPropertyMeta.setFiltered(Object)</code>
<li><code>BeanPropertyMeta.getTransformedClassMeta()</code>
</ul>
<li>{@link org.apache.juneau.BeanPropertyMeta#getClassMeta()} now returns the filtered type of the property.
</ul>
<li><del><code>StringVarResolver</code></del> now has support for chained resolvers.
<li><del><code>StringVarResolver</code></del> now resolves variables inside resolved values.
i.e. if a resolved variable value itself contains a variable, it now resolves that variable too.
<li>Fixed bug where inner interface classes being used in <code>RestResource.filters()</code> were being
interpreted as surrogate classes because they have hidden 1-arg constructors due to being inner classes.
<li>Fixed bug in {@link org.apache.juneau.internal.MultiSet} where exception was being thrown if last set was empty.
<li>New {@link org.apache.juneau.utils.ZipFileList} class for providing efficiently zipped directories through the REST interface.
<li>New <code>RdfProperties.RDF_useXmlNamespaces</code> property.
<li>New <code><del>XmlParserContext.XML_preserveRootElement</del></code> property.
<li>Worked around bug in Sun VM on OS/X where XML parser was throwing an exception when trying to set a reporter.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.rest.response.ZipFileListResponseHandler} class.
<li>Simplified labels in servlet resource bundles:
<ul>
<li><code>"[ClassName].ResourceDescription"</code> is now <code>"[ClassName].label"</code>.
<li><code>"[ClassName].MethodDescription.[methodName]"</code> is now <code>"[ClassName].[methodName]"</code>.
</ul>
<li>Several changes to {@link org.apache.juneau.rest.RestRequest}:
<ul>
<li>Added new methods:
<ul>
<li><code><del>RestRequest.getQueryParameterMap()</del></code>
<li><code><del>RestRequest.getQueryParameterNames()</del></code>
<li><code><del>RestRequest.getPathInfoUndecoded()</del></code>
<li><code><del>RestRequest.getPathRemainderUndecoded()</del></code>
<li><code><del>RestRequest.getTrimmedRequestURI()</del></code>
<li><code><del>RestRequest.getTrimmedRequestURL()</del></code>
<li><code><del>RestRequest.getServletTitle()</del></code>
<li><code><del>RestRequest.getServletDescription()</del></code>
<li>{@link org.apache.juneau.rest.RestRequest#getMethodDescription()}
</ul>
<li>Behavior changes to {@link org.apache.juneau.rest.RestRequest#getPathInfo()} to follow Servlet specs.
Returns <jk>null</jk> instead of blank for no path info.
<li><code><del>RestRequest.getPathRemainder()</del></code> now automatically decodes the path remainder.
Use <code><del>RestRequest.getPathRemainderUndecoded()</del></code> to get the unencoded path remainder.
<li>Bug fixes in <code><del>RestRequest.getRequestParentURI()</del></code> when servlet is mapped to <js>"/*"</js>.
<li>Bug fixes in <code><del>RestRequest.getServletURI()</del></code> when servlet is mapped to <js>"/*"</js>.
</ul>
<li>New string replacement variables:
<ul>
<li><code>$R{contextPath}</code> - Returns value from {@link org.apache.juneau.rest.RestRequest#getContextPath()}
<li><code>$R{methodDescription}</code> - Returns value from {@link org.apache.juneau.rest.RestRequest#getMethodDescription()}
<li><code>$R{resourceTitle}</code> - Returns value from <code><del>RestRequest.getServletTitle()</del></code>
<li><code>$R{resourceDescription}</code> - Returns value from <code><del>RestRequest.getServletDescription()</del></code>
<li><code>$R{trimmedRequestURI}</code> - Returns value from <code><del>RestRequest.getTrimmedRequestURI()</del></code>
<li><code>$E{var}</code> - Environment variables.
</ul>
<li>Added methods <code><del>RestServlet.getDescription(RestRequest)</del></code> and <del><code>RestServlet.getLabel(RestRequest)</code></del>.
<li>{@link org.apache.juneau.rest.RestServletDefault} and <code><del>RestServletJenaDefault</del></code> now provide default HTML titles
and descriptions:
<p class='bcode'>
<ja>@Property</ja>(name=<jsf>HTMLDOC_title</jsf>, value=<js>"$R{resourceTitle}"</js>),
<ja>@Property</ja>(name=<jsf>HTMLDOC_description</jsf>, value=<js>"$R{resourceDescription}"</js>)
</p>
<li>Options pages on {@link org.apache.juneau.rest.RestServletDefault} and <code><del>RestServletJenaDefault</del></code> now provide default descriptions and back links:
and descriptions:
<p class='bcode'>
<ja>@Property</ja>(name=<jsf>HTMLDOC_navlinks</jsf>, value=<js>"{back:'$R{servletURI}"</js>),
<ja>@Property</ja>(name=<jsf>HTMLDOC_description</jsf>, value=<js>"Resource options"</js>)
</p>
<li>New {@link org.apache.juneau.rest.RestServletGroupDefault} class.
<li>Removed <code>RestServletProperties.REST_trimTrailingUriSlashes</code> and <code>RestServletProperties.REST_pathInfoBlankForNull</code>.
<li>New annotations for providing labels and descriptions. Useful if you don't plan on having to support other languages, so you don't
want to provide labels in resource bundles.
<ul>
<li><del><code>RestResource.label()</code></del>
<li>{@link org.apache.juneau.rest.annotation.RestResource#description() @RestResource.description()}
<li>{@link org.apache.juneau.rest.annotation.RestMethod#description() @RestMethod.description()}
<li><del><code>RestMethod#responses()</code></del>
<li><del><code>Attr.description()</code></del>
<li><del><code>Content.description()</code></del>
<li><del><code>HasParam.description()</code></del>
<li><del><code>HasQParam.description()</code></del>
<li><del><code>Header.description()</code></del>
<li><del><code>Param.description()</code></del>
<li><del><code>QParam.description()</code></del>
</ul>
<li>Support for sorting resources by name in {@link org.apache.juneau.rest.labels.ChildResourceDescriptions}.
</ul>
<h5 class='topic'>Samples</h5>
<ul class='spaced-list'>
<li>Added <code>/tempDir/upload</code> showing how to use <code>ServletFileUpload</code> with multipart form posts.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.16"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.16 (June 28, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.16 is a moderate update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>New methods on {@link org.apache.juneau.ClassMeta} that eliminates language-specific code in
the general class metadata.
<ul>
<li><del><code>ClassMeta.getXmlMeta()</code></del>
<li><del><code>ClassMeta.getJsonMeta()</code></del>
<li><del><code>ClassMeta.getHtmlMeta()</code></del>
<li><del><code>ClassMeta.getUrlEncodingMeta()</code></del>
<li><del><code>ClassMeta.getRdfMeta()</code></del>
</ul>
<li>New {@link org.apache.juneau.dto.jsonschema.JsonType#ANY} enum.
<li>New {@link org.apache.juneau.html.annotation.Html#asPlainText @Html.asPlainText()} annotation.
<li>New <code><del>HtmlDocSerializerContext.HTMLDOC_cssImports</del></code> property.
<li>Significant changes to RDF support.
<ul>
<li>New {@link org.apache.juneau.jena.annotation.Rdf @Rdf} and {@link org.apache.juneau.jena.annotation.RdfSchema @RdfSchema}
annotations. These replace the use of defining namespaced through the XML annotations, and allows XML and RDF to be
serialized using different namespaces.
<li>Support for serializing arrays/collections as RDF bags, RDF lists, and multi-valued properties.
<li>Fixed warning message about <js>"tab"</js> setting when using the N3/Turtle serializers.
</ul>
<li>New <code><del>SerializerContext.SERIALIZER_sortCollections</del></code> and
<code><del>SerializerContext.SERIALIZER_sortMaps</del></code> properties.
<li>FindBug fixes.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>New <code><del>RestRequest.getServletParentURI()</del></code> method.
<li>New <code>$R{servletParentURI}</code> variable.
<li>Removed final modifier from {@link org.apache.juneau.rest.labels.ChildResourceDescriptions}.
</ul>
<h5 class='topic'>Samples</h5>
<ul class='spaced-list'>
<li>Added source code links to examples.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.15"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.15 (May 24, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.15 is a minor update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>New properties in <code><del>SerializerContext</del></code>:
<ol>
<li><code><del>SerializerContext.SERIALIZER_relativeUriBase</del></code>
<li><code><del>SerializerContext.SERIALIZER_absolutePathUriBase</del></code>
</ol>
These replace the <code>SERIALIZER_uriAuthority</code> and <code>SERIALIZER_uriContext</code> properties.
</li>
<li>Improvements in {@link org.apache.juneau.csv.CsvSerializer}.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>New properties in <code>RestServletProperties</code>:
<ol>
<li><code>REST_defaultCharset</code>
<li><code>REST_servletURI</code>
<li><code>REST_relativeServletURI</code>
</ol>
<li>Improvements involving path calculations when servlets deployed outside of a war file with a context root.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>New methods in {@link org.apache.juneau.rest.client.RestCall}:
<ol>
<li><code><del>RestRequest.getHeader(String,Class)</del></code>
<li><code><del>RestRequest.getHeader(String,Object,Class)</del></code>
<li><code><del>RestRequest.getHeader(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Class)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Object,Class)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getQueryParameter(String,Object,Type,Type...)</del></code>
<li><code><del>RestRequest.getQueryParameters(String,Class)</del></code>
<li><code><del>RestRequest.getQueryParameters(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getFormDataParameter(String,Class)</del></code>
<li><code><del>RestRequest.getFormDataParameter(String,Object,Class)</del></code>
<li><code><del>RestRequest.getFormDataParameters(String,Class)</del></code>
<li><code><del>RestRequest.getFormDataParameter(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getFormDataParameters(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getPathParameter(String,Class)</del></code>
<li><code><del>RestRequest.getPathParameter(String,Type,Type...)</del></code>
<li><code><del>RestRequest.getBody(Class)</del></code>
<li><code><del>RestRequest.getBody(Type,Type...)</del></code>
</ol>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.14"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.14 (May 10, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.14 is a moderate update.
</p>
<p>
The major addition is support for {@link org.apache.juneau.rest.remoteable Remoteable Services}, the ability
to invoke server-side POJO methods through client-side proxy interfaces.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Simplified {@link org.apache.juneau.utils.PojoIntrospector} class.
<li>New {@link org.apache.juneau.internal.ClassUtils#getMethodSignature(Method)} method.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>New methods in {@link org.apache.juneau.rest.client.RestClient} for working with remoteable services:
<ul>
<li><code><del>RestClient.setRemoteableServletUri(String)</del></code>
<li>{@link org.apache.juneau.rest.client.RestClient#getRemoteableProxy(Class)}
</ul>
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>Added a default OPTIONS page to {@link org.apache.juneau.rest.RestServletDefault} and <code><del>RestServletJenaDefault</del></code>.
<li><code>RestServletProperties.REST_allowMethodParam</code> has been enhanced to allow you to
explicitly specify which HTTP methods can be used in the <code>&amp;method</code> parameter.
<li>New methods added to {@link org.apache.juneau.rest.RestRequest}:
<ul>
<li><code><del>RestRequest.getParser()</del></code>
<li><code><del>RestRequest.getReaderParser()</del></code>
</ul>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.13"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.13 (Apr 24, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.13 is a minor update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>{@link org.apache.juneau.ClassMeta#newInstance()} method can now create new instances of arrays.
<li>Arguments passed to <code><del>Link</del></code> are now serialized using {@link org.apache.juneau.urlencoding.UrlEncodingSerializer}, so arbitrary POJOs can now be passed as arguments.
<li>New date filters: <code>org.apache.juneau.transforms.Datefilter.ISO8601DTZP</code> and <code>org.apache.juneau.transforms.Datefilter.SimpleP</code>.
<li>New <code><del>HtmlDocSerializerContext.HTMLDOC_nowrap</del></code> setting for {@link org.apache.juneau.html.HtmlDocSerializer} class.
Adds <js>"* {white-space:nowrap}"</js> to the style header to prevent word wrapping.
<li>Fixed bug in {@link org.apache.juneau.uon.UonParser} where passing in a blank value on an array or collection type in a form post would cause a <code>ClassCastException</code>.
New behavior creates an empty array or <code>Collection</code>.
<li>Improved implementation of <del><code>UrlEncodingSerializer.serializeUrlPart(Object)</code></del> method.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>{@link org.apache.juneau.rest.RestConverter} API fixed to handle the existence of POJO filters.
{@link org.apache.juneau.rest.converters.Introspectable}/{@link org.apache.juneau.rest.converters.Queryable}/{@link org.apache.juneau.rest.converters.Traversable} classes can now work with filtered POJOs.
<li>{@link org.apache.juneau.rest.annotation.RestResource#messages() @RestResource.messages()} annotation can now be defined on super and subclasses so that NLS messages can be defined in multiple resource bundles.
<li>Performance improvements in <code>RestServletNls</code> class.
<li>Fixed bug where two REST java methods mapped to the same path pattern wasn't triggering an exception when it was supposed to.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>New <code><del>RestCall.setRedirectMaxAttempts(int)</del></code> method to prevent endless redirection loops.
<li>New <code><del>RestCall#setRetryable(int,long,RetryOn)</del></code> method to automatically retry on failed connection attempts.
<li>New <code>RestCallInterceptor.onRetry(RestCall,int,HttpRequest,HttpResponse)</code> method for listening in on retry attempts.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.12"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.12 (Mar 28, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.12 is a minor update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Fixed <code><del>ConfigFile.isEmpty()</del></code> method.
<li>Changed behavior on {@link org.apache.juneau.uon.UonParser} to not treat <js>'~'</js> characters as escapes
unless followed by one of the following characters: <code>( ) , $ = ~</code>.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>New class {@link org.apache.juneau.rest.client.RestCallInterceptor}.
Allows responses to be inspected and modified before being processed.
Replaces <code>RestClientListener</code> class.
<li>Minor connection cleanup fixes.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.11"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.11 (Feb 14, 2015)</h3>
<div class='topic'>
<p>
Juno 5.1.0.11 is a moderate update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Additions to {@link org.apache.juneau.html.annotation.Html @Html} bean annotation.
<ul>
<li>New {@link org.apache.juneau.html.annotation.Html#noTables() @Html.noTables()} annotation that prevents
arrays/Collections from being serialized as tables.
<li>New {@link org.apache.juneau.html.annotation.Html#noTableHeaders() @Html.noTableHeaders()} annotation that prevents
HTML tables from having header rows.
</ul>
</li>
<li>Several improvements to URL-Encoding support.
<ul>
<li>Improved whitespace handling in {@link org.apache.juneau.uon.UonParser}.
<li>New <code><del>UonParserContext.UON_whitespaceAware</del></code> property for controlling whether whitespace is ignored.
<li>New <code><del>UrlEncodingContext.URLENC_expandedParams</del></code> property for controlling whether arrays/Collections
should be serialized/parsed as multi-part parameters.
<li>New {@link org.apache.juneau.urlencoding.annotation.UrlEncoding#expandedParams() @UrlEncoding.expandedParams()}
annotation that specifies that bean properties of type array/Collection be serialized as multi-part parameters (e.g. <code>&amp;key=val1&amp;key=val2</code>).
</ul>
</li>
<li>New <code><del>JsonSerializerContext.JSON_escapeSolidus</del></code> property for controlling whether slash characters should be escaped.
<li>New {@link org.apache.juneau.internal.TeeOutputStream} and {@link org.apache.juneau.internal.TeeWriter} classes.
<li>New {@link org.apache.juneau.ClassMeta#isInstance(Object)} method.
<li>Performance improvements when using the {@link org.apache.juneau.BeanMap#add(String,Object)} method.
Array properties are stored in a temporary list cache until {@link org.apache.juneau.BeanMap#getBean()} is called.
<li>New <code><del>BeanPropertyMeta.add(BeanMap,Object)</del></code> method for adding values to Collection and array properties.
<li>Config INI files now support keys with name <js>"*"</js>.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>REST method parameters can now be generic types (e.g. <del><ja>@Param</ja>(<js>"foo"</js>) Map&lt;String,Integer&gt; foo</del>).
This applies to headers, attributes, and parameters.
<li>New <del><code>@Param.multipart()</code></del>
and <del><code>@Query.multipart()</code></del> annotations
for handling multi-part GET and POST parameters.
<li>GET parameters are now CASE-SENSITIVE per W3C standards.
<ul>
<li>
<li><code>&amp;Content</code> must now be specified as <code>&amp;content</code>.
<li><code>&amp;Method</code> must now be specified as <code>&amp;method</code>.
<li><code>&amp;debug</code> must now be specified as <code>&amp;debug=true</code>.
<li><code>&amp;plainText</code> must now be specified as <code>&amp;plainText=true</code>.
<li><code>&amp;notrace</code> must now be specified as <code>&amp;noTrace=true</code>.
</ul>
</li>
<li>Performance improvements around query parameters.
<li>New methods on {@link org.apache.juneau.rest.RestRequest} for handling multi-part parameters:
<ul>
<li><del><code>RestRequest.getParameters(String,Class)</code></del>
<li><code><del>RestRequest#getQueryParameters(String,Class)</del></code>
</ul>
</li>
<li>Fixed Jetty issue in {@link org.apache.juneau.rest.RestResponse#setHeader(String,String)} where setting
the <code>Content-Type</code> through this method was inconsistent with the behavior in WAS/Tomcat.
<li><code>&amp;noTrace=true</code> now prevents any errors from being logged in log file.
<li>Workaround for Jetty issue where <code>ServletContext.getContextPath()</code> always ends with <js>"null"</js>.
<li><code>RestServletProperties.REST_allowMethodParam</code> is now <jk>true</jk> by default on all subclasses
of {@link org.apache.juneau.rest.RestServletDefault} and <code><del>RestServletJenaDefault</del></code>.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>New method {@link org.apache.juneau.rest.client.RestCall#allowRedirectsOnPosts(boolean)}.
<li>New method <code>RestCall.peekInputStream()</code> allows you to read response bodies without interrupting execution flow.
<li>New method {@link org.apache.juneau.rest.client.RestCall#toString()} now useful for debugging purposes.
Shows all request/response headers and bodies.
<li>{@link org.apache.juneau.rest.client.RestCallException} now includes <code>HttpResponse</code> object for easier debugging.
<li>New method <code>RestClient.addListener(RestClientListener)</code> for registering request/response listeners.
<li>New <code><del>RestClient.setClassLoader(ClassLoader)</del></code> method.
<li>TLS support in <code>JazzRestClient</code>.
</ul>
<h5 class='topic'>Other changes</h5>
<ul class='spaced-list'>
<li><code>samples.ear</code> and <code>samples.war</code> projects
have been replaced with an OSGi bundle with activated servlets in <code>juno.samples</code>.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.10"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.10 (Dec 23, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.10 is a moderate update.
</p>
<h5 class='topic'>Core</h5>
<ul class='spaced-list'>
<li>Major changes to URL-Encoded serializer and parser.
<ul>
<li>Logic for serializing and parsing URL-Encoded key-value pairs moved to {@link org.apache.juneau.urlencoding.UrlEncodingSerializer} and {@link org.apache.juneau.urlencoding.UrlEncodingParser} classes.
<li>Logic for serializing and parsing URL-Encoded values moved to new {@link org.apache.juneau.uon.UonSerializer} and {@link org.apache.juneau.uon.UonParser} classes.
</ul>
</li>
<li>Fix bug where <code>BeanRuntimeExceptions</code> weren't being thrown on subsequent calls to {@link org.apache.juneau.BeanContext#getClassMeta(Class)}.
<li>Moved logic for <code>BeanContext.getPrimitiveDefault(Class)</code> to new {@link org.apache.juneau.ClassMeta#getPrimitiveDefault()} method for performance reasons.
<li>Fixed bug in <del><code>BeanContext.addTransforms(Class[])</code></del> that would cause filter order to get messed up.
<li>{@link org.apache.juneau.ClassMeta#newInstance()} can now create array instances.
<li>Fixed indentation bugs in {@link org.apache.juneau.html.HtmlSerializer}.
<li>Fixed issue in {@link org.apache.juneau.html.HtmlSerializer} where newlines were not being converted into line breaks.
<li>New {@link org.apache.juneau.serializer.WriterSerializer#toString(Object)} method that's identical to the serialize method but throws <code>RuntimeExceptions</code> to make the serializer easier to use for debugging.
</ul>
<h5 class='topic'>Server</h5>
<ul class='spaced-list'>
<li>Fixed major issue that prevented parsing URL-Encoded form posts into POJOs.
Calling <del><code>HttpServlet.getParameter(String)</code></del> was forcing the underlying servlet code to process the HTTP body itself, preventing the <code>UrlEncodingSerializer</code>
class from being able to parse the content. Updated code no longer inadvertantly calls this method.
<li>New <code><del>RestRequest.getQueryParameter(String)</del></code>, <code><del>RestRequest.hasQueryParameter(String)</del></code>, and <code><del>RestRequest.hasAnyQueryParameters(String[])</del></code>
methods that only look for parameters in the URL query string to prevent loading and parsing of URL-Encoded form posts.
<li>New <del><code>@QParam</code></del> and <del><code>@HasQParam</code></del> annotations for accessing query parameters from the URL query string.
<li><code>&amp;plainText</code> parameter can now specify a false value.
<li>Removed properties parameters from <code><del>RestServlet.onPreCall(RestRequest)</del></code> and <code><del>RestServlet#onPostCall(RestRequest,RestResponse)</del></code> methods
since the properties are already accessible through <code>RestRequest.getProperties()</code>.
<li>Added {@link org.apache.juneau.uon.UonSerializer} and {@link org.apache.juneau.uon.UonParser} to serializer and parser lists on
{@link org.apache.juneau.rest.RestServletDefault} and <code><del>RestServletJenaDefault</del></code>.
</ul>
<h5 class='topic'>Client</h5>
<ul class='spaced-list'>
<li>Moved to Apache HttpClient 4.3 to match Jazz 6.0.
<li>Renamed <code>RestResponseEntity</code> to {@link org.apache.juneau.rest.client.RestRequestEntity}.
<li>Improved performance on URL-Encoded form posts by serializing directly to output stream instead of serialized to string first.
<li>New methods on {@link org.apache.juneau.rest.client.RestClient} class that makes it easier to associate serializer and parser attributes with registered serializer and parser:
<ul>
<li><code><del>RestClient#setProperty(String,Object)</del></code>
<li><code><del>RestClient#setProperties(ObjectMap)</del></code>
<li><code><del>RestClient#addNotBeanClasses(Class[])</del></code>
<li><del><code>RestClient.addTransforms(Class[])</code></del>
<li><code><del>RestClient#addImplClass(Class,Class)</del></code>
</ul>
<li>Renamed <code>RestClient.shutdown()</code> to {@link org.apache.juneau.rest.client.RestClient#close()} to mirror change in Apache API.
</ul>
<h5 class='topic'>Samples</h5>
<ul class='spaced-list'>
<li>New <code>CodeFormatterResource</code> for quickly formatting Java and XML code samples in Javadocs.
<li>New <code>UrlEncodedFormResource</code> for showing how to work with URL-Encoded form posts.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.9"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.9 (Dec 1, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.9 is a major update.
There weren't very many code changes, but the source has been made a part of Jazz Foundation.
This required some restructuring of the project.
The project on Jazz Hub will eventually be discontinued.
However, the libraries on IBM Community Source will continue to be updated regularly.
</p>
<ul class='spaced-list'>
<li>Project split up into 3 separate bundles:
<ul>
<li><code>org.apache.juneau</code> - Core serializers and parsers.
<li><code>org.apache.juneau.rest</code> - REST server component.
<li><code>org.apache.juneau.rest.client</code> - REST client component.
</ul>
<li>Code changes to facilitate breaking up bundles:
<ul>
<li><code>org.apache.juneau.rest.labels.Link</code> class moved to <code><del>Link</del></code>.
<li>References to <code>org.apache.juneau.rest.RestException</code> in {@link org.apache.juneau.encoders.Encoder} class changed to <code>IOException</code>.
</ul>
<li>Changed configuration names for consistency with Jazz Framework.
<li>New {@link org.apache.juneau.rest.client.RestClient#execute(HttpUriRequest)} method that allows subclasses to handle their own HTTP request execution.
<li>Changes in <code>JazzRestClient</code> to handle introduction of SSO support in v6.
<li><code>&amp;plainText</code> debug feature was broken.
<li>Removed double-buffering in <code>RestRequest</code>.
<li>Metadata cleanup, Find Bug fixes.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.8"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.8 (Oct 25, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.8 is a moderate update, focused primarily on performance improvements.
</p>
<ul class='spaced-list'>
<li>Improved performance on JSON and URL-Encoding parsers by approximately 50% on large data sets.
<ul>
<li>Rewrote {@link org.apache.juneau.parser.ParserReader} class to handle it's own buffering.
The change allowed several optimizations to be made when dealing with JSON and URL-Encoding
text by avoiding char array copies.
<li>Added a <code>estimatedSize</code> parameter to the {@link org.apache.juneau.parser.Parser} parse methods to
optimize buffering when the input size is known beforehand.
</ul>
</li>
<li>Revamped the {@link org.apache.juneau.BeanContext} API to perform better in multi-threaded environments.
<ul>
<li>Introduced a new <code>BeanPropertyStore</code> class that handles creation of {@link org.apache.juneau.BeanContext} objects.
This allows <code>BeanContext</code> objects to be considered immutable, and therefore cacheable/reusable by the framework.
While this was technically possible to cache these objects beforehand, it relied on a locking mechanism to prevent bean contexts
from being modified after being created. The new mechanism is much more straightforward.
</ul>
</li>
<li>Modifications to the <del>org.apache.juneau.rest.client</del> APIs to make it easier to work with custom Apache HTTP clients.
<ul>
<li>Added overridable <code><del>RestClient#createHttpClient()</del></code> to allow customized subclasses to construct customized HTTP clients.
<li>Removed the <code>DefaultRestClient</code> class since it's now fully redundant with <code>RestClient</code>.
<li>Added <code>RestClient.shutdown()</code> method for cleaning up the internal HTTP client when you're done using a REST client.
</ul>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.7"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.7 (Oct 5, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.7 is a moderate update.
</p>
<ul class='spaced-list'>
<li>Improved error handling.
<li>New <code><del>ParserContext.PARSER_debug</del></code> and <code><del>SerializerContext.SERIALIZER_debug</del></code>.
settings for logging additional information for debugging problems.
<li>New {@link org.apache.juneau.serializer.Serializer#SERIALIZER_ignoreRecursions} setting for explicitely ignoring recursions when
serializing models. Previously, the <jsf>SERIALIZER_detectRecursions</jsf> setting did this, but now it simply looks for recursions
and throws exceptions when they occur.
<li>Improved handling of <code>StackOverflowErrors</code>. When <jsf>SERIALIZER_detectRecursions</jsf> is enabled, a useful error message
is displayed showing the exact chain of objects that resulted in the stack overflow.
<li>Bug fixes in {@link org.apache.juneau.dto.ResultSetList} for Oracle and SQL Server.
<li>Serializers and parsers can now access HTTP request attributes, parameters, and headers through <code>SerializerContext.getProperties()</code> and
<code>ParserContext.getProperties()</code>.
<li>Removed media-type and encoding attributes from <code><del>SerializerContext</del></code> and <code><del>ParserContext</del></code>
since these are now available through context properties, and are typically not used.
<li>{@link org.apache.juneau.xml.XmlParser} now accepts <code>application/xml</code>.
<li>Improved handling of bean property serialization when multiple matching pojo filters for the bean property class exist.
<li>Improved concurrency on BeanContext class.
<li>Fixed bug in {@link org.apache.juneau.rest.converters.Traversable} that was causing it to be executed even if the servlet extra path info was empty.
<li>Fixed bug in {@link org.apache.juneau.rest.converters.Traversable} where it was not picking up filters and properties defined on REST Java methods.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.6"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.6 (Sept 21, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.6 is a moderate update.
</p>
<ul class='spaced-list'>
<li>Simplified API for {@link org.apache.juneau.transform.PojoSwap}.
Since it's rarely used, the <code>beanContext</code> parameter was replaced with a <del><code>PojoSwap#getBeanContext()</code></del> method on
the class.
<li>New simplified way of defining POJO filters without needing to extend {@link org.apache.juneau.transform.PojoSwap}.
See {@link org.apache.juneau.transform.SurrogateSwap} for details.
<li>New {@link org.apache.juneau.html.annotation.Html @Html} annotation.
Will allow the definition of standard XHTML DTOs in future releases.
For now, <del><code>Img</code></del> is an example of defining an XHTML element using Juno DTOs.
<li>{@link org.apache.juneau.json.JsonParser} now ignores trailing <code>';'</code> characters in input so that it can
parse strings of the form <js>"var x = {'foo':'bar'};"</js>.
<li>New <code>TumblrParserResource</code> in the samples war file showing how to combine the REST client and server APIs into a single
resource in order to download Tumblr blogs and convert the response into any supported response content type.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.5"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.5 (Sept 1, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.5 is a moderate update.
</p>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.rest.Redirect} class that simplifies performing redirections in REST methods.
<li>New pluggable {@link org.apache.juneau.rest.ResponseHandler} class and {@link org.apache.juneau.rest.annotation.RestResource#responseHandlers() @RestResource.responseHandlers()} annotation
for defining customer response handlers for special kinds of POJOs.
<li>New method <del><code>UrlEncodingSerializer.serializeUrlPart(Object)</code></del> method.
<li>New method <code><del>RestRequest.getServletURIBuilder()</del></code> for construcing servlet-based URLs more efficiently.
<li>New method {@link org.apache.juneau.rest.RestResponse#getNegotiatedOutputStream()} that uses encoders if a match is found,
and {@link org.apache.juneau.rest.RestResponse#getOutputStream()} that just return the underlying output stream without any modifications.
<li>Fixed bug where some properties were not being propagated correctly when using <code><del>CoreObject.setProperties(ObjectMap)</del></code>
on serializer and parser subclasses.
<li>Fixed bug in {@link org.apache.juneau.html.HtmlSerializer} where URL keys in Maps were not being serialized as hyperlinks.
<li>Fixed bug in {@link org.apache.juneau.json.JsonSerializer} where <js>"_class"</js> and <js>"items"</js> attributes were not quoted in strict mode when using SERIALIZER_addClassAttrs feature.
<li>Fixed bug where <code>Content-Encoding</code> and<code>Character-Encoding</code> headers were being set when calling {@link org.apache.juneau.rest.RestResponse#getOutputStream()}.
These should not be set if interacting with the output streams at a low level.
<li>Eliminated various convenience <code>RestResponse.sendRedirect(...)</code> methods due to the introduction of the {@link org.apache.juneau.rest.Redirect} class.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.4"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.4 (Aug 25, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.4 is a minor update.
</p>
<ul class='spaced-list'>
<li>New <code><del>RestServlet.getPath()</del></code> method.
<li>New <code>SerializerContext.getJavaMethod()</code> and <code>ParserContext.getJavaMethod()</code>
to allow access to REST methods that invoked the serializers or parsers.
For example, can be used to access additional annotations on REST methods to perform special handing
during serialization or parsing.
<li>Better behavior on overriding of filters in <code>BeanContext.addTransforms(Class[])</code>.
Previously, adding multiple conflicting filters resulted in random behavior.
Now filters are overridden when multiple matching filters are applied.
<li>Allow <code><del>HtmlDocSerializerContext</del></code> properties to be set via <code><del>Serializer.setProperty(String,Object)</del></code>.
Previously, these could only be defined through override properties (e.g. through REST class and method annotations).
<li>Fixed memory leak in XML parser.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.3"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.3 (Jun 28, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.3 is a moderate update.
</p>
<h5 class='topic'>Core API updates</h5>
<ul class='spaced-list'>
<li>Ability to detect and use non-public bean classes, getters/setters, and fields using the following new properties:
<ul>
<li>{@link org.apache.juneau.BeanContext#BEAN_beanConstructorVisibility} - Control which bean constructors are visible to Juno.
<li>{@link org.apache.juneau.BeanContext#BEAN_beanClassVisibility} - Control which bean classes are interpreted as beans to Juno.
<li>{@link org.apache.juneau.BeanContext#BEAN_beanFieldVisibility} - Control which fields are visible to Juno as bean properties.
<li>{@link org.apache.juneau.BeanContext#BEAN_beanMethodVisibility} - Control which getters/setters are visible to Juno as bean properties.
</ul>
Removed <code>BeanContext.<jsf>INCLUDE_BEAN_FIELD_PROPERTIES</jsf></code> and <code>BeanContext.<jsf>INCLUDE_BEAN_METHOD_PROPERTIES</jsf></code> properties, since ignoring fields and methods
can be accomplished by setting the appropriate properties above to {@link org.apache.juneau.Visibility#NONE NONE}.
Also, the {@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotation can now be used on non-public fields/getters/setters to override
the default behavior defined by the <code>VISIBILITY</code> properties identified above. This is a convenient way of identifying protected or
private fields or methods as bean properties. Previously, you could only identify public fields/getters/setters using this annotation.
</li>
<li>New {@link org.apache.juneau.BeanContext#BEAN_useJavaBeanIntrospector} property that lets Juno use the Java bean <code>Introspector</code>
class to determine bean properties. In the previous release, the method for determining bean properties was a mixture of Juno-based and Introspector-based.
Now it's either pure Juno-based or pure Introspector-based. The result is considerably cleaner code and consistent behavior.
<li>New {@link org.apache.juneau.annotation.BeanIgnore @BeanIgnore} annotation. Replaces the previous <code><ja>@BeanProperty</ja>(hidden=<jk>true</jk>)</code> annotation
for ignoring bean properties. Can also be used on classes that look like beans so that they're not treated as beans.
<li>Support for parsing into non-static member classes. This applies to all parsers.
<li>New {@link org.apache.juneau.json.annotation.Json#wrapperAttr() @Json.wrapperAttr()} annotation that automatically wraps beans and objects in a wrapper
attribute when serializing to or parsing from JSON.
<li>Changed the default ordering of bean properties to be in parent-to-child class order.
<li>New {@link org.apache.juneau.transform.BeanFilter#readProperty(Object,String,Object) readProperty()} and {@link org.apache.juneau.transform.BeanFilter#writeProperty(Object,String,Object) writeProperty()}
methods added to {@link org.apache.juneau.transform.BeanFilter} class to allow individualized serialization and parsing behavior on a class-by-class basis.
<li>Eliminated previous restriction where bean subtype attributes had to be listed first in JSON objects when using the <code><del>Bean.subTypeProperty()</del></code> annotation.
The previous behavior was not strictly JSON-compliant since JSON objects are supposed to consist of unordered lists of key/value pairs.
While targeted for JSON, the restriction is also lifted for all other parsers.
<li>New fluent-style {@link org.apache.juneau.BeanMap#load(String) BeanMap.load()} methods for initializing bean maps.
<li>{@link org.apache.juneau.html.HtmlDocSerializer} will now embed the data portion of the output in a <code><xt>&lt;div</xt> <xa>id</xa>=<xs>'data'</xs><xt>&gt;</xt></code> element to make it easier to extract the data portion of the page in Javascript in browsers.
</ul>
<h5 class='topic'>REST Server API updates</h5>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.rest.RestRequest#getJavaMethod()} method for getting access to the method used to handle a request.
Useful for accessing the method name or annotations during requests, such as in calls to {@link org.apache.juneau.rest.RestGuard#guard(RestRequest,RestResponse)}.
<li>Fixed bug when using Jetty where you tried to read text input after a header was written.
<li>Added new string variables <del><code>$A{...}</code></del> (request attributes) and <del><code>$P{...}</code></del> (request parameters) to <code>RestServlet.createRequestVarResolver(RestRequest)</code>.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.2"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.2 (Apr 27, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.2 is a minor update.
</p>
<ul class='spaced-list'>
<li>Fixed issue preventing <code>&amp;Accept-Language</code> from being used as a GET parameter.
<li>Minor XSS vulnerability fix.
<li>Empty results on HTML pages now shows <js>"no results"</js> instead of a blank page.
<li>Fixed issues preventing REST pages from rendering HTML in newer versions of Internet Explorer.
<li>Changed <code>RestServletProperties.REST_allowMethodParam</code> to be disabled by default.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.1"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.1 (Jan 25, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.1 is a minor update.
</p>
<ul class='spaced-list'>
<li>Addressed some behavioral differences between Tomcat and WAS.
<ul>
<li>Query parameter lookup is now always case-insensitive (per WAS behavior).
<li>Consistent handling of redirect requests (Tomcat and WAS handle relative redirect paths differently).
</ul>
<li>Fixed bug involving incorrect resolution of overlapping URL match patterns.
<li>Overall improvements in HTTP request parameter and header value resolution.
<li>Made workspace changes so as not to be dependent on the WAS test environment being loaded.
<li>Renamed <ja>@Remainder</ja> annotation to {@link org.apache.juneau.rest.annotation.PathRemainder @PathRemainder}.
<li>Fixed bug involving incorrect calculation of <code>pathInfo</code> on child resources.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.1.0.0"></a>
<h3 class='topic' onclick='toggle(this)'>5.1.0.0 (Jan 18, 2014)</h3>
<div class='topic'>
<p>
Juno 5.1.0.0 is a major update.
</p>
<h5 class='topic'>Major changes</h5>
<ul class='spaced-list'>
<li>Brand new REST client API that uses Apache HttpClient for HTTP communication.<br>
The new client API is simply a thin layer on top of <code>HttpClient</code> that performs
serialization and parsing using Juno parsers, but leaves all the details of the HTTP connection
to the Apache code. <br>
See the <del>org.apache.juneau.rest.client</del> package for details.
<li>New <code>org.apache.juneau.rest.client.jazz</code> package and <code>org.apache.juneau.rest.client.jazz.JazzRestClient</code> class
for performing REST operations against Jazz servers.<br>
Includes improved support for FORM authentication, and better SSL certificate validation.
<li>Completely redesigned URL-Encoding support.<br>
See <a class='doclink' href='org/apache/juneau/urlencoding/package-summary.html#TOC'>org.apache.juneau.urlencoding</a> package for details.
<li>Changes to Parser API.
<ul>
<li>Removal of <code>ExtendedReaderParser</code> abstract class and moved methods into
{@link org.apache.juneau.parser.ReaderParser} class.
<li>Removal of <code>DataFormat</code> class from API since it was no longer necessary
due to API change above.
<li>Removal of <code>ParserStringReader</code> class.<br>
This was a reader optimized to work with <code>String</code> input.<br>
However, it could interfere with garbage collection of the original string object.<br>
Instead, the existing {@link org.apache.juneau.parser.ParserReader} was enhanced to work
well with <code>String</code> input, and tests show no significant performance differences.
<li>New <code>org.apache.juneau.parser.Parser.parse(Object,int,ClassMeta)</code> convenience method added.
</ul>
</ul>
<h5 class='topic'>Other changes</h5>
<ul class='spaced-list'>
<li>Various new methods added to {@link org.apache.juneau.internal.StringUtils} and {@link org.apache.juneau.internal.ClassUtils}.
<li>Improved support on <code><del>BeanContext.getClassMetaFromString(String)</del></code>.<br>
Now supports resolving <code>"long[]"</code>, and so forth.
<li>{@link org.apache.juneau.rest.labels.ResourceDescription} name parameter is now automatically URL-encoded in links.
<li>{@link org.apache.juneau.rest.RestRequest} now correctly handles cases involving URL-encoded characters in the
path info portion of URLs (e.g. <code>http://host/contextRoot/foo%2Fbar</code>).
<li>Removed lazy-initialization that required locking in {@link org.apache.juneau.ClassMeta}.
<li>New <code>BeanContext.setDefaultParser(ReaderParser)</code> method added for specifying
a default parser to use in a bean context (used when converting beans to <code>Strings</code> using
<code><del>BeanContext.convertToType(Object,Class)</del></code>.
Old behavior simply used the default JSON serializer in these cases.
<li>More consistent handling of exceptions across all parsers.
<li>Minor changes to {@link org.apache.juneau.rest.RestRequest} class.
<ul>
<li>Changed the order of parameters on <del><code>RestRequest#getParameter(String,Class)</code></del>.
<li>Added <code>RestRequest.getMapParameter(String,Class,Class,Class)</code> and
<code>RestRequest.getCollectionParameter(String,Class,Class)}</code> methods.
</ul>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.36"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.36 (Dec 18, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.36 is a minor update.
</p>
<ul class='spaced-list'>
<li>Implemented <code>org.apache.juneau.urlencoding.UrlEncodingParser.parseArgs(Reader,int,ClassMeta[])</code>.
<li><code>name</code> parameter of <code><del>ResourceDescription#ResourceDescription(String,String,String)</del></code>.
is now automatically URL-encoded so that the name can contain special characters (e.g. <js>"foo/bar(baz)"</js>).
<li>Support for URL-matching and path info containing encoded characters (e.g. <js>'/'</js>) now supported.
<li>Removed some lazy-initialization of bean information in {@link org.apache.juneau.ClassMeta} that allowed the removal of
some synchronized blocks.
<li>Improved support of <code><del>BeanContext.getClassMetaFromString(String)</del></code>.
Now supports primitive arrays such as <js>"long[]"</js> in addition to the previous support for the equivalent <js>"[J"</js>.
<li>Various new convenience methods added to {@link org.apache.juneau.internal.StringUtils} and {@link org.apache.juneau.internal.ClassUtils}.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.35"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.35 (Nov 26, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.35 is a minor update.
</p>
<ul class='spaced-list'>
<li>{@link org.apache.juneau.rest.RestGuard#guard(RestRequest,RestResponse)} now returns a boolean to allow redirects to login pages.
<li>Fixed bug in RestServlet where occasional false positive "duplicate method with same name and path" errors were occurring.
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.34"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.34 (Nov 10, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.34 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
New support for runtime-replaced variables in REST resource properties:
<p class='bcode'>
<ja>@RestResource</ja>(
messages=<js>"nls/Messages"</js>,
properties={
<ja>@Property</ja>(name=<js>"label"</js>,value=<js>"$L{servletTitle}"</js>), <jc>// Localized variable in Messages.properties</jc>
<ja>@Property</ja>(name=<js>"javaVendor"</js>,value=<js>"$S{java.vendor}"</js>), <jc>// System property</jc>
<ja>@Property</ja>(name=<js>"foo"</js>,value=<js>"bar"</js>),
<ja>@Property</ja>(name=<js>"bar"</js>,value=<js>"baz"</js>),
<ja>@Property</ja>(name=<js>"v1"</js>,value=<js>"$R{foo}"</js>), <jc>// Request variable. value="bar"</jc>
<ja>@Property</ja>(name=<js>"v2"</js>,value=<js>"$R{$R{foo}}"</js>) <jc>// Nested request variable. value="baz"</jc>
}
)
</p>
See <code>RestServlet.createRequestVarResolver(RestRequest)</code> for more information.
</li>
<li>
Eliminated <ja>@Property.type</ja> annotation which was the old way of specifying NLS variables that got resolved at runtime.
</li>
<li>
New methods on {@link org.apache.juneau.rest.RestRequest}:
<ul>
<li><del><code>RestRequest.getVarResolver()</code></del></li>
<li><code><del>RestRequest.getServletURI()</del></code></li>
<li><code><del>RestRequest.getRequestParentURI()</del></code></li>
</ul>
</li>
<li>
New methods on {@link org.apache.juneau.rest.RestResponse}:
<ul>
<li><code>RestResponse.sendRedirect(CharSequence)</code>
</ul>
</li>
<li>
New methods on {@link org.apache.juneau.rest.RestServlet} that allow easier customization by subclasses:
<ul>
<li><code><del>RestServlet.createConfigFactory()</del></code></li>
<li><code><del>RestServlet.createConverters()</del></code></li>
<li><code><del>RestServlet.createDefaultRequestHeaders()</del></code></li>
<li><code><del>RestServlet.createDefaultResponseHeaders()</del></code></li>
<li><code><del>RestServlet.createEncoders()</del></code></li>
<li><code><del>RestServlet.createFilters()</del></code></li>
<li><code><del>RestServlet.createGuards()</del></code></li>
<li><code><del>RestServlet.createMimetypesFileTypeMap()</del></code></li>
<li><code><del>RestServlet.createParsers()</del></code></li>
<li><code><del>RestServlet.createProperties()</del></code></li>
<li><code><del>RestServlet.createRequestProperties(ObjectMap,RestRequest)</del></code></li>
<li><code><del>RestServlet.createRequestVarResolver(RestRequest)</del></code></li>
<li><code><del>RestServlet.createSerializers()</del></code></li>
<li><code><del>RestServlet.createUrlEncodingParser()</del></code></li>
</ul>
</li>
<li>
Changed <code>RestServletNls</code> to use <code>ResourceDescription/MethodDescription</code>
instead of <code>RestResource/RestMethod</code>
</li>
<li>
New property <code>RestServletProperties.REST_htDocsFolder</code>.<br>
New support for serving up static documents from classpath through REST interface.
</li>
<li>
Exception APIs now use {@link java.text.MessageFormat} (e.g. <js>"{0}"</js>) for message variables instead of <js>"%s"</js>.
</li>
<li>
New {@link org.apache.juneau.annotation.Bean#stopClass @Bean.stopClass} annotation for specifying stop classes for bean properties.
</li>
<li>
New <del><code>BeanFilter.setStopClass(Class)</code></del> which is the program equivalent to the annotation above.
</li>
<li>
New methods on {@link org.apache.juneau.dto.ResultSetList}:
<ul>
<li><code>ResultSetList.handleBlob(Blob)</code></li>
<li><code>ResultSetList.handleClob(Clob)</code></li>
</ul>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.33"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.33 (Oct 20, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.33 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
Removed generic parameter from {@link org.apache.juneau.serializer.WriterSerializer} class.
<ul>
<li>
Many of the examples in the documentation were written as follows, which resulted in "unchecked" compile warnings:<br>
<code>WriterSerializer s = <jk>new</jk> JsonSerializer();</code><br>
These compile warnings will now go away.
</li>
</ul>
</li>
<li>
New settings in BeanContext. These can be applied to all serializers/parsers.
<ul>
<li>{@link org.apache.juneau.BeanContext#BEAN_ignoreInvocationExceptionsOnGetters}
<li>{@link org.apache.juneau.BeanContext#BEAN_ignoreInvocationExceptionsOnSetters}
<li>{@link org.apache.juneau.BeanContext#BEAN_notBeanPackages_add}
<li>{@link org.apache.juneau.BeanContext#BEAN_notBeanPackages_remove}
</ul>
</li>
<li>
Eliminated <code>addNotBeanClassPatterns(String...)</code> methods throughout API since these are now controlled by {@link org.apache.juneau.BeanContext#BEAN_notBeanPackages_add} / {@link org.apache.juneau.BeanContext#BEAN_notBeanPackages_remove} properties.
</li>
<li>
New settings in <code>RestServletProperties</code>.
<ul>
<li><code>RestServletProperties.REST_trimTrailingUriSlashes</code><br>
Also removed <code>RestRequest.getRequestURI(boolean trimTrailingSlashes)</code> method which is now redundant with this property.
<li><code>RestServletProperties.REST_pathInfoBlankForNull</code><br>
Also removed <code>RestRequest.getPathInfo(boolean returnBlankForNull)</code> method which is now redundant with this property.
</ul>
</li>
<li>
New JSON-Schema {@link org.apache.juneau.dto.jsonschema.SchemaMap} class for supporting linked schemas.
</li>
<li>
Serializers will no longer throw an exception when <code>maxDepth</code> setting is reached, and will instead simply ignore content below the specified depth.<br>
While the old behavior was as-designed, the new behavior is more in-line with expected behavior.
</li>
<li>
Added support for HTTP header <js>"X-Response-Headers"</js> to {@link org.apache.juneau.rest.RestServlet}. <br>
Allows you to specify one or more headers that should be returned on the response from the servlet.<br>
For example, to get a page to automatically refresh every 1 second, you can append the following to a URL: <code>?x-response-headers={Refresh=1}</code>
</li>
<li>
Removed <code>HtmlDocSerializerContext.<jsf>HTML_REFRESH</jsf></code> setting that added a Refresh meta tag to HTML documents, since this can now be controlled through <code>X-Response-Headers</code>.
</li>
<li>
Small improvements to samples.
<ul>
<li><code>PhotosResource</code> now includes a default entry.
</ul>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.32"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.32 (Oct 5, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.32 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
New support for generating and consuming fully-compliant JSON-Schema documents.<br>
See <a class='doclink' href='org/apache/juneau/dto/jsonschema/package-summary.html#TOC'>org.apache.juneau.dto.jsonschema</a> for information.
</li>
<li>
New methods added to {@link org.apache.juneau.parser.Parser}:
<ul>
<li><code>org.apache.juneau.parser.Parser.parseMap(Object,int,Class,Class,Class)</code></li>
<li><code>org.apache.juneau.parser.Parser.parseCollection(Object,int,Class,Class)</code></li>
</ul>
</li>
<li>
{@link org.apache.juneau.annotation.Bean @Bean} annotation can now be defined on interfaces and inherited by subclasses.
</li>
<li>
Support for customizing serialized values for <code>Enums</code> through overriding <code>toString()</code> and <code>fromString()</code> on the enum class.<br>
Previously used <code>Enum.valueOf()</code> to convert strings back into <code>Enums</code>.<br>
Used for JSON-Schema support to allow {@link org.apache.juneau.dto.jsonschema.JsonType} enum to be serialized to lowercase per the specification (e.g. <js>"string"</js> instead of <js>"STRING"</js>).
</li>
<li>
{@link org.apache.juneau.dto.cognos Cognos} DTOs now have fluent-style bean setters.
</li>
<li>
Support for generic bean objects whose type was erased at compile time.<br>
Previous behavior gave you an error message that the type could not be determined.<br>
New behavior assumes a type of <code>Object</code> when the type is erased.
</li>
<li>
Bug fixes:
<ul>
<li>
When duplicate fluent-style setters were defined with different parameter types (e.g. <code>setFoo(Foo f)</code>, <code>setFoo(Bar b)</code>), the {@link org.apache.juneau.BeanMap} API would sometime choose the wrong setter as the bean property setter. <br>
Now validates that the setter being chosen is the one whose return type matches the property getter.
</li>
<li>
Passing in <code>Accept</code> GET parameters with <js>'+'</js> (e.g. <code>&amp;Accept=text/json+simple</code>) wasn't working anymore.<br>
The <code>Accept</code> parameter is supposed to interpret spaces as <js>'+'</js> to allow you to not have to write <code>&amp;Accept=text/json%2Bsimple</code>.
</li>
<li>
Parsers would not set bean properties of abstract type {@link java.lang.Number}.<br>
Now it detects the numeric type based on input and sets the value accordingly.
</li>
</ul>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.31"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.31 (Aug 9, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.31 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
Simplified the {@link org.apache.juneau.serializer.Serializer} and {@link org.apache.juneau.parser.Parser} class hierarchies.<br>
This reverses a previous change that added a bunch of interfaces in these APIs (and subsequently required compiling with Java 7 to get around a compiler bug).<br>
The new class hierarchy is much simpler to understand.
</li>
<li>
Added {@link org.apache.juneau.transforms.XMLGregorianCalendarSwap} to convert these to ISO8601 strings during serialization, and vice versa during parsing.
</li>
<li>
Added a strict mode to {@link org.apache.juneau.json.JsonParser}.
</li>
<li>
Added default {@link org.apache.juneau.json.JsonParser#DEFAULT_STRICT} parser.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.30"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.30 (Aug 8, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.30 is a minor update.
</p>
<ul class='spaced-list'>
<li>
Fixed bug involving beans using <code><del>Bean.subTypes()</del></code> annotation in addition to <code>subTypes</code> property.
</li>
<li>
Modified the JSON parser to handle non-existent JSON values to get around an issue where Cognos was generating invalid JSON.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.29"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.29 (Aug 2, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.29 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
Revamped the API for filter support:
<ul>
<li>Updated {@link org.apache.juneau.transform.BeanFilter} class to mirror the {@link org.apache.juneau.annotation.Bean @Bean} annotation.</li>
<li>Introduced support for bean <code><del>Bean.subTypeProperty() subtypes</del></code>. </li>
<li>Replaced <code><ja>@Bean</ja>(filter=xxx)</code> with new <del><code>@Transform</code></del> annotation.</li>
</ul>
</li>
<li>
Revamped URL-Encoding support.<br>
The old URL-Encoding serializer and parser simply used the JSON serializer/parser with a thin URL-encoding top layer.<br>
The new URL-Encoding serialize and parser was written from scratch and is considerably more consistent in design and output.
</li>
<li>
Improved number parsing.<br>
The new number parser should handle any valid numeric syntax for decimals and floats that Java itself supports.
</li>
<li>
{@link org.apache.juneau.json.JsonSerializer} LAX mode now quotes reserved word attributes.
</li>
<li>
New predefined DateFilters with millisecond precision:
<ul>
<li><code>org.apache.juneau.transforms.DateSwap.ISO8601DTP</code></li>
<li><code>org.apache.juneau.transforms.DateSwap.ISO8601DTZP</code></li>
</ul>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.28"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.28 (July 9, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.28 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
Fixes an <code>OutOfMemoryError</code> and performance issue caused by incorrect caching of class metadata.
</li>
<li>
Added <code>WriterSerializer.serialize(Object,Writer)</code> convenience method for serializing directly to a writer.<br>
Applies to all serializers.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.27"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.27 (July 7, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.27 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
Fixed some HTML formatting issues in {@link org.apache.juneau.html.HtmlSerializer}.
</li>
<li>
{@link org.apache.juneau.rest.RestServletDefault} now includes {@link org.apache.juneau.plaintext.PlainTextSerializer} and {@link org.apache.juneau.plaintext.PlainTextParser} for plain-text support.
</li>
<li>
Child resources now render on default <code>OPTIONS</code> pages through new method <del><code>ResourceOptions.getChildren()</code></del>.
</li>
<li>
Changes to {@link org.apache.juneau.urlencoding.UrlEncodingSerializer}/{@link org.apache.juneau.urlencoding.UrlEncodingParser} to reduce the need for quoted string values.<br>
More changes are likely in this area of the code to support multipart form posts.
</li>
<li>
FindBugs fixes.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.26"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.26 (Jun 5, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.26 is a minor update.
</p>
<ul class='spaced-list'>
<li>
FindBug fixes.
</li>
<li>
Changed the way child REST resources are defined.<br>
Eliminated the <ja>@RestChild</ja> annotation on getter methods and replaced it with {@link org.apache.juneau.rest.annotation.RestResource#children() @RestResource.children()} defined on the resource class itself.<br>
Child resource paths are specified through {@link org.apache.juneau.rest.annotation.RestResource#path() @RestResource.path()}.
</li>
<li>
New {@link org.apache.juneau.rest.labels.ChildResourceDescriptions} bean for automatically generating the contents of router resource pages.
</li>
<li>
Changed <code><ja>@RestMethod</ja>.pattern()</code> to {@link org.apache.juneau.rest.annotation.RestMethod#path() @RestMethod.path()} for naming consistency.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.25"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.25 (May 11, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.25 is a minor update.
</p>
<h5 class='topic'>Core API updates</h5>
<ul class='spaced-list'>
<li>
New {@link org.apache.juneau.dto.ResultSetList} DTO for serializing SQL result sets to JSON/XML/HTML and so forth.
</li>
<li>
New <code>SqlQueryResource</code> class in the sample war for demonstrating the <code>ResultSetList</code> DTO.
</li>
</ul>
<h5 class='topic'>Server API updates</h5>
<ul class='spaced-list'>
<li>
Fixed issue with media type for CSS files being reported as <js>"text/plain"</js> instead of <js>"text/css"</js>.
</li>
<li>
Moved initialization of class properties to before the call to <code>Servlet.init()</code> so that <code>getProperties()</code> can be called during servlet initialization.
</li>
<li>
New <code><ja>@Property</ja>.type</code> annotation with support for using system properties as resource properties.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.24"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.24 (May 9, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.24 is a major update.
</p>
<h5 class='topic'>Core API updates</h5>
<ul class='spaced-list'>
<li>
New support for {@link org.apache.juneau.dto.atom ATOM}.
<ul>
<li>New <code>AtomFeedResource</code> class added to sample war.
</ul>
</li>
<li>
New <code><del>XmlFormat.CONTENT</del></code> enum value.<br>
Allows bean properties to be persisted as XML element text.
</li>
<li>
New <code><del>XmlContentHandler</del></code> class and <code><del>@Xml.contentHandler</del></code> annotation.<br>
Allows customized serialization and parsing of beans to XML element text.<br>
Added for support of ATOM text content that must support both plain text and embedded XHTML.
</li>
<li>
New {@link org.apache.juneau.xml.annotation.XmlSchema @XmlSchema} and updated {@link org.apache.juneau.xml.annotation.XmlNs @XmlNs} annotations to better mimic JAXB.
</li>
<li>
Removed <code><ja>@Xml</ja>.valAttr</code> annotation since it's now redundant with <code><ja>@Xml</ja>(format=<jsf>CONTENT</jsf>)</code>.
</li>
<li>
Fixed timezone bug in {@link org.apache.juneau.transforms.CalendarSwap}.
</li>
<li>
Simplified <code>Serializer.serialize(Object,Object,SerializerContext)</code> method.
</li>
<li>
Fixed bug where lists returned by {@link org.apache.juneau.ObjectMap#getObjectList(String)} were not updatable.
</li>
<li>
Eliminated old RDF/XML serializer.
</li>
</ul>
<h5 class='topic'>Documentation updates</h5>
<ul>
<li>New {@link org.apache.juneau.json JSON Support Overview} document.</li>
<li>New {@link org.apache.juneau.xml XML Support Overview} document.</li>
<li>New {@link org.apache.juneau.jena RDF Languages Support Overview} document.</li>
<li>New {@link org.apache.juneau.dto.atom ATOM Support Overview} document.</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.23"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.23 (Apr 14, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.23 is a minor update.
</p>
<ul class='spaced-list'>
<li>
Simplified {@link org.apache.juneau.dto.cognos Cognos} support.
</li>
<li>
Fixed bug where <code><ja>@Xml</ja></code> annotation was not being inherited by inner classes.
</li>
<li>
Javadoc stylesheet improvements.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.22"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.22 (Apr 12, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.22 is a minor update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
New <code><ja>@Property</ja>.nls()</code> annotation for specifying localized property values.<br>
For example, allows you to set the <jsf>HTMLDOC_title</jsf> and <jsf>HTMLDOC_description</jsf> properties to localized values pulled from a resource bundle.<br>
See the <code>AddressBookResource</code> class for an example.
</li>
</ul>
<h5 class='topic'>REST Servlet API changes</h5>
<ul class='spaced-list'>
<li>Fix a bug where the <code>&amp;Content</code> query parameter was not always parsed correctly.</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.21"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.21 (Apr 9, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.21 is a minor update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
New <code><del>HtmlDocSerializerContext.HTMLDOC_navlinks</del></code> annotation for addint links to HTML page views.
</li>
<li>
Renamed the properties in <code><del>HtmlDocSerializerContext</del></code> for clarity.
</li>
</ul>
<h5 class='topic'>Servlet API changes</h5>
<ul class='spaced-list'>
<li>
Added new <code>RestServlet.addDefaultProperties(ObjectMap,RestRequest)</code> method for programatically adding properties to the property map per request.
</li>
<li>
Added the following new properties in the properties map to make them easily available to serializers and parsers (since they don't have access to the HTTP request object).<br>
Note that the <code>SerializerContext.SERIALIZER_uriAuthority</code> and <code>SerializerContext.SERIALIZER_uriContext</code> properties were previously available.
<ul>
<li><code>RestServletProperties.REST_servletPath</code></li>
<li><code>RestServletProperties.REST_pathInfo</code></li>
<li><code>RestServletProperties.REST_method</code></li>
</ul>
</li>
<li>
Path variables annotated with <del><code>@Attr</code></del> are now automatically URL-decoded.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.20"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.20 (Apr 7, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.20 is a major update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
New Jena-based {@link org.apache.juneau.jena.RdfSerializer} for serializing POJOs to RDF/XML, RDF/XML-ABBREV, N-Triple, Turtle, and N3.<br>
Serializes ANY POJOs to RDF, even simple objects and primitives.
</li>
<li>
New Jena-based {@link org.apache.juneau.jena.RdfParser} for parsing RDF/XML, RDF/XML-ABBREV, N3, Turtle, and N-Triple back into POJOs.
</li>
<li>
<code><del>XmlSerializerContext.XML_autoDetectNamespaces</del></code> default changed to <jk>true</jk>.<br>
The old default value would cause XML with unmapped namespaces if you didn't manually specify them via the <code><del>XmlSerializerContext.XML_namespaces</del></code> annotation.<br>
While setting the default to <jk>true</jk> is somewhat slower (since the serializer must crawl the POJO tree to find namespaces), the benefits of having it work out-of-the-box outweighs the performance concerns.<br>
For developers concerned about performance, they can always change it back to false and specify the namespaces themselves.
</li>
</ul>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>
Allow inheritance of {@link org.apache.juneau.rest.annotation.RestResource @RestResource} annotation.<br>
Serializers, parsers, filters, properties , guards, and converters definitions are automatically inherited from parent classes and interfaces.
</li>
<li>
Enhancements to {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod} annotation:
<ul>
<li>
New <code>RestMethod.filters()</code> annotation for defining POJO filters at the method level.
</li>
<li>
New <code><del>RestMethod.serializersInherit()</del></code> and <code><del>RestMethod.parsersInherit()</del></code> annotations for controlling how serializers and parsers (and associated filters and properties) are inherited from the class.<br>
This replaces the previous <code>addSerializers</code> and <code>addParsers</code> annotations.
</ul>
</li>
<li>
New <code><del>RestServletJenaDefault</del></code> servlet that includes serialization/parsing support for all Jena-based serializers and parsers.
</li>
<li>
New <code><del>DefaultJenaProvider</del></code> JAX-RS provider that includes serialization/parsing support for all Jena-based serializers and parsers.
</li>
<li>
Eliminated <code>RestServletChild</code> class.<br>
It's redundant with the introduction of inheritable annotations.
</li>
<li>
New methods on {@link org.apache.juneau.rest.RestServlet}:
<ul>
<li><code>RestServlet.createConfigFactory()</code></li>
<li><code>RestServlet.createSerializers()</code></li>
<li><code>RestServlet.createParsers()</code></li>
</ul>
These augment the existing <code>getBeanContext()</code> / <code>getSerializers()</code> / <code>getParsers()</code> methods.
</li>
</ul>
<h5 class='topic'>REST client API changes</h5>
<ul class='spaced-list'>
<li>
New <code>RestCall.setDateHeader(String,Object)</code> method for setting ISO8601 datetime headers.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.19"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.19 (Apr 1, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.19 is a minor update.
</p>
<ul class='spaced-list'>
<li>
New methods on {@link org.apache.juneau.rest.RestServlet}:
<ul>
<li><code><del>RestServlet.onPreCall(RestRequest)</del></code></li>
<li><code><del>RestServlet.onPostCall(RestRequest,RestResponse)</del></code></li>
</ul>
</li>
<li>
<jsf>TRIM_NULLS</jsf> setting changed to <code><del>SerializerContext.SERIALIZER_trimNullProperties</del></code>.<br>
New property default is <jk>true</jk>.
Only applies to bean properties, not map or collection entries.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.18"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.18 (Mar 27, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.18 is a moderate update.
</p>
<p>
The biggest change is the introduction of the {@link org.apache.juneau.jena.RdfSerializer} class that uses Jena to generate RDF/XML, RDF/XML-ABBREV, N-Tuple, N3, and Turtle output.
</p>
<p>
This code should be considered prototype-quality, and subject to change in the future.<br>
There are plans of adding an equivalent <code>RdfParser</code> class in the future, so the serializer logic may need to be tweaked to allow POJOs to be reconstituted correctly in the parser.
</p>
<p>
The <code>RdfXmlSerializer</code> class should be considered deprecated for now.<br>
However, I'm keeping it around, since it's considerably faster and uses far less memory than the Jena-based serializer since it serializes directly from POJOs to RDF/XML.<br>
It may or may not be removed in the future depending on demand.
</p>
<h5 class='topic'>Other changes</h5>
<ul class='spaced-list'>
<li>
New {@link org.apache.juneau.jso.JsoParser} class.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.17"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.17 (Mar 25, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.17 is a minor update.
</p>
<ul class='spaced-list'>
<li>
Charset now passed as a parameter to <code>IOutputStreamSerializer.serialize()</code> and <code>IInputStreamParser.parse()</code>.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.16"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.16 (Mar 25, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.16 is a minor update.
</p>
<ul class='spaced-list'>
<li>
New <code><del>@Properties</del></code> REST method parameter annotation that can be used to get the runtime properties map through a parameter instead of through {@link org.apache.juneau.rest.RestResponse}.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.15"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.15 (Mar 24, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.15 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
Juno-Wink integration components that have been requested by many for a long time!<br>
Refer to <del>org.apache.juneau.rest.jaxrs</del> for information.
</li>
<li>
New <code><del>@Produces</del></code> annotation in place of <code>ISerializer.getMediaTypes()</code> for specifying what media types a serializer produces.<br>
Available when subclassing from {@link org.apache.juneau.serializer.Serializer}.
</li>
<li>
New <code><del>@Consumes</del></code> annotation in place of <code>IParser.getMediaTypes()</code> for specifying what media types a parser consumes.<br>
Available when subclassing from {@link org.apache.juneau.parser.Parser}.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.14"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.14 (Mar 23, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.14 is a major update.
</p>
<p>
The biggest change is that the <code>RestSerializer</code>, <code>RestParser</code>, <code>RestSerializerGroup</code>, and <code>RestParserGroup</code> classes have been eliminated entirely.<br>
Instead, the existing {@link org.apache.juneau.serializer.Serializer}, {@link org.apache.juneau.parser.Parser}, {@link org.apache.juneau.serializer.SerializerGroup}, and {@link org.apache.juneau.parser.ParserGroup} classes of the core API have been augmented to replace them.
</p>
<p>
Adoptions will be required if you have previously used these classes.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
New <code>org.apache.juneau.serializer</code> package.
<ul>
<li>Entirely reworked class hierarchy to make it easier to define new serializers.</li>
<li>New {@link org.apache.juneau.serializer.WriterSerializer} base class for defining character-based serializers.</li>
<li>New {@link org.apache.juneau.serializer.OutputStreamSerializer} base class for defining byte-based serializers.</li>
<li>Updated {@link org.apache.juneau.serializer.SerializerGroup} class with full support for RFC2616 <code>Accept-Content</code> headers.</li>
<li>Improved cloning support on serializers and serializer groups.</li>
</ul>
</li>
<li>
New <code>org.apache.juneau.parser</code> package.
<ul>
<li>Entirely reworked class hierarchy to make it easier to define new parsers.</li>
<li>New {@link org.apache.juneau.parser.ReaderParser} base class for defining character-based parsers.</li>
<li>New {@link org.apache.juneau.parser.InputStreamParser} base class for defining byte-based parsers.</li>
<li>Improved cloning support on parsers and parser groups.</li>
</ul>
</li>
<li>
New <code>org.apache.juneau.transform</code> package.
<ul>
<li>Cleaner class structure.</li>
<li>Improved {@link org.apache.juneau.transform.BeanFilter} class for defining property filters on beans.</li>
<li>Improved {@link org.apache.juneau.utils.PojoQuery} class for defining filters on objects (previously called <code>ObjectFilter</code>).</li>
</ul>
</li>
<li>
New <code>org.apache.juneau.encoders</code> package.
<ul>
<li>Defines API for {@link org.apache.juneau.encoders.Encoder Encoders} for enabling compression in REST servlets and clients.</li>
<li>Previously, gzip compression was enabled by default. This new API allows you to plug in your own compression algorithms.</li>
<li>New {@link org.apache.juneau.encoders.GzipEncoder} class for enabling gzip compression.</li>
<li>New {@link org.apache.juneau.encoders.EncoderGroup} class for managing multiple encoders and finding them based on RFC2616 <code>Accept-Encoding</code> header values.</li>
</ul>
</li>
<li>
New <code>org.apache.juneau.plaintext</code> package.
<ul>
<li>New {@link org.apache.juneau.plaintext.PlainTextSerializer} and {@link org.apache.juneau.plaintext.PlainTextParser} classes for serializing/parsing text/plain content.</li>
</ul>
</li>
<li>
New <code>org.apache.juneau.jso</code> package.
<ul>
<li>New {@link org.apache.juneau.jso.JsoSerializer} class for serializing <code>application/x-java-serialized-object</code> content.</li>
</ul>
</li>
<li>
New <code>org.apache.juneau.soap</code> package.
<ul>
<li>New {@link org.apache.juneau.soap.SoapXmlSerializer} class for serializing <code>text/xml+soap</code> content.</li>
</ul>
</li>
<li>
Improved cloning support on the {@link org.apache.juneau.BeanContext} class.
<ul>
<li>Better caching. Improved caching performance.</li>
</ul>
</li>
<li>
<code>JsonMap</code> and <code>JsonList</code> changed to {@link org.apache.juneau.ObjectMap} and {@link org.apache.juneau.ObjectList} to better reflect that they're not limited to just JSON support.
</li>
<li>
Renamed <code>PojoSwap</code> to {@link org.apache.juneau.utils.PojoQuery} to not confuse it with the new Filter API.
</li>
</ul>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>
Eliminated <code>org.apache.juneau.rest.serializers</code> and <code>org.apache.juneau.rest.parsers</code> packages.
<ul>
<li>All existing REST serializers and parsers merged into the core API.</li>
</ul>
</li>
</ul>
<h5 class='topic'>REST client API changes</h5>
<ul class='spaced-list'>
<li>
Simplified {@link org.apache.juneau.rest.client.RestClient} API.
<ul>
<li>You can now only specify a single serializer or parser per client. This significantly simplifies the code.</li>
<li>Support for {@link org.apache.juneau.encoders.Encoder Encoders}.</li>
</ul>
</li>
<li>
Eliminated <code>RestCmdLine</code> (since it's essentially redundant with CURL).
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.13"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.13 (Mar 14, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.13 is a minor update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
New support for relative URIs.
<ul>
<li>URIs of the form <js>"foo/bar"</js> are interpreted as relative to the context root of the web application.</li>
<li>URIs of the form <js>"/foo/bar"</js> are interpreted as relative to the HTTP authority (e.g. <js>"http://myhost:9080"</js>).</li>
</ul>
</li>
<li>
New <code>SerializerContext.SERIALIZER_uriContext</code> and <code>SerializerContext.SERIALIZER_uriAuthority</code> serializer properties for specifying values for relative URIs.
</li>
<li>
New {@link org.apache.juneau.annotation.URI @URI} annotation that allows you to specify classes and bean properties as URLs that aren't <code>java.net.URI</code> or <code>java.net.URL</code>.
</li>
<li>
New {@link org.apache.juneau.html.HtmlSerializer#HTML_uriAnchorText} HTML serializer property for tailoring how anchor text is rendered.
</li>
<li>
Renamed <code>BeanProperty#uri</code> annotation to <code>BeanProperty#beanUri</code> to make it clear that this property represents the URI of the bean itself instead of an arbitrary property containing a URI.
</li>
<li>
Removed <code>BeanProperty#id</code> annotation.
</li>
</ul>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>
Improvements to {@link org.apache.juneau.rest.RestServlet} to automatically handle relative URIs in POJOs.
<ul>
<li><code>SerializerContext.SERIALIZER_uriContext</code> property set by default to web app context root.</li>
<li><code>SerializerContext.SERIALIZER_uriAuthority</code> property set by default to the request scheme+hostname+port.</li>
</ul>
</li>
<li>
Fixed bug involving <code>Accept-Charset</code> header in Chrome that prevented HTML output from rendering correctly in that browser.<br>
<code>Accept-Charset</code> handling should now be fully W3C compliant.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.12"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.12 (Mar 10, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.12 is a minor update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
Relaxed method naming conventions when using {@link org.apache.juneau.annotation.BeanProperty @BeanProperty} annotation.<br>
Methods with zero parameters are interpreted as getters, and methods with one parameter are interpreted as setters.<br>
Eliminated the <code>BeanProperty.method</code> annotation, since it's now unnecessary.
</li>
</ul>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>
Significantly improved response error messages.<br>
Older messages were rather cryptic. Error conditions should be much easier to debug now.
</li>
<li>
New <code>PlainTextRestSerializer</code> class for serializing <js>"plain/text"</js> requests.<br>
Useful for debugging purposes.
</li>
<li>
<code>Readers</code> and <code>InputStreams</code> can now be passed in as <del><code>@Content</code></del> parameters if you need direct access to the HTTP body content without involving the parsers.<br>
Equivalent to previously calling {@link org.apache.juneau.rest.RestRequest#getInputStream()} and {@link org.apache.juneau.rest.RestRequest#getReader()}.
</li>
<li>
Improved support for the <code>?debug</code> parameter.<br>
Dumps better information to the log file, such as all header parameters.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.11"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.11 (Mar 8, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.11 is a moderate update.
</p>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>
New <code>UrlEncodingRestSerializer</code> and <code>UrlEncodingRestParser</code> classes.<br>
Allows parsing form posts directly to POJOs.
</li>
<li>
Support for <code>Accept</code> and <code>Content-Type</code> <js>"application/x-www-form-urlencoded"</js> added by default on {@link org.apache.juneau.rest.RestServletDefault}.
</li>
<li>
New <code><del>RestServlet.renderError(HttpServletRequest,HttpServletResponse,RestException)</del></code> method to allow customized handling of response errors.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.10"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.10 (Mar 7, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.10 is a minor update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>New {@link org.apache.juneau.ObjectMap#findKeyIgnoreCase(String)} method.
<li>HtmlSerializer will now create 2-dimensional tables for collections of mixed beans/maps if all object have the same set of property names/keys.</li>
</ul>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>New <code>RestServletProperties</code> class that defines all the class-level properties that can be set on the servlet.</li>
<li>Properties can be set through {@link org.apache.juneau.rest.annotation.RestResource#properties() @RestResource.properties} annotation, or new <code><del>RestServlet.setProperty(String,Object)</del></code> method.</li>
<li>New <js>"?noTrace"</js> URL parameter to prevent stack traces from being logged (for JUnit testing of error conditions).</li>
<li>New <code>RestServletProperties.REST_useStackTraceHashes</code> property to prevent the same stack trace from being logged multiple times.</li>
<li>New <code>RestServletProperties.REST_renderResponseStackTraces</code> property for preventing stack traces in responses for security reasons.</li>
<li>New overridable <code>RestServlet.onError(HttpServletRequest,HttpServletResponse,RestException,boolean)</code> and <code><del>RestServlet.onSuccess(RestRequest,RestResponse,long)</del></code> methods for plugging in your own logging and peformance monitoring.</li>
<li>Eliminated <code>RestServlet.getInitParams()</code> method, since it's now redundant with {@link org.apache.juneau.rest.RestServlet#getProperties()}.</li>
<li>Header parameters passed as URL parameters are now case-insensitive.</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.9"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.9 (Feb 26, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.9 is a moderate update.
</p>
<h5 class='topic'>Core API changes</h5>
<ul class='spaced-list'>
<li>
{@link org.apache.juneau.config INI config file support}:
<ul>
<li>A convenient API for reading, writing, and manipulating INI files.</li>
<li>Ability to convert INI files to batch and shell environment variables.</li>
<li>Command-line interface for updating INI files.</li>
<li>Support for encoded INI file values.</li>
</ul>
</li>
<li>Support for fluent-style bean setters (setters that return the bean itself).</li>
<li>Ability to use {@link org.apache.juneau.annotation.Bean @Bean} annotation to override bean identification settings.</li>
<li>New {@link org.apache.juneau.ObjectMap#cast(Class)} method to convert <code>ObjectMaps</code> directly to beans.</li>
</ul>
<h5 class='topic'>REST server API changes</h5>
<ul class='spaced-list'>
<li>Build-in default <code>OPTIONS</code> pages.</li>
<li>New {@link org.apache.juneau.rest.annotation.RestResource#defaultRequestHeaders() @RestResource.defaultRequestHeaders} and {@link org.apache.juneau.rest.annotation.RestResource#defaultResponseHeaders() @RestResource.defaultResponseHeaders} annotations.</li>
<li>New {@link org.apache.juneau.rest.annotation.RestMethod#serializers() @RestMethod.serializers()} and {@link org.apache.juneau.rest.annotation.RestMethod#parsers() @RestMethod.parsers()} annotations.</li>
<li>New {@link org.apache.juneau.rest.annotation.RestMethod#properties() @RestMethod.properties()} annotation.</li>
<li>New {@link org.apache.juneau.rest.annotation.RestMethod#defaultRequestHeaders() @RestMethod.defaultRequestHeaders()} annotation.</li>
<li>New {@link org.apache.juneau.rest.annotation.RestMethod#matchers() @RestMethod.matchers()} annotation and {@link org.apache.juneau.rest.RestMatcher} class.</li>
<li><code>Readers</code> and <code>InputStreams</code> can be specified on <del><code>@Content</code></del> annotated parameters.</li>
<li>New <del><code>@HasParam</code></del> annotation.</li>
<li>Full RFC2616 support for matching <code>Accept</code> headers to serializers.</li>
</ul>
<h5 class='topic'>Other notes</h5>
<ul class='spaced-list'>
<li>Smaller library size (460kB).</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.8"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.8 (Jan 30, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.8 is a minor update.
</p>
<ul class='spaced-list'>
<li>
New {@link org.apache.juneau.config INI file} support.
<ul>
<li>Makes reading, updating, and manipulating INI configuration files a snap. </li>
<li>Supports automatic conversion of data types in line with the functionality of the rest of the product.</li>
<li>Comments and layout of INI files are persisted during saves. </li>
</ul>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.7"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.7 (Jan 20, 2013)</h3>
<div class='topic'>
<p>
Juno 5.0.0.7 is a major update.
</p>
<h5 class='topic'>Core API updates</h5>
<ul class='spaced-list'>
<li>Combined previous 3 libraries into a single library.</li>
<li>
New {@link org.apache.juneau.parser.ParserListener} class.<br>
Adds ability to find and process unknown bean properties during parsing.
</li>
<li>
Enhancements to {@link org.apache.juneau.xml.XmlParser}:
<ul>
<li>Coalescing support</li>
<li>Validations support</li>
<li>Support for replacing entity references</li>
<li>Resolver support</li>
<li>Event allocator support</li>
<li>Trim-whitespace support</li>
</ul>
</li>
<li>
Enhanced XML support:
<ul>
<li>
New {@link org.apache.juneau.xml.annotation.Xml#format() @Xml.format} annotation.<br>
Controls how POJOs get serialized to XML.<br>
Also allows you to collapse collections and arrays.
</li>
<li>
New <code>@Xml.namespaces</code> annotation.<br>
Namespaces can be defined at package, class, method, or field levels.
</li>
<li>
New <code>@Xml.nsUri</code> annotation.<br>
Shortcut for specifying namespace URIs.
</li>
<li>
New <code>@Xml.valAttr</code> annotation.<br>
Serializes a bean property value as an attribute.
</li>
<li>Ability to override XS and XSI namespaces on XML and RDF/XML serializers.</li>
<li>Ability to override RDF namespace on RDF/XML serializer.</li>
<li>New more-efficient namespace resolution.</li>
</ul>
</li>
<li>
New configurable property classes for everything are now structured better and easier to locate and identify through the following new classes:
<ul>
<li>{@link org.apache.juneau.BeanContext}</li>
<li><code><del>SerializerContext</del></code></li>
<li><code><del>ParserContext</del></code></li>
</ul>
</li>
<li>
Enhancements to {@link org.apache.juneau.BeanContext}:
<ul>
<li>
Ability to mark bean properties as hidden using <code>@BeanProperty.hidden()</code> so that they don't get serialized.
</li>
<li>
Simplified <code>ClassType</code> {@link org.apache.juneau.ClassMeta} API.<br>
Combined 4 classes into a single class.
</li>
<li>
New <del><code>@Bean.filter</code></del> and <del><code>@BeanProperty.filter</code></del> annotations.<br>
Used for defining filters on bean classes and bean properties instead of just globally through <code>BeanContext.addTransforms(Class[])</code>.
</li>
<li>
New {@link org.apache.juneau.PropertyNamer} API / {@link org.apache.juneau.annotation.Bean#propertyNamer() @Bean.propertyNamer} annotation.<br>
Used for customizing bean property names.
</li>
<li>
New <del><code>@BeanProperty.beanUri</code></del> and <del><code>@BeanProperty.id</code></del> annotations.<br>
Used for associating beans with URLs and IDs.<br>
Used by XML serializer to add a url attribute on a bean element.<br>
Used by RDF/XML serializer to construct <code>rdf:resource</code> attributes.
</li>
<li>
New {@link org.apache.juneau.annotation.BeanProperty#properties() @BeanProperty.properties()} annotation.
Used for limiting properties on child elements.
</li>
</ul>
</li>
<li>
Automatic support for {@link java.net.URL} and {@link java.net.URI} objects.
<ul>
<li>Converted to hrefs in HTML.</li>
<li>Converted to url attributes in XML.</li>
<li>Converted to resource:about attributes in RDF/XML.</li>
</ul>
</li>
<li>
Improvements to Javadocs.
</li>
<li>
Improved {@link org.apache.juneau.utils.PojoQuery} support.
</li>
</ul>
<h5 class='topic'>REST client updates</h5>
<ul class='spaced-list'>
<li>GZIP compression support.</li>
<li>Bug fixes.</li>
</ul>
<h5 class='topic'>REST server updates</h5>
<ul class='spaced-list'>
<li>
Support for overriding bean context and serializer properties in a REST method call through new <code><del>RestResponse.setProperty(String,Object)</del></code> method.<br>
For example, allows you to control whitespace options on a per-request basis.
</li>
<li>
Several new annotations on REST servlets:
<ul>
<li><code>@RestResource.filters()</code> - Associate post-formatting filters on a resource level.</li>
<li>{@link org.apache.juneau.rest.annotation.RestResource#guards() @RestResource.guards} - Associate resource-level guards.</li>
<li>{@link org.apache.juneau.rest.annotation.RestResource#messages() @RestResource.messages} - Associate a resource bundle with a REST servlet. Comes with several convenience methods for looking up messages for the client locale.</li>
<li>{@link org.apache.juneau.rest.annotation.RestResource#properties() @RestResource.properties} - Override default bean context, serializer, and parser properties though an annotation.</li>
</ul>
</li>
<li>
Several new annotations on REST methods:
<ul>
<li><code>@RestMethod.filters()</code> - Associate post-formatting filters on a method level.</li>
<li>{@link org.apache.juneau.rest.annotation.RestMethod#guards() @RestMethod.guards()} - Associate method-level guards.</li>
</ul>
</li>
<li>
New annotations on REST method parameters with automatic conversion:
<ul>
<li><del><code>@Attr</code></del> - A parameter or URL variable value as a parsed POJO.</li>
<li><del><code>@Param</code></del> - A query parameter value as a parsed POJO.</li>
<li>{@link org.apache.juneau.rest.annotation.PathRemainder @PathRemainder} - The remainder after a URL pattern match as a String.</li>
<li>{@link org.apache.juneau.rest.annotation.Header @Header} - An HTTP header value as a parsed POJO.</li>
<li><del><code>@Content</code></del> - The HTTP content as a parsed POJO.</li>
<li>{@link org.apache.juneau.rest.annotation.Method @Method} - The HTTP method name as a String.</li>
</ul>
</li>
<li>
HTTP response content POJOs can now simply be returned from methods instead of calling {@link org.apache.juneau.rest.RestResponse#setOutput(Object)}.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.6"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.6 (Oct 30, 2012)</h3>
<div class='topic'>
<p>
Juno 5.0.0.6 is a minor update that fixes a small bug in 5.0.0.5.
</p>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.5"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.5 (Oct 29, 2012)</h3>
<div class='topic'>
<p>
Juno 5.0.0.5 is a major update.
</p>
<ul class='spaced-list'>
<li>New <code><ja>@RestChild</ja></code> annotation for identifying child resources.</li>
<li>
New <code>traversable</code> and <code>filterable</code> attributes added to {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod} annotation.<br>
Eliminates the need for <code>PojoResource</code> and <code>FilteredRestResource</code> classes.
</li>
<li>Simplified client API. Easier to use when making multiple connections to the same server.</li>
<li>Support for pluggable authentication in the client API.</li>
<li>Support for authenticating against Jazz Team Servers.</li>
<li>Support for rendering package-level Javadocs in REST resources.</li>
<li>Support for parsing of header values into specific object types.</li>
<li>Changed default XML representation to not include JSON-type attributes. Produces cleaner XML.</li>
<li>
New <code>resourceUri</code> attributed added to <ja>@Bean</ja> annotation to associate beans with resource URIs.
<ul>
<li>Used for automatically creating hyperlinks in {@link org.apache.juneau.html.HtmlSerializer}.</li>
<li>Used for automatically creating <xa>uri</xa> attributes in {@link org.apache.juneau.xml.XmlSerializer}.</li>
<li>Used for automatically creating <xa>rdf:about</xa> attributes in <code>RdfXmlSerializer</code>.</li>
</ul>
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.4"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.4 (Oct 7, 2012)</h3>
<div class='topic'>
<p>
Juno 5.0.0.4 is a minor update.
</p>
<ul class='spaced-list'>
<li>
New {@link org.apache.juneau.rest.annotation.RestMethod @RestMethod} annoation on {@link org.apache.juneau.rest.RestServlet} methods.<br>
Allows the usage of URL pattern matching and automatic conversion of URL variables to arguments passed to method handlers.<br>
See {@link org.apache.juneau.rest.RestServlet} for more information.
</li>
<li>
Enhancements to <code><del>BeanContext.convertToType(Object,Class)</del></code> to be able to convert <code>Strings</code> to classes with
<code>fromString(String)</code>/<code>valueOf(String)</code> static methods or <code>T(String)</code> constructors.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.3"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.3 (Oct 3, 2012)</h3>
<div class='topic'>
<p>
Juno 5.0.0.3 is a minor update.
</p>
<ul class='spaced-list'>
<li>
Support for parsing into read-only beans (i.e. beans with only getters, property values set through constructor args).<br>
To support this, the {@link org.apache.juneau.annotation.BeanConstructor @BeanConstructor} annotation has been added.
</li>
<li>
Merged separate settings classes back into their base classes (simplifies the API).
</li>
<li>
{@link org.apache.juneau.serializer.SerializerGroup SerializerGroups} and {@link org.apache.juneau.parser.ParserGroup ParserGroups} now share {@link org.apache.juneau.BeanContext BeanContexts} to reduce memory consumption of class type metadata.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.2"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.2 (Sept 28, 2012)</h3>
<div class='topic'>
<p>
Juno 5.0.0.2 is a minor update.
</p>
<ul class='spaced-list'>
<li>
Improvements to Javadocs. Most of the information in the Juno Starters Guide wiki has been moved into the overview and package-level javadocs.<br>
Since the information is now written in HTML, you can now copy and paste the code examples directly from the Javadocs.<br>
The code examples are also syntax-highlighted using CSS.
</li>
<li>
Support for defining default XML namespaces on packages and classes for the XML and RDF serializers.
</li>
<li>
Restructured the packages along content type support (e.g. all JSON support moved to <code>org.apache.juneau.json</code>).
</li>
<li>
Automatic support for parsing maps with <code>Enum</code> keys, and parsing <code>Enum</code> strings.<br>
This was previously possible using filters, but now it's built-in for all the parsers.
</li>
<li>
Replaced the <code>ObjectList.toXArray()</code> methods with a new <code>elements(Class&lt;T&gt; type)</code> method that's more efficient and avoids creating an unnecessary array.
</li>
<li>
Support for parsing into beans with read-only properties.<br>
New {@link org.apache.juneau.annotation.BeanConstructor @BeanConstructor} annotation allows you to specify bean property values to be passed in through a constructor.
</li>
<li>
Separated the rest library into separate independent client and server libraries.<br>
Use one, use both, it's up to you.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.1"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.1 (Jun 14, 2012)</h3>
<div class='topic'>
<p>
Juno 5.0.0.1 is a moderate update.
</p>
<ul class='spaced-list'>
<li>
New support for generating XML-Schema documents from POJO models.
</li>
<li>
New support for serializing to RDF/XML.
</li>
</ul>
</div>
<!-- =========================================================================================================== -->
<a id="5.0.0.0"></a>
<h3 class='topic' onclick='toggle(this)'>5.0.0.0 (Jun 11, 2012)</h3>
<div class='topic'>
<p>
Version 5.0 marks a major release milestone for the Juno/JJSON library.
It is now available for download from iRAM under the name "Juno (previously JJSON)".
The Juno Starters Guide has been updated to reflect new functionality in this release.
</p>
<ul class='spaced-list'>
<li>
New name.<br>
Unfortunately, "JJSON" was already trademarked by another similar library.
Therefore, it's been renamed "Juno" (after the Roman goddess and wife of Jupiter) which does not appear to have any similar trademark issues (crosses fingers).
The name is also a play on the word "Uno", indicating that this is a single simple unifying interface of several kinds of technology.
</li>
<li>
Simplified APIs for working with beans.<br>
Significant improvements have been made to the parsers to make it easier to convert serialized POJOs back into their original forms.
</li>
<li>
Serializer/Parser classes now directly subclass from {@link org.apache.juneau.BeanContext}.<br>
In previous releases, if you wanted to change the way beans were handled by the serializers and parsers, you had to construct a separate bean map factory and pass it to the serializer or parser.
Now, you can call the bean map factory methods directly on the serializer or parser class.
</li>
<li>
Simplified Filter API for handling non-standard POJOs.<br>
The API for handling non-standard POJOs has been simplified by introducing the concept of a <del><code>Transform</code></del> class, which is associated with the <code>BeanContext</code> class (and thus the Serializer and Parser classes too) through the <code>BeanContext.addTransforms(Class[])</code> method.<br>
Two new subclasses of <del><code>Transform</code></del>:
<ul>
<li>{@link org.apache.juneau.transform.BeanFilter} - Filter POJO beans.</li>
<li>{@link org.apache.juneau.transform.PojoSwap} - Filter POJOs that aren't beans.</li>
</ul>
This new API replaces the previous separate <code>Cast</code> and <code>BeanFilter</code> APIs which were considerably more complicated and puts them under a common API.
</li>
<li>
Elimination of <code>_class</code> attributes in parsable output.<br>
One of the complaints about the previous version of JJSON was that if you wanted to have the resulting JSON or XML be parsable back into beans, you had to enable the <js>"addClassAttrs"</js> property on the bean map factory class so that <js>"_class"</js> attributes could be added to the output.<br>
This requirement is virtually eliminated in v5. In many cases, the parsers are able to determine through reflection what the correct target type is based on the top-level class passed in on the parse method.
</li>
<li>
Performance improvements.<br>
Several significant performance improvements have been made in this release.
<ul>
<li>
New Reader-based JSON parser.<br>
Previously, the JSON parser required that the entire JSON text be loaded into memory as a String before being parsed.
The new JSON parser is Reader-based which significantly reduces memory consumption.
</li>
<li>
New StAX-based XML parser.<br>
The old XML parser was based on DOM. The new XML parser uses a StAX parser which significantly reduces memory consumption.
</li>
<li>
Caching of reflection data in the <code>BeanMap</code> API.<br>
The number of reflection calls have been significantly reduced in the <code>BeanMap</code> API code.
Reflection is used to determine the class types of property values on beans.
This information is now cached and persisted so that the reflection API calls to determine class types are only performed the first time a bean type is encountered.
</li>
<li>
Automatic support for GZIP compression/decompression in <code>RestServlets</code>.<br>
This is completely transparent to the developer.
The output writer is negotiated by the framework to automatically handle compression and charset requests without the developer needing to know anything about it.
</li>
</ul>
</li>
<li>
Cognos/XML support.
</li>
<li>
JSON-schema support.
</li>
<li>
New {@link org.apache.juneau.utils.PojoIntrospector} class.
</li>
<li>
Significant REST servlet API improvements.
<ul>
<li>
Defining child resources is considerably simpler now.
In addition to the standard doX() methods for handling the requests for the current resource, you can also define getX() methods for returning child resources which automatically become available under the child URL specified by the getter name.
</li>
<li>
Initialization of the child resources occurs automatically when the parent resource initialization occurs.
</li>
<li>
Other improvments have been made in the area of automatic negotiation of input and output type streams.
For example, automatic support is provided for GZIP (<code>Accept-Encoding: gzip</code>) and charsets (e.g <code>Accept-Charset: SJIS</code>) on both incoming and outgoing data.
It's all transparent from a developers perspective.
The developer simply working with POJOs, and all details about content types, encoding, charsets, and so forth are handled by the framework.
</li>
<li>
Support for generating complex <code>OPTIONS</code> pages for resources.
</li>
</ul>
</li>
<li>
Automatic support for SOAP XML output on <js>"text/soap+xml"</js> requests against <code>RestServlet</code>.
</li>
<li>
Support for XML namespaces.
</li>
<li>
Support for setting the XML root element name by either passing in a parameter on the serializer, or by specifying it via a <ja>@Bean</ja> annotation.
</li>
<li>
Support for loading beans directly from Readers and Strings.
</li>
<li>
Parsing support for POJOs of type <code>Enum</code>.
</li>
<li>
Significant improved support for various flavors of parameterized types, such as subclasses of parameterized types (e.g. <code>MyBeanList <jk>extends</jk> LinkedList&lt;MyBean&gt;</code>).
</li>
<li>
Improved ordering of bean properties (should now be ordered as they are defined in the class).
</li>
<li>
Various default filters provided:
<ul>
<li>byte[]&lt;--&gt;Base64 encoded strings</li>
<li>Date/Calendar&lt;--&gt;ISO8601/RFC822/Long</li>
</ul>
</li>
<li>
New {@link org.apache.juneau.html.HtmlParser} and {@link org.apache.juneau.urlencoding.UrlEncodingParser} classes.
</li>
<li>
HtmlSerializer now produces XHTML.
</li>
</ul>
</div>
</div>
</body>