Selecting Dialog Box Options Using Keyboard on Mac OSX

I’ve been always annoyed with inability of selecting dialog box on Mac using keyboard like you can in Windows:

mac dialog

Thanks to this rather-old-post there’s actually a way to enable dialog box option selection / cycling using keyboard. Go to System Preferences -> Keyboard and select All Controls under Full Keyboard Access at the bottom:

mac keyboard shortcuts

Keep in mind Return key will always activates the blue button regardless which button has focus. If you want to active the button that has focus (blue border), use spacebar.

Now there’s one less thing for which you shouldn’t take your fingers off keyboard from.

Tomcat & Apache Reverse Proxy

I have to admit Apache HTTPD has one of the most confusing documentation among other tools out there. Here are my Apache & Tomcat requirements:

  • A domain name mycoolwebsite.com pointing to my hosting server
  • Tomcat running on http://localhost:8080 on my hosting (default)
  • Apache HTTP server running on http://localhost:80 on hosting (default)
  • Request to http://mycoolwebsite.com should be reverse proxied into Tomcat without the end-user noticing the port difference

After 2 hours of reading documentation, trial and error, I managed to get this setup working using following Apache Reverse Proxy and VirtualHost configuration:


   ServerName mycoolwebsite.com
   ProxyPass        / http://localhost:8080/
   ProxyPassReverse / http://localhost:8080/
   ProxyPassReverseCookieDomain localhost mycoolwebsite.com
   ProxyPreserveHost On

Configuration Explained

  1. ProxyPass directive will cause request to http://mycoolwebsite.com/foo/bar (and any other paths) be internally forwarded to http://localhost:8080/foo/bar. Internally here means the user will never know — it will look as if the response came from http://mycoolwebsite.com. Behind the screen (on the server) Apache forwards the request and obtain the response to/from Tomcat. The trailing slash (/) at the end of http://localhost:8080/ is important because without it request to http://mycoolwebsite.com/style.css will be internally translated to http://localhoststyle.css (which is wrong).
  2. ProxyPassReverse directive is useful when Tomcat sends HTTP 3xx redirect response. If Tomcat redirects http://localhost:8080/logout into http://localhost:8080/login, your end user will see http://localhost:8080/login unless you place this directive.
  3. ProxyPassReverseCookieDomain directive will cause the cookie domain be re-written into the intended domain. Without this end-user would see localhost as their cookie domain (which is again wrong).
  4. ProxyPreserveHost directive will cause the domain header be forwarded into Tomcat. Without this Tomcat will see the incoming request coming from localhost. This is handy when you’re planning to serve multiple host name under Tomcat.

You can try this on be adding the above configuration into your httpd.conf file (typically located on /etc/httpd/conf/httpd.conf). Once you’ve edited the config, restart apache using sudo apachectl -k restart command.

Spring MVC + Hibernate + MySQL Quick Start From Scratch

This is a tutorial to build a very simple pizzashop Spring MVC, Hibernate and MySQL application. The main page shows all pizza rows stored on a database table:

03

Technology in Java world moves very fast. Using straight Hibernate might no longer be preferable since Java EE 5 introduces JPA (Java Persistence API) but it’s still good to learn anyway. Spring MVC and Hibernate is one of the most popular Java libraries used out there.

Tools / Environment Required
If you’re just starting fresh and don’t have most of the tools below just install JDK, STS (Springsource Tools Suite) and MySQL server, everything else is bundled within them.

Project Setup and Boilerplate

  1. First, create new Maven project on STS. Skip archetype selection. Pick maven group id, artifact id and select packaging to war.01 02

  2. By default Maven will use JDK 1.5, re-configure it to use 1.6. Add following maven-compiler-plugin section to pom.xml under element. Ensure the change takes effect by updating maven project settings (right click on project -> Maven -> Update project…).
    
      
        
          org.apache.maven.plugins
          maven-compiler-plugin
          3.1
          
            1.6
            1.6
          
        
      
    
    

  3. Add Spring, Hibernate, Java EE and MySQL maven dependencies to pom.xml. Place following under element.
    
      3.2.3.RELEASE
      4.2.2.Final
    
    
    
      
      
        org.springframework
        spring-context
        ${spring.version}
      
      
        org.springframework
        spring-webmvc
        ${spring.version}
      
      
        org.springframework
        spring-orm
        ${spring.version}
      
      
      
      
        org.hibernate
        hibernate-core
        ${hibernate.version}
      
      
      
      
        javax.servlet
        servlet-api
        2.5
        provided
      
      
        jstl
        jstl
        1.2
      
      
      
      
        commons-dbcp
        commons-dbcp
        1.4
      
      
        mysql
        mysql-connector-java
        5.1.25
      
      
    
    

  4. Create a web.xml descriptor file with Spring MVC servlet setup on it, place it on src/main/webapp/WEB-INF
    
    
    
      
        appServlet
        org.springframework.web.servlet.DispatcherServlet
        
          contextConfigLocation
          /WEB-INF/servlet-context.xml
        
        1
      
       
      
        appServlet
        /
      
      
    
    

  5. Create src/main/webapp/WEB-INF/servlet-context.xml Spring bean config file for dispatcher servlet. We configure few important stuffs in here:
    
    
    
      
      
    
      
      
        
        
      
      
      
      
      
      
      
        
        
        
        
        
      
      
      
      
        
        
          
            com.gerrytan.pizzashop
          
        
        
          
            hibernate.dialect=org.hibernate.dialect.MySQLDialect
          
        
      
      
      
      
        
      
      
      
      
    
    
    


