Looking for software experts?
Need an expert advice on software development? Need consulting work done in time and at high standards? Tremend has the right solution for you.

We can provide expertise in:
  •    » high traffic and complex content website infrastructures using Java, PHP or .NET. More here ...
  •    » mobile applications for iPhone, Android or J2ME. More here ...

For an enquiry, send an email to contact [at] tremend [dot] ro.

End to end UTF-8 encoding usage with MySql and Spring

August 25th, 2006 by Ioan Cocan in Java, General, Spring
Setting up a solution to store, manage and display UTF-8 data using MySql was quite a challenge.There are some a few steps that you have to get right, otherwise garbage data will come out at various stages in your application.

Inserting the data

First, make sure your data is UTF-8. You can easily check this with a text editor or maybe your favourite IDE. Next, create the database and tables specifying the character encoding as UTF-8. Here is a sample.

CREATE TABLE `word` ( `Id` int(11) NOT NULL auto_increment, `Name` varchar(30) NOT NULL default ”, `Dname` varchar(40) NOT NULL default ”, UNIQUE KEY `counter` (`Id`), KEY `alfabetic` (`Name`), KEY `dname` (`Dname`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Unfortunately, I have not found a Mysql tool to handle UTF-8 files properly. Opening such file would just result in unreadable characters in tool display and also in database. Still, using command line console would result in the same unreadable charaters. The solution: make sure you are setting the character set of the imported data. You can to that using:

SET NAMES UTF-8;

Selecting inserted data

The Mysql JDBC driver allows setting several parameters as connection string parameter. The connection URL would look like:

connection.url=jdbc:mysql://localhost/t1?useUnicode=true&characterEncoding=UTF-8

Still, setting up Spring using default BasicDataSource would do affect character encoding settings.

<bean id="dataSource" class=" org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName" value="${connection.driver_class}"/>

<property name="url" value="${connection.url }"/>

<property name="username" value="${connection.username}"/>

<property name="password" value="${connection.password}"/>

</bean>

In order to check used parameters for a particular connection, check using a statement like: "SHOW VARIABLES LIKE ‘char%’" Most variables should be UTF-8, at least the client connection property must be UTF-8. In order to have it working, I’ve added a custom data source that would directly add parameters to the driver when creating the connection:

public class CustomDataSource extends BasicDataSource {

public void init() {

addConnectionProperty("useUnicode", "true");

addConnectionProperty("characterEncoding", "UTF-8");

}

}

That can be easily wired in Spring same as the data source above, only with a "init-method" definition that would add the desired connection properties. The really hard part, that took me a while to figure out, was selecting data using a UTF-8 string in the WHERE clause. It all comes down to the collation Mysql is using in comparing the data. Without any collation specified, searching a UTF-8 string would result in ignoring the accents or special characters and match more results.

The solution, specify the collation when you are doing the query: select Id, Name, Dname from word where w.Dname=#param# COLLATE utf8_bin;

Display data in a web page

Spring MVC proves a simple solution for implementing the web layer. There are several things to be done: – set proper encodings in JSP pages. This can be easily done with a filter or including the following in all your pages. <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8" isELIgnored="false"%>

- set meta information in the "head" section of the JSP file <META http-equiv="Content-Type" content="text/html; Submit and handle data from a web page

UTF-8 characters have to be URL encoded before submission, this is easily done in three steps.

First, set the URIEncoding property in the Connector definition:

<Connector port="8080" URIEncoding="UTF-8" useBodyEncodingForURI="true" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" />

That allows the conversion of URLs to UTF-8 and correct submission of parameters using GET method. Second, use encodeURIComponent() in your JavaScript code to encode all submitted data. Without this, even if your page is UTF-8, your parameters will not be handled properly (at least not by IE, Firefox seems to have no problem with this). Third, do not read any parameters in your Controller classes unless you’ve set the right encoding for your request. This can be done using a filter or simply by setting:

request.setCharacterEncoding("UTF-8");

Versions: Mysql 5.0.19/ Mysql Connector 3.1.13/ Spring 1.2.7

read more ...

New uses of the OSGi plug-in model

August 15th, 2006 by Robert Enyedi in Java, General

I grew accustomed to the OSGi plugin model having developed some Eclipse plugins and RCP applications. I found it reasonably simple and useful because it allows Java code isolation and management at a higher level (groups of packages). I think that these plugins are the closest to what component based software development should be.

In the OSGi plugin model there is no global classpath. A plugin has its own classpath or can inherit partially or totally the classpaths of other plugins. With this the so called “JAR hell” with multiple JAR versions on the same classpath is actually avoided.

Others seem to also find this plugin model useful. Recently I’ve heard of several usages of the OSGi plugin model outside of the Eclipse platform:
- in the eRCP project which promises plugin based mobile software development – some elements of this can be achieved even on J2ME: http://www-128.ibm.com/developerworks/wireless/library/wi-osgi/
- componentization of IBM WebSphere 6.1 with OSGi (http://www.eclipsezone.com/eclipse/forums/m92036274.html) with hints on the componentization of the Apache Geronimo project
- the 5 series BMW uses the OSGi specifications as the base technology for its high-end infotainment platform (http://www.hometoys.com/htinews/aug04/interviews/osgi/osgi.htm)
- JSR 291: Dynamic Component Support for JavaTM SE will also use OSGi. This way, among others, the ever growing rt.jar could be easily split into more manageable entities.

This link is a good start for getting to know the OSGi plugin model and how it integrates into the Eclipse platform: http://www-128.ibm.com/developerworks/opensource/library/os-ecl-osgi/.

The Wikipedia article on OSGi is also accurate: http://en.wikipedia.org/wiki/OSGi

read more ...

Intellij Idea versus Eclipse – part II

August 14th, 2006 by Marius Hanganu in Java, General, Tools

>> 10 reasons why Eclipse is better

Most of the following are not checked in Idea 6.0 which is anyways in beta. They refer to 4.x and 5.x Idea versions.

1. The visual editor – one feature that Idea sucks at is the visual editor. While the best at this category is still Netbeans IMO, Eclipse’s Visual Editor, although buggy and slow, is still better than the Idea’s designer based on forms, which needs some Idea internal classes for your swing class to run.

2. Synchronize perspective – excellent idea from Eclipse team to have a perspective showing all diferences between working copy and the one from repository.

3. Automatic mark classes that don’t compile – Eclipse always had the nice feature of showing you in the project tree which classes don’t compile, by coloring with red the class icon and the package icon up to the top-most package. Idea seems to have learn this lesson in 6.0 (still in beta). God knows I missed this feature when using Idea 4.x and 5.x.

4. Large variety of plugins – while this is also a major drawback, overall it’s obviously a good thing. You have plugins for almost anything. Idea doesn’t. Although it’s obviously an advantage, I have to say a few things about how it may turn into a disadvantage: you simply don’t have time to review all existing plugins and choose the best. You have tons of code editing helper plugins and you have no Idea which you should install. Now really, who has the time to try all those. I remember a few years ago searching for the best XML editing plugin. I had no clue which one I should choose. It’s still the same: I read descriptions for 5 plugins doing the same thing and I usually choose the one that’s best advertised and sounds better. For example I have to choose between DBEdit, SQLExplorer, SQLDeveloper, easySQL, DB Studio, and the list can go on (I just picked 5 from the first page on http://eclipse-plugins.2y.net/eclipse/plugins.jsp?category=Database&sort=rating).

5. Javascript – I was amazed by the JS editor from Idea when it first came out. Very powerful. JSEclipse is still the best though, offering amongst others, support for libraries such as dojo, prototype, scriptaculous and others.

6. Context assist for regular expressions – excellent feature. Robert pointed me to it. It really simplifies your life when doing searches using regular expressions. I’m usually avoiding regular expressions when searching, unless there’s no alternative. That’s because editing the right regular expressions (at least for me) takes several tries and sometimes consulting the regex documentation for the text editor I’m using. Well now, Eclipse simplifies your regular expression searches with the context assist. I guess Idea could learn from that too.

7. Automatic selection of same word occurences within the file – when selecting a variable name – Eclipse does highlight that variable in the entire java file. This is useful. Too bad Idea doesn’t do this automatically (see Alexandra’s comment on this)

8. Switching between projects during project loading/resource refreshing – when multiple projects are opened in Idea, sometimes you have to wait for one project to load or finish refreshing resources, since you can’t swith to other Idea windows. It is a reality that a developer may have multiple instances of the same IDE at the same time. This is especially true for Idea which doesn’t support multiple projects in the same window (as opposed to Eclipse which can have multiple projects in one workspace). So why doesn’t Idea support this? I wish I knew the answer.

9. SWT – Eclipse brings SWT (kind of). Don’t know how others feel, but I still see SWT as the one technology that could save Java for desktop. Try build an application like Azureus in Swing. There are examples of good apps built with swing (like Intellij Idea), but SWT is simply looking better. Add to that the entire RCP architecture, the ability to generate native apps for different platforms, build a plugin that can be deployed either as a plugin within the IDE or with relative small effort can be packaged into a new application and you’ll get a very good architecture.

10. Money for IDEA, Eclipse for free – well this would probably be the biggest feature of ‘em all :-) While I would still pay money for Idea out of respect for the quality of the tool and the fact that it set higher standards for productivity, Eclipse is no longer trying to reach Idea in terms of features and options and customizations, but it even brings on new concepts and ideas. And although Eclipse has won the IDE wars for some time now, I think we need Idea for a healthy market.

read more ...

DBUnit loses data

August 14th, 2006 by Martin Paraschiv in Java, General

If not used properly Dbunit can loose data.

I’m using dbunit version 2.1 which has the following bug : when importing a file if the first row in the dataset file has missing columns, no further data from subsequent rows will be imported.

The solution when using dbunit ant task, will be to first perform an export operation to an already initialized database. At export ant operation specify the dtd location:

<dbunit driver="com.vendor.jdbc.Driver userid="user
    password="password">
<export dest="export.xml" dtd=”dtd-file.dtd”/>
</dbunit>

<dbunit driver="com.vendor.jdbc.Driver" url="jdbc:vendor:mydatabase"
    userid="user" password="password">
<export dest="dtd-file.dtd" format="dtd"/>
</dbunit>

The “dtd” parameter from first export task must be the same with the one from the second.The dtd paramter can be either
the file name, or the path to the dtd file as its value will be filled in !DOCTYPE tag:

<!DOCTYPE dataset SYSTEM "dtd-dataset.dtd">

This way next time when an import will be done specifing generated dtd (from export task) will assure that data will be properly imported from data-set file.
Other user have also faced this problem: http://sourceforge.net/mailarchive/message.php?msg_id=8286420.

read more ...

Intellij Idea versus Eclipse – part I

August 10th, 2006 by Marius Hanganu in Java, General, Tools

>> 10 reasons why Idea is better

In this part I’m focusing on advantages of Idea over Eclipse. I plan for a 2nd part to check out the other side – advantages when using Eclipse over Idea.

This is not a major feature comparison, but more of a mix of small experiences intended to ease your life as a developer. I’ve spent a lot of time developing server side applications with both IDEs, so I can’t really speak for differences when it comes to J2ME support or other features. I’ve also had my share of experiences with quite a few Eclipse plugins, but I haven’t tried them all (who did?).

I have to mention I’m talking here about Idea 5.x vs Eclipse 3.1. I played only a bit with Idea 6.0 and barely tried Eclipse 3.2.

1. Navigation – Idea is king when it comes to navigating through hierarchies in Java classes. The ability to go to implementation it’s fun and easy to use. Eclipse may have some plugins that do this, but still not as smooth as Idea.

2. Intentions – when adding methods to your interfaces, Idea automatically suggests you to implement that method in all implementing classes. With Eclipse’s default configuration you can’t do that. Not even sure there are plugins offering this feature. This tremendous feature really improves productivity when you build APIs and continually add methods to your interfaces.

3. One package to rule them all – a lot of functionality packed into one single installer: Idea has almost everything you want packed in one single package. The fact that for Eclipse you have to customize your own distribution is a pain in the a**. There are MyEclipse (not free) which may take Eclipse very close to Idea, or EasyEclipse, which is a distribution packed with almost everything you want.

4. Keyboard shortcuts for ant tasks – Idea allows you to assign keyboard shortcuts for ant tasks which increases productivity. For typical web applications I usually have two shortcuts: one for deploying web resources and one for compiling and deploying java classes. Eclipse didn’t pay too much attention to this feature. I know you can assign one shortcut (don’t ask me how – somebody showed me once and it was so complicated I didn’t bother remembering how to do it). And overall, changing keyboard shortcuts in Eclipse is somehow painful than in Idea. I guess this happens because Idea presents that tree (Settings/Keymap) containing Main Menu and Ant tasks amongst others. Eclipse has two tabs: View & Modify. View shows a long list and Modify shows two combo boxes. Guess the tree control is more suitable here.

5. Exclude folders – Idea has made it so simple to specify which resources you want to exclude from your project: like typical build, dist directories. This is useful for many situations. I’ll just name two:

a) you don’t want to see Idea’s “Updating modified files” loading bar every time you do build or dist your project

b) when opening resources such as XML files, you don’t wanna see two or three XML files with the same name and having to carefully choose which one you edit. In Eclipse it would’ve been so much simpler if they would have use the same Idea of excluded directories. I think I managed to do this once, to avoid the problem from point b), but now I can’t even remember how to do it.

6. Autosave – Idea autosaves each file. Don’t bother manually saving, confirming or discarding file changes. At first, I haven’t appreciated much the Idea. I thought: what happens if I don’t want to save what I modified? If all the text editors and IDEs out there need CTRL+S, why change it? I even found myself pressing CTRL+S out of habit. However, in time I got to appreciate this feature, since 1. it doesn’t bother you with all kind of popups asking whether to save your file or not before running the ant task and 2. it turns out I don’t usually need the option of not saving what has been modified. While it’s not a major feature, it does ease your life and save you from more unwanted mouse clicks.

7. Pinning/unpinning tools windows - Unpinning project window, console window, ant console window or ant window in Idea is a great feature. I usually unpin all my windows and have this way all the screen for editing my java files. And since I customized my keyboard shortcuts, I can easily bring up project window in the left side (I use ALT+~), ant window in the right side (I use ALT+\) and any of the lower windows (debug, run, ant console, etc – Idea’s defaults are ALT+0,1,2…). UPDATE: this can be actually configured also in Eclipse by using fast views on utility windows along with shortcuts for displaying/hiding them. When displaying them, they do however show up over the editor and always on the left side. Almost close to how Idea handles it.

8. Find usages vs References in workspace – Idea finds your usages, automatically selects the first usage, nothing wrong. Eclipse can look for references in workspace, find them, but sometimes forgets to select the first usage. If you have a hierarchy of 5-7 packages, then you’ll understand how painful is to have to open each package to get to the first occurence. I admit with latest versions, Eclipse does its job well almost everytime: searches and focuses automatically on the first reference, but I have no Idea why sometimes (rarely) it just doesn’t do it. It’s so frustrating when it happens.

9. Refactoring in non java resources – when I first discovered you can refactor names in an ant build file I was blown away by how natural this feature seemed. AFAIK in Eclipse you can’t do it (perhaps you know how to do it).

10. Export / import preferences – Idea saves every option you may customize – I still haven’t found some customization that Idea did not saved. As for Eclipse, it has a nice Import/Export preferences feature, but somehow they forgot to save code templates. Since I’m used to templates like “sout” (automatically transformed to “System.out.println” by Idea), I usually customize Eclipse adding a new template, which unfortunately doesn’t get saved when exporting your preferences. I like “sout” better than “sysout” since it’s … shorter.

Part 2 will contain 10 reasons for Eclipse.

read more ...

The package jedit needs to be reinstalled, but I can’t find an archive for it

August 10th, 2006 by Marius Hanganu in Tools

I tried installing the .deb package for jedit. Big mistake :-). Not only that Ubuntu refused installing it, but it also brought my synaptic into an incosistent state: every time I started synaptic I was getting this error:

