Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Wednesday, 3 February 2010

GlassFish v3 and Java EE 6 Sun-Oracle roadshow - key notes

GlassFish Roadshow 2010 - London 03-02-2010

The following is some notes I took down during the above event.

In brief summary of GlassFish v3 and Java EE 6, here are some of the key takeaways:

  • GlassFish v3 continues to be developed and supported, as the Java EE 5 & 6 RI app server
  • GlassFish v3 currently has no clustering, but offers OSGi modularization and extensibility
  • Supports and takes advantage of new Java EE 6 specifications
  • Big push on modularity and flexibility in both GlassFish and Java EE 6
  • Java EE 6 supports annotation based EJBs, RESTful web services
  • Java EE 6 greatly simplified configuration, optional web-inf.xml etc
  • Java EE 6 simplied simple class EJBs and improved JPA specification
  • Ongoing road-map for GlassFish, details TBA later this year


Java EE 6 (Roberto Chinnici):

Released Dec 10 2009

Key new features: New API, Web profiles, Pluggabiliy, dependancy injection

New technologies:
  • Jax-RS 1.1
  • Bean validation 1.0
  • DI 1.0
  • CDI 1.0
  • Managed beans 1.0
Closed down gap between EJB and POJO with unification and annotations

CDI works with POJO and EJB classes

Unification of platform types, more uniform programming model

  • EJB 3.1
  • JPA 2.0
  • Servlet 3.0
  • JSF 2.0
  • Connectors 1.6
  • Interceptors 1.1
  • JAX-WS 2.2
  • JSR-109 1.3
  • JSP 2.2
  • JSR-250 1.1
  • JACC 1.4
  • JASPIC 1.1

Key goal in Java EE 6 - flexibility, pruning, extensibility and web profiles


Profiles:

Bundles of technologies targeting specific classes of applications
Decoupled from each other and the platform
Guarantees compatibility of required technologies, individually and in combination - must satisfy all joint requirements


Web Profile:

Modern Java web application stack
First profile to be definite
Mid sized, fully functional (expected 80% web-app coverage), add additional components via extensibility (such as web services API, 3rd party frameworks)


Web profile contents:

Servlet, JSP/EL, JSTL, JSF, Bean Validation, EJB Lite, JPA, JTA, Di, CDI, Managed beans, Interceptors, JSR-250


Pruning:

Goal - to address bloat concerns

2 step process:
Declare components as "Proposed optional"
The make fully optional for the next release

Proposed optional technologies:

JAX-RPC (JAX-WS)
EJB 2.x Entity beans (JPA entity classes)
JAXR (little use)
JSR-88 (deployment, tools API - not used)

* Don't use - use replacements / alternatives


Pluggability / extensibility:

Focus on web tier
Level playing field for 3-rd party libraries and frameworks
Two major extensibility points: Servlets and CDI
Simplify packaging of web-apps
Zero-configuration!


Modular Web applications:

Libraries can contain web-fragment.xml descriptor
web.xml is now optional
Can server resources out of jars with: /META-INF/resources

e.g.
/WEB-INF/lib/catalog.jar
/META-INF/resources/catalog/books.html

e.g. Dojo jar in resources


Web fragments in servlet 3.0:

META-INF.web-fragment.xml

same structure as web.xml, can override in web.xml


Servlet container pluggability:

ServletContainerInitializer interface implements by extensions

@HandlesTypes to declare interest in on or more annotation types

ServletContext now contains method to dynamically register servlets and filters
i.e. ServletContext API has been extended

Registered using META-INF/services


onStartup method gets called with a Set of classes available

** Can only add services at startup, not dynamically once running


Asynchronous HTTP processing:

New programming model for async request processing
e.g. Comet, char, push apps
Opt-in model
Threads are managed by the container

@WebServlet(asyncSupported=true)
public class MyServlet extends HTTPServlet {

}

Goal - Decouple requests from threads

* Changes to the way filters work - thread not attached to the socket, response not written. Filters modified to make safe - option than can be turned on to identify asyncSupported=true
- do this on servlet and any filter involved in the chain

