Category Archives: Java

Putting it together – Yeoman, AngularJS, Bootstrap, Grunt, Jasmine, Karma

After going through Front-End JavaScript Framework course at Coursera.org, I decide to present something in our Lunch & Learn next week. In order to re-enforce my knowledge, I’ve built two small proof of concept web applications using technologies listed above – AngularJS application using task runners. With Yeoman, I was able to build/deploy really quickly without thinking too much about the dependencies.

Front end technology has been evolved so much and it is a mind boggling to select which JavaScript framework I want to use for my web application. Even keeping it up is very challenge. Of course, there is good old Java template engine (JSP), but it is not the technology that you’d create a Sing Page Application with.

Here is the presentation done by Prezi and two projects in the Github (PoC2, PoC3). PoC3 README.md contains step by step guidance along with the source code. I am planning to enhance these projects into Cloud base applications such as IoT management dashboard in the near future.

 

 

Advertisements

Article: The New Cloud You: Adapting Skill Set and Mindset for Success in the Cloud

Very good article from Oracle. This article explains how cloud solution impacts skill sets and paradigm shift in terms of providing a solution in the cloud as a Solution Architect

Few points from the article.

  • Infrastructure-related skills are no longer needed, and performance tuning, beyond the code level, is also irrelevant.
  • With SaaS, the biggest challenge has been meeting clients’ expectations of reduced implementation costs and shorter timelines. For PaaS, architecting solutions requires a completely different mindset. You need to factor in service compatibility, availability, and security.
  • PaaS – code development, testing, and quality assurance are relevant. Deployment and management concepts have carried over as well while the tooling has changed. For example, more online code repositories such as Git are gaining popularity.
  • Detailed infrastructure design and planning, deployment, and procurement skills are no longer needed as much, built-in templates and the ability of applications to auto-scale change the game significantly.
  • The rapid deployment cycles expected from the cloud have raised expectations for rapid development lifecycles. Agile development is the new norm, and the usual past behavior of a drawn-out implementation with lots of bodies and complex infrastructure provisioning has become history. The entire focus is on getting a solution up and running. In the cloud, principles of solution architecture and platform architecture are different.

Building RESTful WebService/Client using WildFly 8.0.0 Final, RESTEasy, and Maven Deployment

WildFly 8.0.0 Final was released recently. For a new project, I had to convert a legacy WebService into RESTful WebService using RESTEasy on JBoss Application Server. Not only converting RPC style JAX-WS WebService (Axis2-1.3), but I have to convert Ant base build/deployment process to Maven. My experience around RESTful WebService was around Jersey and Maven experience was limited before this project. As for my first step, I built a small prototype using WildFly + RESTEasy + Maven combination based on JEE7. There are several tutorials & resources that I could find in the internet, but it was difficult find a complete example. JBoss RESTEasy API and Java EE 7 tutorial have good reference and sample codes. However, I had difficult time finding the best practice based on my requirement. Most of the internet resources are either out of date or too simple for what I need to achieve. Also, most of examples are contained within the Eclipse environment, so considering deployment on a remote server was additional challenge . Eventually, I put things together and share my experience. 

Requirement

  • JDK 1.7 u51
  • Eclipse Keploer
  • WildFly 8.0.0 Final
  • Maven 3.1.1
  • RESTEasy 3.0.6 – comes with WildFly.

Objective

  1. Create a RESTful WebService using RESTEasy deploy to WildFly using Maven.
  2. Prototype should have a WebService and client.
  3. Build a web page that can be exposed by calling a WebService client.
  4. Retrieve a list of object by passing a list of String as a parameter.
  5. Application uses a single properties file fed from pom file based on environment profile. Assuming DEV/TEST/PROD environments are running on WildFly 8.0.0.
  6. Prototype will be deployed to WildFly standalone server. For this reason, portability wasn’t considered in this prototype.

pom.xml

  • WildFly plugin added
  • Two profiles are created ‘development’ and ‘prod’ to simulate different environment.
  • ${project.version} is a maven project property
  • ${maven.build.timestamp} is a special variable in maven
  • Most of JBoss specific jars are defined as ‘provided’ scope.

application.properties

environment=${env}
build_version=${build_version}
build_date=${timestamp}
build_number=${build_number}
student.restws.url=${student.restws.url}

After “mvn package -P development” command application.properties are populated as below.

