Wednesday, December 7, 2011

test your http posts

Recently, I write an HTTP client for making post requests. Then I search for a way to test it. It's possible to write unit tests of course but that would be great if I see the real deal. Then I find 'Henry's HTTP Post Dumping Server'. Using his server you can easily test your post request and see its content.

Saturday, December 3, 2011

mongodb is evil?

NoSQL databases were quite popular (with cloud computing and scala) at this year's devoxx and one of these databases was MongoDB. The way you define your models with json-style and the performance benefits seemed like the real power of MongoDB but the following article states that you should reconsider your choice if you choose MongoDB in something other than a toy project. See if mongoDB is evil.

Monday, November 28, 2011

flex likes surprises

Recently I got an odd error while working on flex.
While debugging, I saw that the following code seems to have a value in "container.eGrid.selectedItem" part. It's populated with an object of type MyObject.
But "e" of type MyObject is null. Seems nonsense right? I'm just setting what's in right to left.
A bit later, I saw that I mapped MyObject to a wrong java remoteclass. When I fixed this issue my "e" variable got populated.

var e:MyObject = container.eGrid.selectedItem as MyObject;

Tuesday, November 22, 2011

flex surprises again (this time with datefield)

In my "update" screen (in flex), I'm getting the actual date value from the model and showing it to the user. If the user changes this date value in the screen, no problem; it's working. But if he doesn't touch this date field then the value of it is null as far as I can see while debugging.

In my update screen this is the part I define the datefield.
< mx:DateField id="endingDateDatefield" text="{formatDate(myModel.endingDate)}" 
formatString="{FORMAT_STRING}" width="50%" height="25"/> 
Notice that formatDate() returns String.

The datefield is displayed correctly but when I try to save the new model I saw no value in debug. "parentPanel.endingDateDatefield.selectedDate" is null.
So I changed my code to:
< mx:DateField id="endingDateDatefield" selectedDate="{myModel.endingDate}" 
formatString="{FORMAT_STRING}" width="50%" height="25"/> 

Now I set the selectedDate field instead of text in DateField component which fixes the issue.

Tuesday, November 15, 2011

drop thread.sleep(), use timeunit's sleep()

Everybody has a Thread.sleep() call somewhere in his code.
sleep() method only accepts milliseconds and if you need some sleep functionality with another time granularity you have either to calculate the sum of milliseconds and put a magic number in the code
or a more readable way to do it
Thread.sleep(1000L * 60 * 60 * 24);
or a much more readable way;
More beautiful code right?

Thursday, November 3, 2011

queryparameterexception: could not locate named parameter

While testing my hibernate query I got a strange exception;
"nested exception is org.hibernate.QueryParameterException: could not locate named parameter".
I checked that the said parameter is in the hibernate model. Furthermore I checked there's a corresponding column in the database. So the problem was not about these. Later I saw that there's a problem while I was trying to set my named parameter. My hql query was like "from TableName t where t.field=:field1" and I was trying to set the value in "field1" with
query.setBoolean("field_", value);
As "field_" does not exist I got this error.
The correct form was;
query.setBoolean("field1", value);

Wednesday, November 2, 2011

comparing dates in flex

Let's see how we can compare dates in flex.

ObjectUtil.dateCompare(firstDate, secondDate);

This call above will return you -1 if secondDate is later than the first date, 1 if it's the contrary case and 0 if they match.

Tuesday, September 6, 2011


I recommend Chris Kelly's anti-patterns article. A good read imo.

Wednesday, August 17, 2011

fix for the performance problem of mysql memory tables

In our project, a very high database performance is needed. Thus we create our critical tables as memory engine tables but although our queries are using corresponding indices we still can't achieve the needed performance. After few research in google I see that tables of memory type are having "hash" indices by default. After we drop the "hash" indices and replace them with "b-tree" ones, we had a much better performance in our project. So for those of you with performance problems using memory tables, I recommend trying b-tree indices.

Friday, July 15, 2011

mockito tutorial video

I recently find a very good screencast about mockito, a great mocking framework. There it is in three parts:

Thursday, July 14, 2011

why my new transaction is not created spring?

I was inserting a single data from table A to table B and then removing the single instance from table A. I don't want to have a problem if insert happens but the delete does not. So for this action I needed a transactional behavior.

I'm using Spring declaratively and thus using TransactionManager for implementing transactional behavior. I declared my method's propagation as REQUIRES_NEW which mean I absolutely want a new transaction for this method.

