Conhecer as facilidades de e-mails do Spring
Saber agendar tarefas com JDK Task
Saber interceptar métodos com AOP
Saber montar um contexto de teste com JUnit
Saber expor serviço via RMI
Depedências: mail.jar activation.jar• MailSender• Hierarquia de exceptions:
▪Funcionalidades especializadas para o envio de e-mail com suporte MIME(MimeMessagePreparator)
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="host.url.com.br" /> <property name="password" value="senha" /> <property name="username" value="[email protected]" /></bean>
<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage"> <constructor-arg index="0" ref="templateMessage" /> <property name="to" value="[email protected]" /> <property name="text" value=" 123 Testando... " /></bean>
package com.targettrust.spring.email;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.mail.MailException;import org.springframework.mail.MailSender;import org.springframework.mail.SimpleMailMessage;public class TesteEnviaEmail { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("/com/targettrust/spring/email/Spring-beans.xml");
SimpleMailMessage msg = (SimpleMailMessage)ac.getBean("simpleMailMessage"); MailSender ms = (MailSender)ac.getBean("mailSender");
try{ ms.send(msg); } catch(MailException ex) { ex.printStackTrace(); }
}}
package com.targettrust.spring.email;import java.io.File;import javax.mail.internet.MimeMessage;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;public class TesteMimeMessageHelperAtt { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "/com/targettrust/spring/email/Spring-beans.xml"); JavaMailSender ms = (JavaMailSender)ac.getBean("mailSender"); try{
MimeMessage message = ms.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message,true);helper.setFrom("[email protected]");helper.setTo("[email protected]");helper.setText("Email MimeMessageHelper");
FileSystemResource file = new FileSystemResource(new File(".").getCanonicalPath() + "/build.xml");
helper.addAttachment("build.xml", file);
ms.send(message);}catch(Exception e){ e.printStackTrace();}
}}
package com.targettrust.spring.email;import java.io.File;import javax.mail.internet.MimeMessage;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;public class TesteMimeMessageHelperAttImg { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext(
"/com/targettrust/spring/email/Spring-beans.xml");
JavaMailSender ms = (JavaMailSender)ac.getBean("mailSender"); try{
MimeMessage message = ms.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message,true);helper.setFrom("[email protected]");helper.setTo("[email protected]");helper.setText("<html><body><img src='cid:img1'><br>Email MimeMessageHelper com
suporte a imagems em linha!</body></html>",true);
FileSystemResource file = new FileSystemResource(new File(".").getCanonicalPath() + "/imagem.jpg");
helper.addInline("img1", file);ms.send(message);
}catch(Exception e){e.printStackTrace();
} }}
• Agendamento de Tarefas• Utiliza beans• Execução de tempos em tempos• Ecolha: menos XML VS menos
Acoplamento• Timer JDK
package com.targettrust.spring.jdktask;import java.util.Date;import java.util.TimerTask;public class HoraCertaService extends TimerTask{
@Override@SuppressWarnings("deprecation")public void run() {
System.out.println(new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds() );
}}
<?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="horaCertaService"class="com.targettrust.spring.jdktask.HoraCertaService"
/><bean
id="scheduledTask"class="org.springframework.scheduling.timer.ScheduledTimerTask"lazy-init="false"
><!-- Espera 0 ms antes de iniciar --><property name="delay" value="0" /><!-- roda de 1 em 1 segundo --><property name="period" value="1000" /><!-- Ira executar a TimerTask horaCertaService --><property name="timerTask" ref="horaCertaService" />
</bean></beans>
<bean id="timerFactory“
class="org.springframework.scheduling.timer.TimerFactoryBean” > <property name="scheduledTimerTasks">
<list> <ref bean="scheduledTask" /> </list>
</property> </bean>
<?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="horaCertaServiceNaoAcoplada" class="com.targettrust.spring.jdktask.HoraCertaServiceNaoAcoplada“ /> <bean id="scheduledTask“ lazy-init="false" class="org.springframework.scheduling.timer.ScheduledTimerTask” > <!-- Espera 0 ms antes de iniciar --> <property name="delay" value="0" /> <!-- roda de 1 em 1 segundo --> <property name="period" value="1000" /> <!-- Ira executar a TimerTask horaCertaService --> <property name="timerTask" ref="executor" /> </bean> <bean id="executor" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean“ > <property name="targetObject" ref="horaCertaServiceNaoAcoplada" /> <property name="targetMethod" value="showTime" /> </bean> <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean“ > <property name="scheduledTimerTasks"> <list>
<ref bean="scheduledTask" /> </list> </property> </bean></beans>
• Utiliza AOP com AspectJ• Abstrações sobre o AspectJ• Weaving em runtime• Dependências:
• aspectjweaver.jar• aspectjrt.jar
package com.targettrust.spring.aop;public interface Service {
public void fazAlgo();}
package com.targettrust.spring.aop;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class ServiceA implements Service{
private static final Log log = LogFactory.getLog(ServiceA.class);@Overridepublic void fazAlgo() {
log.info("Fiz algo do tipo A");}
}
package com.targettrust.spring.aop;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class ServiceB implements Service{
private static final Log log = LogFactory.getLog(ServiceB.class);
@Overridepublic void fazAlgo() {
log.info("Fiz algo do tipo B");}
}
package com.targettrust.spring.aop;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class ServiceC implements Service{
private static final Log log = LogFactory.getLog(ServiceC.class);
@Overridepublic void fazAlgo() {
log.info("Fiz algo do tipo C");}
}
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <aop:aspectj-autoproxy/> <bean id="aspecto“ lazy-init="false" class="com.targettrust.spring.aop.Aspecto“ /> <bean id="sa“ class="com.targettrust.spring.aop.ServiceA“ /> <bean id="sb“ class="com.targettrust.spring.aop.ServiceB“ /> <bean id="sc“ class="com.targettrust.spring.aop.ServiceC“ /> <bean id="services“ class="java.util.ArrayList“ > <constructor-arg index="0"> <list>
<ref bean="sa" /><ref bean="sb" /><ref bean="sc" />
</list> </constructor-arg> </bean></beans>
package com.targettrust.spring.aop;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class Aspecto {
private static final Log log = LogFactory.getLog(Aspecto.class);
@Before("execution(* com.targettrust.spring.aop.Service.*(..))")public void execucaoDeFazAlgoAntes() {
log.info("To sabendo antes da execução de Service");}
@After("execution(* com.targettrust.spring.aop.Service.*(..))")public void execucaoDeFazAlgoDepois() {
log.info("To sabendo depois da execução de Serice");}
@Around("execution(* com.targettrust.spring.aop.ServiceB.faz*(..)))") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
Object retVal = pjp.proceed(); log.info("To sabendo around SericeB"); return retVal;}
}
• Integração com Junit e TestNG•Auto-injeção de propriedades •Rollback automático após o teste•Prove testes integrados sem servidor de aplicação, mas usando transação e banco de dados.•Cache
•AbstractDependencyInjectionSpringContextTests•AbstractAnnotationAwareTransactionalTests:
• @DirtiesContext: Annotation que faz o mesmo que o método setDirty isso fará que o contexto seja recarregado nesse método.• @ExpectedException: Annotation que sinaliza que o método deve retornar um exception específica, se ele não retornar o teste irá falhar.• @NotTransactionl: Indica que esse método roda fora do contexto de transações do Spring.• @Repeat: Essa annotation recebe um número, por exemplo 5. O Spring irá repitir esse teste 5 vezes.
•AbstractTransactionalDataSourceSpringContextTests
package com.targettrust.spring.testing;import java.util.Date;import junit.framework.Assert;import org.springframework.test.AbstractDependencyInjectionSpringContextTests;public class TestDataService extends AbstractDependencyInjectionSpringContextTests {
private DataService dataService;
public void setDataService(DataService dataService) {this.dataService = dataService;
}
@Overrideprotected String[] getConfigLocations() { return new String[]{"classpath:com/targettrust/spring/testing/Spring-beans.xml"};}
@SuppressWarnings("deprecation")public void testDataDoDataService(){
Date d = dataService.getSysDate();Date l = new Date();
Assert.assertEquals(d.getDay(),l.getDay());Assert.assertEquals(d.getMonth(),l.getMonth());Assert.assertEquals(d.getYear(),l.getYear());
}
}
• Exposição de beans•Pode ser: RMI, JAX-RPC, JMS, Hessian, Burlap, Http Invoker e até mesmo EJB.•Para RMI:
•Serializable•Porta na máquina•Abstração sob o RMI
package com.targettrust.spring.remoting;import java.util.Date;public interface HoraService {
public Date getDate();}
package com.targettrust.spring.remoting;import java.util.Calendar;import java.util.Date;public class HoraServiceImpl implements HoraService{ public Date getDate() { return Calendar.getInstance().getTime(); }}
<?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="horaService" class="com.targettrust.spring.remoting.HoraServiceImpl” />
<bean class="org.springframework.remoting.rmi.RmiServiceExporter”> <property name="serviceName" value="Target-HoraService"/> <property name="service" ref="horaService"/> <property name="serviceInterface“ value="com.targettrust.spring.remoting.HoraService"/> <property name="registryPort" value="1199"/> </bean></beans>
<?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="horaService” class="org.springframework.remoting.rmi.RmiProxyFactoryBean" > <property name="serviceUrl" value="rmi://localhost:1199/Target-HoraService"/> <property name="serviceInterface" value="com.targettrust.spring.remoting.HoraService"/> </bean></beans>
1. Crie um Aspecto para logar todas as chamadas aos dados de um sistema2. Crie um agendamento com JDK Task que de 5 em 5 segundos manda um
e-mail para uma pessoa informando se ouve alguma mudança no sistema.3. Crie um serviço de calculadora e exporte ele via RMI, faça um porgrama
cliente com o suporte de Junit do Spring e suas classes de teste.