22 May 2014

A POJO service using an axis2 servlet within embedded jetty

“Alice came to a fork in the road. 'Which road do I take?' she asked.'Where do you want to go?' responded the Cheshire Cat.'I don't know,' Alice answered.'Then,' said the Cat, 'it doesn't matter.” 


“The sun is simple. A sword is simple. A storm is simple. Behind everything simple is a huge tail of complicated.” 


Embedded Jetty

Embedding Jetty 1.9.5 in your application is simple and in fact encouraged by it's creators. That there is a whole bunch of complexity behind the scenes is for moment irrelevant. We create a class that extends AbstractHandler, attach it to the server and start the server. The only requirement is the jetty.jar, which is easily found with maven.

HelloHandler.java
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class HelloHandler extends AbstractHandler {
  
    final String _greeting;
 
    final String _body;
 
    public HelloHandler() {
        _greeting = "Hello World";
        _body = null;
    }
 
    public HelloHandler(String greeting) {
        _greeting = greeting;
        _body = null;
    }
 
    public HelloHandler(String greeting, String body) {
        _greeting = greeting;
        _body = body;
    }
 
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<h1>
" + _greeting + "<h1>
");
        if (_body != null) response.getWriter().println(_body);
    }
}

And then adding the Handler to a Jetty server.

SimplestServer.java
import org.eclipse.jetty.server.Server;

public class SimplestServer {
 public static void main(String[] args) throws Exception {
  Server server = new Server(1111);
  HelloHandler root = new HelloHandler();
  server.setHandler(root);

  server.start();
  server.join();
 }
}

Easy as two pies!

Run the application and test the server:
http://localhost:1111/

Embedded Axis

Running an Axis 1.6.2 HTTP server is almost as easy. Axis allows us to expose a POJO as a webservice and it takes care of the wsdl and xsd generation. This makes writing services very easy, but the trade-off is that the server configuration is a bit more tricky. Here we will create an Axis Server configuration from scratch (no axis2.xml). We only need a few jars: org.apache.axis2 - axis2 - 1.6.2, axis2-transport-http, axis2-transport-local and log4j - log4j - 1.2.17.

First we create our POJO. It's a simple service that can say "Hello" and subtract two numbers.

HelloPojo.java
public class HelloPojo {
 public String sayHello(String name) {
  return "Hello " + name;
 }

 public int subtract(int a, int b) {
  return a - b;
 }
}

Now we need to create an axis2 context from scratch. Remember we did not install axis.

Axis2SimpleServer.java
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;

public class Axis2SimpleServer {
 public static void main(String[] args) throws Exception {
  // create empty config context
  ConfigurationContext context = ConfigurationContextFactory
    .createDefaultConfigurationContext();
  AxisConfiguration cfg = context.getAxisConfiguration();
  // add a POJO to it
  AxisService service = AxisService.createService(
    HelloPojo.class.getName(), cfg);
  cfg.addService(service);
 }
}

and now we need to use this configuration to start our server.

  // Use the SimpleHTTPServer to specify a port
  HttpFactory f = new HttpFactory(context);
  f.setPort(1111);
  SimpleHTTPServer server = new SimpleHTTPServer(f);
  server.start();

If you run the application now and test the server you will not notice the problem immediately:
http://localhost:1111/
forwards to:
http://localhost:1111/axis2/services
and displays the POJO as a service. Click on the service an you get the WSDL.
All good so far!

The problem comes in when you execute the service:
http://localhost:1111/axis2/services/HelloPojo/subtract?a=99&b=12
No output is generated and a NullPointerException is generated at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:172) !
This happens because there is no output transport defined. 

Axis2 generates a default http input transport when we send it an empty configuration, but does not do the same for the output. This is easily fixed by adding a TransportSender to the configuration before we pass it to the server:

  TransportOutDescription transportOut = new TransportOutDescription("http");
  CommonsHTTPTransportSender sender = new CommonsHTTPTransportSender();
  sender.init(context, transportOut);
  transportOut.setSender(sender);
  cfg.addTransportOut(transportOut);

and now our class looks like this:
Axis2SimpleServer.java
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.transport.http.CommonsHTTPTransportSender;
import org.apache.axis2.transport.http.SimpleHTTPServer;
import org.apache.axis2.transport.http.server.HttpFactory;

