Category: Java

How to mock static methods : PowerMock

1. First check versions of Junit being used and download matching PowerMock.
2. Those are the dependencies that you will need if you are using Mockito already:
<dependency org="org.powermock" name="powermock-module-junit4" rev="1.4.12" />
 <dependency org="org.powermock" name="powermock-api-mockito" rev="1.4.12" />
powermock-module-junit4 : this provides integration with Junit4
powermock-api-mockitor : this provides PowerMock classes to work with Mockito
3. Usage is quite simple. Check the link above.
– include those annotations on the class level:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ControllerUtil.class)
– include the following line first (if you have @Before method, it’s best to keep it there)
PowerMockito.mockStatic(ControllerUtil.class);
– do the mocking:
Mockito.when(ControllerUtil.roleExists(anyString())).thenReturn(true);

 

Absent Code attribute in method

I needed to include @RolesAllowed annotation into the project.
For that I’ve used the following IVY dependency:
<dependency org=”javax” name=”javaee-api” rev=”6.0″ conf=”compile->default”/>
This dependency basically provides interface to most of java ee components without implementation.
Hence, it is usually used to compile the project, because implementation is usually within the web container (eg. Tomcat).

However, the project used to fail with an error above whenever I ran ant test task.
Mock of HttpServletRequest object was failing. My guess is that reflection was trying to go deeper into actual implementation which dependency above does not provide.

It was even harder to spot, because IDE was running all tests just fine. Probably, because classes were loaded in a different order in IDE and in ANT.
JVM grabs whichever class is loaded first and ignores the next one, hence error did not show in IDE.
IDE was loading full implementation, while ANT was loading interface (dependency above) first.

Getting a smaller jar file that contains implementation of javax.annotation.security package helped solve the problem.
<dependency org=”javax.annotation” name=”jsr250-api” rev=”1.0″ conf=”compile->default”/>

Good times!

org.tigris.subversion.javahl.ClientException: svn: No repository found in …

This happened when I was trying to use repository from Eclipse using Subclipse plugin. The first time I was setting up repository in Eclipse I specified password based authentication, password was memorized and never asked again (because I clicked on checkbox to memorize it).

Because Subclipse and JavaHL got compatibility issues, and the error was mentioning JavaHL I was thinking problem is still with Subclipse and JavaHL versions incompatibility. Tried to re-install different Subclipse versions. Didn’t help.

So, here goes solution:

1. Clean passwords saved in Eclipse. Remove .keyring file from (eclipse_installed_dir/configuration/org.eclipse.core.runtime/)

2. Change authentication type to File based and specify path to your ~/.ssh/id_rsa (note, not id_rsa.pub)

3. Do any SVN action (update / commit / checkout … )

Deploy multiple virtual hosts on Tomcat 6

Dedicated to those of you who have spent TOO much time on this way under-documented topic:

First let’s start with a tomcat file structure.

TOMCAT FILE STRUCTURE

1. webapps – folder where applications should be placed to run (unless unpackWARs is set to false)
2. work/Catalina/host_name – place where temporary files are created when Tomcat is running, eg: servlet classes
When “unpackWARs” is set to false (in server.xml) entire site structure is created
* we should not care about this directory much because it is generated dynamically each time

DEPLOYING HOSTS without actual file structure
Add line as follows, and that’s it:

<Host name=”xxx” appBase=”webapps”
unpackWARs=”false” autoDeploy=”true”
xmlValidation=”false” xmlNamespaceAware=”false” >
<Context path=”” docBase=”/wherever/xxx.war” debug=”0″ reloadable=”true”/>
</Host>

* note: this way application FILE STRUCTURE is not created, probably because “webapps” folder cannot be used. Not sure about this one though, whatever the reason is what is important that no error messages are generated and application gets created in work/Catalina directory and, apparently, works happily from there.

– The problem with this approach is that if we cannot deploy web application that will read files on the server side.
– Application will fail to find files on the server, because files do not exists. Actually they exist in work/Catalina directory, however it is not the path application looks for while running. Application MUST be physically located in WEBAPPS directory for files to be found.

DEPLOYING HOSTS with actual file structure (THE RIGHT WAY!)
Add line as follows:

