ICE09 . playing with java, scala, groovy and spring .

Playing with Spring

Archive for July, 2008

Mailing with Velocity

Posted by ice09 on July 13, 2008

Download Eclipse project

Java Mailing is also leveraged by Spring, in the usual templating way some optimisations have been added. Therefore, we will write a small mailing application here.
We will add Velocity for mail templating.

MailSample:

package sample.mail;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class MailSample {

	private JavaMailSender mailSender;
	private VelocityEngine velocityEngine;

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public static void main(String[] args) throws Exception {
		ApplicationContext app = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		MailSample mailer = (MailSample) app.getBean("mailer");
		mailer.send();
	}

	private void send() {
	      MimeMessagePreparator preparator = new MimeMessagePreparator() {
	          public void prepare(MimeMessage mimeMessage) throws Exception {
	             MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	             message.setTo("mail.receiver@web.de");
	             message.setFrom("mail.sender@web.de"); // could be parameterized...
	             Map model = new HashMap();
	             model.put("key", "testtext");
	             String text = VelocityEngineUtils.mergeTemplateIntoString(
	                velocityEngine, "test.vm", model);
	             message.setText(text, true);
	          }
	       };
	       this.mailSender.send(preparator);
	}
}
  • the following part is also copied from the Email tutorial.

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
			<value>server.com</value>
		</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
			</props>
		</property>
<property name="username"><value>username</value></property>
<property name="password"><value>password</value></property>
	</bean>

	<bean id="mailer" class="sample.mail.MailSample">
<property name="mailSender" ref="mailSender" />
<property name="velocityEngine" ref="velocityEngine" />
	</bean>

   <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
         <value>
            resource.loader=class
            class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
         </value>
      </property>
   </bean>

</beans>
  • we just need two more files, of course the POM.

POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>velocitymail</groupId>
  <artifactId>velocitymail</artifactId>
  <name>velocitymail</name>
  <version>0.0.1-SNAPSHOT</version>
  <description/>
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring</artifactId>
  		<version>2.5.5</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.mail</groupId>
  		<artifactId>mail</artifactId>
  		<version>1.4</version>
  	</dependency>
  	<dependency>
  		<groupId>velocity</groupId>
  		<artifactId>velocity</artifactId>
  		<version>1.4</version>
  	</dependency>
  </dependencies>
</project>
  • and the velocity template, which is very simple in this case.

test.vm:

hello $key

and finally the project structure:

Advertisements

Posted in Mail, Velocity | Tagged: , , | Leave a Comment »

Quick Tip: Testing Spring

Posted by ice09 on July 12, 2008

Download Eclipse project

You can read detailed and good written documentation about unit testing with Spring here.
But as always, when combining Spring with Maven using Eclipse, some things have to be considered.

  • Create a “no archetype” Maven project in Eclipse (compare the other posts).
  • Create the test case first (following TDD) with Eclipse. This can be a JUnit 3 or 4 test case.
  • Afterwards, within Eclipse the class generation can easily be done using the Quick Fix funtionality (Strg + 1).

The test case must extends Spring’s AbstractDependencyInjectionSpringContextTests, making it much easier to use Spring in unit tests. It is best combined with the call to setPopulateProtectedVariables(true) in the constructor. Using this feature, Spring can inject Beans into protected fields, avoiding the need for setters in test cases.
By defining getConfigLocations(), special Spring configfiles for unit tests can be chosen. However, using Maven, we are always seperating test and main resources (compare project structure).

Test case:

package test.sample;

import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

public class SpringTest extends AbstractDependencyInjectionSpringContextTests {

	protected BeanUnderTest testbean;

	public SpringTest() {
		setPopulateProtectedVariables(true);
	}

	public void testBeanUnderTest() {
		assertEquals(1, testbean.return1());
	}

	@Override
	protected String[] getConfigLocations() {
		return new String[]{"applicationContext-test.xml"};
	}
}

Class under test (BeanUnderTest):

package test.sample;

public class BeanUnderTest {

	public int return1() {
		return 1;
	}

}

applicationContext-test.xml (currently this is the only config):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

	<bean id="testbean" class="test.sample.BeanUnderTest"/>

</beans>

And the Maven POM. It is important to include the Compiler 5 switches if JUnit 4 is used:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>testingsample</groupId>
	<artifactId>testingsample</artifactId>
	<name>testingsample</name>
	<version>0.0.1-SNAPSHOT</version>
	<description />
	<build>
		<finalName>testingsample</finalName>
                <plugins>
                        <plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.5</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>2.5.5</version>
		</dependency>
	</dependencies>
</project>

That’s it, Maven, JUnit and Spring can be combined very smoothly and Spring again shows with the AbstractDependencyInjectionSpringContextTests how it provides the useful little glue between these components.

Posted in Unit Tests | Tagged: , , | 1 Comment »