Using mock object with jmock 2

Okay, finally you decide it’s time to create a unit testing for your project (after a long ad hoc programming life :p).
When you create a sample unit testing, it’s all seem so simple.. you fascinate by the junit easiness, how it can do reflection and make it simple.

When you want to create a real unit testing for your project, you realize that a ‘real’ method is not like just adding 2 int argument and return a result. It’s more complex and using interface as parameter is common…
Now a thought cross your mind “do I have to create all stupid classes to implement all the interface I need?”, you starting to think that creating unit testing is really waste of time & you don’t want to do it anymore :p

It’s time mock object framework come to rescue… before you fall to the darkness of untested code :)
There’re several mock object framework like jMock, easymock, etc

Here’s an example creatin HttpMethod mock-object with jMock 2 & JUnit 3

[sourcecode language='java']
public class sampleJMockTest extends MockObjectTestCase {
public void testCreateHTTPMethod() {
final HttpMethod httpMethod = mock(HttpMethod.class);
checking(new Expectations() {
{
allowing(httpMethod).getResponseBodyAsString();
will(returnValue(“sample response”));
}
});
SomeObject someObject = new SomeObject();
someObject.someMethod(httpMethod);
}
}[/sourcecode]
This sample will create an instance of HttpMethod (which is an interface) and when this mock object’s ‘getResponseBodyAsString’ method called it’ll return “sample response”.
So now we can easily create all interface implementation we need.Of course there’re more in jMock than just this simple feature, check it more at jMock Cookbook

Java – Adding new Classpath at Runtime

There are cases where we need to add classpath at runtime. For example adding jar to classpath, but depends on configuration or some logic at runtime.

The class who responsible for handling classpath list is URLClassloader.
You can get current system URLClassLoader with:
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

If you check javadoc about this class you’ll see:

protected void addURL(URL url)
Appends the specified URL to the list of URLs to search for classes and resources.

So you’ll just need to call the addUrl method to add new path/jar file.
But wait a minute, the method is protected… :( do I need to create a subclass or put the caller class on same package?
Creating a subclass is one way to do it, but there’s simpler way (I’ll create article about creating URLClassLoader subclass next time :p)

Here come the savior : Reflection
By using reflection we can break OOP concept about encapsulating method. It’s feel good to break the rules right (warning : use this at your own risk, you know you’re breaking the OO rule. So I won’t responsible if your computer explode or you’ll fighting with OO fans because of this)

Here a sample how to called it with reflection:
[sourcecode language='java']
public static void addPath(String s) throws Exception {
File f = new File(s);
URL u = f.toURL();
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod(“addURL”, new Class[]{URL.class});
method.setAccessible(true);
method.invoke(urlClassLoader, new Object[]{u});
}[/sourcecode]
Happy reflecting.. :)

NetBeans 6 Bug – ConfigurationException Class in Apache Common Configuration is not Throwable?

When I using Netbeans 6 (final released) and using Apache Common Configuration library, I encounter this bug.
Here’s how I found the bug :

  • Create a java application project
  • Add the library, I create a library name ‘Apache_Common_Configuration’ and add commons-configuration-1.5.jar to that library
  • Then I wrote the code

public static void main(String[] args) {
try {
INIConfiguration ini = new INIConfiguration("sample.ini");
} catch (ConfigurationException ex) {
ex.printStackTrace();
}
}

  • But the editor showing error on ‘ConfigurationException ex’ saying that ConfigurationException is not subclass of Throwable Class (I’ve upload the screenshot)

NetBeans 6 Bug - ConfigurationException Class

  • When I try to build it’s showing different error “class file for org.apache.commons.lang.exception.NestableException not found”
  • It’s look like Apache Common Configuration is using Apache Common Lang library (I also look to the source-code ‘ConfigurationException extends NestableException’). Error when compile showing me more help than error in editor.
  • So I create a library name ‘Apache_Common_Lang’ and add commons-lang-2.3.jar to that library
  • After add the library the editor still showing the same error : “ConfigurationException is not subclass of Throwable Class”
  • But when I run build, it run successful . No error at all. (Now I confused)
  • It’s look like there’s a bug in the Editor. And that red line & error icon in project window really bugging me, although I know it’s the editor bug not my code error.
  • So to make this ‘red-line’ disappeared, I combined commons-configuration-1.5.jar & commons-lang-2.3.jar into 1 jar file. And set a library to this jar (instead using 2 library or 2 jar file).
  • After this combined the editor not showing the error again.

