Category Archives: Web-development

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

A quick experiment on HTML5 Canvas

Photobucket

/** Vietnamese: một thử nghiệm nhỏ lên trang canvas của HTML5 **/

HTML5 is out for a while, and many people have already play with it. Inspired by the great article here, I managed to make a simple dirty experiment.


<!DOCTYPE html>

<html lang="en">

  <head>

    <title>Good night</title>

  </head>

  <body><script type="text/javascript">
  if ( !window.requestAnimationFrame ) {

    window.requestAnimationFrame = ( function() {

      return window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {

        window.setTimeout( callback, 800 / 60 );

      };

    } )();

  }
</script><script type="text/javascript">
var canvas, context;
var xx = new Array();
var yy = new Array();
for (var i = 0; 40 > i; i++) {
   xx[i] = Math.random()*600;
   yy[i] = Math.random()*150;
}

init();
animate();
function init() {
  canvas = document.createElement( 'canvas' );
  canvas.width = 600;
  canvas.height = 400;
  context = canvas.getContext( '2d' );
  document.body.appendChild( canvas );
}
  
function animate() {
  requestAnimationFrame( animate );
  draw();
}
function draw() {
  var time = new Date().getTime() * 0.001;
  var x = Math.cos( time ) * 250 + 300;
  var y = Math.sin( time ) * 250 + 300;
  
  if(150 >= y) {context.fillStyle = 'rgb(250,250,250)';}
  else {
    if (200 >= y) {
      context.fillStyle='rgb(200,200,200)';
    } else {
      context.fillStyle='rgb(14, 14, 14)';
    }
  }
  
  context.fillRect( 0, 0, 600, 400 );
    
  context.fillStyle = 'rgb(255,255,0)';

  context.beginPath();
  
  context.arc( x, y, 15, 0, Math.PI * 2, false );
  context.closePath();
  context.fill();
  
  context.fillStyle = 'rgb(0,0,255)';
  context.fillRect(0, 215, 600, 400);
  
   for (var i = 0; 15 > i; i++) {
      
      context.fillStyle = 'rgb(255,255,255)';
      context.beginPath();
      context.arc(xx[i], yy[i], 1, 0, Math.PI * 2, false );
      context.closePath();
      context.fill();
  
      if (y > 200) {
          if (Math.floor(time) % 2 == 0) {
            context.fillStyle = 'rgb(255,255,255)';
            context.beginPath();
            context.arc(xx[i], yy[i] + 215, 1, 0, Math.PI * 2, false );
            context.closePath();
            context.fill();
          } else {
            context.fillStyle = 'rgb(255,255,255)';
            context.beginPath();
            context.arc((yy[i] / 150) * 600, (xx[i] / 600)*150 + 215, 1, 0, Math.PI * 2, false );
            context.closePath();
            context.fill();
          }
        }
      } 
    }
    </script>
  </body>
</html>

You can view the example online here.

Free ads: thanks for the start-up Handcraft for letting me quickly “craft” this product.

Lorem Lipsum

Lorem Lipsum

Source: http://www.lipsum.com/

“Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.”

Do you find the above passage familiar? If yes, can you guess what language it’s written by?

“Lorem lipsum” is simply a dummy passage which often appears on mocking website. Since the first appearance at 1500s, it soon become the standard text for printing and typesetting industry. Surprisingly, such an old standard still survive till today.

There are 3 reasons to use “Lorem lipsum”. First, it looks more like natural English than “Content here Content here …” text. Reading it give the customers a more accurate image of how the text look like when the site is complete. Second, the content on mocking website shouldn’t be uP/nderstandable, because many studies have point out that people are inclined to be distracted by readable text. And finally, since it has become a standard, it’s a shared background for any content layouters.

And… in case you don’t know, the content of “Lorem lipsum” actually has a meaning. It’s a Latin text taken from ”de Finibus Bonorum et Malorum” (The Extremes of Good and Evil) by Cicero, written in 45 BC – a popular book during the Renaissance.

I have been developeing website for more than a year, and such simple things always make people surprised…

P/s Thanks bro Lai Huu Nhon – a senior from my company (Evolus) – for this piece of knowledge. And by the way, I think his layout is cool.

Text

Running JMeter from command line

I trust that someday, you will understand me.

Though out there are plenty documents to run JMeter with Ant task, sometimes it’s not the best solution. For example, if the plan is to run several test scripts on several cloud server instances, it may not worth the effort to install Ant on each of those instances.

In that case, we can run JMeter script from command line, using one statement in the followings:

[jmeterBinDirectoryPath]/jmeter -n -t <testfile> 

or

[jmeterBinDirectoryPath]/java -jar ApacheJMeter.jar -n -t <testfile>

Credit goes to this blog post and this discussion in mailing list.