public class Axis2SimpleServer {
 public static void main(String[] args) throws Exception {

  // create empty config context
  ConfigurationContext context = ConfigurationContextFactory
    .createDefaultConfigurationContext();
  AxisConfiguration cfg = context.getAxisConfiguration();
  // add a POJO to it
  cfg.addService(AxisService.createService(
    HelloPojo.class.getName(), cfg));
  
  // create a sender
  TransportOutDescription transportOut = new TransportOutDescription("http");
  CommonsHTTPTransportSender sender = new CommonsHTTPTransportSender();
  sender.init(context, transportOut);
  transportOut.setSender(sender);
  cfg.addTransportOut(transportOut);

  // deploy on an Axis2 server on default port 6060
  // new AxisServer().deployService(HelloPojo.class.getName());
  
  // Use the SimpleHTTPServer to specify a port
  HttpFactory f = new HttpFactory(context);
  f.setPort(1111);
  SimpleHTTPServer server = new SimpleHTTPServer(f);
  server.start();
 }
}

Adding services is now as easy as creating a POJO and adding it with:

  cfg.addService(AxisService.createService(
    GoodbyePojo.class.getName(), cfg));

Running an axis2 servlet inside Jetty

Put both of these together and we can run axis2 in Jetty by creating the configuration programmatically.

JettyAxisServer.java
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.AxisServiceGroup;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.transport.http.AxisServlet;
import org.apache.axis2.transport.http.AxisServletListener;
import org.apache.axis2.transport.http.CommonsHTTPTransportSender;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyAxisServer {
 public static void main(String[] args) throws Exception {

  // create an empty configuration
  ConfigurationContext context = ConfigurationContextFactory
    .createDefaultConfigurationContext();
  AxisConfiguration cfg = context.getAxisConfiguration();

  // create a receiver
  TransportInDescription transportIn = new TransportInDescription("http");
  AxisServletListener receiver = new AxisServletListener();
  receiver.init(context, transportIn);
  receiver.setPort(1111);
  transportIn.setReceiver(receiver);
  cfg.addTransportIn(transportIn);

  // create a sender
  TransportOutDescription transportOut = new TransportOutDescription("http");
  CommonsHTTPTransportSender sender = new CommonsHTTPTransportSender();
  sender.init(context, transportOut);
  transportOut.setSender(sender);
  cfg.addTransportOut(transportOut);
  
  // add a group and a service
  AxisServiceGroup group = new AxisServiceGroup(cfg);
  group.setServiceGroupName("POJOs");
  AxisService service = AxisService.createService(
    HelloPojo.class.getName(), cfg);
  group.addService(service);
  cfg.addServiceGroup(group);
  cfg.addToAllServicesMap(service);

  // deploy as a servlet in Jetty
  Server server = new Server(1111);
  WebAppContext root = new WebAppContext();
  // pass the axis context to the servlet context
  root.setAttribute(AxisServlet.CONFIGURATION_CONTEXT, context);
  // create a servlet
  AxisServlet s = new AxisServlet();
  ServletHolder holder = new ServletHolder(s);
  root.addServlet(holder, "/axis2/*");
  root.setResourceBase("./src/main/webapp");
  server.setHandler(root);

  server.start();
  server.join();
 }
}

Note

For this project I suggest you use maven2 because it lets you find the dependencies quickly and also gets any required dependencies for you.

24 November 2013

Random acts of kindness

Nov 2013: This has been lying around for a while now maybe time to finish it.

April 2013: My thoughts on the Boston Marathon bombing.

It is a tragedy that some people feel the need to hurt other people to make themselves heard. Bombings and violence do not solve anything. At best it makes a point about something or other but if you do not claim responsibility and state your issue then your voice is mute and all that remains are shattered lives, shattered bodies, a group outraged people and a year's worth of increased security checks at airports.

What should our reaction be to "senseless" violence?

Our initial reaction is of course shock and horror that the act has taken place. Commiseration with those that are affected follows shortly thereafter. Facebook and Google+ statuses get updated, Candles lit (even if they are virtual), T-shirts worn (or not), Ribbons hauled out. But does all of this address violence in general and this bombing in particular? Does it make a difference to the perpetrators of violence? Does it make a difference to those affected? I think the answer is: "Very little". We seem to be hiding in our cave (virtual or otherwise) and are too afraid of doing something. But can we actually do something?

Where do we (as a global community) go from here?

I think our reaction not be more substantial, more visible, more active.

Nov 2013:
There is a need for us all to see our fellow man (or woman) and help out where we can. Do small acts of kindness. Not out of pity but as a gesture of helpfulness.

08 March 2013

A Scientist and Religious Person talk. (A Socratic dialogue) Part 2