The package jedit needs to be reinstalled, but I can't find an archive for it

and then no package was displayed. One of the reasons I like Linux (Ubuntu) over Windows is apt and the synaptic interface. Imagine my desolation.

I tried various “apt-get remove jedit”, clean, autoclean options. No luck. Neither the guys on Ubuntu mailing list could help me out here. Tried removing it using dpkg and I got

dpkg: error processing jedit (--purge):

Package is in a very bad inconsistent state - you should reinstall it before

attempting a removal.

Errors were encountered while processing: jedit

But I finally got it working. This command forced the removal of my incosistent jedit package:

dpkg --remove --force-remove-reinstreq jedit

 

Update: after I managed to fix it and post this entry, I was finally pointed on ubuntu users mailing list to http://ubuntuforums.org/showthread.php?t=232849&highlight=jedit. Phew! lots of replies before the author figured the answer for himself.

read more ...

Perforce Windows shell integration

August 10th, 2006 by Ioan Cocan in Java, General, Tools

I’m happy again. Perforce shell integration used to make my machine hang on every file browse operation. As we are working with a remote Perforce server we’ve set up a Perforce proxy so we do not hit the remote US machine for the same files.

If the proxy was up and remove server communication was down Windows could not load even items on desktop. Even with all connections in place, right clicking or browsing became a nightmare. Fed up with all this I decided to take the final drastic measure: uninstall the Windows client and somehow work with command line tools. Then it hit me: the Uninstaller has a remove Explorer integration option. Back to work.