environment=development
build_version=0.0.1-SNAPSHOT
build_date=2014-03-30 19:29:52
build_number=00001
student.restws.url=http://localhost:8080/RestWebServiceTest/rs/json

 web.xml

  • I wanted to prefix the RESTful WebService URL with ‘rs’, so I can differentiate normal Web Application from the WebService.

WebService Challenges

I need to retrieve a list of object based on user selected strings from list box. This list box has about 100 of items and there is a possibility that user can select “All” from the list box. There seem to be two ways of doing this : Convert string collection to JSON or comma delimited single string, use @PUT instead of @GET if string collection is too long. @PUT is for update, but I can safely pass the parameter in the body rather than URL as a @QueryParam. Also, I came across another way of doing this by passing long string parameter in the Header, but I couldn’t find an example code to follow. Especially, building WebService client passing long string to Header.

 

WebService Client

JAX-RS 2.0 defines client API, which makes it much easier to develop client side. I always felt developing RESTful WebService Client side is difficult because of different implementations use different classes/methods although underneath principle is the same.

Deployment

mvn clean compile package -P development wildfly:deploy-only

Source Code

https://github.com/mjtoolbox/RestWebServiceTest

Conclusion

I felt importance of RESTful WebService becomes bigger and bigger. It is due to modern Web Application development is moving away from server side generated front end pages. For this reason, I feel I need to improve hands on experience and understand the details. Some of learning points from this experience.

  • New JAX-RS 2.0 spec in JEE 7 made client side development easier. At least defines a standard way of implementation.
  • Working on the latest technology requires time and patient : much of the configuration resources are based on the old version.
  • Haven’t handled the security. Need to expand that later post.

 

 

 

 

 

WebSocket Chat application using JEE 7 with Glassfish 4.0

I was interested in WebSocket technology since last year. I have a posting related to WebSocket using Grizzly implementation. Since then, WebSocket becomes a part of JEE 7 release and Glassfish 4.0 with JEE 7 has been released. There are tons of articles that explains what’s changed in JEE 7 and how to start using JEE 7.

Experience

In this posting, I’d like to briefly discuss my experience with WebSocket implementation in JEE 7.

  • Very simple : using @ annotation, I can declare POJO into WebSocket Server/Client Endpoint really easiy.
  • There is a way of creating a WebSocket Server Endpoint without using @ annotation.
  • It seems I can not use both in one project. Programmatic WebSocket implementation overwrites the annotation implementation.
  • WebSocket URI gave me a hard time. After I figure it out, it is obvious. However, when I was in it, I really didn’t see. It took me a while to realize those WebSocket sample codes does not specify the webcontext name. This is critical piece. I was struggled with “undefine” error.
  • ws://domain:port#/webcontext(project name)/serverendpoint

Even though my WebSocket chat application is very simple application, I found it much easier to implement – compare with Grizzly implementation.

Idea

Web is evolving so fast and new ideas are keep pouring out. I think WebSocket will be very useful technology in terms of replacing point to point messaging. Especially, the connection has to be maintained constantly. One application that I used to maintain uses applet to satisfy this requirement. I think replacing an applet with WebSocket will be beneficial.

Resources

I presented this topic to my colleagues in the company Lunch & Learn session. Here is my presentation using Prezi.

Original Prezi Link HERE.

Source Code at GitHub is HERE.

Configuring JEE7 with GlassFish (4.0-b87) on Eclipse

JEE7 release is just around the corner. Due to JRE security reason, my understanding is the release was postponed until next year. Short summary about Java EE 7 (JSR-342) can be found here and overview can be found here with very cool slide. My interest in WebSocket technology was high since last year. I’ve struggled to create my first WebSocket demo last year – there were many earlier implementation postings, but I had hard time finding newer GlassFish implementation. I learned that WebSocket 1.0 as a part of JEE7 supports method annotations around WebSocket lifecycle methods along with straight method implementations. If you want to know the detail, check this out.

In this posting, I’d like to explain how to set up GlassFish (latest build 4.0-b87) within Eclipse and explain some of troubles that I had. I didn’t want to install OEPE bundle. OEPE gives the whole package and makes it easier to configure, but I had some frustrating experience previously and decide not to go with OEPE.

Pre-Condition

