Tag Archives: java

Configure UnitTesting with Autowired in Spring context

/* Vietnamese:  Một bài viết trình bày cách viết Unit Test sử dụng Dependency-Injection(Autowiring) trong Spring Framework. */

Unit-testing is surely not a new idea, since it was proposed around the 1980s. But it’s still one of the core concepts of Test Driven Development, Agile programing, Scrum,… & some other “hot” programming methodology that arise recently. In “Clean code”, Robert C. Martin writes: “If you want to write a line of debug/log message, consider writing a test instead”.

Those ideas are really cool – if you want to know more about how writing tests stop regression bugs, improve productivity & help the designs overall, go on & read “Clean code”. I will return to the topic here: How to write Unit test in Spring context.

The second I read those above lines of Martin, I decided to try it right away. But to do Unit test in a Spring web project, I need a way to inject my services into the test case (well, there’s a HUGE pile of services). The way is easy, but only if you know what to do.

It took me quite a time to make a running system.

Here’s how I did it:

package longle.action.services;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml",
"file:src/main/webapp/WEB-INF/actions-servlet.xml"})
public class ActionServiceImplTest {
	@Autowired
	private ActionService actionService;

	@Test
	public void testHelloAction() {
		assert actionService.helloUnitTest().equals("Hello Unit Test, hope we have a good time together!");
	}
}

Hope that should cover the topic

Source code can be found here: http://www.mediafire.com/file/ww79etrez40j4gl/action.zip

Reference: (not all of these links are referred in this article. But every of them help me “go near the truth”, so I put them all here.)

  1. http://stackoverflow.com/questions/7313983/test-case-by-junit-how-to-read-web-xml
  2. http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/testing.html
  3. http://stackoverflow.com/questions/6546871/spring-junit-testing
  4. http://stackoverflow.com/questions/5733959/junit-custom-runner-with-spring-application-context
  5. http://stackoverflow.com/questions/8502327/application-context-and-spring-context-is-same
  6. http://stackoverflow.com/questions/8666720/configuration-problems-unable-to-locate-spring-namespacehandler-for-xml-schema
  7. http://stackoverflow.com/questions/412717/how-to-use-maven-surefire-plug-in-with-different-groups-for-test-and-integration
  8. http://maven.apache.org/plugins/maven-surefire-plugin/
  9. http://mekongnet.ru/index.php?mod=News&sid=37510&stprint=1

Quick note on Java time

The analog timer, From openclipart.org
One of the things I dislike most in Java is… unfriendly. DateTime manipulation is a typical example. I think at least one time, a Java developer will encounter this message: getYear() is deprecated.

Such a simple and often-heavily-used function is deprecated. So programmers must walk around by the Calendar class.

Calendar localCalendar = Calendar.getInstance();
Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Date date = new Date();
localCalendar.setTime(date);
utcCalendar.setTime(date);

TimeZone localTimeZone = localCalendar.getTimeZone();

System.out.println("Year: " + localCalendar.get(Calendar.YEAR));
System.out.println("Month: " + localCalendar.get(Calendar.MONTH) + 1);
System.out.println("Day: " + localCalendar.get(Calendar.DATE));
System.out.println("Day of week: " + localCalendar.get(Calendar.DAY_OF_WEEK));
System.out.println("Hour: " + localCalendar.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute: " + localCalendar.get(Calendar.MINUTE));

System.out.println("Timezone: " + localTimeZone.getDisplayName());
System.out.println("UTC Hour: " + utcCalendar.get(Calendar.HOUR));
System.out.println("UTC Minute: " + utcCalendar.get(Calendar.MINUTE));

Although Java big heads all have valid reasons for this inconvenience – which is the complexity of time manipulation, I still think this way is over-killing. Yes, no computer is accurate enough to calculate the correct solar time. But we are no astronomy expert, who cares if the time lacks one or two leap seconds*? Daylight saving stuffs is still necessary, but shouldn’t be too much of a problem.

In the end, I think Java powerful libraries should also make it easy to do simple tasks, instead thinking ahead too much for easy enlargement later**. With the Internet as popular as today, I think we can safely calculate “simple” time only, leaving the task to do additional astronomy calculation for the big servers, and cover the gaps by synchronizing.


(*) Like leap year, a leap second is sometimes added to our current timeline to cover the gaps between solar year & normal year. Because a leap second is too small,  people seldom notice. Reference: http://tycho.usno.navy.mil/leapsec.html

(**) Java has the reputation for easy scaling, and this is very true in my experience. On the opposite, small application is suddenly heavy at their very first cradle time, because a fair amount of efforts are put in “making room” for future changes.

Lesson learned from the Exception Filter

Long time ago, while I’m still a student, I have a chance to read Foundation of Programming“. “All exception should be captured, to show a understandable, friendly error message to customer”.

But now I realize that it’s not enough. In a recent web project, I created an exception filter to handle all exceptions popping out:

@Override
public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String errorMessage = "";

		try {
			chain.doFilter(request, response);
		} catch (SessionExpiredException e){
		    log.info(e.getMessage(), e);
                    errorMessage = "Your session has been expired";
                    request.sendRedirect(...);
		} catch (InvalidFacebookIdException e) {
                   // ...
		} catch(FacebookAccountAlreadyRegisteredException e) {
                   // ...
		} catch (Exception e) {
                   // ...
		}
	}

