Wednesday 29 February 2012

How to mock http servlet with jetty to test some http-post,http-get in unit test?

1. Write you own mock servlet
public class MockServlet extends HttpServlet {
    private String servletData;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        contextService(req, resp);

    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);

    private void contextService(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        servletData = IOUtils.toString(req.getInputStream());

        resp.getWriter().print("Response from mock server: Submit is success.");

    public String getServletData() {
        return servletData;

2. define mock beans in spring application context (servlet and jetty server)
2.1 servlet:

<bean id="mockServlet" class="my.MockServlet"/>

2.2 jetty server

                    <property name="host" value="localhost"/>
                    <property name="port" value="8900"/>
                    <property name="contextPath" value="/"/>
                        <bean class="org.mortbay.jetty.servlet.SessionHandler">
                    <property name="resourceBase" value="c:/temp"/>
                                        <property name="name" value="defaultServlet"/>
                                            <bean class="org.mortbay.jetty.servlet.DefaultServlet"/>
                                                <entry key="resourceBase" value="./"/>
                                        <property name="name" value="mockServlet"/>
                                        <property name="servlet" ref="mockServlet"/>
                                                <entry key="resourceBase" value="./"/>
                                        <property name="servletName" value="defaultServlet"/>
                                        <property name="servletName" value="mockCharityServlet"/>

3. You Http Client code

final HttpPost post = new HttpPost("");
final HttpResponse resp = hc.execute(post);
final HttpEntity respContent = resp.getEntity();
final InputStream is = respContent.getContent();
final StringWriter strWr = new StringWriter();
IOUtils.copy(is, strWr);
return strWr.toString();

4. Junit
String expected = "Response from mock server: Submit is success.";
String actual = mockClient.submit();
assertEquals(expected, actual);

How to test email of junit

How can it test email of junit? Solution use dumbster as a fake smtp server 1. add dependency to pom.xml


2. add bean definition to spring applicationContext.xml

    <constructor-arg index="0" value="2525"/>

using javax mail session


    <constructor-arg ref="mailSession" type="javax.mail.Session"/>

or if you using spring mail sender:
<bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender" p:host="localhost" p:port="2525"/>
3. define one util class
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SmtpMessage;
import com.dumbster.smtp.SmtpResponse;
import com.dumbster.smtp.SmtpState;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import java.util.Iterator;

public class BodySmtpMessage extends TypeSafeMatcher<Smtpmessage> {
    private SmtpMessage smtpMessage;

    public BodySmtpMessage(SmtpMessage smtpMessage) {
        this.smtpMessage = smtpMessage;

    public boolean matchesSafely(SmtpMessage smtpMessage) {
        return smtpMessage.getBody().equals(smtpMessage.getBody());

    public void describeTo(Description description) {
        description.appendText("not same body message");

    public static <T> Matcher<smtpmessage> bodyEqualTo(SmtpMessage smtpMessage) {
        return new BodySmtpMessage(smtpMessage);

    public static SmtpMessage getExpectedSmtpMessage(String body) {
        SmtpResponse smtpResponse = new SmtpResponse(1, "", SmtpState.DATA_BODY);
        SmtpMessage expectedMessage = new SmtpMessage();, body);

        return expectedMessage;

    public static SmtpMessage getFirstReceivedMessage(SimpleSmtpServer simpleSmtpServer) {
        Iterator<smtpmessage> receivedEmail = simpleSmtpServer.getReceivedEmail();

        while (receivedEmail.hasNext()) {
        return null;
4. Junit
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SmtpMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

import static*;
import static;
import static org.junit.Assert.*;

@ContextConfiguration(locations = "classpath*:applicationContext-test.xml")
public class TestEmailerImpl {
    @Resource(name = "saveYourCarEmailer")
    private EmailerImpl emailer;
    @Resource(name = "fakeSmtpServer")
    private SimpleSmtpServer simpleSmtpServer;

    private static String EXPECTED = "Dear Jianjun Shou,\n" +
            "\n" +
            "Here is the permanent link to the vehicle you have created:\n" +
            "\n" +
            "\n" +
            "\n" +
            "Thank you for vising the Toyota website.\n" +
            "\n" +
            "Regards,\n" +
            "\n" +
            "The Toyota Team";

    public void testEmail() throws Exception {"Jianjun", "Shou", "", "");
        assertTrue("test failed", simpleSmtpServer.getReceivedEmailSize() > 0);
        SmtpMessage sentMessage = getFirstReceivedMessage(simpleSmtpServer);
        SmtpMessage expectedSmtpMessage = getExpectedSmtpMessage(EXPECTED);
        assertThat(sentMessage, is(bodyEqualTo(expectedSmtpMessage)));

Friday 17 February 2012

How to enable jmx on tomcat in linux

create in $CATALINA_HOME/bin, add following lines to here

CATALINA_OPTS=" -Djava.rmi.server.hostname="

Important!: don't forget to give quote(")

Thursday 16 February 2012

Tomcat: “java.lang.OutOfMemoryError: PermGen space” error


create as follow and put it into $CANTLINA_HOME/bin

JAVA_OPTS="-Xms256m -Xmx512m -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:MaxPermSize=256m"