Wednesday Jul 24, 2013

BeanManager: Obtain Contextual Reference to Beans (TOTD #215)


javax.enterprise.inject.spi.BeanManager allows to programmatically obtain contextual references to beans. Even though the primary purpose is to allow a portable extension to interact directly with the container, it can be used by any Java EE component as well.

There are three ways to obtain BeanManager:
  • @Inject BeanManager bm;
  • BeanManager bm = CDI.current().getBeanManager();
  • BeanManager bm = null;
    try {
        InitialContext context = new InitialContext();
        bm = (BeanManager)context.lookup("java:comp/BeanManager");
    } catch (NamingException | NullPointerException ex) {
        Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace(out);
    }

The instance is with the scope @Dependent and qualifier @Default. It can be used to programmatically obtain the list of beans that are available for injection such as:

Set<Bean<?>> beans = bm.getBeans(Greeting.class);

BeanManager has lots of other useful methods to, for example to obtain a contextual reference, an injectable reference, and non-contextual instance. Go read the javadocs.

Check out the complete sample source code at:

https://github.com/arun-gupta/javaee7-samples/tree/master/cdi/beanmanager

How would you use BeanManager in your applications ?

Tuesday Jul 23, 2013

JSON Binding with JAX-RS - Moxy, JSON-P, Jackson, Jettison (TOTD #214)


One of the typical questions asked during presentations is how do I enable JSON support in JAX-RS ?

There are three basic approaches and four different modules in Jersey that enable them. Here is a quick summary:


MOXy
JSON-P
Jackson
Jettison
POJO-based JSON Binding
Yes
No
Yes
No
JAXB-based JSON Binding
Yes
No
Yes
Yes
Low-level JSON parsing & processing
No
Yes
No
Yes

MOXy is the default and preferred way of supporting JSON binding in your Jersey applications. A new sample is now added at:

https://github.com/arun-gupta/javaee7-samples/tree/master/jaxrs/moxy

The resource definition is:

@Path("endpoint")
public class MyResource {
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public MyObject echoObject(MyObject mo) {
        return mo;
    }
}


POJO is defined as:

public class MyObject {

    private String name;
    private int age;

    public MyObject() {
    }

    public MyObject(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Application class is:

@ApplicationPath("webresources")
public class MyApplication extends Application {
}

And the client code is:

Client client = ClientBuilder.newClient();

WebTarget target = client.target("http://"
        + request.getServerName()
        + ":"
        + request.getServerPort()
        + request.getContextPath()
        + "/webresources/endpoint");
System.out.println("POST request");
MyObject mo = target
        .request()
        .post(Entity.entity(new MyObject("Duke", 18), MediaType.APPLICATION_JSON), MyObject.class);
out.println("Received response: " + mo.getName() + ", " + mo.getAge() + "<br><br>");

JSON MOXy module (jersey-media-moxy.jar) is in your classpath then Jersey automatically discovers the module and enable JSON binding support via MOXy.

jersey.java.net/documentation/latest/media.html provide more details on all the approaches and modules.

Sunday Jul 21, 2013

Geek Bike Ride at JavaOne Shanghai

Here are some pictures from the fun #GeekBikeRide at JavaOne Shanghai. Thank you InfoQ China, bike angels, and everybody else who made the ride so much fun!
















And the evolving album from JavaOne Shanghai so far ...


Thursday Jul 18, 2013

Java EE 7 Samples Galore


The Java EE 7 SDK provides a comprehensive set of samples for different technologies - both new and updated. They are very nicely documented, runs using Maven + using Cargo, and demonstrate a good usage of the different APIs.

The question I get typically asked is "how do you learn all these APIs and technologies ?".

The SDK samples, reading specifications, and whitboarding with specification leads is indeed a big source of my learning. But I need to write my own code, simple "hello world" style samples that demonstrates point usage of different APIs. I truly believe in "let the code talk" and have given several slide-free code-driven session on Java EE 7 around the world. The source for these talks is about 100+ samples I've written over the past few months.

All of these samples are now available at: github.com/arun-gupta/javaee7-samples

They are all Maven-based projects and have no documentation at all. However they are logically arranged by technologies and I've tried to give intuitive names to the directories. I don't intend to write any documentation so please don't ask for it ;-) But at least now you've access to all the samples.

Here is the complete list of samples at this time:

javaee7-samples
  + batch-samples
    + batchlet-simple
    + chunk-checkpoint
    + chunk-exception
    + chunk-mapper
    + chunk-optional-processor
    + chunk-partition
    + chunk-simple
    + decision
    + flow
    + batch-listeners
    + multiple-steps
    + split
    + chunk-simple-nobeans
  + concurrency-samples
    + dynamicproxy
    + executor
    + schedule
    + threads
  + ejb-samples
    + embeddable
    + timer
    + lifecycle
    + el-samples
    + standalone
  + javamail-samples
    + definition
  + jaxrs-samples
    + async-client
    + async-server
    + beanvalidation
    + jaxrs-client
    + dynamicfilter
    + endpoint
    + filter
    + filter-interceptor
    + interceptor
    + invocation
    + invocation-async
    + link
    + readerwriter
    + readerwriter-json
    + server-sent-event
    + jsonp
    + moxy
  + jms-samples
    + send-receive-simple
    + send-receive
    + temp-destination
    + jmscontext-cdi
  + jpa-samples
    + criteria
    + entitygraph
    + jpa-listeners
    + multiple-pu
    + schema-gen
    + storedprocedure
    + jndi-context
    + locking-optimistic
    + schema-gen-scripts
  + jta-samples
    + transactional
    + transaction-scope
    + user-transaction
    + tx-exception
  + jsf-samples
    + contracts
    + contracts-library
    + flows-simple
    + flows-mixed
    + flows-programmatic
    + flows-declarative
    + passthrough
    + radio-buttons
    + viewscoped
    + file-upload
    + components
    + bean-validation
  + json-samples
    + object-builder
    + object-reader
    + streaming-generate
    + streaming-parser
  + servlet-samples
    + nonblocking
    + protocol-handler
    + servlet-security
    + metadata-complete
    + validation
    + methods
  + websocket-samples
    + binary
    + chat
    + encoder
    + encoder-client
    + encoder-programmatic
    + endpoint
    + endpoint-async
    + endpoint-javatypes
    + endpoint-programmatic
    + endpoint-programmatic-async
    + endpoint-programmatic-injection
    + endpoint-security
    + httpsession
    + injection
    + javase-client
    + messagesize
    + parameters
    + properties
    + websocket-vs-rest
    + subprotocol
    + websocket-client
    + websocket-client-config
    + websocket-client-programmatic
    + websocket-client-programmatic-config
    + websocket-client-programmatic-encoders
    + whiteboard


Will continue to add more as I dig into other pieces. I gave a 3-hour presentation explaining some of these samples at UberConf and captured the screen during the session. Those two-part videos are available.

The first part covers:
  • WebSocket 1.0
  • Batch 1.0
  • JSON Processing 1.0
  • Java Persistence API 2.1



The second part covers:
  • JavaServer Faces 2.2
  • Java API for RESTful Web Services 2.0
  • Java Message Service 2.0
  • Java Transaction API 1.2
  • Bean Vaildation 1.1
  • Concurrency Utilities for Java EE 1.0



Enjoy!

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« July 2013 »
SunMonTueWedThuFriSat
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
19
20
22
25
26
27
28
29
30
31
   
       
Today