Ideal when waiting for some external resource etc.
Low level API - not very elegant
Idea is that frameworks will use this - see for example Atmosphere framework which is based on annotations - under the hood this async API is used.


JSF 2.0:

Facelet as a standard view declaration language
Composite components
Ajax (declarative and programmatic) e.g. f:ajax tag
Partial state saving (track deltas and sends changes in response, previously all would have been sent even if not changed!)
System events e.g. f:event tag
Resources
Validation e.g. new f:validateBean tag (better integration, validation API. can handle multiple errors, not first one at a time!)


EJB 3.1:

@Singleton beans
@Startup beans (invoked at app startup, works well with Singleton pattern)
@Asynchronous invocations (biggest change, allows non-blocking sync EJB invocations as first class call. Method must be either void or return a Future object)
No interface view (bean impl does not need an interface anymore, now 1 class = 1 EJB!)
Define EJBs directly inside a web app, inside a war file
New API - EJBContainer API works on Java SE, can bootstrap an EJB container in a Java SE application (ideal for testing/development, could be useful in client applications)


Simplified packaging:

EJB class directly into the war file
Previously must built an EJB jar to be included


EJB 3.1 lite:

A subset of EJB 3.1
All types of session beans (stageful, stateless, singleton) - other bean types not supported (timer, entity etc)
Declarative transactions and security
Interceptors
ejb-jar.xml descriptor allows (is optional, probably not useful)

* Class loading, new visibility rules in Java EE spec

Slight differences in class loading rules - if in doubt check the specs


New JNDI Namespaces:

Until now - only java:comp
Now added:
java:module - a module (war, ejb, jar)
java:app - an application
java:global the whole server / cluster

e.g. @Resource(lookup="java:app/CustomerDB") DataSource db;

EJB components have global names now:

e.g. java:global/app1/module2/SomeBeanIcom.acme.Foo

Helps solve problem of remote EJB communication in same app server


Dependency injection (DI):

Combination of DI 1.0 / CDI 1.0
New @Inject annotation
@Inject @LoggedIn User user; (@LoggedIn = "Which one", User = "What")
Beans auto-discovered at start-up
Extensible
Injection metamodel (BeanManager API)
@Resource still available for container resources

* Identified by type and qualifiers (no longer just a string name alone)

* No bean declaration as per Spring declaration, bean discovery at startup
* Injection errors all reported at startup, rather than on use at runtime

Beans can be associated with session - i.e. loggedIn
Beans can be more ephemeral, i.e. for request
Beans can be more long lived, i.e. shopping cart conversation flows
Can add class for beans on the fly, via APIs at runtime

Example of DI annotation:

@Inject
CheckoutHandler(
@LoggedIn User user,
@Reliable @PayBy(CREDIT_CARD)
PaymentProcessor processor,
@Default Cart cart)

* Note that constructor injection is possible
* Note different scopes, PaymentProcessor is probably conversation scope, LoggedIn is session, PaymentProcessor is probably application scope singleton

* Instance and state management handled "for free" by framework/APIs

JAX-RS 1.1:
Already widely adoped
Really a high level HTTP API
Annotation-based programming model
Programmatic API when needed

* think of it as the new HTTP level API (higher level than HTTPServlets, remove low level detail and tedium)

Jax-RS resource class, example:

Identified by the @Path annotation

