Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Spring Capitulo 05

5,764 views

Published on

  • Be the first to comment

  • Be the first to like this

Spring Capitulo 05

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

×