The Business Functionality

  1. Now all the boilerplate code done, we can start coding the business functionality. For this simple app we will have a pizza database table with just id, name and price column. Create the Pizza entity class representing the table
    package com.gerrytan.pizzashop;
    // imports ..
    
    
    (name = "pizza")
    public class Pizza {
      @Id  private long id;
      private String name;
      private double price;
      /* getters & setters */
    }
    

  2. Create a DAO class to obtain Pizza entity persisted on database. Note that we won’t create service layer classes for the sake of simplicity (on real-life complex business application adding service layer is a good practice).
    package com.gerrytan.pizzashop;
    // imports..
    
    
    s({"unchecked", "rawtypes"})
    public class PizzaDAO {
       private SessionFactory sessionFactory;
      
      /**
       *  annotation below will trigger Spring Hibernate transaction manager to automatically create
       * a hibernate session. See src/main/webapp/WEB-INF/servlet-context.xml
       */
      
      public List findAll() {
        Session session = sessionFactory.getCurrentSession();
        List pizzas = session.createQuery("from Pizza").list();
        return pizzas;
      }
    }
    

  3. Create a Spring MVC controller to handle request from the main page. Note that PizzaDAO reference is injected, and after collection of Pizza entity objects are obtained it’s passed to the view using Model object.
    package com.gerrytan.pizzashop;
    // imports..
    
    
    ("/")
    public class PizzaController {
      
       private PizzaDAO pizzaDAO;
      
      /**
       * This handler method is invoked when
       * http://localhost:8080/pizzashop is requested.
       * The method returns view name "index"
       * which will be resolved into /WEB-INF/index.jsp.
       *  See src/main/webapp/WEB-INF/servlet-context.xml
       */
      (method = RequestMethod.GET)
      public String list(Model model) {
        List pizzas = pizzaDAO.findAll();
        model.addAttribute("pizzas", pizzas);
        return "index";
      }
    }
    

  4. Add a JSP view to list all the pizza entities passed by the controller
    src/main/webapp/WEB-INF/index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    
    
    
    Pizzashop
    
    
            

    List of All Pizzas

    • ${p.id} - ${p.name} - ${p.price}

  5. And finally prepare MySQL pizzashop database schema:
    CREATE SCHEMA `pizzashop`;

    And pizza table:

    CREATE  TABLE `pizzashop`.`pizza` (
      `id` BIGINT NOT NULL AUTO_INCREMENT ,
      `name` VARCHAR(45) NULL ,
      `price` DOUBLE NULL ,
      PRIMARY KEY (`id`) );
    

    And insert some data into it

    INSERT INTO `pizzashop`.`pizza` (`id`, `name`, `price`) VALUES ('I', 'Italian', '7.5');
    INSERT INTO `pizzashop`.`pizza` (`id`, `name`, `price`) VALUES ('2', 'Thin Crust', '6');
    INSERT INTO `pizzashop`.`pizza` (`id`, `name`, `price`) VALUES ('3', 'Pepperoni', '6.2');
    

    It is assumed you have MySQL server running on your local machine (localhost) on the default port 3306. The name of the schema is pizzashop and table pizza. Have a look at Spring beans configuration section above to reconfigure this.

Running The Code

  1. The easiest way to run your code is using in-memory Maven Tomcat plugin. It will launch on-the-fly Tomcat server with your code deployed. Make sure your project is selected on the project exploded and setup a maven run configuration on STS. Go to Run -> Run Configurations.. and create a new maven build entry like this:
    maven goal
  2. Click Run and navigate your browser to http://localhost:8080/pizzashop

