Proxy Pattern Application

“In computer programming, the proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else.” – Wikipedia
In other words, particularly in java programming language practice, you can use java.lang.reflect.Proxy class to construct instance of an interface.

When and why do you want to adopt Proxy pattern?

In a fashion of loosely coupled design, it is possible to get a set of interfaces without their concrete classes because there’s no multiple inheritance in java. If you want the entities to inherit from a base, there is no way of using concrete classes to bridge the persistence layer and presentation layer. To store and carry data to the persistence layer which is invisible to the presentation layer, you can either build another set of concrete classes or use proxy pattern. There are different concerns for both routes. I used the traditional one for my demo project looseCoupling branch. Whereas, for the EAR project assignment, I got the code following the proxy pattern.
From my study, I found if you want use MOXy, you can only parse XML. Other frameworks don’t support proxy pattern. Thus, if you need to use JSON, the traditional way is what you probably should go for.

A practice on Proxy pattern in parsing XML

In order to do XML binding with a proxy pattern. There are 3 steps to do it:

  1. Setup JAXBContextFactory;
  2. Build an ObjectFactory;
  3. Implement MessageBodyReader and MessageBodyWriter.

1. Setup JAXBContextFactory

To use MOXy, you need to add it into the project library. For maven, add the following to the pom.xml:

Define javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory in and place this file along with your Models or ObjectFactory.

Build an ObjectFactory

Before building the ObjectFactory class, you should have some interfaces like IUser to be manipulated against:

