Wednesday, November 27, 2013

Tip: Parent controller to handle exception in Spring MVC

Spring MVC is a powerful framework and I got a tip that can be useful. Spring MVC uses the technique of something called Controller which can be bound to handle the different user request to do a prerequisites before showing the user a specific page he requested.
In case you got many controllers and you need to handle the common exceptions for your application. You can do that by making a parent class which I prefer to call Parent Controller that can handle the exception as the bellow examples shows. Then you can extend that class in your other different controllers.
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

public class ParentController {

 private ModelAndView modelAndView;
 public ModelAndView handleNullPointerException(NullPointerException e) {
  // Display the error page
  modelAndView = new ModelAndView("404");
  modelAndView.addObject("message", "NullPointerException occured - " + System.currentTimeMillis());
  return modelAndView;

Friday, June 7, 2013

Tip: Null casting

When having overloaded methods in one class and calling one of these methods to pass the null value as a parameter. This causes ambiguity to the compiler to decide which method to use. So you can cast the null to the specific type for the method you want to call. Bellow is a snippet to make things clear.
 * @author Belal
public class MyClass {

    public void setObject(String s) {
        System.out.println("In setObject(String s)");

    public void setObject(Long l) {
        System.out.println("In setObject(Long l)");

    public static void main(String[] args) {
        (new MyClass()).setObject("test");
        (new MyClass()).setObject(new Long(0L));
        (new MyClass()).setObject((String) null);
        (new MyClass()).setObject((Long) null);
The output should be similar to this:
In setObject(String s)
In setObject(Long l)
In setObject(String s)
In setObject(Long l)

Java EE 7 arrives on 12 June

I have just received a newsletter email about the announcement of the Java EE 7 on 12 June, 2013. It's pretty interesting to learn more about the new features of the Java EE 7. The pig picture of the theme for the upcoming Java EE 7 as mentioned in the I <3 Java page on facebook is the following:
Java EE 7 will help in:
  • Delivering HTML5 dynamic, scalable applications
    • Reducing response times, simplify JSON parsing, creating RIA using WebSocket, and delivering high-performance RESTful services.
  • Increaseing developer productivity
    • Simplifying architectures, reducing boilerplate code, adding more annotated POJOs, and enhancing portability.
  • Exceeding enterprise requirements
    • Processing batch jobs more efficiently, easily defining managed concurrent tasks, and simplifying application integration.
You can visit this link and you will find there the registration link for the Live Webcast.

1- I <3 Java facebook page.

Sunday, March 31, 2013

How to validate XML file against XSD in Java

private boolean validateAgainstXSD(InputStream xml, InputStream xsd) {
 try {
         SchemaFactory factory = 
         Schema schema = factory.newSchema(new StreamSource(xsd));
         Validator validator = schema.newValidator();
         validator.validate(new StreamSource(xml));
         return true;
 catch(Exception ex) {
     return false;

How to return the root element as a JAXB object from marshaled XML file

public static Object getRootElement(String xmlpath, String package_names){
 Object object = null;
 try {
  JAXBContext context = JAXBContext.newInstance(package_names);
  File file = new File(xmlpath);
  FileInputStream fileInputStream = new FileInputStream(file);
  Unmarshaller unmarshaller = context.createUnmarshaller();
  object = unmarshaller.unmarshal(file);
  if (object instanceof javax.xml.bind.JAXBElement) {
   javax.xml.bind.JAXBElement root = (javax.xml.bind.JAXBElement)object;
   object = root.getValue();
 } catch (JAXBException e) {
 } catch (FileNotFoundException e) {
 return object;

Saturday, March 9, 2013

How to get the path of the WEB-INF or any folder under it in Struts

You may have a folder for resources under the WEB-INF of your Struts application or even any Java web application. For example if you have a folder called "resources" which is under the WEB-INF and you would like to retrieve the absolute path so you can read or write on it. You can do this by:-

First: Get the ServletContext through the ServletActionContext.getServletContext().
ServletContext servletContext = ServletActionContext.getServletContext();

Second: Get the path of the WEB-INF or the "resources" folder.
//path of the Web Content
String path1 = servletContext.getRealPath("");
//path of the WEB-INF
String path2 = servletContext.getRealPath("/WEB-INF");
//path of the folder "resources" under the WEB-INF
String path3 = servletContext.getRealPath("/WEB-INF/resources");

The good thing is that the ServletContext is an interface in Java web API which means that there should be an implementation for this interface by all the vendors unless you are accessing a servlet on a remote system not on the local system of your application.

1. Thanks to this post made by Hazem Saleh

Friday, March 8, 2013

Lambda and Parallelism in Java 8 by Mike Keith

In the first day of JDC2013, Mike Keith has presented two sessions the first one was "Java EE 7, The new and shiny bits" and the second one was "Creating a configuration standard for Java EE". The good thing is that he finished the second session earlier by 30 minutes and he asked whether to start talking about another interesting topic or not. The attendees agreed to continue talking about another useful and interesting topic. It was about "Lambda and Parallelism in Java 8". It was really interesting topic and I got to say that there is a nice change will happen on how we code Java in certain cases :D.
For more information about Lambda and Parallelism you can check this article on DZone.

Sunday, January 13, 2013

Oracle must move faster against this

I have just read about the security issue that affects Java 7 update 10 running in web browsers and for more information about it you can visit this link for the topic description. Mozilla warned about this through the security director on its security blog. I hope it can be fixed so soon.

1- Oracle Security Alert for CVE-2013-0422.
2- Protecting Users Against Java Vulnerability at Mozilla Security Blog.

Wednesday, January 9, 2013

Get ready for JDC 2013

EGJUG has announced about the call for speaker for the JDC 2013 in a post in their website. I missed this amazing event last year but I will do my best this year to be able to attend it. As they say, It's the Java biggest conference in the Middle East and North Africa. I get inspired and I get much of knowledge by attending it. There are always new things to discover by attending this event. Hope to see you there too ;)

2- JDC 2013 call for speaker.

Friday, January 4, 2013

Retrieving a tree in Oracle database SQL

Assume that we have an Employee table with a self relation to represent that each employee has many  managers. There is a solution to retrieve the tree of all the managers for a specific employee in a hierarchical query as a tree in Oracle database SQL using the pseudocolumns. The pseudocolumns behave like a column table but not stored in the database and also are like functions but with no arguments. However, functions without arguments typically return the same value for every row in the result set, whereas pseudocolumns typically return a different value for each row.

The syntax for doing so would be:
SELECT [LEVEL] , column , expr ...
FROM table
[WHERE condition(s)]
[START WITH condition(s)]
[CONNECT BY PRIOR condition(s)]

So for example for employee and his bosses
SELECT ename , empno , mgr
FROM emp
START WITH empno = 7839
CONNECT BY PRIOR mgr = empno ;

Thanks goes to Ahmed Hisham for this information :).

1- Pseudocolumns in Oracle® Database SQL Reference (10.2).
2- Hierarchical Query with example.

Tuesday, January 1, 2013

Syntax Highlighter is enabled

I have enabled Syntax Highlighter in my blog. It's an open source Java Script client side code syntax highlighter. I can say that it's considered as the most used script for that purpose and there are many many people and companies who use it in their own blogs or websites. Check this link to know who else is using it. I have checked the themes provided here and I liked the eclipse theme so it's the one enabled here at the moment. Now it's time to say Hello World!.

 * @author Belal
public class HelloWorld {

  * @param args
 public static void main(String[] args) {
  System.out.println("Syntax Highlighter: Hello World!");

It's important to make sure that the code used with this script is character escaped. Postify would do that for you. So now I can say that the blog is ready to start posting some code snippets, stay around ;)

1- Blog post that shows the steps to enable Syntax Highlighter in your blog.
2- Another useful blog post.
3- Syntax Highlighter by Alex Gorbatchev.
3- Postify for characters escaping.
4- Moreover for characters escaping