feedburner
Enter your email address:

Delivered by FeedBurner

feedburner count

libstdc++2.10-glibc2.2 on Linux Ubuntu Hardy 8.04

Labels: , , , , ,

The libstdc++2.10-glibc2.2 package is not on the Ubuntu Hardy 8.04 Linux repositories so it can't be installed using apt-get or synaptic package manager.


$ sudo apt-get install libstdc++2.10-glibc2.2
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libstdc++2.10-glibc2.2 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or is only available from another source
E: Package libstdc++2.10-glibc2.2 has no installation candidate

In order to install libstdc++2.10-glibc2.2 on Ubuntu hardy 8.04 Linux, you need to download libstdc++2.10-glibc2.2_2.95.4-24_i386.deb and install it using dpkg:

wget mirrors.kernel.org/ubuntu/pool/universe/g/gcc-2.95/libstdc++2.10-glibc2.2_2.95.4-24_i386.deb
sudo dpkg --install libstdc++2.10-glibc2.2_2.95.4-24_i386.deb

libstdc++2.10-glibc2.2 contains libstdc++-libc6.2-2.so.3 which is required by Eclipse tptp agent controller, Eclipse based Java profiler.
The upgrade from Ubuntu Gutsy 7.10 Linux to Ubuntu Hardy 8.04 Linux removes the package. Because of this the Eclipse tptp Agent Controller fails to start.

$ ./ACStart.sh
Starting Agent Controller.
ACServer: error while loading shared libraries: libstdc++-libc6.2-2.so.3: cannot open shared object file: No such file or directory
ACServer failed to start.

Distributed Caching Essential Lessons

Labels: , ,

InfoQ have a presentation about distributed caching which describes some of the challenges and points to consider when you plan to implement or integrate a distributed caching system. The presentation was given by Cameron Purdy from Tangosol (Oracle) and was recorded at JavaPolis 2005. Although it was a long time ago, I think it is still relevant and might be helpful to whoever needs a distributed caching system.

Create log4j configuration file using wizardforge log4j wizard

Labels: , , ,

Log4j is a widely used Java based logging framework. If you worked with Java open source projects you definitely used log4j in your applications. Controlling of the output of the logs is done using the log4j configuration. If you decided to use log4j in your Java application or you are using a 3rd party Java library which uses log4j for logging and requires log4j, you will need to write a log4j configuration file.
Using wizardforge log4j wizard we can create a log4j configuration file. This log4j wizard comes in handy when you do not know the log4j configuration file structure, syntax or if you forgot one of the appenders parameters.

How to use JNDI with your J2SE application

Labels: , , , , ,

Have you ever wished you could have a JNDI (Java Naming and Directory Interface) server in your J2SE application? Do you need to unit test a Java class which gets its resources from JNDI? Well, you can. One of the nice things about JBoss is that it's Java open source project and that it's built from different components which can be used own their own. One of these components is the Java Naming Provider (JNP). Using the JBoss JNP we can add naming abilities to our J2SE application.

What we need is the following Java jars files:

   jnpserver.jar
jbossall-client.jar
log4j.jar
Of course we need to have a log4j configuration file (log4j.properties or log4j.xml) in our Java classpath.

In order to start the JNP we need to write the following code
  System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");

NamingBeanImpl jnpServer = new NamingBeanImpl();
jnpServer.start();

This will start the JNP in a different thread.

We can put the following jndi.properties file in the classpath
   java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
and then we can remove the System.setProperty(...) from the code.

