JavaOne Session Video

We are having such a great days here in JavaOne 2016 (San Francisco). Today was the day that we did our talk – “High Availability with Docker and JavaEE (Step by Step)” – and fortunately it was recorded! So I’ll give you the link in the case you wanna watch it.

I’ll give some impressions about some points of view, but probably will wait some more days to do it.

Enjoy and leave your comments!

Check the video here!

EJB Injection with JBoss 6 and Struts 1

Why the heck somebody would still use Struts 1? Well for a bunch of reasons… One of them could be a whole team already trained on it… another could be some company legacy systems using it.

And why would you use JBoss 6 with all brand new versions of this and another application servers? Worst: with all those application servers already certified for Java EE 7? The answer is: the customer has a whole environment based on it… and it is huge.

Ok, so let’s do it…

But you are a cool programmer and wanna use EJB 3 and get all its benefits. And being a cool programmer,of course you wanna just open your Action code and write:

@Inject
MyEJB myEJB;

Right? No easiest way to use an EJB to handle your action methods…

Wrong! Why?

  1. In a Struts Action the container is not handling the Action. The framework (Struts) is;
  2. So the Action instance were not created by the container;
  3. If the container didn’t created the Action instance it doesn’t get “involved” in the request cycle;
  4. The framework has no damn idea of what is the “@Inject” command. So it will ignore it;
  5. If the container is not involved and the framework doesn’t know what to do with it, how do you think you will get an EJB instance being injected if it is supposed to come from the container?

Well you probably already got the answer. The injection won’t happen! The “myEJB” will be null.

Please, please, please… don’t do it:

//@Inject
MyEJB myEJB = new MyEJB();

You will surely get a new instance, but it is not handled by the container. So you will need to do all the container duties (transaction management, pooling, security, concurrency, entity injection, etc) with your own hands. Not cool at all… (specially for a cool programmer…).

So what would you do? Answer in four classes!

The entity:

@Entity
@NamedQuery(name=FooEntity.FOO_FIND_ALL, query="SELECT f FROM FooEntity f ")
public class FooEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	public static final String FOO_FIND_ALL = "FooEntity.findAll";

	@Id
	@Column(name="FOO_ID")
	private long fooId;

	@Column(name="FOO_NAME")
	private String fooName;

	public FooEntity() {

	}

	public long getFooId() {
		return fooId;
	}

	public void setFooId(long fooId) {
		this.fooId = fooId;
	}

	public String getFooName() {
		return fooName;
	}

	public void setFooName(String fooName) {
		this.fooName = fooName;
	}
}

The EJB:

@Stateless
@EJB(name=FooEJB.JNDI_NAME)
public class FooEJB {

	public static final String JNDI_NAME = "java:global/fooenv/ejb/foo";

	@PersistenceContext
	EntityManager em;

	public FooEJB() {
	}

	public List<FooEntity> findFoo() {
		return em.createNamedQuery(FooEntity.FOO_FIND_ALL).getResultList();
	}
}

The Service Locator:

public class ServiceLocator {

	public static <T> T getFromContainer(Class<T> clazz,String name) throws Exception {
		InitialContext ctx = new InitialContext();
		return (T) ctx.lookup(name);
	}
}

The Struts Action:

public class FooAction extends DispatchAction {

	private FooEJB fooEJB;

