Wednesday, October 30, 2013

Setup Derby from scratch

The very first step after Derby is install is to create a database. In order to create a database, I must have a command prompt ready. And then decide where am I going to put my database. Assume I'll create the database in this path /home/derby/ (if derby folder doesn't exists, created one), make sure the current directory is showing /home/derby when pwd command is issued. After this, I am going to launch Derby ij tool to create the database. Try either one of the following command to launch that tool:

  1. java -jar $DERBY_HOME/lib/derbyrun.jar ij
  2. $DERBY_HOME/bin/ij

This is very important, this tool must be launch where the database is going to create. If the database create under /home/the_database directory, make sure the current directory is locate at the_database, no elsewhere. Otherwise an error message say Unable to establish connection will shown.

Now issue this command to create a database > connect 'jdbc:derby:thedb;create=true', a new folder named thedb will be created under the /home/derby directory. Usually a database will come with user authentication to ensure the data are secure. Unfortunately Derby set this configuration to false by default. To enabled user authentication, make sure derby.properties is exists in Derby installation path. If not, create it. The content should look like below. Replace username with your prefer user ID, and password with your desire password.

derby.connection.requireAuthentication=true
derby.user.username=password

To connect the database, use this command > connect 'jdbc:derby:DB_name;user=username;password=password'; Alternately, it can also be connect in this way > connect 'jdbc:derby:DB_name' user='username' password='password'; Since I am setting up the Derby for R&D on my local PC, and I have no intention to do serious work, thus I am keeping the authentication as simple as possible.

Sunday, October 20, 2013

Return immediately after exception has been capture.

I was being captured by exception. You know what? I miss out the very important point on Exception Handling in JAVA. Let’s take a look on the code below:
public static void main(String args[]) {
 System.out.println("Before Exception");
 
 try {
  System.out.println("Before throw");
  System.out.println(args[1]);          // (1)
  System.out.println("After throw");
 }
 catch( Exception e ) {
  System.out.println(e);                // (2)
 }
 finally {
  System.out.println("Cleaning resources");
 }
 
 System.out.println("After Exception");    // (3)
}
When there is an exception error on (1), immediately (2) will get invoked. Somehow the code will never stop executing after (2) and will continue its execution until (3). This could lead to a disaster if subsequent implementation is highly depends on the process in try block. Thus to play it safe, return the code immediately if exception is being capture in the catch block. No worry on the finally block because the code will still execute giving me a chance to clean up my resources.

ReferenceError: "myfaces" is not defined.

I was running a Blackbox unit testing on a page consisting of JSF page using Selenium 2. If I were to use FirefoxDriver to run the test, the test completed successfully. But if I run the test using HtmlUnitDriver, it will fail and following error would be seen.
java.lang.RuntimeException: org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "myfaces" is not defined.
Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_30'
Driver info: driver.version: HtmlUnitDriver
 at com.anteambulo.SeleniumJQuery.jQueryFactory.js(jQueryFactory.java:124)
 at com.anteambulo.SeleniumJQuery.jQuery.js(jQuery.java:608)
 at com.anteambulo.SeleniumJQuery.jQuery.jsref(jQuery.java:612)
 at com.anteambulo.SeleniumJQuery.jQuery.click(jQuery.java:226)
 at org.huahsin.authentication.ForgotPassword.testEmptyLoginId(ForgotPassword.java:32)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
 at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
 at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
 at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "myfaces" is not defined.
Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', java.version: '1.6.0_30'
Driver info: driver.version: HtmlUnitDriver
 at org.openqa.selenium.htmlunit.HtmlUnitDriver.executeScript(HtmlUnitDriver.java:497)
 at com.anteambulo.SeleniumJQuery.jQueryFactory.js(jQueryFactory.java:115)
 ... 29 more
Caused by: com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "myfaces" is not defined.
 at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:669)
 at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:601)
 at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:507)
 at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:601)
 at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:576)
 at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:1005)
 at org.openqa.selenium.htmlunit.HtmlUnitDriver.executeScript(HtmlUnitDriver.java:491)
 ... 30 more
Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: ReferenceError: "myfaces" is not defined.
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3603)
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3587)
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:3657)
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:1749)
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.name(ScriptRuntime.java:1690)
 at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1622)
 at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:798)
 at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
 at com.gargoylesoftware.htmlunit.javascript.host.EventHandler.call(EventHandler.java:81)
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2378)
 at net.sourceforge.htmlunit.corejs.javascript.BaseFunction.execIdCall(BaseFunction.java:304)
 at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:89)
 at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1531)
 at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:798)
 at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
 at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:405)
 at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:275)
 at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3031)
 at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:103)
 at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$4.doRun(JavaScriptEngine.java:594)
 at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:654)
 ... 36 more

As I search through the documentation, the default JavaScript engine of HtmlUnitDriver is from Rhino. Somehow not every browser following the same standard and have their very own version of implementation on JavaScript.