Now lets see how we can use it to test JDBC code which gets its connection to the database from a DataSource object which is bound to JNDI Using JUnit and DbUnit.
Here is the class which we want to test:
public class DatabaseClass {

public static final String DB_JNDI_NAME = ...

public Connection getConnection() throws SQLException, NamingException {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(DB_JNDI_NAME);
return ds.getConnection();
}

public void insertData() {

Connection con = null;
try {
con = getConnection();
...
...
}
...
}

You can see that the method gets the connection to the database from JNDI.
Here is the JUnit test class:
public class TestClass {

@Test
public void testData() throws Exception {
System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");

DataSource ds = new EmbeddedDataSource();
((EmbeddedDataSource) ds).setUser("");
((EmbeddedDataSource) ds).setPassword("");
((EmbeddedDataSource) ds).setDatabaseName("testdb");
((EmbeddedDataSource) ds).setCreateDatabase("create");

NamingBeanImpl jnp = new NamingBeanImpl();
jnp.start();

Context initContext = new InitialContext();
initContext.createSubcontext(DatabaseClass.DB_JNDI_NAME);
initContext.rebind(DatabaseClass.DB_JNDI_NAME, ds);

DatabaseClass db = new DatabaseClass();
db.insertData();

// assert the database content using DbUnit
}
}

Then we can use DbUnit to assert the content in the database with the expected content. This way we can unit test the Class although it relies on the J2EE application server naming service.

Some problems you might encounter:
  Exception in thread "main" java.lang.NoClassDefFoundError: org/jboss/logging/Logger at org.jnp.server.NamingBeanImpl.(NamingBeanImpl.java:48)
You need to add jbossall-client.jar to your classpath.

I used to run the JNP by writing the following Java code:
  org.jnp.server.Main.main(new String[] {});
as opposed to
   NamingBeanImpl jnpServer = new NamingBeanImpl(); jnpServer.start();
The last time I tried, I got the following exception:
  java.lang.NullPointerException
at org.jnp.server.Main.getNamingInstance(Main.java:301)
at org.jnp.server.Main.initJnpInvoker(Main.java:354)
at org.jnp.server.Main.start(Main.java:316)
at org.jnp.server.Main.main(Main.java:104)
Looking at the source code I noticed the NamingBeanImpl class and Scott Stark comment
  * A naming pojo that wraps the Naming server implementation. This is
* a refactoring of the legacy org.jnp.server
Using the NamingBeanImpl class I managed to solve the problem.

How to Create Connection to an Embedded Derby Database (Java DB)

Labels: ,

The Derby database also known as Java DB is an open source Java database. It is part of the Apache project and it is distribute with Sun Java JDK 6.
In order to create a Connection or a DataSource Object to an embedded Derby database, we need to have the derby jar file in our Java classpath. Derby comes with JDK 6. If you don't have it you can download it from the derby web site or from sun site. On Ubuntu Linux you can download it using apt-ge:
apt-get install sun-java6-javadb

In the following Java examples the database files are at data/testdb, the user name and the password are empty and the driver is set to create the database if it is doesn't exist.

Creating a single connection to an embedded Derby database:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
return DriverManager.getConnection("jdbc:derby:data/testdb;create=true", "", "");


Creating a DataSource Object to an embedded Derby database:
javax.sql.DataSource ds = new EmbeddedDataSource();
((EmbeddedDataSource) ds).setUser("");
((EmbeddedDataSource) ds).setPassword("");
((EmbeddedDataSource) ds).setDatabaseName("data/testdb");
((EmbeddedDataSource) ds).setCreateDatabase("create");

Eclipse DbUnit Plugin

Labels: , , ,

The eclipse DbUnit plugin in eclipse 3.3 is a shell project and is missing the DbUnit jars.
Because of this, the DbUnit Test Case wizard fails with the following error:


Creation of element failed.

java.lang.reflect.InvocationTargetException
at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:383)
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:313)
at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:934)
at org.eclipse.ui.internal.progress.ProgressManager$5.run(ProgressManager.java:1149)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:67)
at org.eclipse.ui.internal.progress.ProgressManager.runInUI(ProgressManager.java:1142)
at org.eclipse.datatools.enablement.jdt.dbunit.internal.wizards.DbUnitWizard.finishPage(DbUnitWizard.java:69)
at org.eclipse.datatools.enablement.jdt.dbunit.internal.wizards.NewTestCaseCreationWizard.performFinish(NewTestCaseCreationWizard.java:63)
at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:742)
at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:373)
at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:618)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:227)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1101)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3319)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2971)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:820)
at org.eclipse.jface.window.Window.open(Window.java:796)
at org.eclipse.ui.internal.actions.NewWizardShortcutAction.run(NewWizardShortcutAction.java:135)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:546)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:490)
at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:402)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1101)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3319)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2971)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2389)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2353)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2219)
at org.eclipse.ui.internal.Workbench$4.run(Workbench.java:466)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:289)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:461)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:106)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:169)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:106)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:76)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:363)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:176)
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.eclipse.equinox.launcher.Main.invokeFramework(Main.java:508)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:447)
at org.eclipse.equinox.launcher.Main.run(Main.java:1173)
Caused by: java.lang.NoClassDefFoundError
at org.eclipse.datatools.enablement.jdt.dbunit.internal.wizards.NewDbUnitTestCaseWizardPage1.class$(NewDbUnitTestCaseWizardPage1.java:674)
at org.eclipse.datatools.enablement.jdt.dbunit.internal.wizards.NewDbUnitTestCaseWizardPage1.createGetDataSet(NewDbUnitTestCaseWizardPage1.java:673)
at org.eclipse.datatools.enablement.jdt.dbunit.internal.wizards.NewDbUnitTestCaseWizardPage1.createTypeMembers(NewDbUnitTestCaseWizardPage1.java:520)
at org.eclipse.jdt.ui.wizards.NewTypeWizardPage.createType(NewTypeWizardPage.java:2053)
at org.eclipse.jdt.ui.wizards.NewTypeWizardPage$7.run(NewTypeWizardPage.java:2543)
at org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation.execute(WorkspaceModifyDelegatingOperation.java:68)
at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:101)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1797)
at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:113)
at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:369)
... 46 more
Caused by: java.lang.ClassNotFoundException: org.dbunit.dataset.IDataSet
at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:434)
at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:369)
at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:357)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:83)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
... 56 more