JMeter – Simulate multi-users scenario with counter

/** Vietnamese: bài viết trình bày về cách dùng JMeter Counter để  giả lập nhiều user truy xuất hệ thống cùng lúc **/

In load testing field, JMeter is a powerful tool, and powerful tool often means high learning curve. The fact that JMeter document is not so well-written caused programmers lots of troubles getting around with it. If you know how things to be done, it’s very simple. If not, you are going to spend several hours searching for the solution.

The situation: I need to simulate 1000 users to login in my system, using different username (ofcourse). After logging in, each user must input their activation code, gotten from the database. Then they go for the site functions as usual.

The interesting thing is that the activation code are random strings: I have no control how it be. But I must do mapping accurately from user to activation code. To do that, I write bootstrap code to generate  1000 users (user1 -> user1000) and their activation code. Next, export them to a CSV file to be read by JMeter.

  • user1,12345
  • user2,52341
  • user3,12534

But how to get those information to  JMeter? Using bean shell script, I managed to put these values in custom variables CurrentUser and CurrentUserActivationCode. But I must only put one pair of different value for each thread. Since JMeter have no global variable, I can’t tell it to increase each time a new thread start!

I searched for global variables for a while and try some suggestion (properties and the likes) without success. And then I remember that I only need a counter, because it simply doesn’t matter if the users log in in a order or not.

Solution: It’s JMeter Counter Config Element(actually I have no idea why a counter is a Config Element).

Gotchas of Authentication Flow for application on Facebook – OAuth 2.0 (1)

/**

Vietnamese: bài viết này trình bày một số điểm có thể gây nhầm lẫn trong quá trình chứng thực Facebook OAuth 2.0

**/

The Facebook Authentication Flow is rather complicated than it seems, and not very well documented. Here are some tips that maybe helpful if you are trying to make things work:

1. Notice parameters returned from Facebook:

  • code: When Facebook returns “code” parameter in Http request to your redirect URI, it means you need to use that code to request for access token.
  • signed_request: Signed request has several children parameters. An usual presumption is that this signed request always has Facebook ID of the current user. In fact it does if your application has already been authorized by that user. If not, you need to redirect the user to the giving-permission page.
  • request_ids: is used if your application has the “invite friends” functions. This is a comma-separated string (for example: “158187550924606,158187550924608,158187550924614″). Each number in that string is ID of an invitation sent (maybe by > 1 user). So we can say that a new user can accept the invitation of more than 1 Facebook user. In fact it is, since the app request may appears like “Viet X & Nam Y has invited you to use this app“. People often find it confused because they presume that a user can only be referred by only 1 user.

2. Always ask Facebook if your access token valid:

Even if you ask user to give “offline_access” right to your application, there’s a good chance that your stored access token will get expired. How do you know? Well, the only way available now is using your access token to request something, and if it fails, ask for a new one. That’s the way it works.

sometimes it’s hard to say a thing, though simple.

(to be continued)

Fav-icon – the simple trademarks of website

Facebook Favicon

God is in the details, said the architect Ludwig mies van der Rohe. Our world is built from billions of tiny elements, which is impossible to recognize if we just look on the surface. But coming closer, even a dust may have its history.

And a fav-icon has a history itself, too.

Did you ever notice that tiny icon which appears on top of your browser page/tab, whenever you visit a website? Yes, it has a name – a favicon. I’m not going to tell you about how the standard established. I’m going to tell you what I feel: about how it’s easy to miss these icons.

As a young web developer, I did not too much, but at least some real website. And yet it’s unbelievable that I doesn’t know about the favicon until recently. Maybe my teachers in university have mention it while I’m sleeping? Don’t know.

And one beautiful day, I suddenly realize how difficult to move among my chrome tabs without seeing their icons. Then I learn about favicon and how to make them. All that costs not more than 15 minutes. Now I know how to make a favicon myself.

@sagisou: this post is for you.

Put Tomcat in Eclipse

Photobucket

/**

Vietnamese: bài viết hướng dẫn về cách cấu hình để tích hợp Tomcat vào Eclipse

**/

Since most of the step-to-step-guide about this problem (at least the guides I found) are a bit out-dated, I think I had better create a guide here. In fact, this guide is taken from my brothers at Evolus. Special thanks to bro Trương Xuân Tính and bro Lê Hồ Bá Phước for this piece of knowledge and their patience to repeat-and-repeat this damn process for me.

Notice: this guide is not a complete guide, just some kind of a checklist. I’ll add more details over time. Please feel free to ask if there’s something you don’t understand.

0. Download & install Tomcat & Eclipse.

1. Find the Tomcat sysdeo plugin for eclipse. I found a download source here, but the location can change in the future.

