Wednesday, 29 February 2012

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

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

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

    @Override
    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.setContentType("text/html");
        resp.setStatus(HttpServletResponse.SC_OK);
        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"/>
                                    
                                    
                                        
                                            
                                                /test/myAction
                                            
                                        
                                        <property name="servletName" value="mockCharityServlet"/>
                                    
                                
                            
                        
                    
                
                
                
            
        
    


3. You Http Client code

final HttpPost post = new HttpPost("http://127.0.0.1:9800/test/myAction");
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

    dumbster
    dumbster
    1.6
    test

2. add bean definition to spring applicationContext.xml

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

using javax mail session

    
        
            127.0.0.1
            2525
        
    


    <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;
    }

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

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

    @Factory
    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();
        expectedMessage.store(smtpResponse, body);

        return expectedMessage;
    }

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

        while (receivedEmail.hasNext()) {
            return receivedEmail.next();
        }
        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 au.com.hothouse.toyota.utils.email.BodySmtpMessage.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@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" +
            "http://test.email.hothouse.com.au\n" +
            "\n" +
            "Thank you for vising the Toyota website.\n" +
            "\n" +
            "Regards,\n" +
            "\n" +
            "The Toyota Team";

    @Test
    public void testEmail() throws Exception {
        emailer.email("Jianjun", "Shou", "sean.shou@hothouse.com.au", "http://test.email.hothouse.com.au");
        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 setenv.sh in $CATALINA_HOME/bin, add following lines to here

CATALINA_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8086 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=192.168.4.38"


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

Thursday, 16 February 2012

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

solution:

create setenv.sh as follow and put it into $CANTLINA_HOME/bin

#!/bin/sh
JAVA_OPTS="-Xms256m -Xmx512m -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:MaxPermSize=256m"