In order to fix the problem we need to fetch the missing DbUnit jars by running the fetch-lib.xml ANT script in the DbUnit plugin directory (plugins/org.dbunit_2.2.0.200706071).

<?xml version="1.0"?>

<project default="main" basedir=".">
<target name="main">
<mkdir dir="libs" />
<property name="base.url" value="http://superb-west.dl.sourceforge.net/sourceforge/dbunit"/>
<get usetimestamp="true" src="${base.url}/dbunit-2.2.jar" dest="libs/dbunit-2.2.jar" />
<get usetimestamp="true" src="${base.url}/dbunit-2.2.jar" dest="libs/dbunit-2.2-javadoc.jar" />
<get usetimestamp="true" src="${base.url}/dbunit-2.2.jar" dest="libs/dbunit-2.2-sources.jar" />
<eclipse.refreshLocal resource="org.dbunit" depth="4"/>
</target>
</project>

Another options is to download the DbUnit jar manually to the DbUnit libs plugin directory. We will need to copy the file to libs/dbunit-2.2.jar, libs/dbunit-2.2-javadoc.jar and libs/dbunit-2.2-sources.jar.

JUnit 4 Features

Labels: ,

One of the main differences between JUnit 3 and JUnit 4 is the use of annotation instead of naming convention.

Using @Test to define a test method
using the @Test annotation we can define any method as a unit test no matter what the name of the method is. In JUnit 3 we needed to start a method name with the word 'test' . In JUnit 4 we can write the word 'test' in the beginning of the method name but it will have no effect. We will need to add the @Test annotation before the method

@Test
public void testMethod() {
...
}
or we can just write:
@Test
public void method() {
...
}

Expecting Exceptions
If out test case need to check that exception is thrown we can use the @Test(expected=Exception.class) annotation. The test will fail if no Exception will be thrown.
@Test(expected=IllegalArgumentException.class)
public void checkForException() {
throw new IllegalArgumentException();
}

Test Timeout
If we want to make sure that our code is execute within a time limit, we can define a timeout for the test. The following test will fail after 100 milliseconds.
@Test(timeout=100)
public void method() {
Thread.sleep(1000);
}

Disable Test
In case we want to disable a test but we still want to see it on the tests list we can use the @Ignore annotation. This way we can write why did we disabled it. The comment will be visible in the final report
@Ignore("This is an example on how to ignore JUnit tests")
@Test()
public void method() {
...
}

@Before and @After instead of setUp() and tearDown()
@Before
public void doSomthing1() {
...
}
@After
public void doSomthing2() {
...
}

We can choose whatever method name we want.
We can define as many method as we want with @Before and @After. Each one of them will be execure before or after any unit test method in the class.

In order to define a method that will be execute before or after the whole class we can use the annotations: @BeforeClass and @AfterClass

Test Suites
This test suite will run the classes Test1, Test2, Test3 and Test4 one after the over.
package com.shimi.example;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses( {
Test1.class,
Test2.class,
Test3.class,
Test4.class
})

public class TestSuite {

}

Parameterized Unit Tests
Parameterized unit tests is a feature which came to help us with cases when we need to pass different parameters to our unit test. To define a parameterized unit test we need to use the @RunWith(value=Parameterized.class) annotation for the class. We need to define a Collection with the parameters values and the @Parameters annotation. We will need to write a Constructor which will get the parameters values and will set them in the class variables. In the following example the unit test will run 6 times. Each time JUnit will call the class Constructor with a different pair of Strings from the paramsValues Collection. The Constructor will initialize the class members with the given values. Then, it will call the unit test method which will check if the two Strings are equals.

@RunWith(value=Parameterized.class)
public class ParameterizedTest {

private String param1
private String param2

@Parameters
public static Collection paramsValues {
return Arrays.asList( new Object[][] {
{ "abc", "abc" },
{ "ab", "ba" },
{ "a", "b" },
{ "ab", "a" },
{ "abcd", "abcd" },
});
}

public ParameterizedTest(String param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}

@Test
public void test {
assertEquals(param1, param2);
}
}

Assert Results
using the JUnit assert method we can assert different results values and assign an error message.
assertEquals("Object 1 and Object 2 are different", object1, object2);
The assertEquals method assert Objects. If we will use it for primitive
assertEquals("Object 1 and Object 2 are different", 1, 1);
The result will be false. Java will use autoboxing in order to convert the primitives to Object. We can compare primitives by using the method assertTrue()
int param1 = 1;
int param2 = 1;
assertTrue("Param 1 and Param 2 are different", param1 == oparam2);