In my Service class' process() method I call insertAndDeleteTrxNew().

public void process(){
Record records = stuff();

insertAndDeleteTrxNew() method inserts from table A to table B and deletes from table A. Spring's log tells me that it did not create a transaction for my method.
What I exactly get is:
Don't need to create transaction for [Service.insertAndDeleteTrxNew()]: This method isn't transactional.

After few time searching I found out the root cause of my problem. Spring build a proxy for my Service class and any transactional behavior will work on this level. If I set process() transactional and call it first I'll implicitly go to the proxy and call proxy's process() method then proxy will call the instance's process() method which's why transactional behavior will work: I first meet with the proxy. My call is handled by the proxy. Why my insertAndDeleteTrxNew() does not work? This is because when I do this call from my process() method, I'm calling this specific instance's method not the proxy's method.

I fixed this problem by extracting this method to another Service. Now, Service X's process() method calls Service Y's insertAndDeleteTrxNew() method which implicitly calls Y's proxy and as you can guess it works.

Monday, July 11, 2011

surprise with spring while doing dependency injection to a child object

My child class (ChildDaoImpl) extends a parent class (ParentDaoImpl) and they are both managed by Spring. When I try to call a parent functionality from the child class with super.parentsMethod() I get NullPointerException.
I debug and see that the parent's injections are not complete at all. The DataSource field that should be injected in ParentDaoImpl is null. But the injection definitions seem ok in application context so where's the problem? I call the parent's bean separately and it works!

Spring does not trace the whole object hierarchy from the child class to the first ancestor which means that it does not do the necessary dependency injections to the parent chain. Thus my DataSource field in the ParentDaoImpl is not injected.
If you extend some class in your java code and you want the child class to work properly with parents' functionality you have to tell Spring explicitly that your child class has a parent.

So your application context should go from


Monday, June 13, 2011

problem while using dbcp with oracle database

We have two different databases in a project; an Oracle and a MySql one. Both of them need connection pooling for a better performance. First, I add dbcp context for mysql to my application context. The settings were quite straightforward. But when I try to use the same settings (except for the connection url and the driver class name of course) for the Oracle data source I got the following exception:

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ORA-00923: FROM keyword not found where expected

which can be translated as "there's some FROM statement missing somewhere while setting your connection". My validation query for MySql was just "SELECT 1" which annoys Oracle database. I change it to "SELECT 1 FROM DUAL" and it's fixed.

Tuesday, June 7, 2011

three screens in vlc media player while playing wmv

If you're trying to watch a video of Windows Media Video (WMV) format with vlc player but vlc is opening three windows of the video in the same time let me give you a hand. First open Video - Video Track from the menu and then select disable and then track 1. One window is better than three for a movie, right?

Monday, May 30, 2011

EmptyResultDataAccessException in your face

Recently I get an EmptyResultDataAccessException in a project where we use Spring JDBC. The full exception listing is "org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0". When I trace the exception I see that I'm calling queryForLong() method of JdbcTemplate for "SELECT Column FROM TABLENAME" on an empty table. Column here is of Long type. Now, I plan to catch the exception and return an unusual value (like -1) as a result. On the service layer, I plan to check for equality to the unusual value and proceed with the right logical flow.

Notice that if you use some function like count(), min(), max() ... in the same query (SELECT MAX(Column) FROM TABLENAME) you won't get the same exception but a "0" result instead.

Wednesday, May 11, 2011

a great way of improving your java code: findbugs!

We decided to make our project's code more robust and bug-free. I suggested the use of Findbugs which is basically a program that uses static analysis to search for bugs in your java code. It can be used as IDE plug-in or as a stand-alone application. Findbugs pinpoints problematic places in your code. There are many type of pre-defined problems that Findbugs looks for like duplicate case branches in switch statements, streams which are not closed in all cases, inefficient use of map iterator, redundant comparison to null ... etc. I can't recommend Findbugs enough.

Tuesday, February 22, 2011

bufferedwriter or windows, which one of you is my enemy?

I was planning to name a file I generated using the username and the date of generation, so my naming format was like "01-03-2010-13:33-user1". When I'm trying to do that with BufferedWriter of our beloved Java, this file is not created. ":" is not allowed by Windows so a file with "01-03-2010-13" as a name is created and nothing is inserted although I called bufferedWriter.write("something"). The good part is that no exception is thrown by BufferedWriter. Great isnt it?

Monday, February 7, 2011

thank you axis2 for this handful of close_wait

In one of our projects we are using axis2 1.4 for generating the client side of the web service. Our web service part is working for few hours but gets stuck for no apparent reason. After I investigate a little I saw that it generates lots of sockets with CLOSE_WAIT state which results this freeze. I google a bit about similar problems with Axis2 and saw that this a known bug. Here's the source I used for fixing it. As explicitly calling the garbage collector didn't seem like a good solution, and as I can't upgrade axis2, I opt for changing the HTTP version to 1.0. For this I set a single field in the ServiceStub by calling


from ServiceStub where this object is created.
After that, this CLOSE_WAIT bug is fixed.

Thursday, February 3, 2011

no such method? you must be joking java.lang.NoSuchMethodError

In our project we use Spring Security's new release and we didn't care about the versions of different Spring components like Spring Beans, Core etc and probably left few old versions next to new versions. The result is a nice exception and I had to figure out why.

java.lang.NoSuchMethodError: org.springframework.beans.MutablePropertyValues.add(Ljava/lang/String;Ljava/lang/Object;)Lorg/springframework/beans/MutablePropertyValues;

After a little bit of googling I saw that the root cause is the fact that we use old versions in some Spring components next to new ones. I removed the old ones from pom.xml and everything's fixed.

Friday, January 14, 2011

et tu log4j? java.lang.classnotfoundexception: org.apache.log4j.enhancedpatternlayout

While I was setting log4j for our new project I got the following exception:

log4j:ERROR Could not instantiate class [org.apache.log4j.EnhancedPatternLayout].
java.lang.ClassNotFoundException: org.apache.log4j.EnhancedPatternLayout

I have log4j in my pom and its jar in my local repository so why EnhancedPatternLayout is missing?
This class is not in our log4j but in log4j-extras. You have to add the necessary extras jar to your pom.


I added the version 1.0 because version 1.1 requires log4j 1.2.16 while I'm using log4j 1.2.15.

classcastexception while working with quartz + spring

I was trying to integrate Quartz to Spring and while everything seemed OK I got the following exception:

java.lang.ClassCastException: org.quartz.impl.StdScheduler

I had everything in hand for the simple job I implemented to work.

A simple Job class that implements QuartzJobBean:

public class Job extends QuartzJobBean{

protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

The necessary spring context:

All I had to do is instantiate the bean with getBean() but I was getting "java.lang.ClassCastException: org.quartz.impl.StdScheduler" everytime. My code for instantiating the SchedulerFactoryBean was below:

SchedulerFactoryBean d = (SchedulerFactoryBean) appCon.getBean("scheduler");

I was trying to downcast to a wrong class. It seemed quite straightforward to use SchedulerFactoryBean but it was wrong. As the exception said I changed it to StdScheduler (of Quartz) and I fixed it.
Here's the correct form:

StdScheduler d = (StdScheduler) appCon.getBean("scheduler");

I hope that easy solution will be helpful for somebody out there.

Tuesday, January 11, 2011

datetime fun with mysql: when do i lost my time?

In our project, we chose the data type of a column as datetime in MySQL. We built models that are in line with our tables. For the datetime attribute in the database I chose to use the Date object in Java model and the show begun.

When I tried to use my model's Date attribute for setting the corresponding field (with setDate()) on the prepared statement I saw that the object types dont match. What I have in the model is java.util.Date while the prepared statement asks for java.sql.Date. Ok then I'll convert it. I googled a bit and found a solution, or rather thought that I found a solution.

ps.setDate(1, new java.sql.Date(model.getDateField().getTime()) )

First I was converting to a millisecond unix timestamp with getTime() and then converting it to second (by dividing with 1000) and then wrapping the result into a java.sql.Date object.
The result was far from satisfying. The time part of the date (hour, minute and second) were missing in the result. The date in the model was '2010-10-26 14:13:33' and the result in the database was '2010-10-26 00:00:00'.

After that I googled a bit more and inspected few javadocs then came up with not one but two solutions.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ps.setString(1, dateFormat.format( model.getDateField() ));

The first solution creates a SimpleDateFormat object which formats the Date attribute of the model as a String and we use setString() of the prepared statement for setting it.

The second solution is below.

ps.setTimestamp(1, new java.sql.Timestamp(model.getDateField().getTime()));

We first get the Date attribute and then convert it to unix timestamp in milliseconds for wrapping it into a Timestamp object and call the related setter.

I didn't notice major performance difference in one of the solutions I offer which means that you have to test it in your cases.