Anyone having this problem too?

You can vote for this bug on : http://www.netbeans.org/issues/show_bug.cgi?id=124241

Sniffing/capturing tcp data connection in Linux

When debugging my wapsite, I want to know the header from mobile HTTP request.
It’s said from some mobile-operator, they’ll include msisdn info on HTTP header.

Now tcpflow come to rescue ^^
Just type “tcpflow -ci <your-ethernet> port <port-number>”
for example “tcpflow -ci eth0 port 80″

It’ll print on console all the request to port 80 :)

Netbeans 6 – Configure which editor (representative class) for new type extension

A friend who is using Netbeans 6 ask how to configure Netbeans so it’ll open his start.tml as an html file not just as ordinary text file (So the editor will full with color I assume, not just black text :p)

I didn’t asked him why the hell he using .tml not just .html :) but I tell him that he can configure Netbeans 6 with:

  1. Choose Tools – Options
  2. Click on ‘Advanced Options’ button (on bottom left)
  3. Open the tree : ‘IDE Configuration’ – ‘System’ – ‘Object Types’
  4. Find ‘HTML Objects’
  5. Add extension tml to ‘Extension and MIME Types’ property
  6. Close
  7. Now evertime you double click .tml file it’ll call HTML objects’ representative class :)

*Check this article on NetBeans Community Doc ^^

Simple Log4J implementation

Why do we need a library for logger? doesn’t System.out.println help us enough?
When you try log4j you wouldn’t use System.out.println ever again… (Ok.. you will still used it.. occasionally :p)

What do you need? of course you need to download log4j first ;) , get it at log4j download page
And open your favorite Java IDE.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
*
* @author jimmy
*/
public class SampleLog4j {

private final static Logger LOGGER = Logger.getLogger(SampleLog4j.class);

public static void main(String[] args) {
PropertyConfigurator.configure(“log4j.properties”);
LOGGER.trace(“Level trace”);
LOGGER.debug(“Level debug”);
LOGGER.info(“Level info”);
LOGGER.warn(“Level warn”);
LOGGER.fatal(“Level fatal”);
}

}

This program will read file log4j.properties in the folder for log4j configuration.
Example of log4j.properties:

### file appender
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=sample.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%n
### console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%nlog4j.rootLogger=debug, console
# uncomment the line below if you want log output to file
# log4j.rootLogger=debug, file

And it’ll produce output:

2007-11-15 18:19:09,812 — DEBUG testing.SampleLog4j(main):26 — Level debug
2007-11-15 18:19:09,828 — INFO testing.SampleLog4j(main):27 — Level info
2007-11-15 18:19:09,828 — WARN testing.SampleLog4j(main):28 — Level warn
2007-11-15 18:19:09,828 — FATAL testing.SampleLog4j(main):29 — Level fatal

Why the log “Level trace” doesn’t logged, because we set the log level only to debug.
You should learn the configuration. There are 2 appender, 1 will log to console and other will log to a file.

Now why shouldn’t I used standard System.out.println?

  • You can’t set the level of log with println only
  • You will end up delete/comment the log using println
  • It won’t be that easy to create log to file with different filename daily (daily-rolling)
  • I wonder how your println can print class name, line number easily :)
  • … you can add more after you try it ;)

Answer to 'What should I do to marry a rich guy?'

A friend send me this email, which is very interesting for me :)

———————————————————————

A young and pretty lady posted this on a popular forum:

Title: What should I do to marry a rich guy?

I’m going to be honest of what I’m going to say here. I’m 25 this year. I’m very pretty, have style and good taste. I wish to marry a guy with $500k annual salary or above. You might say that I’m greedy, but an annual salary of $1M is considered only as middle class in New York . My requirement is not high. Is there anyone in this forum who has an income of $500k annual salary? Are you all married? I wanted to ask: what should I do to marry rich persons like you? Among those I’ve dated, the richest is $250k annual income, and it seems that this is my upper limit. If someone is going to move into high cost residential area on the west of New York City Garden , $250k annual income is not enough.

I’m here humbly to ask a few questions:
1) Where do most rich bachelors hang out? (Please list down the names and addresses of bars, restaurant, gym)
2) Which age group should I target?
3) Why most wives of the riches is only average-looking? I’ve met a few girls who doesn’t have looks and are not interesting, but they are able to marry rich guys
4) How do you decide who can be your wife, and who can only be your girlfriend? (my target now is to get married)

Ms. Pretty