RP: Oh, Hi there, have you come to your senses yet?
S: My senses are definitely with me. I really liked our little chat the other day, but I'm afraid we have more to talk about.
RP: Definitely.
S: Right then shall we start?
RP: Yes, lets!
S: Well then, I think we need to set some ground rules for this chat so that we don't talk in circles. Agreed?
RP: It's you who is talking in circles, but OK, some rules are always good.
S: Do you mind if I ask you a question before we get to the rules.
RP: By all means, go straight ahead.
S: What do you hope to accomplish with this chat?
RP: What do you mean?
S: What is it you want to change? Why are we having this discussion, when all I wanted in the first place is to be left alone to do my experiments and teach some science?
RP: Oh, that’s easy, I want you to believe in GOD.
S: Then this discussion can be over right now, I DO believe in God. But I think the way I "define/see/think about" God may not agree with what you want me to beleive.
RP: How dare you define God!?
S: That's why I put it in quotes. I think everybody "defines" God differently because they have different experiences with God.
RP: But that doesn't change the fact that he is there and greater than we can imagine.
S: Of course it doesn't. But do you agree that everybody has a different experience of God.
RP: Yes. Everybody experiences God differently.
S: And therefore thinks about God differently.
RP: Yes.
S: Can we also agree that humans are fallible?
RP: Of course they are. The Bible says so right in the very beginning.
S: Wonderful, we can agree on some things. We are making progress.
RP: Are you going to make me agree with everything you say?
S: Perhaps. But I have a suspicion there are deeper issues that need resolving.
RP: I don't have deeper issues! I just want you to believe!
S: Great so now we have a motive. But we also have agreed on two points. Can we call them facts, or do you have a different word for them?
RP: Two? I only saw one.
S: No, two! 1) Humans experience differently. and 2) Humans are fallible.
RP: Indeed. And we can call them "facts" if you like.
S: Excellent! I'm so glad we are following a scientific method.
RP: What? I don't want to follow a scientific method!
S: That slipped out, but I'm afraid when you are talking to me you'll have to.
RP: Um, right, maybe I can still convince you.
S: On to the next rule! But once again, a question first. What is it you want to know from science? Are there any things you would like to know that will make you live your life as a Religious Person?
RP: I have several: the Precambrain explosion, Monarch butterfly migration, modern fossils in Australia, the still missing link, or for that matter all missing links, the primordial soup experiment and Haeckel embryos.
S: That's quite a list, you have there! I cannot fail to notice that all your questions are related in some way to evolution. You have no questions for science about how to live your life? Be a good person? Have fun?
RP: No God has already told me all I need to know about that.
S: And what do you think will happen (to you) once I have answered all your questions about evolution to your satisfaction?
RP: Hm. I have not thought about that. I'm hoping that while answering you will see that the theory of evolution is wrong and that God made everything the way it is now. And therefore you will start believing in God.
S: But I have told you that I already do.
RP: In that case that your belief in God changes to more closely resemble my own.
S: But wouldn't that be boring if everybody believed the same thing?
RP: Not at all.
S: I'll let that stand there right now, but back to your questions. You have no questions about how electricity works or how a car moves forward, or how aeroplanes and birds stay in the sky? Which admittedly is more closely related to my area of science.
RP: Does that mean you won't answer my questions?
S: Not at all, I'll do my best but I may have to refer to some people whom I consider experts.
RP: But your experts are all scientists and most of them are even atheists!
S: Indeed. You got me there, but on the other hand how would you convince a person on the street to believe in God?
RP: Well, first I'll tell him or her a great story, then illustrate the reason for telling and how God has changed the character's lives...
S: and that if he starts believing his life will similarly change for the better.
RP: Exactly.
S: Where do you get your stories? How can you be sure that the story you just told is good?
RP: There's the Bible. And then there are all the Saints and Priests and even ordinary people that have shared their stories of God.
S: How do you know the story has been created by a religious person?
RP: It contains a life lesson that would not be possible without God.
S: Would you consider the author an expert?
RP: No, never! Nobody can ever be an expert on God!
S: I did not say "an expert on God". I simply wanted to know whether you consider the author an expert on life, human interaction, religious matters?
RP: If you put it that way, maybe, it depends.
S: On what? Track record? Statements made that match your own? Impact on your life?
RP: Yes, no, all of the above.
S: I can see you are confused. Shall we stop here for today. I promise to answer you questions soon.
RP: OK.

A Scientist and Religious Person talk. (A Socratic dialogue) Part 1

Scientist: I have a theory that this is how this (specific thing) works.
Religious person: Oh, so you don't really know how it works. It's just a "theory".
S: Yes. I have conducted verifiable and repeatable tests and as far as I can determine, this is how it works.
RP: But it's still just a "theory"
S: Yes. I'm not 100 percent sure, but until something better comes along I'll stick with what I have because it describes the "thing" in enough detail to be workable.
RP: I have something better! It's called GOD and faith.
S: How does this describe how this "thing" works?
RP: God says it works differently and I have faith that God is right.
S: Where is your proof? repeatable experiment? verifiable outcomes?
RP: I have faith that it works as God says.
S: Sorry, but that does not sound like a better description. I'll stick with mine.
RP: But your "theory" is not correct because the missing link is still missing.
S: I'm not concerned with the missing link, only that my description of this thing is as accurate as possible.