Download The Source Code

Source code for this demonstration can be obtained using git:

git clone https://bitbucket.org/gerrytan/pizzashop.git -b basic

Congratz!

Well done on making it this far. Hopefully that was a quick and nice introduction to Spring MVC + Hibernate + MySQL and you can see how the tedious database to java class mapping is now simplified. You might have lots of questions in your mind by now — feel free to ask in the comment section below. Following are few official references and community article links you can browse around:

See Also

Java EE & Spring Cheatsheet

JSTL 1.2 Core JSP Taglib (aka c tag)

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

JSTL implementation jar has to exist on the classpath, eg add following dependency (in provided scope if container doesn’t provides it)


  jstl
  jstl
  1.2

See this blog post for more info.

Spring Taglib

  • Spring:
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
  • Form:
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

JSTL fmt Taglib

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

web.xml deployment descriptor

  • v2.3
    
    
    
      
    
    
  • v3.0
    
    
        
    
    

Commons DBCP / MySQL Spring Bean Config



  
  
  
  
  
  

Hibernate / MySQL Session Factory & Transaction Manager Spring Bean Config



  
  
    
      com.gerrytan.hibernatefiddle
    
  
  
    
      hibernate.dialect=org.hibernate.dialect.MySQLDialect
    
  




  

Log4j Properties File

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n

This will print log in following format:

2013-06-26 10:15:35 DEBUG com.gerrytan.hibernatefiddle.StudentDAO:21 - StudentDAO created

To create file logger, limited to 5 file with max size 1000KB:

# Root logger option
log4j.rootLogger=WARN, file
 
# Rolling file appender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=MyLog.log
log4j.appender.file.MaxFileSize=1000KB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n

If you’re using tomcat the log file typically goes to bin folder. To place it on logs you can use:

log4j.appender.file=${catalina.base}/logs/MyLog.log

Hibernate Logging

log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.engine.transaction=DEBUG

On Hibernate 3 or earlier transaction logger is:

log4j.logger.org.hibernate.transaction=DEBUG

Hibernate 4.2.2 Transactions Logging

I just a hard time trying to enable transactions logging for hibernate. Checked many times and it said the logger name is

org.hibernate.transaction=DEBUG

But not a single logging output is given.

I then dig a bit deeper into the source code. Realized my hibernate version is 4.2.2 (latest doc as of writing this post is 4.2.1) and they seem to have refactored the package name into

org.hibernate.engine.transaction=DEBUG

And yes finally I can see my transactions being logged.

C++ min max Macro When Including Windows API

This is yet another quirks of C++ programming I found (and could be very hard to debug).