First of all, I had to get rid of previously install GlassFish Plug in and GlassFish Tool in the Eclipse Juno. Click Help > About Eclipse > Install Details and remove any GlassFish related installation. I skipped this step and couldn’t deploy web application from the Eclipse. Symptom was the deployment hangs at 69% and no response from the server in Eclipse. There is a blog about how to clear old version of GlassFish tools in the Eclipse. For details, look at this blog.

Installation & Configuration

Once you are done,

  1. Time to download and install GlassFish 4.0.  Scroll to the bottom and download the latest GlassFish.
  2. Install GlassFish.
  3. Start up Eclipse and make sure you have the latest JDK. At least 7.
  4. Now, it is time to install GlassFish Tool. It seems there are two ways of doing it. In my case, first approach (Preeference > Install/Update > Add Available Software Site) didn’t work well. Site URL is  http://download.java.net/glassfish/eclipse/juno.
  5. Second approach is Help > New Software Install > past above URL.
  6. As soon as you do that, GlassFish Tool and Document will show up and you can install those in the Eclipse.

Coding & Testing

Now, time to code and test. I captured the code from Markus Eisele’s blog. The servlet is demonstrating by print out JSON object from JsonObjectBuilder.

Testing is simple, just start the GlassFish 4.0 and test localhost:8080/JEE7Test/JsonTester

Conclusion

Since I configured GlassFish 4.0 with JEE7, I’d like to modify my WebSocket chat demo using annotations and deploy to GlassFish 4.0. This will be a fun exercise and I will have a chance to read more JEE7 API documents.

Custom Tags in JSF 2.0 for Shiro Authorization

Apache Shiro provide JSP Tag library. In JSP, I could use Shiro provided custom tag to determine show/hide html elements based on user’s permission. However, the private project I am working on, I use JSF with facelets and this gives me a dilemma.

  • JSP tag doesn’t meet the JSF lifecycle, so JSP tag from Shiro doesn’t work.
  • I need a conditional statement in the faclets (XHTML). Something like “If user has a permission, display this link. If user doesn’t have a permission, don’t display the link.”
  • Adding a conditional statement in the managed bean doesn’t help because I need to control the logic in the GUI rather than controller layer.
  • Applying security constraints in the web.xml do not help. It helps to prevent unauthorized navigation based on the role, but does not prevent users from clicking the link in the facelet.
  • I thought about implementing permission logic in the managed beans and add conditional statement in the faces-config.xml to navigate different pages based on the permission logic. However, similar to above reason, it is not the solution that I want to have.

Shiro doesn’t have official JSF custom tag support yet. However, I found Deluan’s blog where he created custom tag library for Shiro. His custom JSF 2.0 tag solves the issues that I have in the facelet.

To understand the JSF custom tag, I took a look at the several web sites that explains the JSF custom tag. To summarize my understanding,

  • Most of the custom tags are the UI component related custom tags.
  • Create a custom tag in an XHTML format.
  • Define custom tag details in a tag library.
  • Register the tag library in web.xml.

Above steps are fairly simple and many examples can be found in the  web.

For custom JSF tag, I followed Deluan’s code and simplify several things. Also, based on existing Shiro’s JSP tags, kept the same tag name.

  • Except Principal tag, all other tags doesn’t not need to return any UI output. For me this statement clarifies many things. Below three methods that need to be overridden.
    • encodeAll() –  If this component returns true from isRendered(), render this component and all its children that return true from isRendered(), regardless of the value of the getRendersChildren()flag.
    • saveState() – Invoked after the render phase has completed, this method returns an object which can be passed to the restoreState of some other instance of UIComponentBase to reset that object’s state to the same values as this object currently has.
    • restoreState() – Invoked in the “restore view” phase, this initialises this object’s members from the values saved previously into the provided state object.
    • For a custom component, it is recommended that I should focus on Restore View and Render Response which are the beginning and the end process. See JSF Lifecycle.
  • For other permission view control tags, they are extended from TagHandler. These classes returns true/false based on the Shiro’s SecurityUtils methods. E.g. isPermitted().
  • Define custom tag details in the tag library : shiro-face.taglib.xml. See below.
<tag>
 <tag-name>principal</tag-name>
  <component>
   <component-type>tag.PrincipalTag</component-type>
  </component>
<attribute>
 <description></description>
 <name>type</name>
 <required>false</required>
</attribute>
<attribute>
 <description></description>
 <name>property</name>
 <required>false</required>