read more ...

Accessing Java Constants from JSTL

August 7th, 2006 by Iulian Cutui in Java, General

It’s been a while now since the first specifications of JSTL. Since then it emerged as a standard for the presentation layer in web applications, replacing the ugly scriptlets with nice looking tags that resembles the HTML or XML markup. JSTL provides tags for typical presentation layer tasks, such as iterations, conditional content, data formatting, XML manipulation and database access, and its expression language makes working with dynamic attribute values a lot easier.

If you have used EL before, notations like:

${object}

may look familiar. The EL supports accessing fields of objects and elements of collections by using its defined accessors (dot and brackets). Though these accessors may be used interchangeable, it is recommended to use dot for accessing members and brackets for collections.

${user.phone} – the equivalent of user.getPhone()

and

${users[2]} – the equivalent of users.get(2) where users is a List

or

${users["John"]} – the equivalent of users.get(“John”) where users is a Map

Looking at the last example, what happens when you want to use in your application constants for the keys in your map. Supposing that you have a Constants class:

class Constants {

public static final String NAME = “name”;

}

a notation like this:

${users[Constants.NAME]}

will not work. That’s because the Constants class is not by default available to any of the web contexts, hence is not accessible by the EL expressions. Second, if you would make it available through <jsp:useBean> tag, a constants class by its nature will not follow the Java Beans properties accessors specifications (i.e. in our case it will not have getters for its fields).

