Sunday, May 26, 2013

JavaScript is a Revolutionize myths

Frankly speaking, I personally feel that JavaScript is a toy language?
No, not that way. JavaScript has make a lot of improvement due to the brain from the Safari, Firefox, and Chrome, it has already become a lot more faster now. And getting more fun and interesting.
This programming language is a design fault.
Before JavaScript, there are HTML and CSS. HTML is responsible for the structure of the web content; CSS is responsible for adding in style to bring some color and life to the content. Whereas JavaScript is like a controller that could control the behavior of the content, and it works together with HTML and CSS.
Programming JavaScript is a real fun.
Since it doesn't need any fancy tool, just a simple notepad to do the coding and then load it up into the browser and it just run. Thus it should be the first programming language teach to the student. But during my time, although I did attend to this class but I don't find my interest on it as C++ is my interest during that time.

 

Connecting Derby...

This is a real annoying every time I come to connecting Derby, I just can't remember the command. After few hours searching, this command is the most friendly to remember.

connect 'jdbc:derby:mydb' user 'username' password 'abcd1234';

Friday, May 24, 2013

Grant read permission to spring.security.strategy to Tomcat 6

I have a Spring project initially was developed on computer A, it is working fine and no error. When I transfer it to computer B, I got this error during the Tomcat start up:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.context.HttpSessionSecurityContextRepository#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.context.HttpSessionSecurityContextRepository]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:964)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
 at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282)
 at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204)
 at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4205)
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:4704)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
 at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
 at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
 at org.apache.catalina.core.StandardService.start(StandardService.java:525)
 at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
 at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
 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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.context.HttpSessionSecurityContextRepository]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
 at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:141)
 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:74)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$3.run(AbstractAutowireCapableBeanFactory.java:952)
 at java.security.AccessController.doPrivileged(Native Method)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:950)
 ... 28 more
Caused by: java.lang.ExceptionInInitializerError
 at org.springframework.security.web.context.HttpSessionSecurityContextRepository.(HttpSessionSecurityContextRepository.java:62)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
 at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
 at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126)
 ... 32 more
Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission spring.security.strategy read)
 at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
 at java.security.AccessController.checkPermission(AccessController.java:549)
 at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
 at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1285)
 at java.lang.System.getProperty(System.java:650)
 at org.springframework.security.core.context.SecurityContextHolder.(SecurityContextHolder.java:53)
 ... 38 more
May 24, 2013 9:52:10 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.context.HttpSessionSecurityContextRepository#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.context.HttpSessionSecurityContextRepository]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:964)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
 at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282)
 at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204)
 at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4205)
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:4704)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
 at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
 at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
 at org.apache.catalina.core.StandardService.start(StandardService.java:525)
 at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
 at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
 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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.context.HttpSessionSecurityContextRepository]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
 at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:141)
 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:74)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$3.run(AbstractAutowireCapableBeanFactory.java:952)
 at java.security.AccessController.doPrivileged(Native Method)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:950)
 ... 28 more
Caused by: java.lang.ExceptionInInitializerError
 at org.springframework.security.web.context.HttpSessionSecurityContextRepository.(HttpSessionSecurityContextRepository.java:62)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
 at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
 at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126)
 ... 32 more
Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission spring.security.strategy read)
 at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
 at java.security.AccessController.checkPermission(AccessController.java:549)
 at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
 at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1285)
 at java.lang.System.getProperty(System.java:650)
 at org.springframework.security.core.context.SecurityContextHolder.(SecurityContextHolder.java:53)
 ... 38 more
This is so mysterious. But anyhow, I got the solution on this problem in Spring forum where I'm required to grant the read permission to spring.security.strategy. Do this in catalina.policy under the <tomcat_dir>/conf:
    permission java.util.PropertyPermission "spring.security.strategy", "read";
    permission java.lang.RuntimePermission "accessDeclaredMembers";
    permission java.net.SocketPermission "127.0.0.1:3306", "connect, accept";