When you use Windows API (eg: you have #include ), it will pull min() and max() macro.

Apparently this will cause confusion for the compiler if you’re including another 3rd party library which expects standard library min() and max(). The error message you get is something like this (how obscure is this?):

1>c:mongodbsrcsrcmongodb../bson/bsonelement.h(630): warning C4003: not enough actual parameters for macro 'max'
1>c:mongodbsrcsrcmongodb../bson/bsonelement.h(630): error C2589: '(' : illegal token on right side of '::'
1>c:mongodbsrcsrcmongodb../bson/bsonelement.h(630): error C2059: syntax error : '::'
1>c:mongodbsrcsrcmongodb../bson/bsonelement.h(630): error C2143: syntax error : missing ';' before '{'

To avoid pulling the macros from Windows API, hash define following:

#define NOMINMAX

Merging Git Conflicts On Github

This article applies to following environments (but conceptually it can be applied to any environment):

  • Github
  • Windows 7

If you’ve been relying on the github GUI, you may get (very) annoyed when the conflict screen appear (Failed to sync this branch due to unmerged files)

gitmerge

This is few (often not so) simple steps to resolve the conflicts:

  1. Click OPEN SHELL, a windows powershell will come up
  2. Start by running git status, this command will help you as you progress resolving the conflict. It also contain pretty clear instruction on how to mark a file resolved, and how to finish conflict resolution
  3. In this examply (luckily) I only have 1 file in conflict hello.txt. Open it using a text editor, and edit the conflict. Conflicts are presented in a unified diff format:
    hello world
    <<<<<<< HEAD
    mary
    =======
    bobby
    >>>>>>> bobby
    the many
    testing
    file
    

    Above example is saying you changed the 2nd line to “mary”, but your colleague changed it to “bobby”. You now have to decide either (or merge both).

  4. For every conflict you resolved, you can tell git so by git add command, eg: git add hello.txt
  5. Once all conflicts are resolved do git rebase –continue command (if you’re in rebase mode — sometime github will use other conflict resolution and will tell you what command to run when completed)

Deploying Standalone Java Project

There are two common approaches to deploy a Java program in a standalone environment:

Single (Uber Jar) Approach

“Uber Jar” is a single jar with all dependent classes and resources are dumped inside. This can be done easily using Maven assembly plugin:



  org.apache.maven.plugins
  maven-assembly-plugin
  2.3
  
    
      jar-with-dependencies
    
  

mvn clean package assembly:single

However this method could be faulty. Multiple dependency jars could have configuration file with the same path and they will overlap each other. For example both spring-context.jar and spring-beans.jar has META-INF/spring.handlers file:

spring-context-3.2.3.RELEASE.jar/META-INF/spring.handlers
spring-beans-3.2.3.RELEASE.jar/META-INF/spring.handlers

Exploded Deployment Approach

This slightly take more effort, but saver approach. Instead of dumping everything in a Uber Jar, deploy in an exploded fashion. You can get all runtime dependencies (that is “runtime”, “compile” and “provided” maven scope) placed inside target/dependency folder by configuring maven-dependency-plugin:



  maven-dependency-plugin
  2.8
  
    
      
        copy-dependencies
      
      
        runtime
      
    
  

Then deploy your jar in production server in directory structure similar like following

C:myscript
  +-- dependency
        +-- dep1.jar
        +-- dep2.jar
        +-- dep3.jar
  +-- myjar.jar
  +-- run.bat

The run.bat script is a simple java program to run your code (assuming MainClass name of com.mycompany.MainClass)

java -jar "./*;dependency/*" com.mycompany.MainClass

Using BeanUtils Reflection to Print HTML Table Without Hardcoding the Column

Apache Commons BeanUtils is a little (very) useful library you can use to perform metadata reflection work on the runtime. To use it with Maven, add following dependency (check http://search.maven.org for latest version)


  commons-beanutils
  commons-beanutils
  1.8.3

Supposed you have a simple domain class that represent a user with 3 properties (name, age, weight) like this

public class User {
        private String name;
        private int age;
        private int weight;
        
        /* Getters & Setters */
}

You can get all the name of the properties on the runtime simply by using describe method of BeanUtils

User u = new User();
Map props = BeanUtils.describe(u);

// Below will print [weight, name, age, class]
System.out.println(props.keySet());

Which means.. you can use BeanUtils to introspect your property names and do useful stuff .. eg: printing HTML table without even hardcoding the column

// Print headings
sb.append("");
for(String prop : props) {
  if(prop.equals("class")) continue; // we don't need the class name
  sb.append("" + prop + "");
}
sb.append("");

// Print rows
for(User u : users) {
  sb.append("");
  for(String prop : props)  {
    if(prop.equals("class")) continue; // we don't need the class name
    sb.append("" + BeanUtils.getProperty(u, prop) + "");
  }
  sb.append("");
}

And of course you have to take this further. Eg: on Spring MVC you can do similar thing: dump all the column name and values into your model object, and you can have a generic view that prints all sorts of domain object collection into a table.

How cool is that :).

Creating New Java EE 7 Maven Eclipse Project

Still on the Java EE 7 hype, here’s a quick cheat sheet on how to create a minimal Java EE 7 ready maven project:

  1. Ensure you have Eclipse Indigo installed with m2e (maven connector). If not you can drag and drop this logo into running Eclipse instance

    (thanks m2e team)
  2. Create new maven project, tick Create a simple project (skip archetype selection), on the next screen provide Group Id, Artifact Id, and set Packaging to war. Hit Finish
    new maven proj cut
  3. Open pom.xml, switch to source view. Add Java EE 7 dependency. Set the scope to provided so that it is included at compile time, but not on the war bundle (because it should be provided by container)
    
      4.0.0
      com.gerrytan
      jee7fiddle
      1.0
      war
      
      
      
        
          javax
          javaee-api
          7.0
          provided
        
      
    
  4. Tell Maven to compile using JDK 7, otherwise the deafault is JDK 5
      
        
          
          
            maven-compiler-plugin
            3.1
            
              1.7
              1.7
            
          
    
  5. And finally prevent maven-war-plugin from complaining because of missing web.xml. New Java EE 7 style provides good annotation support, web.xml can be omitted for a simple project
          
          
            maven-war-plugin
            2.3
            
              false
            
          
        
      
    
    
  6. Right click on the project -> Maven -> Update Project… -> OK. This will cause m2e to synchronize with all changes we made
  7. Test your new project by running clean package
    maven run cut
    You should end up with a war bundle with your project name under target directory