2. Install the plugin (taken from the official guide). Extract the plugin file (in my case, its version is 3.3.0). Copy the plugin to:
- “Eclipse_Home/dropins” for Eclipse 3.4, 3.5 and 3.6
- “Eclipse_Home/plugins” for Eclipse 2.1, 3.0, 3.1, 3.2 and 3.3

Plugin activation for Eclipse 3.x :

  • launch eclipse once using this option : -clean
  • if Tomcat icons are not shown in toolbar : select menu ‘Window>Customize Perspective…>Commands’, and check ‘Tomcat’ in ‘Available command groups’

Set Tomcat version and Tomcat home : Workbench -> Preferences, select Tomcat and set Tomcat version and Tomcat home (Tomcat version and Tomcat home are the only required fields, other settings are there for advanced configuration).

This plugin launches Tomcat using the default JRE checked in Eclipe preferences window.

  • To set a JDK as default JRE for Eclipse open the preference window : Window -> Preferences -> Java -> Installed JREs. This JRE must be a JDK (This is a Tomcat prerequisite).
  • The plugin sets itself Tomcat classpath and bootclasspath. Use Preferences -> Tomcat ->JVM Settings, only if you need specific settings. Often, I set the variable -Denv=dev to use different config file for development & production.

3. Finalize

Go to the plugin folder, you will see 2 files: “DevLoader.zip” & “DevloaderTomcat7.jar”. As their name implies, you will use “DevLoader.zip” for Tomcat with version less than 7, and “DevLoaderTomcat7.jar” for Tomcat 7.

  • If you are using Tomcat 7, copy “DevloaderTomcat7.jar” to <TOMCAT_HOME>/lib
  • If you are using other Tomcat 6, rename “DevLoader.zip” to “DevLoader.jar”, then put it in <TOMCAT_HOME>/lib.

Create a web project (I’m using Maven to manage the builds). Go to the properties of your project, go to “Tomcat/Class Loader/”, un-check “servlet-api.jar” and other libraries that are already provided by Tomcat. This is for preventing conflicts among duplicate libraries.

Also in “Project/Properties”,  set the context name and web application root. Context name is the name that you use to access the web-app, for example, if the context name is “test”, your server url may be like: “localhost:8080/test/”. Web application root is the place you put your web-application (it’s the folder that contains WEB-INF folder, often named webapp).

If you are using Maven, remember, all these eclispe settings will be removed if you do “maven eclipse:clean”, so don’t use that command unless you want to do config again. Only use “maven eclipse:eclipse” instead.

That should complete the task. Good luck!

Reference: http://www.eclipsetotale.com/tomcatPlugin.html

Annotation Validation in Spring Framework 3

/* Vietnamese: bài viết hướng dẫn một cách ngắn gọn cách thực hiện kiểm tra điều kiện của đối tượng (validation) bằng cách dùng ký hiệu (annotation) với Spring Framework */

Validation is not a problem in Spring Framework, at least, by the normal way.

But the “Validation by Annotation” is not that popular, since this utility was only available from Spring 3. Up to now I found no resource which give a short & comprehensive tutorial yet (at least to this time – 05/2011)

How to make annotation validation works in Spring Framework 3

1. Configure Maven to include Hibernate Validator

2. Setup default validator bean in config file:
[sourcecoce language="xml"]
<bean id=”validator” class=”org.springframework.validation.beanvalidation.LocalValidatorFactoryBean” />
[/sourcecode]

3. Add @annotation

Let’s see what is annotation validation in its action:

public class User implements Serializable {
        private long id;
        @NotNull(message=&quot;{user.name.notnull}
        @Length(max = 255, message=&quot;{user.name.length}&quot;)
	private String username;
	public void setUsername(String name) {
		this.username = name;
	}
	public int getUsername() {
		return username;
	}
}

Code for the controller:

@Controller
@RequestMapping(&quot;/administration/*&quot;)
public class AdministrationController {
    /**
     * For every request for this controller, this will
     * create a user instance for the form.
     */
    @ModelAttribute
    public User newRequest(@RequestParam(required=false) String id) {
        return (id != null ? userService.getUserById(id) : new User());
    }

    @RequestMapping(value=&quot;/editUser&quot;, method=RequestMethod.GET)
	public final String edit(@Valid User user, BindingResult result) throws Exception {

		if (user == null) {
			return &quot;redirect:/administration/manageUser&quot;;
		}

		return null;
	}

	@RequestMapping(value=&quot;/editUser&quot;, method=RequestMethod.POST)
	public final String updateUser(@Valid User user, BindingResult result) throws Exception {

		if (result.hasErrors()) {
			return null;
		}

		userService.updateUser(user);

		return &quot;redirect:/administration/manageUser&quot;;
	}
}

And in the end, for the jsp:

&lt;/pre&gt;
&lt;h1&gt;Edit Site User&lt;/h1&gt;
&lt;div&gt;
&lt;fieldset&gt;&lt;legend&gt;Edit Site User&lt;/legend&gt;
 &lt;input type=&quot;hidden&quot; name=&quot;userId&quot; value=&quot;${user.id}&quot; /&gt;
				&lt;p&gt;
					&lt;form:label for=&quot;id&quot; path=&quot;id&quot;&gt;Id&lt;/form:label&gt;
					&lt;br /&gt;
					&lt;form:input path=&quot;id&quot; readonly=&quot;true&quot; /&gt;
					&lt;font color=&quot;red&quot;&gt;&lt;form:errors path=&quot;id&quot; /&gt;
					&lt;/font&gt;
				&lt;/p&gt;
				&lt;p&gt;
					&lt;form:label for=&quot;username&quot; path=&quot;username&quot;&gt;User Name&lt;/form:label&gt;
					&lt;br /&gt;
					&lt;form:input path=&quot;username&quot; readonly=&quot;true&quot; /&gt;
					&lt;font color=&quot;red&quot;&gt;&lt;form:errors path=&quot;username&quot; /&gt;
					&lt;/font&gt;
				&lt;/p&gt;
&lt;/fieldset&gt;
&lt;/div&gt;
&lt;pre&gt;

Load Testing with JMeter

**Vietnamese: mục tiêu của bài viết này là giới thiệu sơ lược về công cụ JMeter và cách áp dụng nó để kiểm tra tính bền vững của một website với số lượng truy cập lớn. **

The purpose of this article is to make a quick introduce about JMeter tool and how to apply it to test the performance of a website with high loading.

Why using JMeter for load testing

JMeter is a free tool, with a wide range of supported functions, and is very popular. Well, as I know (from several StackOverflow questions) there’s hundreds of popular web-testing tools out there. Just pick one, and this time I take JMeter.

Another notice is that this article won’t tell you how to configure Ant to use it along with JMeter. This tutorial is the guide to build a basic test plan to run with the JMeter GUI.

Build a test plan

First you need a test plan. For example, you want to test a Library Website when there are 200 users access at the same time. This is a very high load, given the fact that if your website has about 1000 users,  it’s very rare to see 10 of them access the website resource simultaneously.

We need to specify what a typical user do when accessing our website, for example:

  1. The user login
  2. The user browse books in library
  3. The user review some page of the book

To perform those actions, the user (unconsciously) send HTTP request to web-server through the browser. Assume they are:

  1. {server-address}/user/login
  2. {server-address}/books/browse
  3. {server-address}/book/preview/{page-number}

To achieve a list of requested links (and their parameters), you may use proxy server of JMeter, or an intercepting program like Fiddle2. But we don’t go into details of that issue here.

Get your test plan to JMeter:

After opening jmeter.bat, it makes a blank test plan ready for you. Here’s a screenshot:

JMeter screenshot

JMeter screenshot

Add a thread group: a thread group is the simulation of a user (a thread). In this thread group, we will add many HTTP Sampler Request – the action that the user will perform. Several important parameters of thread group is:

  • Number of thread(user): the number of thread will run simultaneously. For example, if you want to run 100 user at a time, this number is 100.
  • Loop: the number of times the thread will repeat.
  • Ramp up time: the time for the system to increase the thread number to the value specified by “number of thread”. If ramp-up time is 100s for 100 users, it means the time for JMeter to start 100 thread is 100s. If not specified, the system will try to start all the thread at 0s, which may cause overloading for the machine running JMeter.

Add a HTTP Sampler Request: this is a fake HTTP request, to an URL specified. You may select the request type (POST/GET), include data in parameter table or by specifying an included file.

Add custom variable: Not all request to web server is static. Some of them maybe dynamic, based on the previous request. Hence JMeter supports perl-like syntax to include variables in request URL.

Extract information from response: JMeter support extracting value from response to put it in local variable (which may be used in following requests). The value can be extracted by XPath or Regular expression.

Add a listener: To view and do statistics on the results, you will need a listener. In JMeter, there are lots of Listener type for you to choose. Basically, “View result tree” and “View result table” listeners is used to check the server concrete response; the others are statistic reporters that summarize the result of the load-test. The most important reporters are Aggregate Report and Summary report.

User think time: An easy-forgettable parameter in building test plan is user think-time. It bases on the fact that a user can not request as rapidly as a computer, but rather, having time to think(inputting forms, viewing items,…). JMeter has various timer object to have a request delayed for a specified (maybe dynamic) time.

Estimation:

Mostly the estimation is rather subjective, based on parameters like:

  1. Error rate
  2. Average response time
  3. Max response time
  4. 90% Line
  5. CPU/ RAM usage of server

I don’t go into details of all those parameters here. But maybe it’s a subject of another post.