Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, May 19, 2015

RESTful Service on an embedded Glassfish/Payara


Last posts were about making a RESTFul service and run it on Jersey with an embedded Jetty.
This time I will set up a more Java EE like solution with the same REST Resource, but instead run it on an embedded Glassfish (actually, I will go for Payara). I will take the same model as before. Next part I will also add a JSF 2.2 client to use the RESTful service.

I will create this as a maven multi module with a parent project and two subprojects. One will be a web-project and the other will be a "runner" for the embedded Glassfish. I will not use maven to run, but will create a class that will run the embedded Glassfish with the war-file from the other project.

As it is pretty easy I use NetBeans to create maven projects for me.

The structure will be like this:

  • embgf
    • task-web
    • gf-runner
    • pack-dist

task-web

To start with, instead of having to set up a Servlet on "/api" path, we will create a configuration class that extends JAX_RSs Application.

And this will be the class for the Task service.


The service will be available at [http://localhost:2001/task-web/api/tasks] (depending what you use as port and contextRoot)
Just to have some Tasks to start with since we have a simple cache in a HashMap, we create a startup bean to create some.



gf-runner

Embedded Payara

Trying to follow [http://www.payara.co.uk/using_payara_embedded_and_payara_micro_with_mav] I ran in to some issues. The dependency on that page does not really work, it end up with the following message:


There is a bug-report on this. But to get on, I will download the jar and do a "quickie" and add it as a system dependency and get on.

The code to get up and running with the war-file from task-web on an embedded Payara is just a few lines:


pack-dist

As I am a bit lazy and want to avoid copy jars manually I created a pom-project just to copy dependencies. The needed jar file will end up in the root folders under ./dist/, I also added a bat file to start the embedded Payara with the following content:


I also tried the jersey-client from the previous post with s slight modification for the context-path and it still works. (or you can start the payara with "/" as context path)

In next part I will add a JSF client on top of this service to show some nice stuff in Java EE 7 and JSF 2.2.

[The full project can be found at: https://bitbucket.org/pejomstd/embedded-gf-payara]

Saturday, May 2, 2015

REST with Jersey and Jetty part 3

REST with Jersey and Jetty part 3

Adding JSON support.

The first two parts  in this small series of posts were about setting up the server and be able to run it with Jersey. [REST with Jersey and Jetty part 1, REST with Jersey and Jetty part 2].

This time there will be a bit more work. And I will take it step by step.

The service we will implement will handle tasks. To start with, there will only be one task list where all tasks will go.

The api will be the following.
Task class:


To start with we add support for getting the list, there will be some hardcoding until we have the working JSON support, since the first thing we want is a working Jersey with JSON support, not to complicate things further. When we have that, we can start adding functionality. But in the end, we will try to support:

  • list all
  • show a single task
  • create a task
  • update a task
  • remove a task
  • show range of tasks
  • get task count

But starting with some hardcoded stuff, to get the server running with JSON, this will be the stating point for the TaskResource


If you start the server and try to surf to this [http://localhost:2001/api/tasks] will yield the following in the log.


so we need to add some stuff to have JSON support.

Well, just a shor Googling, and it was pretty easy to add. [http://stackoverflow.com/questions/25474223/jersey-rest-messagebodywriter-not-found-for-media-type-application-jso] gives a hint. Just added moxy and it works to get JSON with the @GET.

So lets go for some real coding. We will add a simple cache, To avoid having a database for this simple example it will only contain a map with the tasks.

Lets start with some simple support of the cache:


Lets first add a method to create a task and one for getting a specific task.

To test this, we will need to also add a method to get a single task and a client to test it.

First, the client.


So far the client just adds a Task, gets the URI to the created Task and then gets it using the @GET for the methods added above.

Next step, fix the getAll().
The client cannot handle a List without wrapping it in a GenericType, but that is really all there is too it, we can still return List from the method.


The only thing we need to add now is update and delete. We will also add some code to test it in the client.

I also made some changes in the client:
Enjoy your Task microservice in REST using embedded Jetty with Jersey.

Read more about Jersey [https://jersey.java.net/documentation/latest/index.html]

Friday, May 1, 2015

REST with Jersey and Jetty part 2

REST with Jersey and Jetty part 2

Getting Jersey into play

In this part, we will introduce Jetty as serving with rest. We will att a class serving a @GET request.

We will need an extra dependency for Jersey to work, and after getting a strange error under startup I ended up changing the dependency on Jetty from the previous post [http://ironicprogrammer.blogspot.se/2015/04/rest-with-jersey-and-jetty-part-1.html]. I got the following error:


When adding the dependency for Jersey 2.17 after th Jetty dependency. Actually I got it to work by moving the Jetty dependency to after the Jersey dependency. But reading the log you can see that 2.17 if Jersey used Jetty 9.1.1 so, updating Jetty dependency to 9.1.1.v20140108, the order does not matter.
This is the dependencies for this part.



We will also create a new statup-class, It will not be much more code than the one in the previous part, but some extra stuff is needed to get Jersey into play.


The difference here is that we use a ServletHolder with some init parameters to set Jersey up. We also set the path to serve to "/api/*" instead of plain root "/".
That brings us to REST, we need something to show that it works. To do this we have a class under "rest" package called HelloResource.


So now the only thing you have to do is to start upp JerseyServer and surf into [http://localhost:2001/api/hello] and you should see the hello message. And there you have your first little Microservice ;)

In future post will explore how to use more than @GET and also how to add JSON support to this.


Thursday, April 30, 2015

REST with Jersey and Jetty part 1

REST with Jersey and Jetty part 1

Running Jersy standalone with a Servlet.

A few days ago I started to look into how to run a REST service with an embedded container. Now a friend of Springframework will say, that is easy with Spring, but after looking at a tutorial [http://spring.io/guides/tutorials/bookmarks/] I notice a couple of things. The annotations are not the standard JSR 331/339 ones, and there is a lot of other things from spring framework coming into play. Well, sorry Spring-guys, I don’t want that. I want to go with standard JSR annotations, and no specialities from Spring.

So my ide is to use Jersey which is the reference implementation och JSR 311/339 and run it on a server that can be embedded. What I want to do is to have the following support.

  • Ability to run with an embedded server (my choise: “jetty”)
  • Ability to serve REST calls (my choise: “Jersey”)
  • Ability to communicate wiht JSON. 
After some research I noticed that it is not easy to find any good resource on how to run Jersey with an embedded server. the bes I could find was [http://jlunaquiroga.blogspot.se/2014/01/restful-web-services-with-jetty-and.html] , but I don’t like blogs saying “you only need to include the jars necessary or use maven” but leaving out the information of which the necessary jars are or the specific maven dependencies needed.. the documentation over Jersey is scarce in examples.

I will start this “journey” by building it up step by step. In this part, I will do only what is necessary to start an embedded server.

I used the above blog as a starting point. First step I will show is how to run a servlet in an embedded Jetty.

The first thing to do is to have a dependency to Netty.



The server will be started in a class with a main method, 



There will also be a simple servlet to run in it.



Next post is about how to create a REST service based on Jersey and run it in Jetty.
(Update: changed the version of Jetty dependency, since I in next post use Jersey 2.17 and there was some issues running with Jetty 9.0.2)

Wednesday, November 13, 2013

Designing a “modular” web application

Background

I would like to separate functionality for a web application into separate jar-modules and include these in a war project.
The purpose for this is to separate development and deployment, that is, to develop functionality separately and include it in the war-packaging and it should automatically be usable with templates, menues etc.
Sorry if the code don't display so well. But putting codes with Generics is not so well handled by Bloggers editor, so until I have time to fix it you will have to live with it ;) and I will use [] instead of <>


Structure

To make it modular it is nescessary to have some common code (placed in “common-web”). The structure for this is basically:

  • common-web: will contain code common to modules and web-applications.
    • templates: for reuse in different modules, basic templates is put in a common module.
    • login: (out of scope, will not implement login in this example) for reuse of login-form etc. i.e. the same files and functionality applies to all web-applications that uses login.
    • resources: common css and images is placed to be reused.
    • menu: functionality to assemble n menu(es) from m modules so they will present in web-applications no matter in what module a page is used.
    • common code: code for hoding and generating menu(es), common utility code for JSF, ManagedBeans etc.
  • war: web-project with war-packaging that will use modules.
  • webmoduleA..X: functional parts that implement a function or group af functions that logically belong together.
    • as an example I will implement at “todo-webmodule” in a PoC to show the functionality.


Menu

Basic functionality for menu is placed in common-web.

What am I trying to solve here?

A module can have different kind of needs, to access parts of its functionality we need a menu with 1 or more items (even if a module can be without menu, for example common-web may not need one, even if it is also a kind of a module).


Requirements:
  • A menu sholud be able to present itself as a top-menu in a menubar
  • A menu should be able to present itself as a part of another menu (i.e. not on toplevel) but in another menu.
  • Should be able to order children of a node.
  • Support to up to 4 levels of menues (more level will not be displayed)


Assumptions:
  • If a menu has no children it should have an action attached (=no expression needed)
  • If a menu has children, it has no action attatched to it.(=no expression needed)
  • Only SubMenus can be placed, not single menues (MenuItem). And they can only be placed in other SubMenus.



Placement:
“/” is root, putting menues under “/” would put them in top menubar.
Take as an example; you have 3 top menus (Admin, Project, Help). These should all be placed under “/”


Further, say we want to capture this endresult for menues.
  • /
    • admin
      • add user
      • list users
    • project
      • add project
      • list projects
      • issues
        • add issue
        • list issues
    • help
      • about


/admin
/admin/add user
/admin/list users
/project
/project/add project
/project/list projects
/project/issues
/help
/help/about

We have Issues under its own grouping and this should be inserted under project. (The reason behind this is that it may be developed in another module and we want to insert it under project in this application)

Ordering

When it comes to ordering, I want to speify an order on all levels. The purpose of this is that when adding top menues dynamically I do not know which order they will appear, hence it is usefull to be able to define it on top-level.
Another purpose is, that since it is possible to insert a menu into another, this may disturb the order or we want the inserted menu group to in another position than it gets inserted to.

This solution for this is to sort all items alphabetically and then resort according to supplied ordering (which is allowed to just use the ones it wants to sort in from start)

Solution

Model



Description


I will describe the solution by taking my example project on bitbucket as an example.
The example project (on bitbucket) have the following structure:


In this example the only “working” code for a MenuGroup that I will implement is the TODO-functionality, and of course the supporting code to have it modular. As goes for the concept of menus I will add a couple of MenuGroups undermodule-web itself. (Do not be surprised if the code here differs from the one on bitbucket, because there may be improvements done in the real code.). There is also mockup code to add the menues as described above to get more than one menu.


To have a menu for “Todo”, the following code will give me that as a “MenuGroup”





To have it modular and generate modules, this is done by having the menu.xhtml and supporting classes in common-web. The most important are MenuBean (that assemble the menu for the view), MenuAssembler (that assembles a menu for MenuBean from the groups it is provided)


To get menu groups aswell as config of orderings and placement from other modules, a bit of CDI is used.




Since we do not know which MenuGroups will exist when developing common code, we inject any type in an Instance. The view will call getMenus() tha if empty will try to assemble the menu. The placement and ordering should be provided from outside aswell, not hardcoded as in this case.


The order we do this is:

  1. add MenuGroups
  2. add rules
    1. placement and/or ordering (defined in a WebMenuConfig implementation)
  3. call assemble()


The last call will assemble the menu and return a list of the top menus. These menus will after returning be rendered in the view.


The implementation of the WebMenuConfig in this case is defined like this:




This will give a menu that looks like:









Friday, March 26, 2010

Tutorials

I have started a Java tutorial for starting up with Java. It can be found at my Google-site. The tutorial is basic Java.

http://sites.google.com/site/ironicprogrammer/tutorials/ironic-programmer-java-tutorial

I will continuosly add more stuff to the site. Even if the first lessons may be a bit text to read. I will try to do programming by examples.

Friday, March 5, 2010

File upload in JSF2 using base class

Surfing the net for JSF2 resources can be a tedious task. Actually for file upload I actually found a couple of blogs describing how to do it the firs I found actually only (FileUpload with JSF 2 and Servlet 3.0) made a taglib based on the second one. And it includes maven which I do not use.

I had to remake the example a bit since I got question to provide a sample application. When extracting the code I noticed it did not work anymore. The reason is probably the one mentioned at this blog: http://mcatr.blogspot.com/2010/01/multipart-requests-and-jsf.html.To make it work again, I did a solution that I am not happy with but it works. It takes the idea from this blog, joined with some from the other blogs mentioned. The former blog states that a multipart request to JSF 2 do not work, because it can not extract parameters from that kind of request.

The problem is that for what I actually wanted it was not right and one was a little bit overkill. So as usual I took another approach. I got some helf from Uploading files with JSF 2.0 and Servlet 3.0 but that solution includes making a custom component and renderer, and is dependant on classes found in Uploading files in Servlet 3.0. I actually copied all the code and tried it...but I got a failure when loading the page. So I wanted something with less code. and simpler to use, and I have a case when I am going to store vCards in a database so a solution to save the file on disk means I have to modify code anyway.

I took the following approach:

  • Use standard html <input type="file" />
  • Use @ManagedBean
  • I first had a base class to handle the file and extended the Managed bean with this one, but since this stopped working I had to add:
    • A Wrapper to wrap multipart requests
    • A Filter to catch multipart request and transform them to the Wrapper type.
  • I also have a FacesUtil class to simplify getting request and parameters
Here is the code:

In the view (vCardForm.xhtml)

Class to represent the uploaded file (UploadFile.java)

I created a class to store some information about the file being upload, I can later choose if I want to store to disk or in a database, for example sending this to an EJB and the EJB descides what to do.

The managed bean (VCardBean.java)

The interesting thing going on here is that i initialize the base class with the request for use of the request. Probably I could have done this in the constructor of the baseclass, but something you have to have to refactor.

MultipartRequestWrapper


MultipartRequestFilter



Session bean for handling the storage.

For the example this only stores it in the session.

Finally the class to inherit to make it all work

This is now obsolete, but I keep it in case JSF will handle the mutlipart form in the future. But even then it may not be needed.

The only thing needed in the Managed bean is to call findFile("vcardFile") on the multipart request to get the file that is being uploaded and take action on that.

A sample project (for netbeans) can be found here: http://sites.google.com/site/ironicprogrammer/home/jsf-file-upload-example

Sunday, January 10, 2010

Netbeans tutorial "Generating a JavaServer Faces 2.0 CRUD Application from a Database"

I went through this tutorial today. Nice example, but there was something I did not like. As a geek I sit on a sunday and try out a tutorial on my home computer. Lazy as I am I do not want to start my MySql instance, since adding more running components tend to slow down my almost four year old Toshiba laptop.

Since I was going to run Glassfish v3 anyway I was thinking a better idea is to have the database in the form of JavaDB, so I tweaked the script to fit into Derby instead, not much tweaking to do actually and doing it made me happy to not be forced to start MySql (My mysql is by the way a bit old and installed the same time as I installed InstantRails long time ago, and probably needs to be updated). The insert script in the tutorial work more or less as it is in JavaDB just remove the 3 SET-clauses in the top and the COMMIT in the end and it should work.

The script can be found at my google-site http://sites.google.com/site/ironicprogrammer/home/jsf-2-0-tutorial-db-script

Wednesday, October 7, 2009

Making SSL calls with Grails

All of a sudden I realised that I have to call a service I have behind a SSL connection.

Using grails, this is easy to set up. Just create a couple of Groovy-classes and use it from the controller. It may be nescessary though to add the certificat of the SSL site to your JVM.

Adding the certificate
  • download  the certificate you need, name it to something usefull, for example theSite.cer.
  • use keytool to add it. (needs JAVA_HOME/bin in the path)
keytool -import -keystore /pathToJava/jre/lib/security/cacerts -file theSite.cer 

Class to make the call
this is the class to actually do the work, calling the SSL url you want to reach.
Class for password authentication
this class is needed to authenticate you at the remote site.

In the controller you can then use the class to get a responsestring from the remote server.


/Peter

Saturday, October 3, 2009

Grails and EJB

Read Jason Rudolphs article about grails and EJB a while ago. Grails + EJB Domain Models Step-by-Step. It is a nice article but not what I want.

However it seamed a little bit of inventing the wheel again to import the classes into Grails in the same package structure, and I also wanted some other things that EJB3 gave me.

  1. I want the EJB level to handle application rules. In that way, I can reuse the EJBs from other places as well
  2. I have information i two different schemas in Oracle and grails was not supporting more than one.
  3. I like "hit and run" session beans to provide services. which means that I use interface in the sessionbeans to provide CRUD and listing methods. 


So I started to elaborate with putting the EJB.jar file in Grails library folder to try it out. It worked out nice, the only thing I have to do is to put some lookup code and start using the session beans. I also get access to all model POJOs.

I like this approach because I can use grails rapid application development with the robustness of EJB3 without doing very much extra.

The downside is that as I am a little bit lazy and avoid writing too much code, is that I have to run it on the same glassfish and I have to copy the jar-file every time I change the interface. I also have to make a war of the grails application and run it on glassfish.

 /Peter

Friday, September 4, 2009

GroovyWS or Java WS Client?

We had a project this winter/spring which I designed to use Webservices on a web connected to EJBs, the clients we build in Grails for fast development.

Well we started using GroovyWS because that gave us the opportunity to get up and running pretty quick.

First we had some problems with the time it took to generate the stubs everytime we called a web service, however, this was becaus we stupidly put the creation of the client stubs in the actions so it was done every time. This was easy to sol by making a Groovy singleton class and let it create the service stubs once.

Eventually I decided to move over to making JAX-WS clients in Java using Netbeans. The reasons for this was mostly to try to get better performance and the possibility to put on SSL on the Web Service layer. From information I found and the experience during the first month of the project, I realised some shortcommings with GroovyWS mainly:
  • there is no support for https calls using GroovyWS
  • for some reason I had to wrap lists into a class. GroovyWS only regarded the list as one object and took the first one and skipped the rest and making workarounds in the WS-layer to fix this is something I don't want
  • restarting Glassfish sometimes made problems with the grailsapps and made them crash, this I think is because some of the services tokk some time to start and when GroovyWS tried to make stubs they were not there and after that the wars refused to work.
However making a WSClient in Java from Netbeans is an easy task, even if Java 1.6_07 or later is required for JAX-WS it is not such a big deal to make an jar-file and put it into the grailsapps lib folder, after that it is easy to call the java-classes from the Groovy code.