Do take note that by adding the permission to spring.security.strategy is not enough. After this permission has been granted, there will subsequent permission error showing up. To avoid this, I also need to grant others permission as shown in the code above.

Alternative solution on PreRenderView

Usually when I want to determine whether the page is first loaded, I will put the following code in Facelet template.

    

Unfortunately that solution does not work under JSF 2.0 and below. The alternative is to add beforePhase attribute name right inside the <f:view> tag like this:

On the action class, add following code to perform the necessary task need to be complete before a page is render:
    public void doPreRenderView(PhaseEvent event) {
      
      if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
        // do your stuff
      }
    }

Can not find Facelets taglib in JSP


This is an old project develop using JSP, my plan was to inject some new element into this project. I got the error Can not find the tag library descriptor for http://java.sun.com/jsf/facelets when the following line was included in this JSP page:

< %@ taglib uri="http://java.sun.com/jsf/facelets" prefix="ui"% >

This is impossible because Facelets is to replace JSP, it is a XML based view technology which is designed to be a successor of JSP. If I do this, this is definitely a brainless move. No choice, in order to use Facelets, I must have XHTML but not JSP.

Alias in Java

There is a very interesting question I got in the JAVA exam. Take a look at the following code, when does the object at line marked (0) will be the candidate for garbage collection?
String objA = “ABC”;  // (0)
String objB = a;

objA = “DEF”;  // (1)
objB = “GHI”;  // (2)
The answer is the line marked (2). Why not the line marked (1)? Because String objB is holding a reference of objA thus it will not get garbage collected. Until line marked (2), objB is assigned a new object, objA is no longer get reference by objB or no other objects are holding a reference of it, thus this is the great chance to dispose the object.

Saturday, May 18, 2013

Bootstrap.jar was not found in classpath?

I was working on Tomcat 7 and I suspecting there are some problem with my existing Tomcat installation, thus I decided to re-download again to make sure a clean copy was use in my development. This time I download it into another folder name to ensure the old Tomcat directory is no longer using. Here is the problem, when I start the server, I get the following error:

The archive: D:/tool/Tomcat7/bin/bootstrap.jar which is referenced by the classpath, does not exist.

What a joke? My existing project (in Eclipse) was not reflected by the new Tomcat location? No, not that way. I mean take a look at the server classpath, goto Run -> Debug/Run Configuration -> Classpath tab, notice that the new bootstrap.jar path was there but the old path were still remain. Thus I have to manually remove the one and put the new one in exactly the same order as the existing one.

Transition from Mockito to PowerMock

There was an error throwing out when I change the mocking framework from Mockito to PowerMock. See this error stack:

java.lang.ExceptionInInitializerError
 at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.(ConditionalStackTraceFilter.java:17)
 at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:30)
 at org.mockito.exceptions.base.MockitoException.(MockitoException.java:19)
 at org.mockito.exceptions.misusing.MockitoConfigurationException.(MockitoConfigurationException.java:18)
 at org.mockito.internal.configuration.ClassPathLoader.loadImplementations(ClassPathLoader.java:145)
 at org.mockito.internal.configuration.ClassPathLoader.findPluginImplementation(ClassPathLoader.java:110)
 at org.mockito.internal.configuration.ClassPathLoader.findPlatformMockMaker(ClassPathLoader.java:106)
 at org.mockito.internal.configuration.ClassPathLoader.(ClassPathLoader.java:59)
 at org.mockito.internal.util.MockUtil.(MockUtil.java:21)
 at org.mockito.internal.MockitoCore.(MockitoCore.java:40)
 at org.mockito.Mockito.(Mockito.java:932)
 at org.huahsin.BuilderTest.(BuilderTest.java:41)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
 at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
 at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.createTestInstance(PowerMockJUnit44RunnerDelegateImpl.java:188)
 at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.createTest(PowerMockJUnit44RunnerDelegateImpl.java:173)
 at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:195)
 at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
 at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
 at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
 at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
 at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
 at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
 at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
 at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
 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: java.lang.NullPointerException
 at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.(StackTraceFilter.java:21)
 ... 33 more