To use such a class we have to present it to the EL in a way that it can access it. A Map is a good solution for this. The idea is to implement a method to look to a Constants class through reflection, and make a Map with all its public static final fields, and use that Map in EL. Here is one idea of how to do this:

Class c = Constants.getClass();

Field[] fields = c.getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

Field field = fields[i];

int modifier = field.getModifiers();

if (Modifier.isFinal(modifier) && !Modifier.isPrivate(modifier))

try {

this.put(field.getName(), field.get(this));

}

catch (IllegalAccessException e) {}

}

You can use this code to create the desired Map and place this Map somewhere at the ApplicationContext for further usage.

Even there could be many variations to the above code, more creative, funnyer or smarter, this is not my recommended solution. Following the Principle No. 6 from our internal guide, the “DRW concept” (don’t reinvent the wheel :) ), the solution is simple: the unstandard tag library from Apache. Here’s how to use it:

<%@ taglib prefix=”un” uri=”http://jakarta.apache.org/taglibs/unstandard-1.0″%>

<un:useConstants var=”Constants” className=”com……Constants” />

and later in you code, an expression like:

${users[Constants.NAME]}

will work like a charm.

read more ...

Think twice before loving Apple

August 7th, 2006 by Marius Hanganu in Tools

Some time ago I switched my development environment to MacOS. This means I used it intensively and tried to discover all those nice usability things Mac is well known for and if no trick available, try to emulate the little things that made my life easier on Windows.