	public FooAction() {
		super();

    	try {
			fooEJB = ServiceLocator.getFromContainer(FooEJB.class, FooEJB.JNDI_NAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    public ActionForward fooAction(ActionMapping actionMapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) {

    	request.setAttribute("findFoo", fooEJB.findFoo());
        return actionMapping.findForward("fooAction");

    }

}

Explaining:

  • The entity: just a regular entity. Just one note to the static property
    FOO_FIND_ALL that I use to name the named query and use it across the project;
  • The EJB: pay attention to the JNDI_NAME static property. It will used to registry the EJB in the container. See: @EJB(name=FooEJB.JNDI_NAME). And will be used to reference the same JNDI name in the Service Locator;
  • The Service Locator: a regular one. Receive an EJB type and name, do its job and return the instance;
  • The Struts Action: on each instance it requests to the container an EJB instance thru JNDI. As the container give the instance all the cycle is handled by it, including the EntityManager injection (@PersistenceContext).

So you can have all the benefits from a managed bean with just a simple locator and can use it with your legacy environment!

Even better: no XML files, no interfaces, no complication at all.

Do you have another good solution? Feel ok to tell me in the comments bellow.

Why getting the Java Enterprise Architect Certification?

Since this year has begun I’ve started my “journey” to the “Oracle Certified Master, Java EE 6 Enterprise Architect“. It’s been fun and either a lot of work to be done (not that I am doing all I’m supposed to do, but…).

Since I decided to do it some people had asked “why do you want this certification?”. Even I asked it for myself so many times… 😉

Well I don’t know if I have a really clear answer to this question as it involves a bunch of things for me, but I’ll try to organize the whole picture.

First of all, after I have attended to JavaOne LA last year I got a scary conclusion: I’ve became obsolete! I was doing good, in a nice job, doing a nice work, with a good salary but… became almost a dinosaur.

Those three awesome days were like a crowbar for my “old” mind (hey I’m not old ok…). I went to all the labs that I could and attended to every single talk that was possible without being omnipresent. I was starving for those informations that I had lost over time.

At end of the final keynote I went home guessing “what should I do now?“. I really needed to do something or my career would collapse in a short time.

Making the long story short I realized that my skills, preferences and experiences were pointing to architecture area. I have worked with it some periods of time and always had a lot of fun. So it was decided: I would do everything to become the best architect that I could be. Period.

The first problem to overcome was that I couldn’t make much progress in this area in the company where I was working. The matter was not the company, but my responsibilities there. So then the “Certification Project” has come.

What was my point? Well if I need to learn and understand a bunch of things to become what I want to become, why not starting by getting “officially” recognized? Mainly due the fact that I couldn’t develop the needed skills where I was working then.

Yeah, I know… getting a certification doesn’t mean you master those skills, but is a very good starting point. And I know it based on my on previous experience.

I’m still on the way to get the certification (my first test will be on May 31th), but I can already identify the benefits for running this run. As I said to some people, the certification is only a excuse to learn somethings that I need and to reach the point that I want.

How to build an Apache TomEE cluster

If you have an application or a system and it is running, you surely want it to be available. Depending on the scenario, you need it to be highly available! Or perhaps you just want to balance the loading on your server.

In any of those cases a good choice maybe is to build a cluster. Just to give you an overview and in the case this is a new word for you, cluster is a set of independent servers that communicate to each other thru a network in order to make a service or a system to be more available than if you used just one server.

Each server of the cluster is called a node. That are some different types of cluster, but we will cover it in another post.

If you are a Java developer and are familiar with Tomcat you will find TomEE quite easy to use. They have almost the same structure and are very likely to setup. The “plus” for TomEE is: it is Java EE (6) compatible for web profile.

What does it mean? Means that it implements all the Java EE 6 web API’s related. So if you are a Web Developer and wanna take advantage of Java EE 6 on your project, the Apache TomEE could be a good choice.

So you have an application, want to run it in a TomEE and want to do it in a cluster? Easy! Let’s do it step by step.

  • Download and install the JDK and the Apache TomEE. I’ll assume you are familiar with it. I am wrong, please leave a message at the comments bellow;
    • The versions used were: JDK 1.8.73 and Apache TomEE 1.7.3 Web Profile. The SO was a Mac OS X 10.11.3 (El Captain).
  • After installing try to run your TomEE and see if it is working;
  • Go to your TomEE Home folder and edit the following file:
    • /conf/server.xml
  • Add those lines to the “Engine” node:
<Cluster
className=”org.apache.catalina.ha.tcp.SimpleTcpCluster”
channelSendOptions=”6″>
<Manager
className=”org.apache.catalina.ha.session.BackupManager”
expireSessionsOnShutdown=”false”
notifyListenersOnReplication=”true”
mapSendOptions=”6″ />
<Channel
className=”org.apache.catalina.tribes.group.GroupChannel”>
<Membership
className=”org.apache.catalina.tribes.membership.McastService”
address=”228.0.0.4″
port=”45564″
frequency=”500″
dropTime=”3000″ />
<Receiver
className=”org.apache.catalina.tribes.transport.nio.NioReceiver”
address=”auto”
port=”5000″
selectorTimeout=”100″
maxThreads=”6″ />
<Sender
className=”org.apache.catalina.tribes.transport.ReplicationTransmitter”>
<Transport
className=”org.apache.catalina.tribes.transport.nio.PooledParallelSender” />
</Sender>
<Interceptor
className=”org.apache.catalina.tribes.group.interceptors.TcpFailureDetector” />
<Interceptor
className=”org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor” />
<Interceptor
className=”org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor” />
</Channel>
<Valve className=”org.apache.catalina.ha.tcp.ReplicationValve”
filter=”.*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt” />
<Deployer
className=”org.apache.catalina.ha.deploy.FarmWarDeployer”
tempDir=”/tmp/war-temp/”
deployDir=”/tmp/war-deploy/”
watchDir=”/tmp/war-listen/”
watchEnabled=”false” />
<ClusterListener
className=”org.apache.catalina.ha.session.ClusterSessionListener” />
</Cluster>
  • Save and close your file, then restart your TomEE. If everything is ok, your log file should have something like this:
org.apache.catalina.ha.tcp.SimpleTcpCluster startInternal
Cluster is about to start
org.apache.catalina.tribes.transport.ReceiverBase bind
Receiver Server Socket bound to:/192.168.0.104:5000
org.apache.catalina.tribes.membership.McastServiceImpl setupSocket
Setting cluster mcast soTimeout to 500
org.apache.catalina.tribes.membership.McastServiceImpl waitForMembers
Sleeping for 1000 milliseconds to establish cluster membership, start level:4
org.apache.catalina.tribes.membership.McastServiceImpl waitForMembers
Done sleeping, membership established, start level:4
org.apache.catalina.tribes.membership.McastServiceImpl waitForMembers
Sleeping for 1000 milliseconds to establish cluster membership, start level:8
org.apache.catalina.tribes.membership.McastServiceImpl waitForMembers
Done sleeping, membership established, start level:8
  • Great! Now you have the first node of your cluster up and running. Not enough, right? So do it to another server, could be another machine or even a VM. Do it to as many servers as you want according to your needs. Each time you add a new node, the log file of other nodes should contain something like this:
org.apache.catalina.tribes.io.BufferPool getBufferPool
Created a buffer pool with max size:104857600 bytes of type:org.apache.catalina.tribes.io.BufferPool15Impl
org.apache.catalina.ha.tcp.SimpleTcpCluster memberAdded
Replication member added:org.apache.catalina.tribes.membership.MemberImpl[tcp://{192, 168, 0, 107}:5000,{192, 168, 0, 107},5000, alive=1016, securePort=-1, UDP Port=-1, id={111 -38 59 -66 -68 -29 72 -69 -103 12 -121 -120 -13 -25 -90 17 }, payload={}, command={}, domain={}, ]
  • Now you have your beautiful cluster fully happy and working! There is just one thing missing: your application deployed to it. Simple:
    • Edit the web.xml of your application;
    • Add this attribute: <distributable />;
    • Save the file, close it and deploy to your cluster.

Couldn’t be easier, right? Of course there are some other aspects, some architectural gaps and another options, but I will leave it for your comments and for another posts.

See ya!