Here’s a reply from a Wall Street Financial guy:
Click Here For The Answer

Change junit & run file (main class) working directory at Netbeans 5.5 Web Project

If you create a new project with Netbeans and select to create “web application”.
You’ll notice that at ‘project properties’ – ‘Run’ there’s no ‘Working Directory’ configuration, unlike General Java Project.

But what if you want to create some console application (with main method) in that project with Netbeans. You run it with Netbeans shortcut shift+F6 (run file) and realize that Netbeans set the working directory to project base path.
Then you also try to run your unit testing (junit) and realize the same thing.
You put some configuration file to specific directory in your source folder, and of course your console app & unit testing can’t find it.

I’m not very familiar with Netbeans, but after some googling I found out that Netbeans using ant : file build-impl.xml in nbproject folder. If we change the project properties configuration Netbeans will re-generate the build-impl.xml.
Netbeans also provider file build.xml in project base folder for customizing project build & run.

So i add at build.xml (copy from build-impl.xml and modify the tag ‘dir’ value)

 <target name=”-init-macrodef-junit”>
<macrodef name=”junit” uri=”http://www.netbeans.org/ns/web-project/2″>
<attribute name=”includes” default=”**/*Test.java”/>
<sequential>
<junit showoutput=”true” fork=”true” dir=”${basedir}/build/web/WEB-INF/classes” failureproperty=”tests.failed” errorproperty=”tests.failed”>
<batchtest todir=”${build.test.results.dir}”>
<fileset dir=”${test.src.dir}” includes=”@{includes}”/>
</batchtest>
<classpath>
<path path=”${run.test.classpath}”/>
</classpath>
<syspropertyset>
<propertyref prefix=”test-sys-prop.”/>
<mapper type=”glob” from=”test-sys-prop.*” to=”*”/>
</syspropertyset>
<formatter type=”brief” usefile=”false”/>
<formatter type=”xml”/>
</junit>
</sequential>
</macrodef>
</target>

<target name=”-init-macrodef-java”>
<macrodef name=”java” uri=”http://www.netbeans.org/ns/web-project/1″>
<attribute name=”classname” default=”${main.class}”/>
<element name=”customize” optional=”true”/>
<sequential>
<java fork=”true” classname=”@{classname}” dir=”${basedir}/build/web/WEB-INF/classes”>
<jvmarg line=”${runmain.jvmargs}”/>
<classpath>
<path path=”${build.classes.dir.real}:${javac.classpath}:${j2ee.platform.classpath}”/>
</classpath>
<syspropertyset>
<propertyref prefix=”run-sys-prop.”/>
<mapper type=”glob” from=”run-sys-prop.*” to=”*”/>
</syspropertyset>
<customize/>
</java>
</sequential>
</macrodef>
</target>

So every unit test & run-file at Netbeans will have working directory to {project basedir}/build/web/WEB-INF/classes

Using svn+ssh with Netbeans 5.5 + Windows

After you install Netbeans 5.5 you need to download/install subversion module.
At Netbeans menu select ‘Tools’ – ‘Update Center’ to add subversion module.
If the installation finished, you will see menu Subversion on Netbeans menu.

You’ll also need to install SVN : download page here

I’m using PuTTY’s plink.exe for ssh. You can get PuTTY package here.
Extract PuTTYto a directory and add path to that directory.
How to setting enviroment variables in Windows:

  • Open System Properties (by right click ‘My Computer’ – ‘Properties or by press button ‘windows’ + ‘break’)
  • Select tab Advanced & click button ‘Environment Variables’
  • You can edit System Variable : ‘path’
  • Add path to your PuTTY directory. (don’t delete other path, just add with ‘;’ as separator)
  • OK
  • You can check whether you have correctly add PuTTY’s path by running console (cmd) and run plink.exe without fullpath.

Then open subversion configuration file at : %APPDATA%Subversionconfig
Assuming you using default folder it will be : “c:Documents and SettingsusernameApplication DataSubversionconfig”
Open file config using notepad or other text-editor.
Edit the [tunnels] section and add :

ssh = $SVN_SSH plink.exe -l <username> -pw <password>

Of course change the <username> and <password> with yours. lol.

Then save it & restart your Netbeans.
After that you should able to check out/import project via svn+ssh.

  • Select menu ‘Subversion’ – ‘Checkout…’
  • URL example : svn+ssh://100.1.1.1/opt/subv/myproject/trunk
  • Leave username & password empty
  • Click next & follow the instructions.

If there’s no errors then Congratulations :-)