public interface IUser extends IModel {
    String getName();
    void setName(String name);

There are several ways to create an instance out of the interface, here is the route of using Proxy with an InvocationHandler. In this way, the instance to be generated will have a class signature something like this (example for IUser): public class Proxy$1 extends Proxy implements IUser. To implement the InvocationHandler interface, do the following:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
class InterfaceInvocationHandler implements InvocationHandler {
    private Map values = new HashMap();
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
            return values.get(methodName.substring(3));
            values.put(methodName.substring(3), args[0]);
        return null;

This implementation basically performs/mocks getters and setters of the properties and stores the values in a HashMap.

import java.lang.reflect.Proxy;
public class ObjectFactory {
    public User createUser() {
        return createInstance(User.class);
    private <T> T createInstance(Class<T> anInterface) {
        return (T) Proxy.newProxyInstance(anInterface.getClassLoader(), new Class[] {anInterface}, new InterfaceInvocationHandler());

In the ObjectFactory, you can list as many models as you need. Although, they have to fit for your InterfaceInvocationHandler.

Implement MessageBodyReader and MessageBodyWriter

Based on my study, when building a REST service, there is no actual need for implementing the MessageBodyWriter because the out going message can retrieve data from the interface models. As long as you specified @Consumes(MediaType.APPLICATION_XML) annotation to ether the method or class level of your REST service, JAX-B will automatically perform marshaling for the models. However, you do need to implement the MessageBodyReader and let it help processing the in coming message.
As mentioned in above sections, since the Proxy class is the direct ancestor of the interface, you should let MessageBodyReader capture Proxy class (instead of doing it for each model classes) and do the parsing/unmarshaling before the message reach the certain REST method. It’s like an implicit interceptor to be enabled for the method once you annotate @Consumes(MediaType.APPLICATION_XML) on the REST service method or class.
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

@Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class ProxyMessageBodyReader implements MessageBodyReader {
 public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
  return type.getClass().isInstance(IModel.class);// the ancestor of IUser
 public Proxy readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
  try {
   JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
   final Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
   return (Proxy) unMarshaller.unmarshal(entityStream);
  } catch (final JAXBException ex) {
   LOG.error(ex.getMessage(), ex);
   throw new WebApplicationException(ex.getMessage(), Status.INTERNAL_SERVER_ERROR);

If you look closer to this code and the one in my assignment I linked to, you can see a slight difference on instantiating the JAXBContext. Unlike this one, it uses CDI. However, they are doing the same thing.

This blog may not be up to date. Please see the original post from Blogger
via IFTTT.

JAAS Setup Walkthrough

Few days ago, I was asked to write this article by my friend and classmate Ali Almutawakel. Thanks for this request, I got a lot of fun digging into JAAS.
JAAS stands for Java Authentication and Authorization Service, which is a JVM level security solution for Java applications. That means, in practice, it requires some setups with the platform to get it works. In this article, I will use WildFly as an example application server to demonstrate how it works. The source code that will be using in this article can be found on my github. There is a project I created few days ago called “demo“.

About the Demo Project

Regarding to this project, I want to thank my instructors, Aaron Warsylewicz, John O’Loughlin and Nicole Berard. They contributed their time to inspire me even though this project was not covered by my current program. Without them, I can’t start this article or get the project to work. In my opinion, JAAS by itself, is one of the toughest concept to understand. However, in this article, I’ll skip all the lower level details*, and directly jump into the practice.
To run this project, you need to download and import the source code to Eclipse, and run it on a WildFly application server along with a database (scripts for MySQL and Oracle are provided). You can download some tools to test against the RESTful Web Services, or you can just run the JUnit tests.
If you check my database script in the project, you will find 3 tables. They are a User table, a Group table, and a bridging table. This structure is very common and works well with JAAS. Notice that, although I have a persistence layer and all the entities, JAAS will not use them in this particular project with my settings.

Setting Steps

There are 3 steps to get JAAS working properly:

  1. configure the Application Server
  2. configure the project
  3. add annotations to your code (or you can do it in a programmatic way)

Configure the Application Server

To configure the security settings on WildFly in order to read credentials from database, you need to setup a data source for your database connection first. You can set all the configurations through the web console, or by changing the configuration file.
Web console solution:

  1. Login to WildFly web console (localhost:9990)
  2. Go to Configuration / Subsystem / Security
  3. Add a security domain. The name of the security domain will be used later in jboss-web.xml
  4. Open the security domain. Within the Authentication view, click Add to add an authentication module
  5. Click on Edit to edit the properties of this module (module option key value pairs).
Configuration File:
<security-domain name="demo" cache-type="default">
        <login-module code="Database" flag="required">
            <module-option name="dsJndiName" value="java:/DemoDS" />
            <module-option name="principalsQuery"
                value="select password from demo_user where name=?" />
            <module-option name="rolesQuery"
                value="select, 'Roles' from demo_user u, demo_group g, demo_user_group ug where and and" />
            <module-option name="hashAlgorithm" value="SHA-256"/>
            <module-option name="hashEncoding" value="BASE64"/>
            <module-option name="ignorePasswordCase" value="true"/>
            <module-option name="hashStorePassword" value="false"/>
            <module-option name="hashUserPassword" value="true"/>
There are few example security domains in the configuration file by default. So, it shouldn’t be difficult to find where to insert the above configuration. You can also check out my README.txt for configuring the application server.
This is the only section that really depends on the which application server you are using. However, most of them shares similar concepts. In addition, you can also create your own authentication mechanism, and setup in the application server.

Configure the Project

Project configurations for JAAS is pretty straight forward. However, knowing the limitations of it would be helpful when building your own applications. There are 2 files (for WildFly and JBoss) to be edited: web.xml and jboss-web.xml.


In web.xml, there are 3 tags and their sub tags you need to manage in order to get JAAS configured within your project. Since you’ve configured the security domain in your application server, JAAS is already sitting there for you to use. So, you don’t have to configure the project to get the user principals. You can programmatically do the authentication and authorization with the user principals. In other words, you will be able to use annotations to automate the authentication and authorization processes.

This tag allows you to apply authentication process by specifying which web resource you want to constraint with what roles. A more general constraint will be overridden by the more specific constraints. For example: in the web.xml file of my project, the constraint “protected” will be applied to all urls with a pattern of /rest/*, except the put method for /rest/user/*, which is using the constraint “public”. In addition, if you don’t specify a role, then everyone can access.

Within this tag, you can config what method is used to do the authentication. BASIC can be a good choice for RESTful Web Services. However, since the password is not asked to be encrypted, you need SSL to encrypt the user credential. (SSL will not only encrypt the user credential but mostly everything, which is nice. But you need a dedicated IP to enable it. Check this article for details)

You can list all the roles (or I call “groups” in my project based on the database structure). These roles are used to associate with the authorizations by annotating them in your code. However, there are pros and cons for doing this. When there are a lot of changes with the security constraints or the security roles, hard configuring them is not a nice way that you want to go.

Personal experience
I had a project which the roles and constraints were constantly changing. For example, the accessibility of each level admin changed every few months, new roles were added, old roles were removed. In that case, since we didn’t predict this requirement, the web.xml configurations locked down all the roles and constraints, we lost the flexibility to change them within java code. To fix it (and meet the deadline), we actually made the program to rewrite the web.xml file. Because of that, every time the system applied new roles and constraints, the server had to restart to apply the changes. That was a disaster in my opinion. So, to know what the clients really need (not only what they say), and choose an appropriate approach is always critical to a complex system.


jboss-web.xml is an JBoss/WildFly extension of web.xml file. If you see this file in my project, you’ll find it’s very straight forward, which only contains the name of the security domain.

Add Annotations

The Java security annotations are fairly simple. You add them to method level (code example) in different layers. It means, you don’t only take control of the security in your RESTful Web Services, but also the business logic layer or even persistent layer (code example).
There are 3 annotations being used mostly:,, You can find them in the code examples.

Programmatic Approach

Unlike to apply annotations, you can do the authorization programmatically without configuring roles and constraints in web.xml file. To do that, you need to know if the caller is in a particular role, or you may also want to get caller principle from SessionContext.
* For more details about JAAS theory, there is an unpublished book JAAS in Action you can look into.

This blog may not be up to date. Please see the original post from Blogger
via IFTTT.

Build RESTful Web Services

REST is an end point to transfer data using XML or JSON. There are several advantages about REST Web Services you may want to look into.
To build RESTful Web Services, there are 4 major specifications to make:

  1. Path
  2. Media type
  3. Method type
  4. Path Parameter Injection
In addition, because REST takes paths mainly as parameters, it’s possible to nest paths from one to another.

1. Path

To make the service accessible, you need to give it an application path and sub paths. The application path can be specified in web.xml or through annotation:



public class MyStoreApplication extends {
    /* empty class body */
For sub paths, @Path is placed on the class level. E.g. to reach the following class with above settings, the URL is http://<domain&gt;:<port>/<application_name>/mainpath/subpath
public class Service{}

It is possible to put @Path on method level, and this will be talked in the following sections.

2. Media Type

There are mainly 2 types data that REST can produce or consume: XML and JSON. In particular, @Produces indicates the methods to send out responses with the XML or JSON data, whereas, @Consumes is for methods receiving XML or JSON data attached with requests. When they are annotated on the class level, it means the same as to annotate on every method within the class.

public class Service{}

3. Method Type

Obviously, the RESTful Web Services should respond to different request accordingly. In order to do that, you can use @GET @POST @PUT @DELETE annotations on the methods to map with CRUD operations against database.

public class Service{
    public Response findById(String id){
        // ett can be a JSON String or the Entity object(s)
        return Response.status(Status.OK).entity(ett).build();

4. Path Parameter Injection

In order to get the path parameter, which is a portion of the URL, @Path and @PathParam is used as following:

public class Service{
    EntityEJB entityEJB;

    public Response findById(@PathParam("id") String id){
        Entity ett = entityEJB.findById(id);
        return Response.status(Status.OK).entity(ett).build();

In the above code, the braces surrounding id in @Path annotation indicates that id is a place holder in the URL. id in @PathParam means the value of this portion of URL is injected into the String id. For example, if the URL is .../subpath/a1-5, the value of String id will be “a1-5“.
In addition, the JSON object attached with the request can also be injected implicitly. Here is an example:

public Object create(Entity ett) {
    return entityEJB.persist(ett);

Topic: nested path

There are cases you may want to organize methods of a Service in several classes. Check this code about Service and SubService to find more.

This blog may not be up to date. Please see the original post from Blogger
via IFTTT.

Send HTTP Request

When testing RESTful Web Services, you can’t just enter a URL in browser since that can only send a GET request. In order to conduct other request types, one way you can do is to use a ClientBuilder.

There are 3 steps to send a request using ClientBuilder:
  1. Create an Entity; (
  2. Configure an Invocation$Builder;
  3. Use Invocation$Builder to send a request attached with the Entity.


Because ClientBuilder itself is defined in, it needs a JavaEE container, or at least, the RESTEasy JAX-RS API, which I like to recommend.

Step 1. Create an Entity

The Entity creating here is mainly considered as a JSON or XML object wrapped by the Entity class, although you have many options. The following code shows how an Entity is conducted:

// Conduct an entity using content, which is an JSON String
Entity<String> entity = Entity.entity(content, MediaType.APPLICATION_JSON);

You can notice that the content is not necessarily to be a String, and the generic type of the entity is going to change accordingly.

Step 2. Configure an Invocation$Builder

To configure an Invocation$Builder, use ClientBuilder.newClient() to create a new Client object, configure the Client object, and build the Invocation$Builder:

  1. Create a new Client object;
  2. Configure the Client object;
  3. Build the Invocation$Builder.
// Create a new Client object
Client client = ClientBuilder.newClient();

// Set an authentication (if needed)
client = client.register(new BasicAuthentication(username, password));

// Set the url, which can be a String or wrapped object
WebTarget target =;

// Build a builder
Builder builder = target.request();

Step 3. Use Invocation$Builder to send a request attached with the Entity.

Depending on what method you want to invoke on the server side, you can do GET, POST, PUT, DELETE, which generally are mapped to CRUD operations on the server side:

// To attach anything with GET method, modify the url
Response response = builder.get();

Response response =;

Response response = builder.put(entity);

Response response = builder.delete(entity);

See another example of using the ClientBuilder in a demo project.

This blog may not be up to date. Please see the original post from Blogger
via IFTTT.

Get start with CDI

CDI Quick Start

CDI, or Welding is a mechanism to assemble components (classes, methods, properties). In other words, you don’t instantiate objects by yourself. It is done by the container, instead of doing new Foo(); manually. The general concepts of CDI are also adopted by other Java standards, such as EJB.

There are 2 steps to enable CDI:

  1. Specify where injectable objects are (and configure the container if not using default settings);
  2. Specify where to be injected.

Here is an example of injecting a repository class into a servlet class.

Step 1: Specify where injectable objects are

To specify your injectable object, in this case, your repository class, you need to make it a managed bean by specifying its scope.* There are several scopes for managed beans. They control the behaviors of the beans, such as life cycle, the numbers of instances, etc.
See the example code, you’ll notice the @RequestScoped annotation is placed on the class level.
* Explicitly put @default can also make a java class a managed bean.

Configuration Options

As mentioned, it’s possible to customize the bean configurations in order to change the detection scope of the container. It is an attribute in bean.xml file called bean-discovery-mode. You don’t need to create this file if you are using the default configuration, annotated. There are 2 other options: all and none.

  • annotated: all managed beans are looked up
  • all: all types (classes) are looked up
  • none: disable the look ups

Step 2: Specify where to be injected

To inject an object, you need to place the @inject annotation to the field, attribute etc.
See the example code, you’ll find that there is no manual instantiating needed anymore.


Most CDI or EJB implementations manage those injectable objects or beans behind scene, e.g. pooling, passivation, activation (Stateful Session Bean), listening (Message-Driven Bean). Therefore, it is not common to manage lifecycle events in constructors. There are 2 lifecycle events wildly used with both CDI and EJB: @PostConstruct and @PreDestroy.

  • @PostConstruct: invoked before the first call
  • @PreDestroy: invoked before leaving the scope

See UserRepository. Since the scope is within a request, right before the first call is made in line 122 in the LoginServlet, @PostConstruct annotated method in UserRepository is invoked, and @PreDestroy annotated method will be invoked after the request is sent back to a JSP and written to the client.
Code stub around line 122:

private String authUser(final String username, final String password) {
    final User dbUser = userRepository.findUser(username);
Follow the link to find more information about lifecycle of CDI and EJB.

Deal with Ambiguous Derivations

In the real world, it is very unlikely to inject the actual concrete classes with CDI. A problem then comes out with ambiguous derivations. If an interface is derived by many subclasses, you need to tell the container which one you want to use when injecting the object.
There are two ways of dealing with it:

  1. Use @Named annotation to give the type a CDI name
  2. Override @Default annotation


@Named annotation can be placed on the injectable type to give it a name value. At the injecting point, you just need to annotate @Named with the particular name. The following is an example:

/* the interface used at injecting point */
public interface Boo{}

/* named class to be injected */
public class Doo implements Boo{}

public class Goo{

    /* a field to inject Doo */
    Boo doo;

    /* a method to inject Doo */
    public void setDoo(@Named("Foo") Boo doo){}


@Default is a default qualifier for any injectable type, which means this annotation will be implicitly applied to managed beans. For example, the UserRepository class in the above sections has @Default annotation implicitly. However, since all the derivations have the same qualifier, it will confuse the container when injecting an interface with multiple derivations. To specify a particular class to inject with, you can define a customized qualifier, then use it at the injecting point.*
* The linked project for explaining how qualifier works is different to the one used in the above sections.

This blog may not be up to date. Please see the original post from Blogger
via IFTTT.

Setup Oracle Database Connection in Eclipse

To setup Oracle Database Connection in Eclipse is very much similar to any other Databases. There are 3 steps you need to follow.

Install Oracle Database

Since I didn’t find a non-install Oracle Database package, I assume that there is no such thing. So you have to install it, which takes a little bit more time but makes it way easier to setup.

  1. Download from Oracle (the link might be changing over time, just search on google)
  2. Install it

Note, for 11g express, the default Database Service Name is XE. To check that out, execute the following code in SQL Command Line.

select value from v$parameter where name like '%service_name%';

Oracle Database shipped with a cheapo Command Line tool which you can find once the installation finished. You can type connect or conn in it to connect to database.

Install Oracle Database Driver in Eclipse

You need to download Oracle Database Driver first.

Then in the Eclipse, open Preferences, and go to Data Management -> Connectivity -> Driver Definitions. You should probably not find any Oracle drivers there if you didn’t install Oracle Database Tools previously. Click add, it will pop up a dialog asking you what driver template you want to use. Again, if you don’t have Oracle Database Tools installed, you would just see Oracle Database Driver for 10g, Oracle Thin Driver for 8g to 11g and Other Driver for 8g to 11g. I found it doesn’t really matter to choose either one, but I choosed Thin Driver for 11g just because I’m using 11g. Switch to JAR List tab, and add JAR/ZIP you just download. Leave properties there, and done.

If you ever installed Oracle Database Tools, you’ll be having drivers installed. I’ll talk about that in another article: Introduction of Oracle Database Tools.

Setup Database Connection

Switch to Database Development Perspective and you will find Data Source Explorer window. Right click on Database Connections folder -> new. Choose the Oracle then next. Choose the driver you created earlier and fill out the properties as follows:

Service name:XE (ether one works by default)
Host: localhost
Port number: 1521
User name: SYSTEM (you can change users if you want)
Password: the password you set when installing the database (or created with your other users)
Connection URL: jdbc:oracle:thin:@localhost:1521:xe (auto complete, don't change)

You can try connection before created. If everything is right, you should be good to go.

Introduction of Oracle Database Tools

A Brief Description why you want Oracle Database Tools

This article will introduce you how to setup a GUI for your oracle database in Eclipse with Oracle Database Tools.

Note that most Databases actually have their own GUI tool programs, but Oracle 11g express is not shipped with one. For general purposes with almost every database, you can use Beaver DB, which is a really good tool you can also find in Eclipse Marketplace. But Oracle Database Tools are optimized specifically for Oracle DB, means they give you more capabilities to work with Oracle DB.


To setup Oracle Database Tool, go to Eclipse Marketplace within your Eclipse. Search Oracle Database Tools, and you will find it. It is developed by Oracle, and is free.

Once you done installation, you’ll find some icons in the Data Source Explorer are actually changed. If you haven’t setup Database Connection yet, check Setup Oracle Database Connection in Eclipse.

Start using it

If you have tables created by users other than SYSTEM, and you logged in using SYSTEM, you can find the tables under that user’s schema (the schema name is the user’s name). The following SQL code shows how to create a user:

CREATE USER <username> IDENTIFIED BY <password>
GRANT [privileges] TO <username>;

Once you created a user, you can expand that user’s schema in the hierarchy and explore all the contents of it. By right click on Tables and Edit Schema, you can view and edit the physical ERD of all tables this user has. The Tools can actually generate DDL as you editing the table on GUI.