Do you notice the duplicate code? At any exception caught, the system must log the error, compose the mesage, then redirect to the error page.There are more than dozen of exceptions like that. How can we “clean” the code?

Thanks bro Tinh, here’s a (customized) solution:

@Override
public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
//...
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
                   errorMessage = e.getMessage();
                   log.error("Error occur: " + e.getMessage(), e);
                   res.sendRedirect(...);
		}
	}

All errors now are caught in one place: general Exception instead of concrete type.Two problems remain:

  • How to catch the right exception, because they are wrapped by Servlet Exception.
  • Guarantee all Customized Exception have a message

The answer for the first question:

private String getUsefulMessage(Exception e) {
Exception default = e.getMessage();
do {
if (e.getClass().getName().equals(InvalidFacebookId.class.getName())) return e.getMessage();
// ... same for other exceptions
e = e.getCause();
} while(e.getCause() != null);

return default;
} 

It’s the same, yes, for logic. But the later is more clearer.

The second question is more about coding policy than a technical problem, so I leave it out. In the case of our team, we decide that each exception should have an understandable getMessage().

Finding key issues of the framework

Website System

1. How to learn a framework fast?

2. To learn a framework, you should grasp the “key” issues. But how to know what is a key issue?

Those two questions are pinned in my head somehow.

Not long ago, I’m investigating MVC model in Spring Framework 3.0. Most of the concept is fine, but I have problems doing the work with Spring 3 annotation config. It just seems all the book out there mention about Spring 2.x syntax, which is “xml configuration”. It’s easy to understand because that Spring 3 just appear and it will take a relative time to make a book available. So my habit about following book guides was discarded aside. I must try to find another source.

According the advice of my seniors, I go to the Spring document & find most of the thing is already here. Enough details, though a bit complex to a not-quite-familiar-with-java coder. I struggle with those concept a bit. But by comparing the document to several examples, finally I got some “working things”, which is great.

But here comes the most complicated part: integrating between frameworks. In one of my projects, I should use Spring combined with Freemarker. I investigate, and luckily enough, find this page which tell me how to use Freemarker macro to perform bindings (it’s not an easy luck).

But WTH, I can’t find a way to use the formCheckboxes! I found no working sample, and I’m not alone.

Dozens people out there can’t find a way to use that macro.

And the solution?

Well, I write my own macros.

It took me quite a time before I relize that simple solution, and curse how stupid I am. Since the end results of freemarker is HTML, who cares if it was rendered by supported macro or customed macro?

When you know what actually happens inside that big system, the answer seems to be natural.


Still remember 2 questions at the beginning of this post?

I must says the truth, that I don’t know the best answer. But I have something that seems to work:

The solution depends on the needs. If you just use the surface of the libraries API as the common “players”, some popular tutorials might be enough. Parsing XML maybe a good example for this issue. With the same reason, I think with beginner, Grails (instead of Spring) is a good start, cause it requires little work to make a full-fledge simple application.

If you want to create a customized & not-so-popular web application, it requires more tons of work. And a solid background is preferable.

Having fun with Groovy syntax

Sometimes programming can be quite fun enough. Take a look at the following code:


package fun.groovy

class Template {
  String template;

  def setTemplateGreen() {
    template = "Green"
  }

  def setTemplateBlue() {
    template = "Blue"
  }

  def showTemplate() {
    return template
  }
}

Above is a class in Groovy language. It looks not different to a normal java class, doesn’t it? Ok, Groovy roots from Java, and it seems the only difference is that Groovy doesn’t have any semi-colon. Is it just that?

But the surprise lies silently in how one can use the method:

def color = "Blue"

def template = new Template()

template.('setTemplate' + color)()

Try running it with groovyConsole and have fun :)

Dollar sign($) and the ReplaceAll Gotchas

/* Vietnamese summarization: String.replaceAll() là một hàm tiện dụng của Java, nhưng do cách đặt tên lại dễ bị hiểu nhầm tác dụng với String.replace(). Bài viết trình bày sự khác biệt giữa hai hàm này qua một trường hợp nhầm lẫn ngớ ngẩn của người viết. */

Today I got a “big” mistake, which take a fairly long time to solve. It’s a problem related to String.replaceAll() function of Java. The experience is so hot that I want to share it immediately.

Here’s the simplified problem: I need to construct a template for sending Email. The web application will take the template and insert user information into it. This task is performed by replacing some placeholder by user true information, for example:

Template: {USER_NAME}‘s hometown is {USER_COUNTRY}

Sending content: Long‘s hometown is Vietnam.

Usually, content = template.replaceAll(“{USER_NAME}”,username); is enough. It works well in most cases, but problem occurs when username contains some special characters, specifically, the dollar signs ($).

I know the “$” must have been interpreted different by Regex, so I try to escape the character. My first thought is that replacing “$” by “$”, but no matter how many “”, “QE” or “String.quote()” I put in, replaceAll still refuse to work.

I do a quick search on Google, and find this post. The writer once had the same problem but find no answer, so he decided to go for a quick fix. Temporarily, I accept the proposed solution.

But when asking the seniors about the solution, he tells me that there’s one thing I missed at the beginning: in Java6, ReplaceAll is for regex-replacement , in my case, I can use String.replace() instead!

In short, replaceAll() when you use Regex, if not, a String.replace() is enough.