1. Make your java app
REST enabled
Anthony Dahanne Confoo 2013 — Feb. 28th, 2013
2. About me …
§ Software Engineer at Terracotta
– Working on EhCache management REST API and
webapp (aka Terracotta Management Console, TMC)
– Strong interest in CI, build tools (maven)
– Android developer when time permits ...
Confoo 2013 2
3. Terracotta
§ Founded 2003 in San Francisco, CA
§ Joined Software AG in 2011
§ Present in India, Europe
and pretty much all over the globe!
§ The company behind :
Confoo 2013 3
4. Agenda
§ The Terracotta Management Console example
§ Introduction to REST, Java integration
– REST
– The Java case : JAX-RS
§ Securing your REST interface
– JEE included authc and authz options
– Apache Shiro
§ Final words...
2
22. What you can do with the TMC
§ Access your Caches / Cache Managers stats
§ Restart a Terracotta server
§ Clear a cache
§ Dynamically change your Cache / CM config
8
23. What you can do with the TMC
§ Access your Caches / Cache Managers stats
§ Restart a Terracotta server
§ Clear a cache
§ Dynamically change your Cache / CM config
§ Demo !
8
25. A few words about REST…
§ Web services leveraging standard HTTP verbs
– GET,POST,PUT,DELETE,OPTIONS,HEAD
§ Conneg (multiple representations)
– to negotiate the format (JSON, XML, etc.)
§ Stateless communication
§ HATEOAS
10
26. JAX-RS : Java specification for REST Services
§ Version 1.1 appeared in Java EE 6
§ Server only spec (until 2.0, out Q2 2013)
§ Annotations driven API
§ Oracle / Sun Jersey is the reference impl.
– Redhat Resteasy, Restlet, Apache CXF are among others
11
27. JAX-RS : Binding your REST services to your
app
§ Using web.xml:
13
28. JAX-RS : Binding your REST services to your
app
§ Customizing loading of resources
14
37. JAX-RS : Raw Content Handlers
§ By default, you can bind your request payload or your
response to streams
@PUT
@Path("/inputstream")
@Produces("text/plain")
public Response getInputStream(InputStream is) throws IOException {
System.out.println(inputStreamToString(is));
return Response.noContent().build();
}
16
38. JAX-RS : Raw Content Handlers
§ By default, you can bind your request payload or your
response to streams
@PUT
@Path("/inputstream")
@Produces("text/plain")
public Response getInputStream(InputStream is) throws IOException {
System.out.println(inputStreamToString(is));
return Response.noContent().build();
}
@GET
@Path("/outputstream")
@Produces("text/plain")
public StreamingOutput getOutputStream() {
return new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
output.write("hello".getBytes());
}
};
}
16
39. JAX-RS : Adding your own Content Handler
§ Implementing
– MessageBodyReader<T> : handle the request
– MessageBodyWriter<T> : handle the response
§ Examples :
– FileProvider from jersey-core
– AbstractJAXBProvider from jersey-core
16
40. JAX-RS : JAXB Content Handlers
§ Using JAXB you can convert POJOs to XML (or JSON)
and vice versa
@XmlRootElement
public final class Agent {
private TYPE type;
private String name;
private String groupId;
private String agentLocation;
private Integer connectionTimeoutMillis;
private Integer readTimeoutMillis;
//etc...
}
16
41. JAX-RS : Meaningful error responses
– Implementing
and registering your own
ExceptionMapper
@Provider
public class DefaultExceptionMapper implements ExceptionMapper<Throwable> {
public Response toResponse(Throwable exception) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(
String.format("{"error" : "%s" , "details" : "%s"}",
errorMessage, extraErrorMessage))
.build();
}
}
16
42. JAX-RS : Testing anyone ?
§ Integration testing to validate
– the REST API
– end to end testing
§ How to do integration testing against JAX-RS ?
– creating a client and making assertions :
• java.net.HttpUrlConnection, Apache HttpClient
– RestAssured from Jayway :
expect().statusCode(404).when().get("/cacheManagers/hello");
String expectedResourceLocation = "/api/config/agents/Local Connection 4343";
expect().contentType(ContentType.JSON).body(containsString("Local Connection 4343"),
containsString("10000")).statusCode(200).when().get(expectedResourceLocation);
16
46. Standard JEE security : basic authentication
GET /private/index.html HTTP/1.1
Host: www.example.org
HTTP/1.1 401 Authorization Required
Content-type: text/html
WWW-Authenticate: Basic realm="Secured Realm"
If the user is “anthony” and password is “terracotta”, the client sends
GET /private/index.html HTTP/1.1
Host: www.example.org
Authorization: Basic YW50aG9ueTp0ZXJyYWNvdHRh
Since base64(anthony:terracotta) = YW50aG9ueTp0ZXJyYWNvdHRh
18
66. Security with Apache Shiro
§ Shiro is about :
– Authentication
– Authorization
– Realms
– Session Management
– Cryptography
20
67. Why choose Shiro over JEE security ?
§ Shiro is deployment agnostic
– not necessarily a webapp
§ Shiro secures all the layers of your application
– not only the “web layer”
§ Highly customizable
– Realms, filters, listeners, etc...
20
68. Securing your REST application with Shiro
§ Register the Listener and the Filter
<listener>
<listener-class>c.t.m.s.w.s.TMSEnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>securityFilter</filter-name>
<filter-class>c.t.m.s.w.s.TMSSecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>securityFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
–
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
21
69. Shiro Realms used
§ For Terracotta REST agents
– TCIdentityAssertionRealm
§ For the Terracotta Management Console
– TCIniRealm
– LdapRealm
– ActiveDirectoyRealm
21
72. Switching to REST for management
§ Brought us :
– consumption from outside the Java world
– scriptability
– “firewalls compatibility”
– existing monitoring tools (Nagios, etc...)
18
74. Lessons learned creating the rest agents ...
§ Prepare for classloading issues
– JBoss wants to deploy REST resources using RestEasy
– OSGI does not play nice with Jersey resource scanning
18
75. Lessons learned creating the rest agents ...
§ Prepare for classloading issues
– JBoss wants to deploy REST resources using RestEasy
– OSGI does not play nice with Jersey resource scanning
§ Be a nice REST citizen
– respect the HTTP status codes
– return meaningful error responses
18
76. Lessons learned creating the rest agents ...
§ Prepare for classloading issues
– JBoss wants to deploy REST resources using RestEasy
– OSGI does not play nice with Jersey resource scanning
§ Be a nice REST citizen
– respect the HTTP status codes
– return meaningful error responses
18
77. Lessons learned creating the rest agents ...
§ Prepare for classloading issues
– JBoss wants to deploy REST resources using RestEasy
– OSGI does not play nice with Jersey resource scanning
§ Be a nice REST citizen
– respect the HTTP status codes
– return meaningful error responses
§ Security brings complexity
18
78. Lessons learned creating the rest agents ...
§ Prepare for classloading issues
– JBoss wants to deploy REST resources using RestEasy
– OSGI does not play nice with Jersey resource scanning
§ Be a nice REST citizen
– respect the HTTP status codes
– return meaningful error responses
§ Security brings complexity
18
79. Lessons learned creating the rest agents ...
§ Prepare for classloading issues
– JBoss wants to deploy REST resources using RestEasy
– OSGI does not play nice with Jersey resource scanning
§ Be a nice REST citizen
– respect the HTTP status codes
– return meaningful error responses
§ Security brings complexity
§ Ldap has a lot of different schemas ...
18
80. Useful tools to develop / debug / test
§ Fast deploy your REST based application
– Maven jetty:run(ner), or tomcat7:run(ner)
– JRebel (not to stop/start your container for every change)
§ Monitor HTTP traffic
– Membrane
§ Hand tailor HTTP messages
– Curl
– Chrome Advanced REST Client (via Chrome Store)
§ Inspect your SSL Keystores and Trustores
– Keystore Explorer
18
81. Useful resources
§ HTTP
– Cours du soir, by @paulgreg (en français)
§ REST
– Roy Fielding’s thesis
§ JAX-RS / Jersey
– RESTful Java, by @patriot1burke
– Arun Gupta presentation on JAX-RS 2.0
§ Shiro
– Shiro official documentation
18
82. terracotta | terracotta.org
Vote now !
https://joind.in/7901
Thank you !
twitter | @anthonydahanne
email | adahanne@terracottatech.com
blog | blog.dahanne.net