@Path("widgets./{id}")
@Produces("application/widgets+xml")
public class WidgetResource {
pubic WidgetResource(@PathParam("id") String id { … }

@GET
Widget getWidget() { … }
}

Provides higher level HTTP handling, more declarative, better match with conceptual needs of developer


Bean Validation 1.0:

Integrated with JSF, JPA
Constraints represented by annotations

e.g.

@NotNull
@Size(max=40)
String address;

Fully extensible
@Email
String recipient;

Validation API's for validation directly, create a new validation object etc
Validation of trees of objects is possible (including loops)


JPA 2.0:

Supported for collections of basic types and embeddable objects
JPQL enhancements e.g. CASE WHEN, NULLIF
Pessimistic locking added (annotations added)
Criteria API for dynamic query construction

Criteria API: Uses the canonical metamodel classes

CriteriaBuilder, create criteria
CriterialQuery, typed criteria

Strongly types checking, type parasitised equals checking, compiler errors generated if query does not have the right types etc, so robust and safe query (rather than say String SQL construction directly).

Connectors 1.6 added too (not covered in any detail)


Summary overview:

Improved, more powerful, more flexible, more extensible, easier to use

http://java.sun.com/javaee


--

GlassFish V3 (Alexis Moussine-Pouchkine):

Java EE 6 Reference Implementation (RI)

Geographic download map:

http://maps.glassfish.org/server

Healthy increase in downloads and usage over time

GlassFish V1 first shipped 2006, reusing much from Tomcat

V2.1.1 Nov 2009, V3 (Java EE 6) Dec 10th 2009

GlassFish V3 Open Source CDDL, GPL (with 'classpath exception') licensing

Java EE 5 & 6, enterprise quality - full support is available.

Sub projects:
  • Jersey (JAX-RS)
  • Metro (JAX-WS)
  • Grizzly (NIO)
  • Atmosphere (Comet)
  • OpenMQ (JMS)
  • and scripting jRoR Grails and now Django (python)

Main difference from Tomcat - Grizzly core (rewritten)

Netbeans 6.8 tooling
Support available in Eclipse too

GlassFish development continues
Support contracts through to 2017+ unlimited
Remains the Java EE reference implementation
Now also sold with WebLogic and standalone

Roadmap -> expected soon for remaining year

Don't have to deliver as much standard runtime / frameworks jars as part of the application jar

Netbeans in-place edit of classes, incremental compilation, deploy on save, GF v3 preserves session across redeployments(!)

Session retention:
Deployment option to maintain statefull sessions across re-deployments!


GlassFish v3 key goals:

Modular and dynamic
Modular: Apache Felix (OSGi)
Extensible: HK2 (100k kernel)
Still very fast!

Centralized configuration, modules configured through centralised control


Key Features:

No ejbjar.xml needed, no web.xml, annotation driven, EJB's as single classes

Declarative annotations:

@Stateless annotation for class stateless bean
@Schedule annotation for timers

Eclipse - GlassFish tool bundle for eclipse (contains everything!)

Ultra fast auto-deploy of all Java EE and static artefacts

Maven support: mvn gf:run gf:start gf-deploy

Containers can be added / removed dynamically


New API for EJB testing (EJBContainer):

Example:

EJBContainer c = EJBContainer.createEJBContainer();
Context ice = c.getContext();
SimpleEjb ejb (SImpleEjb)ic.lookup("java:global/sample/SimpleEjb");
ejb.sayHello();


GlassFish "Embedded" - allows all features of GlassFish to be automated

org.glassfish.api.embedded.Server server;
Server.Build builder = new Server.Builder();
server = builder.build();
ContainerBuilder b = server.createConfig(ContainerBuilder.Type.web);
server.addContainer(b);

File archive = new File("hello.war");
server.getDeployer().deply(archive);

i.e. Ship app server inside an application!


OSGi:

GlassFish runs on top of OSGi (Felix by default)
Also runs unmodified on Knopflerfish and Equinox
GlassFish ships with 200+ bundles
Can run without OSGi (static mode based on HK2)
Can use OSGi management tools (CLI or Web)

Any OSGi bundles will run in GlassFish v3
Drop it in glassfish/modules

Servlets can get hold of OSGi bundles (using @Resource DI)


Update centre:

Graphical tool (GlassFish does not need to be started), available in web admin console
CLI version available
Was in v2.x but not from admin console


RESTful admin API:

JAX-RS/Jersey + Grizzly to provide REST interfaces to
Configure runtime (via GET, POST, DELETE)
Invoke commands (restart, stop, deploy, etc)
Monitoring (GET only)
Log rotation etc

e.g. Available from:
localhost:4848/management/domain
localhost:4848/monitoring/domain


Further advantages:

Dynamic language support via modules:
Rails, Grails, Django, Scala/Lift


Comet:
Cometd/Bayeux
Atmosphere

Full support for:
mod_jk
WebDAV, CGI, SSI

OpenMQ 4.4

Web Services Metro 1.4
.NET 3.5 interoperability


v3 Clustering:
Lower priority after Java EE 6 and modularity, so not yet...
Clustering is not built in as per v2
More similar to v1, single instance
Have to take on own clustering (load balancing, deployment)
See roadmap for details...


Doing More with GlassFish (Steve Elliott):

GlassFish v3 - Management and monitoring

Management:

User Friendly, pluggable and extensible for administration
Feature rich Admin console (GUI)
Easy to use Command Line Interface (CLI)
RESTful management and monitoring API
Fully documented AMX API (app server management API)
All management features built on AMX API

OSGi, load on demand = fast initial start up

v3 AdminConsole:
Frame-set removed, now Ajax based pages
Pluggable console (admin panes, trees etc loaded on demand)


Monitoring:

Lightweight prode architecture
Ad hoc monitoring in Production
Client-scripting (JavaScript)
DTrace integration on Solaris (similar to OS probes, uniform tracing experience with MySQL etc)
Extensibility / Pluggability

No overhead when there is no monitoring
Allows Monitoring to be turned on in a production environment with minimal impact
Generate and listen to only interested
Turn on monitoring when needed
BTrace integration
Portable and dynamic


Instrumentation:

Modules expose probes
POJO with annotations
XML

Modules register probe listeners

In code, POJO annotations can be used

@ProbeProvider(providername="glassfish", modulename="web")

ProbeProvider XML configuration also possible

ProbeListeners
JMX exposed

@ManagedAttribute(id="jspcount")


OSGi:

big move to OSGi technology
Big move to more modular development approach

Demands and enforces stronger modularity

OSGi is largely under the covers
Visible to GlassFish developers, but not to GlassFish users


Service based architecture:

Core modules loaded on app startup
Rest loaded on demand

Module Management:
add, remove, update installed modules

OSGi as a container


Web services - Metro : JAX-WS / Jersey : JAX-RS

Metro - SOAP-based web services stack
Built into GlassFish
Works with any servlet 2.5 compliant web container
WebLogic, WebSphere, JBoss, Tomcat
Also standalone
Advances interoperability with .NET 3.x/4.0

Project Tango - focused on interoperability with .NET

JAXB based XML Data Binding (XSD, XPATH)

SOAP Messaging MTOM etc

Bi-directional interoperability with .NET (Java or .NET as client or server)


Standards:

JCP: JAX-WS 2.2 & JAXB 2.2
W3C SPAP 1.1/1.2 WSDL 1.1, WS-Addressing
… etc


JAX-RS:

JAX-RS 1.1 is final and part of EE6

Not a web profile
but included with GlassFish v3 web profile
JCP 311
Spec - JSR 311

http://www.oracle.com/java
Contains links to GlassFish etc


.

Thursday, 21 May 2009

How to add GZIP compression to a .NET WCF REST POX client

Bandwidth is important! Even these days where everyone has broadband, now we want the same performance on the move, over wireless and 3G networks. Even when clients individually have enough bandwidth, put 100 or 1000 users together in a corporate environment and it's the IT department that may start have the headache instead. Then there's the server side, ultimately all this traffic comes together down a finite number of "pipes" to our servers, so really we still have to consider bandwidth usage at all levels.

We needed to add GZip compression support to a .NET 3.5sp1 client application using WCF for REST POX web services. The responses were sent compressed using GZIP, so the client needed to be able to decompress these, before passing up the stack to the Data Serialisers and application code layers.

The server in this instance is a Java EE web application returning XML, GZipped using a filter servlet. Implementing the server side filter is fairly trivial, however it's companion in .NET on the client side is not.

Since this gave me a little bit of a challenge recently (very little documentation around or good examples) I thought I'd put up a quick blog about it. It's not that there's a lot of code involved, it's understanding the WCF with sufficient clarity to be able to extend it, and debug it when it's not quite right.

One of the issues that crops up straight away is that most examples of extending the WCF for compression are based around the WS.* web service support, the original incarnation of WCF.

However, later versions of the WCF added support for REST/POX web services, and this is where I wanted to add the GZIP compression support. You can not mix WS.* and Rest (aka Web in WCF) web services in the WCF, without creating a runtime error as the WCF channel is instantiated.

So, enough of the preamble already, lets cut to the chase, what's needed?

Well, assuming you have a WebHttpBinding to start with...

WebHttpBinding webHttpBinding = new WebHttpBinding();


Then, in order to add the GZIP compression support, we need to pull apart the binding, into its constituent elements and then reassemble it, adding in the new binding element.

I enlisted the help of a content mapper to force the content to XML:


public class XMLMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType(string contentType)
{
return WebContentFormat.Xml; // always
}
}