This is the text extract from the documentation:
When we say "javascript" we actually mean "javascript and the DOM". Although the DOM is defined by the W3C each browser out there has its own quirks and differences in their implementation of the DOM and in how javascript interacts with it. HtmlUnit has an impressively complete implementation of the DOM and has good support for using javascript, but it is no different from any other browser: it has its own quirks and differences from both the W3C standard and the DOM implementations of the major browsers, despite its ability to mimic other browsers.
To fix this issue, a true parameter need to be pass in to the constructor of HtmlUnitDriver as shown below. This is to mimic the JavaScript version running on Internet Explorer.
   ...
   new HtmlUnitDriver(true);
   ...

Tuesday, October 15, 2013

Effective way to cure VirtualBox

Sometimes the VirtualBox were just get stuck; sometimes the /etc/init.d/virtualbox were just missing in action; sometimes I can't even start the VM. This is so much irritating to me. No worry, I found a new ways to cure VM without reinstalling the whole package.

Follow this steps
  1. sudo apt-get install build-essential linux-headers-`uname -r`
  2. sudo dpkg-reconfigure virtualbox-dkms
  3. sudo dpkg-reconfigure virtualbox

Why SimpleGrantedAuthority cannot be resolve to a type?

I am using Spring Security 3.0.8, and have the following code:
    public class MyAuthServiceProvider implements UserDetailsService {
        ...
        ...
        public static List< GrantedAuthority > getGrantedAuthorities(List< String > roles) {
         List< GrantedAuthority > authorities = new ArrayList< GrantedAuthority >();
         for( String role:roles ) {
          authorities.add(new SimpleGrantedAuthority(role));
         }
         return authorities;
        }
    }
As mention in the title, SimpleGrantedAuthority couldn't be resolve. There are 2 solutions on this, the first one is to replace SimpleGrantedAuthority with GrantedAuthorityImpl as shown below:
    ...
    authorities.add(new GrantedAuthorityImpl(role));
    ...
The second one is to replace SimpleGrantedAuthority with SwitchUserGrantedAuthority, but I need to implements AuthenticationProvider. I refuse this solution because I feel that (correct me if I'm wrong) this doesn't sound right for MyAuthServiceProvider to implement AuthenticationProvider and UserDetailsService at the same time.

I'm sure I have include spring-security-core library in MAVEN. May I know what else was missing causing this error on SimpleGrantedAuthority? It has been confusing me for a long time, now I got the answer. SimpleGrantedAuthortiy is a replacement of GrantedAuthorityImpl, and this class will be deprecated in Spring Security 3.1. In addition, both of this class are implementing GrantedAuthority, have a look here for SimpleGrantedAuthority and GrantedAuthorityImpl. Thus it has no issue since both of them implementing the same function.

To conclude this, since I'm using version 3.0, then I am safe to use GrantedAuthorityImpl class.

Monday, October 7, 2013

How to handle commandLink in Selenium 2?

My initial assumption on the link is constructed using <a href...="">. Thus when I initiate my test using following code, it was failed unexpectedly.
WebElement clickMe = webDriver.findElement(By.partialLinkText("Click Me"));
clickMe.click();
Why this happened? I have double verify on my code, it just looking fine. But when I view the page’s source, I got the following code in my mind.

    Click Me

Doesn’t it sound funny? Consider the page was build using JSF and the link is construct using commandLink in JSF like this:


I wasn’t sure the background on how JSF is render on the browser. But one thing I am sure is the link has JavaScript. Without further ado, my temporary solution is to workaround the JavaScript using third party library called SeleniumJQuery. It is quite straight forward to use and pretty simple, to click on the link containing JavaScript, do this code:
jQueryFactory jq = new jQueryFactory();
jq.setJs(webDriver);

WebElement clickMe = webDriver.findElement(By.partialLinkText("Click Me"));
jq.query(clickMe).click();
It will work like charm.

AnnotationConfiguration is deprecated?

The SessionManager utility class is the famous one among JAVA programmer who has been working with Hibernate.
public class SessionManager {

 private static final SessionFactory sessionFactory = buildSessionFactory();
 
 private static SessionFactory buildSessionFactory() {
  
  try {
   return new AnnotationConfiguration().configure().buildSessionFactory();
  }
  catch( Throwable e ) {
   
   throw new ExceptionInInitializerError(e);
  }
 }
 
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

Unfortunately, I just realize that AnnotationConfiguration has already been deprecated Since Hibernate 3.6. Do you know what is the new implementation of this class? Well, replace this with Configuration.

Do you save login password in Keystore?

I don’t know the real use of Keystore? But I do know it was a file created using keytool provided by JDK. What I’m concern about is do you keep username and credential of a web application in keystore? The feedback I got from forum is not encourage to do so because Keystore is a file, keeping this file somewhere else will create additional vulnerabilities.