I don’t know where this stupid NullPointerException came from? The java.lang.ExceptionInInitializerError is real misleading, and I was being fool with this stupid error. If I am able to realize that MyTestClass has implement PowerMock framework already, then the mock implementation should also has to change accordingly. The actual problem on this error is that I was mess up the mock framework where I suppose to use the PowerMock’s API instead of Mockito’s API.

This is the code that causes the error shown above.

@RunWith(PowerMockRunner.class)
@PrepareForTest(CommonDao.class)
public class MyTestClass {

   private static TheMockClass theMockClass = Mockito.mock(TheMockClass.class);
}

To resolve this issue, use PowerMock.mock(TheMockClass.class); when initialize a mock object.

Sunday, May 12, 2013

Have some fun with encryption and decryption

I just had some fun with gpg command on Windows. Basically when I first download and install from the Gpg4win site, the first thing I am going to do is to encrypt a file, called secret_file.txt. No! Wait! Before this can be done, gpg need to be setup first.

Do this: gpg --gen-key

A series of interview question, just answer them accordingly. No worry, just a very simple question, you should able to answer. After this, get ready to encrypt the file.

Sending out this command: gpg --encrypt --recipient secret_file.txt

This will generate an output file, called secret_file.txt.gpg. To decrypt the encrypted file, send this command:

gpg --output secret_file.txt --decrypt secret_file.txt.gpg

Enjoy!

Wednesday, May 1, 2013

When there is a class inherited from parent class, how could I mock the parent class with Mockito?

Unit testing consisting of running a series of test case on the particular unit/module, in this case, the unit is referring to a JAVA class. This should not be a problem if it is a standalone class, but things started to get complicated when it comes to inheritance where the parent class is doing all the preliminary work for a child class.

When this is the case, it is impossible for me to execute the test on parent class since the scope of this test is only focus on the child class, which is mine module. It is worth the effort if I could mock the parent class regardless of whether the parent class is running correctly or not and I'll just concentrate on my module.

This is the code snippet I'm trying to do how it could be done.
public class ClassA {

 private int a = 1;
 
 public int getA() {
  return a;
 }
}

public class ClassB extends ClassA {

 private int b;
 
 public int getB() {
  return getA() + b;
 }
 
 public void setB(int b) {
  this.b = b;
 }
}

public class TestMainApp {

 ClassA a;
 ClassB b;
 
 @Before
 public void setup() {
  
  a = Mockito.mock(ClassA.class);
  Mockito.when(a.getA()).thenReturn(2);
 }
 
 @Test
 public void testFunctionA() {
  
  b = new ClassB();
  b.setB(a.getA());
  
  assertEquals("testFunctionA()", b.getB(), 3);
 }
}
In this sample, I am trying to mock the parent class, ClassA to return me a value 2 instead of 1, and pass it to ClassB will return me 3. Thus the output of this test is success.

Import local source code into empty repository using GIT

Today I just setup Bitbucket account, feeling so excited to give it a try. Setting up account is as easy as one two three. When come to import the existing code from my local hard drive into my own remote repository, Git give me a surprise!!

fatal: Not a git repository (or any parent up to mount point /home)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).

What kind of nasty error is this? This seem to me that Git couldn't find any Git info on my workspace. I think this could be a false alarm because I don't have any local Git repository being setup yet. There should be some configuration need to be done.

Searching in Stackoverflow.com I found a guide on how could I import the source from local to Git repository without 'cloning' the remote first. Put in other words, I have the empty repository created then only I push my source into it.

Here is the step:
  1. Create the remote repository.
  2. git init.
  3. git add.
  4. git commit -m "initial commit".
  5. git remote add origin .
  6. git push origin master.
After the source is being push into the repository, following output should be seen.
Counting objects: 34, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (34/34), 6.57 KiB, done.
Total 34 (delta 3), reused 0 (delta 0)
remote: bb/acl: huahsin68 is allowed. accepted payload.
To https://huahsin68@bitbucket.org/huahsin68/jaassampleproject.git
 * [new branch]      master -> master