First, get the binding elements out of the WebHttpBinding, using the CreateBindingElements() function.


BindingElementCollection bec = webHttpBinding.CreateBindingElements();

WebMessageEncodingBindingElement wmbe = bec.Remove();
HttpTransportBindingElement htbe = bec.Remove();

wmbe.ContentTypeMapper = new XMLMapper();

GZipMessageEncodingBindingElement compBindingElement = new GZipMessageEncodingBindingElement(wmbe);

bec.Add(compBindingElement);
bec.Add(htbe);

CustomBinding cb = new CustomBinding(bec);

binding = cb;

HttpRequestMessageProperty httpRequestMessageProperty = new HttpRequestMessageProperty();

httpRequestMessageProperty.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
httpRequestMessageProperty.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");




Ok, so now binding is a rebuilt binding, based on WebHttpBinding where a GZIP encoder has been used to wrap the WebMessageEncodingBindingElement from the original binding's binding elements.

Note that the HttpTransportBindingElement must be the last binding element in the binding element collection (protocol stack) or a runtime error will be thrown when trying to instantiate the channel.

Now we can create the channel in the normal way:


// create a channel factory
ChannelFactory cf = new ChannelFactory(binding, hostPath);

// create webhttpbehavior for rest / pox get/invoke behaviour support
WebHttpBehavior webHttpBehavior = new WebHttpBehavior();
webHttpBehavior.DefaultOutgoingRequestFormat = WebMessageFormat.Xml;
webHttpBehavior.DefaultOutgoingResponseFormat = WebMessageFormat.Xml;