But I found Cedric Otaku’s entry about MacOS-Windows comparison as being an excellent confession of all the problems MacOS has. And since everyone embraces Apple and all its products with unconditionate love, I welcome Cedric’s pragmatism. Apple lovers need to open their eyes a little bit.

I loved MacOS for its design. The UI of MacOS looks better than Windows: you have all kind of interesting concepts like the finder or very useful things like sticky notes, calendar, calculator, available on one shortcut and so on. However, when you start using it more seriously and try to move your development environment entirely you’ll soon see the gripes of MacOS.

Here are some quotes from Cedric’s entry:
- “I can only resize from one corner and the cursor doesn’t change. Windows has let me resize windows from all four corners and even from all four edges of windows since the early 90′s. What’s taking Apple so long?”
- “Mixing up the quicklaunch bar and the taskbar is a mistake. The little arrow under the icons to indicate which ones are open are confusing, and I find Windows’ solution (two separate and distinct-looking bars) much more intuitive and more practical.”
- “There is no right mouse button on the laptop. Are you kidding me? Yes, I know that you can plug in a mouse and the right button will work right away, but I never use a laptop with a mouse, so I find myself doing the insane Control-click all the time. This is preposterous. And coupled with the absence of a Delete key (see below), I am finding myself doing finger aerobics much more often than I should.”