<Host name=”xxx” appBase=”webapps/xxx”
unpackWARs=”false” autoDeploy=”true”
xmlValidation=”false” xmlNamespaceAware=”false” >
<Context path=”” docBase=”/wherever/xxx.war” debug=”0″ reloadable=”true”/>
</Host>

Create directory in webapps folder called xxx. Copy-paste “manager” and “host-manager” directories from “webapps” directory to this directory. This step is very important, otherwise you will get this extremely annoying error in log files:

SEVERE: Error starting static Resources

…xxx/host-manager does not exist or is not a readable directory

Some online documentation will claim that you will need to mess with /conf/Catalina/xxx folder. Maybe with older Tomcat versions you will need to do that. I tested with version 6.0.32, all files in that folder are automatically generated.

Hope it makes someone’s life easier!

Java frameworks popularity trends

I couldn’t compare words such as Struts and Spring, because they are used very extensively in other contexts as well.

Hence, I used, as a common denominator, word JAVA. Which might under-estimate the frequency of such words as GWT, because it is not usually used together with “Java” word.  Nevertheless, we can see the trends, at least the growth rates.

java jsf, java spring, java struts, java gwt, java ejb

Things to notice:

– Spring is steady, and seems to be the most popular so far

– Struts is dying

– JSF started very well, but seems to be steady now (still not as popular as Struts though)

– GWT is not mainstream, but again it is hard to say anything for sure

Argument passing in Java revisited

They say “It doesn’t matter till it affects you directly”… very right so!

Recently when doing a Swing application I was amazed how object passing seems to throw surprises at times. In short, object changed / reassigned in one class/method does not always change in another class/method. Hence, my assumption that objects are passed by reference in Java needed some clarification.

That’s when I started delving into more details of the mysterious “argument passing” in Java, which I always tried to avoid by just grabbing the basics. Here is what I discovered:

Arguments are ALWAYS passed by value in Java.

What I knew before was that in Java:

– primitive variables are passed by value

– objects are passed by reference

However, this was “pseudo-truth”. As a matter of fact, in Java all object variables are just “pointers” (references) to the memory locations. This fact is hidden by Java that’s why many developers don’t even know about it.

When such a “reference” is passed as an argument it’s copy is created (which points to the same memory location), hence we have an illusion that objects are passed by reference. But here is where problem occurs. Consider the code below:

swapper(Object x, Object y){
	Object temp = y;
	y = x;
	x = temp;
}

One might consider this function helps to swap variables in an easy way. But it DOESN’T!

The reason is because variables x and y are now local to “swapper” method. Hence, reassigning them would mean nothing to the “calling” method.

NOTE: As expected, changing state of x and y objects within a “swapper” method affects x and y objects in “calling” method.

Hibernate with DB Visual Architect tool from VisualParadigm

Important things to note:

1. If you want to see “relationship” fields in generated classes -> in ERD (Entity Relationship Diagram) -> right click on the property -> open specifications -> generated: always
2. Note that it will also require property to be set as NULLABLE and have a default value (i use NULL)
1. If working with NetBeans check that error is not actually happening somewhere in the code. Especially if it says something like:
ERROR JDBCExceptionReporter:101 – Unknown column ‘ParentId’ in ‘where clause’
In addition, compiler will not show you the exact position in the code.
I was so frustrated, I actually started doing manual Hibernate code… till I decided to give it a final try!

Ant and Tomcat error: Tried to use command /reload via a GET request but POST is required

When using Ant builder to restart Tomcat 7 server I came across the following error:

Tried to use command /reload via a GET request but POST is required

Here is a piece of code from Ant builder script:

	<target name="reload" description="Reload application in Tomcat">
		<reload url="${tomcat.manager.url}" username="${tomcat.manager.username}" password="${tomcat.manager.password}" path="/${name}" />
	</target>

With a new Tomcat 7 a very special role (called “manager-script”) is required to run GET commands. Regular web based “manager” application allows POST commands only. Therefore, we need to bind “manager-script” to a user at hand.

<tomcat-users>
<user name="user" password="password" roles="admin-gui,manager-gui,manager-script" />
</tomcat-users>

Note, that we don’t need to specify roles like before. Roles are predefined by default .

In addition, note that a new Tomcat manager URL is as follows:

tomcat.manager.url=http://localhost:8080/manager/text