// add webhttpbehahvior to channelfactory endpoint
cf.Endpoint.Behaviors.Add(webHttpBehavior);

if (ENABLE_COMPRESSION)
{
// add our custom behavior...
cf.Endpoint.Behaviors.Add(new HttpEndpointBehavior());
}

// create our IService channel
channel = cf.CreateChannel();



So far so good, but what about this GZipMessageEncodingBindingElement?

Well, this can be found in the Microsoft WCF samples:

http://msdn.microsoft.com/en-us/library/ms751458.aspx


Detailed steps of integrating the MS WCF GZip example into your code:

http://www.vistax64.com/indigo/113763-wcf-client-j2ee-server-using-gzip.html

Note: I had to make some minor modifications to make my client work correctly, details can be provided if anyone leaves a comment expressing an interest.



Further Resources:

Various threads discussing similar problems:

http://social.msdn.microsoft.com/forums/en-US/wcf/thread/5c67b0da-9e50-4ee1-b7ac-a4733c580980/


http://social.msdn.microsoft.com/forums/en-US/wcf/thread/ddfe06b1-f07c-4da2-a1f1-d06126e4f96e/


http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644


Neomax - provide software products to extend the WCF framework, including support for compression:

http://www.noemax.com/products/wcfx/features.html#gzip_compression


Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1: BETA

http://www.microsoft.com/downloads/thankyou.aspx?familyId=a91dc12a-fc94-4027-b67e-46bab7c5226c&displayLang=en


.

Sunday, 9 November 2008

c# code generation added rest describe code gen

Announcement: c# code generation added to google rest describe code gen api:

At last, the google rest describe code gen api now has a c# code generator. Targeting c# .net 3.5 WCF. This gives an easy route from existing services or WADL to c# client code/framework. I hope to be blogging about it soon, with some details of how it works and any limitations you shoud be aware of...


Monday, 7 July 2008

Netbeans 6.1 Rest JSR-311 RI library problem

Found a minor problem with Netbeans 6.1 and Rest (Jersey RI) today, thought I'd capture the problem and solution.