And there are more… These 3 were some of my biggest frustrations in using MacOS. And looking at the replies, you can find some “solutions” for some problems, but noone talks about the first two. I bet the Apple fans wish inside their hearts they would have those problems fixed. It’s just that they should let it out :-).

Some Apple fans say that: “Hey, Apple invented this and we should be grateful and full of respect, while Microsoft copied it”. Well, we are respectful, but sometimes inovation comes from copying an existing idea and taking it few little steps forward. Being stubborn and maintaining one style won’t help Apple too much. Everyone is going to take their good ideas and improve them.

One other argument is that for users moving from Windows environment to MacOS, you will be frustrated at first, but once the true power of MacOS will be revealed you will never go back to Windows.

What is that? Some sort of a masonic organization – the Holy Grail of computing and user interface usability is hidden in using MacOS for some time? I don’t know how he pulled it, but Steve Jobs has definitely managed to create a network of Apple fanatics. I bet if he’d start a war he would imediately gather all Apple users, while on the other side, Windows would have too few soldiers since they are not fanatics or interested in such a war.

I see MacOS as an illustrious figure in IT history. Although brilliant and well respected, it’s sometime like a dinosaur who refuses to see the inovation, keeping some things “the old way”. This is not healthy for them and it’s too bad, since a company such as Apple could really make a difference and maintain a higher standard of usability.

read more ...

Develop with pleasure – IntelliJ Idea 6.0 Beta

August 6th, 2006 by Ioan Cocan in Tools

IntelliJ’s Idea 6.0 Beta is out and available free for evaluation. Most expected features were GWT support, TeamCity integration, UI designer enhancements and productivity/editing features. I have not tried (yet) UI and team integration but here are some things that cought my eye.

Built-in Code coverage support – Programmers love improving their code and what better way to do this than seeing coverage percentages of your tests right within the IDE. If you are using unit testing a lot, this gives you good insights about where to focus your tests.

Project-wide error-highlighting – This is something that Eclipse had for a long time, gives you good understanding of where you should go for errors without having to recompile.

There is one missing feature that Eclipse has: selecting a variable should highlight all usages in current block.

read more ...

HTML visual editor

August 1st, 2006 by Ioan Cocan in Tools

I’ve been looking around for a freeware, not so sofisticated HTML visual editor. Tried out a few popular Tucows downloads and found everything I needed in PageBreeze. Free for non-commercial use, it has drag-and-drop form design with easy preview within the application.

read more ...