This dialogue resulted from a flame-war that erupted on a facebook post that I made where Neil deGrasse Tyson is depicted, stating: I don't have an issue with what you do in church, but I'm going to be up in your face if you're going to knock on my science classroom and tell me they've got to teach what you are teaching in your Sunday school. Because that's when we're going to fight.

25 February 2013

odd phrases in my head

chocolate tampon - after half reading the cover of Truman Capote's In Cold Blood.
motorcycle quantum mechanic - after mishearing a conversation of a colleague

21 December 2012

3d printed shoes

The next revolution is on it's way. When anybody can make their own shoes, clothes and accessories or sell them to those that can't or don't want to, things will become interesting.

It has started with 3d printed shoes.



Image source:
http://www.infoniac.com/offbeat-news/dutch-artist-creates-3d-printed-shoes.html

18 December 2012

why is the sky not violet

After reading this xkcd strip I wondered the same thing. Off to my favourite activity: seach the internet for answers.

The sky is blue because:
1) Shorter wavelengths are scattered more (Rayleigh scattering) than longer ones and therefore the radiation that reaches use is shifted to the blue-violet part of the visible spectrum.
2) But our eyes see better towards the middle of the visible spectrum and can't see the violet as well as the blue.
And therefore the sky looks blue to us humans.

Source:
http://www.msnbc.msn.com/id/8631798/
http://apollo.lsc.vsc.edu/classes/met130/notes/chapter19/rayleigh.html

30 November 2012

i before e except after c exceptions

The one I always remember is weird, but it turns out there are many exceptions to the rule "i before e except after c".



Here is a list:
beige, cleidoic, codeine, conscience, deify, deity, deign,
dreidel, eider, eight, either, feign, feint, feisty,
foreign, forfeit, freight, gleization, gneiss, greige,
greisen, heifer, heigh-ho, height, heinous, heir, heist,
leitmotiv, neigh, neighbor, neither, peignoir, prescient,
rein, science, seiche, seidel, seine, seismic, seize, sheik,
society, sovereign, surfeit, teiid, veil, vein, weight,
weir, weird


Also:
This list could obviously be extended by adding more derivatives of Latin "scire", and by adding inflected forms of some of the basic words listed. The list has "conscience", "prescient", and "science", but there are also, for example, "omniscient" and "nescient". To "eight" could be added "eighty", "eighteen", and "eighth". And the list could be greatly extended by adding the plurals of all words ending in "cy".

(Is someone going to cite a word ending in "cy" that doesn't form its plural with "cies"? I can't think of any at the moment, given that I'm excluding capitalized words from my discussion.)

With regard to the extension added by some people for "neighbor" and "weigh", and the fact that this is only a start toward covering all the sounds of "ei", I have broken down my list according to the six different sounds "ei" had in that list. In doing so I have excluded cases where the "ei" or "ie" was not a digraph. Here is the list as so reorganized:

It seems the exceptions almost outweigh the rule. But I often fiend it useful to remember when writing words like receive, retrieve etc.

Sources:
http://alt-usage-english.org/I_before_E.html

23 November 2012

shortstraw waterworks lyrics

One of my facebook friends posted this video on his timeline.
It features beautiful music and poignant scenes of the relationship between father and daughter.

I was disappointed that I could not find the lyrics.

ShortStraw is a South African band with facebook, myspace, soundcloud and boom.com presence.

05 November 2012

Deum fortem viuum

This last weekend I visited a friend who had the most exquisite (and by her account expensive) picture in her house. It was a framed piece of vellum with the Latin words:

Deum fortem vivum: quando veniam & apparebo ante faciem Dei.
Fuerunt mihi lacrimæ meæ panes die ac nocte: dum dicitur mihi quotidie: Ubi est Deus tuus?
Hæc recordatus sum, & effudi in me animam meam: quoniam transibo in locum tabernaculi admirabilis, usque ad donum Dei: 
In voce exultationis 




The font and the faint lines however made it difficult to read and transcribe correctly. I did however, after searching for several similar phrases get to the source and the English translation:

It is part of Psalms 42:3-5 (although the Latin numbering indicates 41)

the strong living God. When will I draw close and appear before the face of God?
My tears have been my bread, day and night. Meanwhile, it is said to me daily: “Where is your God?”
These things I have remembered; and my soul within me, I have poured out. For I will cross into the place of the wonderful tabernacle, all the way to the house of God, with a voice of exultation