Symptom:
Can't launch a Rest application using Jersey (JSR-311 RI) libraries - error given is:

HTTP status 500

exception

javax.servlet.ServletException: java.lang.NoSuchMethodError: javax.servlet.jsp.JspFactory.getJspApplicationContext(Ljavax/servlet/ServletContext;)Ljavax/servlet/jsp/JspApplicationContext;
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:274)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

Because the Jersey (JSR-311 RI) libraries include jsp 2.0 jsp-api-2.0-20040521.jar from Netbeans6.1\enterprise5\modules\ext\rest\ which is an older version of the JSP API.

Fix, copy a newer jsp in or remove the entry from the library definition and add a newer jsp library in.


Example Solution:

Go to tools\libraries
Select the Jersey libary
In the Library classpath, remove the offending jsp-api-2.0-20040521.jar
Now add the newer JSP libary, e.g. Netbeans 6.1 ships with servlet2.5-jsp2.1-api.jar one level up in the Netbeans6.1\enterprise5\modules\ext\ directory.
Remove the Jersey libraries from your project (if already added).
Re-add the Jersey libraries to your project and recompile - problem solved.

Monday, 2 June 2008

Integrating REST POX web services and .NET WCF

Notes:

WCF 3.5 supports REST POX services using the web service model.

WebHttpBinding supports cookies for session support etc, e.g:

WebHttpBinding webHttpBinding = new WebHttpBinding();
webHttpBinding.AllowCookies = true;

using (ChannelFactory cf = new ChannelFactory(webHttpBinding, hostPath))
{ ...

Issues:

  • WebInvoke method POST: post data sent only as JSON or XML - no support for simple form encoded parameters.
  • General inflexibility when mixing types of data or overloading services make it harder to leverage existing services that support existing AJAX/rich Internet systems.


Blogs, articles and useful resources:

http://bitworking.org/news/125/REST-and-WS

HTTP Programming with WCF and the .NET Framework 3.5 - http://msdn.microsoft.com/en-us/magazine/cc135976.aspx

http://msdn.microsoft.com/en-us/library/system.servicemodel.aspx

http://hyperthink.net/blog/2008/01/18/WCF+Web+Programming+Model+Documentation.aspx

http://msdn.microsoft.com/en-us/library/bb412176.aspx

Rick Strahl's excellent articles:

How to consume REST services with WCF - http://blogs.msdn.com/pedram/archive/2008/04/21/how-to-consume-rest-services-with-wcf.aspx

Simple example with DataContract: http://dev.aol.com/node/595

A set of WCF tutorials:

http://dotnet.org.za/hiltong/pages/Windows-Communication-Foundation-_2800_Indigo_2900_-Hello-World-Tutorial.aspx



Interesting problem with XML serialiser quota that you could run into at some point:

http://www.timrayburn.net/2007/10/02/XmlSerializerFormat+Plus+Huge+Schema+Equals+Trouble.aspx

Wednesday, 21 May 2008

REST WADL - tools and information

I'm interested to use REST or REST-like web services within a traditional thick client (as well as AJAX web apps) - using WADL to describe them (from existing services) and tools to automatically generate client API code (in a variety of languages).

Standards:
  • JAX-RS (JSR 311)

Digging around, I come across some interesting articles and blogs, including:

REST Describe and REST Compile:

Thomas Steiner's blog http://blog.tomayac.de/index.php?date=2007-03-12&time=17:11:27&perma=Automatic+Multi+Lang.html describing two tools to be developed.


Java.Net resources:

Other resources and blogs:

http://blogs.msdn.com/dotnetinterop/archive/2008/02/06/wadl-and-wsdl-and-rest-oh-my.aspx

An article on REST WADL http://searchsoa.techtarget.com/tip/0,289483,sid26_gci1265367,00.html

Blog by William Martinez Pomares with interesting follow up discussion http://acoscomp.com/wblog//index.php/a/2007/06/10/wadl_rest_and_wsdl


REST Describe and REST Compile tools:

Trying the on-line REST Describe on an existing web service I'd published previously showed promising results.

The current status of REST Compile is that is supports:
  • Java
  • PHP5
  • Ruby
  • Python

but .Net is not provided as yet.