</attribute>
<attribute>
 <description></description>
 <name>defaultValue</name>
 <required>false</required>
</attribute>
</tag>
<tag>
<tag-name>hasPermission</tag-name>
<handler-class>tag.HasPermissionTag</handler-class>
<attribute>
 <description></description>
 <name>name</name>
 <required>true</required>
</attribute>
</tag>
  • Define below custom UI component in face-config.xml.
<component>
 <component-type>tag.PrincipalTag</component-type>
 <component-class>tag.PrincipalTag</component-class>
</component>
  • At last, add custom tag library in the web.xml
<context-param>
  <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
  <param-value>/WEB-INF/shiro-face.taglib.xml</param-value>
</context-param>

Usage of Shiro custom tag in the JSF.

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:shiro="http://xproject.flightCenter/tag">
...
<shiro:hasPermission value="navigation:viewCities">
 <li><h:link value="Cities" outcome="viewCities.xhtml"/></li>
</shiro:hasPermission>

Basically above tag means that if this user has a Permission in following actions (navigation:viewCities:*).  Shiro defines behavior or actions in three sections; domain, action, instance. For Shiro’s permission, go here.

Summary

I encounter a need to have a facelet tag to determine if a user has a permission to navigate to certain page. Shiro provides only JSP tag library and Deluan’s blog provides custom JSF tag for Shiro. I tried to understand his code and eventually used in my XProject Facelet pages. In order to understand the whole process, I needed to understand,

  • Shiro Permission
  • Making custom tag in JSF
  • JSF lifecycle

JAX-RS parsing XML

I have encountered a few issues when I try to parse XML object from the JAX-RS WebService. Many tutorials out there uses simple object. Just like I did in the previous post. Using one single class. However, in reality, if the Java class represents a complex object, typical Java will implements interface(s) and involves in parent/child relationship. In this circumstance, it is difficult to put @XmlRootElement all over the classes.

There are three options that we can take.

1. @XmlJavaTypeAdapter : Apply the adapter to hide implementation. By using adapter, you can specify the object that will be marshaled/unmarsharled. See JAXB Guide. I tried myself, but it has a problem at marshaling and I didn’t have a chance to dive into this route. At least, it didn’t complain about the object is an interface.

2. Simplify the object : Use a transfer class to make the object simple. Unless you need to pass the whole object & its attributes, simply the structure to represent the data.

3. Assign @XmlRootElement in the hierarchy : Make the JAXB work all the object in the hierarchy. Still it may require a trick. In case, declared variable is an Interface type, if the Interface is not complex, use substitute variable. If complex, use #1 technique or declare @XmlRootElement tag in the implementation class.

Conclusion

In my opinion, #2 seems the best solution when you need to deal with a complex object. Multiple inheritances with interface and abstract classes. Class is structured in this way to be flexible and useful within the domain. However, it may not be suitable to the outside of the domain. WebService is the tool to communicate the data to the outside, so why not spending little more time to make the object simpler?

Glassfish Basic Authentication

In my previous post, I used Apache Shiro to authenticate users. However, I can use basic authentication from Glassfish server.

web.xml

 <security-constraint>    
   <web-resource-collection>        
   <web-resource-name>Secure Application</web-resource-name>        
   <url-pattern>/*</url-pattern>        
   <http-method>GET</http-method>        
   <http-method>POST</http-method>    
   </web-resource-collection>      
   <auth-constraint>        
      <role-name>Users</role-name>    
   </auth-constraint>   
</security-constraint>    
<login-config>    
  <auth-method>BASIC</auth-method>    
  <realm-name>file</realm-name>  
</login-config>    
<security-role>    
   <role-name>Users</role-name>  
</security-role>

Just like weblogic.xml at work, sun-web.xml needs to be modified with role mapping.

sun-web.xml

<security-role-mapping>    
      <role-name>Users</role-name>    
      <group-name>Users</group-name>  
</security-role-mapping>

Depending on the security realm (admin-realm, certificate, file), I can configure different realm. To be simple, I used file realm. By clicking Manage Users, you can add username/password. This information will be stored in the keyfile (C:\glassfish3\glassfish\domains\domain1\config). Same thing can be done through asadmin console.

Above example will use BASIC authentication. A login popup screen will be prompted to the users prior to access any url (based on the url pattern). The details of form based login is in the JEE 6 Tutorial.