这篇里,做一些简单轻松的配置,邮件服务器的连接与资源的存储。

         第一篇的架构中就有提到,通常在开发Web程序时,要连接的外部辅助系统不仅仅只是数据库,还有很多其他的系统需要连接,故而将业务层下面一层叫做Pin, 来做与外部系统的数据交互。这里就列举一些:比如LDAP 服务器,即轻量级目录访问协议的服务器,简单而言是一种优化了读操作的数据库;用来连接其他Web或非Web程序的Web-Service ;邮件服务器;资源管理服务器等等。

        很明显,我们的架构是:业务逻辑(Business)层将业务数据模型(Entity)传递给Pin层,Pin层将Entity解析为外部系统能够接受的形式后交由外部系统使用或帮助本系统代管;反方向地,Pin层将外部系统的数据读到并封装成本系统的Entity 后交给Business层做相应处理。

       LDAP和Web-Service将会放在后面的两篇。这里,配置两个简单的:邮件服务器,资源管理服务器

      1,邮件服务器。用法很容易想到,我们都见过很多的邮件服务器的Web Application,因为

           这里笔者就不再废话连篇,上代码:

           在@Configuration的ApplicationContext.java文件中ApplicationContext  类体中加入:

 
  
  1. @Bean   
  2. public JavaMailSender mailSender() {   
  3.     Properties parameters = WebConfiguration.getSysParams();   
  4.     JavaMailSenderImpl jms = new JavaMailSenderImpl();   
  5.     jms.setHost((String) parameters.get("mail.smtp.host"));   
  6.     jms.setUsername((String) parameters.get("mail.smtp.username"));   
  7.     jms.setPassword((String) parameters.get("mail.smtp.password"));   
  8.     jms.setDefaultEncoding((String) parameters.get("mail.smtp.encoding"));   
  9.     jms.setPort(Integer.parseInt((String) parameters.get("mail.smtp.port")));   
  10.     jms.setProtocol((String) parameters.get("mail.transport.protocol"));   
  11.     jms.setJavaMailProperties(parameters);   
  12.     return jms;   
  13. }  

        JavaMailSender类在org.springframework.context-support-x.x.x.RELEASE.jar包中,不要忘记导此包入WEB-INF/lib下

当然,还要有JavaMail API的类库,在Spring文档http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mail.html中写的是

mail.jar和activation.jar

        由于activation.jar即JAF已经成为标准的Java组件而被包含在1.6版本以上的JDK中,所以1.6版本以上的JDK不再需要activation.jar,然后新版的JavaMail API应该是6个jars.分别为:mail.jar  mailapi.jar dsn.jap  imap.jar  pop3.jar smtp.jar

 

Parameters 自然还在sysParams.properties文件中去写。

 
  
  1. mail.store.protocol=pop3   
  2. mail.transport.protocol=smtp   
  3. mail.smtp.encoding=utf-8   
  4. mail.smtp.host=127.0.0.1   
  5. mail.smtp.port=25   
  6. mail.smtp.username=root   
  7. mail.smtp.password=root   
  8. mail.smtp.socketFactory.port=465   
  9. mail.smtp.auth=true   
  10. mail.smtp.timeout=10000   
  11. mail.smtp.starttls.enable=true   
  12. mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory   

        而后,在pin层新建接口IMailPin.java,  在pin.imap下新建该接口实现类SpringMailPin.java

        代码如下:

 
  
  1. package com.xxxxx.webmodel.pin.impl;   
  2.    
  3. import java.io.Serializable;   
  4.    
  5. import javax.annotation.Resource;   
  6. import javax.mail.Message.RecipientType;   
  7. import javax.mail.MessagingException;   
  8. import javax.mail.internet.InternetAddress;   
  9. import javax.mail.internet.MimeMessage;   
  10.    
  11. import org.springframework.mail.javamail.JavaMailSender;   
  12. import org.springframework.mail.javamail.JavaMailSenderImpl;   
  13. import org.springframework.stereotype.Component;   
  14.    
  15. import com.xxxxx.webmodel.pin.IMailPin;   
  16.    
  17. @Component   
  18. public class SpringMailPin implements IMailPin,Serializable {   
  19.        
  20.     private static final long serialVersionUID = -1313340434948728744L;   
  21.     private JavaMailSender mailSender;   
  22.    
  23.     public JavaMailSender getMailSender() {   
  24.         return mailSender;   
  25.     }   
  26.     @Resource   
  27.     public void setMailSender(JavaMailSender mailSender) {   
  28.         this.mailSender = mailSender;   
  29.     }   
  30.     @Override   
  31.     public void testMail() {   
  32.         JavaMailSenderImpl jms = (JavaMailSenderImpl)this.mailSender;   
  33.         System.out.println(jms.getHost());   
  34.         MimeMessage mimeMsg =jms.createMimeMessage();   
  35.         try {   
  36.                    mimeMsg.setSubject("Test James");   
  37.             mimeMsg.setFrom(new InternetAddress("xxxxxx@tom.com"));   
  38.             mimeMsg.setRecipient(RecipientType.TO, new Inter-netAddress("xxxxx@live.com"));   
  39.             mimeMsg.setRecipient(RecipientType.CC, new Inter-netAddress("xxxxxx@yahoo.com"));   
  40.             mimeMsg.setRecipient(RecipientType.BCC, new Inter-netAddress("xxxxx@mail.com"));   
  41.             mimeMsg.setText("Hello");   
  42. //          MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMsg, true, "utf-8");   
  43. //          mimeMessageHelper.setFrom("hitmit1314@tom.com");   
  44. //          mimeMessageHelper.setTo("palmtale@live.com");   
  45. //             
  46. //          mimeMessageHelper.setCc("palmtale@yahoo.com");   
  47. //          mimeMessageHelper.setBcc("palmtale@mail.com");   
  48. //          mimeMessageHelper.setSubject("Test mail");   
  49. //          mimeMessageHelper.setText("Hi, Hello", true);   
  50.             mailSender.send(mimeMsg);   
  51.         } catch (MessagingException e) {   
  52.             e.printStackTrace();   
  53.         }      
  54.     }   

      然后还有简单的单元测试类

 

 
  
  1. package com.xxxxx.webmodel.test.pin;   
  2. import javax.annotation.Resource;   
  3.    
  4. import org.junit.BeforeClass;   
  5. import org.junit.Test;   
  6. import org.junit.runner.RunWith;   
  7. import org.springframework.test.context.ContextConfiguration;   
  8. import org.springframework.test.context.TestExecutionListeners;   
  9. import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;   
  10. import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;   
  11. import org.springframework.test.context.support.DirtiesContextTestExecutionListener;   
  12. import org.springframework.test.context.transaction.TransactionalTestExecutionListener;   
  13.    
  14. import com.xxxxx.webmodel.pin.IMailPin;   
  15. import com.xxxxx.webmodel.util.ApplicationContext;   
  16. import com.xxxxx.webmodel.util.WebConfiguration;   
  17. @RunWith(SpringJUnit4Cla***unner.class)   
  18. @ContextConfiguration(classes={ApplicationContext.class})   
  19. @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, DirtiesContext-TestExecutionListener.class, TransactionalTestExecutionListener.class })   
  20. public class MailPinTest {   
  21.    
  22.     private IMailPin mailPin;   
  23.        
  24.     public IMailPin getMailPin() {   
  25.         return mailPin;   
  26.     }   
  27.     @Resource   
  28.     public void setMailPin(IMailPin mailPin) {   
  29.         this.mailPin = mailPin;   
  30.     }   
  31.    
  32.     @BeforeClass   
  33.     public static void init() throws Exception {   
  34.         new WebConfiguration().onStartup(null);   
  35.     }   
  36.        
  37.     @Test   
  38.     public void test() {   
  39.         mailPin.testMail();   
  40.     }   
  41. }   

        可以运行起一个James做简单测试http://james.apache.org/,3.0的新版还未有Release出Stable版本来,最新稳定版本是2.3.2.

       Download  Stable James Server2.3.2后的得到james-binary-2.3.2.tar.gz或 james-binary-2.3.2.zip

       解压后放到自己的安装目录下,然后读下面链接的内容,来获知基本用法;

http://wiki.apache.org/james/JamesQuickstart

       以及下面的内容,获知如何将James安装为系统的service

http://wiki.apache.org/james/RunAsService

       一切就绪后,测试。成功与否就查自己的邮件吧,有些邮件服务器发不到,多试一些。

       比如,我在雅虎邮箱里能收到上述测试邮件

其它需求可以在上述Spring文档中查阅。

 

       2,资源管理服务器。什么是资源管理服务器?用来存储诸如图片,音频,视频,文档等资源的服务器。有人会说,存储在部署Web的服务器本身的硬盘上不就行了么。 好,文件系统,最简单的资源管理服务器。可是,把这些资源放到Local的文件系统上,这样的Case会有不适合的情况。例如我们需要部署一个Web服务集群以供并发量较高的访问,有好多台服务器部署着同样的WebApp,一个控制Node去管理是哪台机器响应用户的访问,这时,你就需要同步每一台服务器的文件系统的同一个位置上的所有资源(文件)。虽然可以做到,但是跑一个线程去同步N个 /var/resources比起配置所有服务器通过某协议访问一个固定的Socket(Host:Port)还是复杂,而且前者会遇到实时拖延问题:是说在一个时刻,A用户访问到了A服务器需要B资源,可是当时正好B资源还没有被跑着的线程挪过来到A服务器上。所以用一个固定的资源管理器是个不错的选择,比如Amazon 的S3服务器。想地有点儿远了,自己架设个FTP比什么都强。

 

        这部分很简单,直接贴代码喽:

       接口:

 
  
  1. package com.xxxxx.webmodel.pin;   
  2. import java.io.InputStream;   
  3.    
  4. public interface IResourcePin {   
  5.        
  6.     public boolean isExisting(String key) throws Exception;   
  7.     public void storeResource(String key,Object data) throws Exception;   
  8.     public <Form> Form achieveResource(String key,Class<Form> clasze)throws Exception;   
  9.     public void removeResource(String key) throws Exception;   
  10.        
  11.     enum DataType{   
  12.         Base64(String.class),ByteArray(byte[].class),InputStream(InputStream.class);   
  13.    
  14.         @SuppressWarnings("rawtypes")   
  15.         DataType(Class claze){   
  16.             this.dataType=claze;   
  17.         }   
  18.         @SuppressWarnings("rawtypes")   
  19.         private Class dataType;   
  20.         @SuppressWarnings("rawtypes")   
  21.         public Class getDataType(){return dataType;}   
  22.     }   
  23. }   

  测试方法:

 

 
  
  1. package com.xxxxx.webmodel.test.pin;   
  2.    
  3. @RunWith(SpringJUnit4Cla***unner.class)   
  4. @ContextConfiguration(classes={ApplicationContext.class})   
  5. @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, DirtiesContext-TestExecutionListener.class, TransactionalTestExecutionListener.class })   
  6. public class ResourcePinTest {   
  7.    
  8.     private String testKey =  "projectA/belong1/belong2/doc3";   
  9.     private IResourcePin resourcePin;   
  10.     @BeforeClass   
  11.     public static void init() throws Exception{   
  12.         new WebConfiguration().onStartup(null);   
  13.     }   
  14.     @Resource(name="ftpResourcePin")   
  15.     public void setResourcePin(IResourcePin resourcePin){   
  16.         this.resourcePin = resourcePin;   
  17.     }   
  18.     @Test   
  19.     public void testIsExisting()throws Exception {   
  20.         Assert.assertFalse(resourcePin.isExisting(testKey));   
  21.     }  
  22.     @Test   
  23.     public void testStoreResource()throws Exception {   
  24.         resourcePin.storeResource(testKey, "Test Resource".getBytes("UTF-8"));   
  25.         Assert.assertTrue(resourcePin.isExisting(testKey));   
  26.         resourcePin.removeResource(testKey);   
  27.         resourcePin.storeResource(testKey, new ByteArrayInputStream("Test Re-source".getBytes("UTF-8")));   
  28.         Assert.assertTrue(resourcePin.isExisting(testKey));   
  29.         resourcePin.removeResource(testKey);   
  30.         resourcePin.storeResource(testKey, new BASE64Encoder().encode("Test Re-source".getBytes("UTF-8")));   
  31.         Assert.assertTrue(resourcePin.isExisting(testKey));   
  32.         resourcePin.removeResource(testKey);   
  33.     }   
  34.    
  35.     @Test   
  36.     public void testAchieveResource() throws Exception{   
  37.         resourcePin.storeResource(testKey, "Test Resource".getBytes("UTF-8"));   
  38.         InputStream is0 =resourcePin.achieveResource(testKey, null);   
  39.         byte[] resultBytes0 = FileCopyUtils.copyToByteArray(is0);   
  40.         Assert.assertTrue(new String(resultBytes0,"UTF-8").equals("Test Resource"));   
  41.         InputStream is =resourcePin.achieveResource(testKey, InputStream.class);   
  42.         byte[] resultBytes = FileCopyUtils.copyToByteArray(is);   
  43.         Assert.assertTrue(new String(resultBytes,"UTF-8").equals("Test Resource"));   
  44.         byte[] byteArray = resourcePin.achieveResource(testKey, byte[].class);   
  45.         Assert.assertTrue(new String(byteArray,"UTF-8").equals("Test Resource"));   
  46.         String base64Code = resourcePin.achieveResource(testKey,String.class);   
  47.         Assert.assertTrue(new String(new BASE64Decoder().decodeBuffer(base64Code),"UTF-8").equals("Test Resource"));   
  48.         try{resourcePin.achieveResource(testKey, Integer.class);}   
  49.         catch(Exception use){   
  50.             Assert.assertTrue(use.getMessage().startsWith("Data Type is not support-ed"));   
  51.         }      
  52.         resourcePin.removeResource(testKey);           
  53.     }   
  54.    
  55.     @Test   
  56.     public void testRemoveResource() throws Exception{   
  57.         resourcePin.storeResource(testKey, "Test Resource".getBytes("UTF-8"));   
  58.         Assert.assertTrue(resourcePin.isExisting(testKey));   
  59.         resourcePin.removeResource(testKey);   
  60.         Assert.assertFalse(resourcePin.isExisting(testKey));   
  61.     }   
  62.    
  63. }  

   FileSystem实现:

 

 
  
  1. package com.xxxxx.webmodel.pin.impl;   
  2.     
  3. @Component   
  4. public class FileSystemResourcePin implements Serializable,IResourcePin {   
  5.    
  6.     /**  
  7.      *   
  8.      */   
  9.     private static final long serialVersionUID = -8508501371117792553L;   
  10.    
  11.     private String fileSystemRoot;   
  12.        
  13.     public static long getSerialversionuid() {   
  14.         return serialVersionUID;   
  15.     }   
  16.     public FileSystemResourcePin(){   
  17.         try{   
  18.             this.fileSystemRoot =   WebConfigura-tion.getSysParams().getProperty("resource.storage.relativePath");   
  19.             if(!this.fileSystemRoot.startsWith("/"))this.fileSystemRoot='/'+this.fileSystemRoot;   
  20.         }   
  21.         catch(Exception e){this.fileSystemRoot= "/fileStorage";}   
  22.         this.fileSystemRoot = this.getClass().getResource("/").getFile().replace("/WEB-INF/classes",this.fileSystemRoot);   
  23.     }   
  24.     @Override   
  25.     public boolean isExisting(String key) throws Exception {   
  26.         return isExisting(new File(this.fileSystemRoot,key));   
  27.     }   
  28.    
  29.     private boolean isExisting(File file){   
  30.         return file.exists();   
  31.     }   
  32.        
  33.     @SuppressWarnings("unchecked")   
  34.     @Override   
  35.     public void storeResource(String key, Object data) throws Exception {   
  36.         if(key==null||key.trim().length()==0||data==nullreturn;   
  37.         @SuppressWarnings("rawtypes")   
  38.         Class dataType = data.getClass();   
  39.         for(DataType supportedType: DataType.values()){   
  40.             if(supportedType.getDataType().isAssignableFrom(dataType))   
  41.             {   
  42.                 File targetFile = new File(this.fileSystemRoot,key);   
  43.                 if(!targetFile.exists())   
  44.                     {target-File.getParentFile().mkdirs();targetFile.createNewFile();}   
  45.                 FileOutputStream fos = new FileOutputStream(targetFile);   
  46.                 switch(supportedType){   
  47.                 case Base64:data =(Object) new BASE64Decoder().decodeBuffer((String)data);   
  48.                 case ByteArray:data = (Object)new ByteArrayInputStream((byte[])data);   
  49.                 case InputStream:FileCopyUtils.copy((InputStream)data, fos);   
  50.                 default:return;   
  51.                 }   
  52.             }   
  53.         }   
  54.         throw new Exception("Data Type is not supported");   
  55.     }   
  56.        
  57.     @SuppressWarnings("unchecked")   
  58.     @Override   
  59.     public <Form> Form achieveResource(String key, Class<Form> clasze)   
  60.             throws Exception {   
  61.         File keyFile = new File(this.fileSystemRoot,key);   
  62.         if(!keyFile.exists()||keyFile.isDirectory())return null;   
  63.         if(clasze==null)return (Form) achieveResource(key,InputStream.class);   
  64.         for(DataType supportedType: DataType.values()){   
  65.             if(clasze.equals(supportedType.getDataType()))   
  66.             {   
  67.                 FileInputStream fis = new FileInputStream(keyFile);   
  68.                 switch(supportedType){   
  69.                 case InputStream:return (Form)fis;   
  70.                 case ByteArray:return (Form)FileCopyUtils.copyToByteArray(fis);   
  71.                 case Base64:return (Form)new BASE64Encoder().encode(FileCopyUtils.copyToByteArray(fis));   
  72.                 }   
  73.             }   
  74.         }   
  75.         throw new Exception("Data Type is not supported");   
  76.     }   
  77.    
  78.     @Override   
  79.     public void removeResource(String key) throws Exception {   
  80.         new File(this.fileSystemRoot,key).delete();   
  81.     }   
  82.    
  83. }   

    FTP实现

 

 
  
  1. package com.xxxxx.webmodel.pin.impl;    
  2. @Component("ftpResourcePin")   
  3. public class FTPResourcePin implements Serializable,IResourcePin{   
  4.    
  5.     /**  
  6.      *   
  7.      */   
  8.     private static final long serialVersionUID = -4273201499908924422L;   
  9.     private FtpClient ftpClient;   
  10.     private String ftpUser="admin";   
  11.     private String password="password";   
  12.     private SocketAddress ftpServerAddress = new InetSocket-Address("127.0.0.1",FtpClient.defaultPort());   
  13.     private String releateRootPath="/ftproot";   
  14.        
  15.     public FTPResourcePin(){   
  16.         String ftpURL = null;   
  17.         try{   
  18.             ftpURL =WebConfiguration.getSysParams().getProperty("resource.ftp.url");   
  19.             if(ftpURL!=null){   
  20.                 int protocolIndex = ftpURL.indexOf("://");   
  21.                 if(protocolIndex>=0)ftpURL=ftpURL.substring(protocolIndex+3);   
  22.                 int usrIndex = ftpURL.indexOf('@');   
  23.                 if(usrIndex>=0){   
  24.                     this.ftpUser = ftpURL.substring(0,usrIndex);   
  25.                     ftpURL = ftpURL.substring(usrIndex+1);   
  26.                 }   
  27.                 int hostIndex = ftpURL.indexOf('/');   
  28.                 if(hostIndex>=0){   
  29.                     String[] socket = ftpURL.substring(0,hostIndex).split(":");   
  30.                     this.ftpServerAddress = new InetSocket-Address(socket[0],socket.length>1?Integer.parseInt(socket[1]):FtpClient.defaultPort());   
  31.                     ftpURL=ftpURL.substring(hostIndex);   
  32.                 }   
  33.                 this.releateRootPath=ftpURL.startsWith("/")?ftpURL:"/"+ftpURL;   
  34.             }   
  35.             this.releateRootPath+=WebConfiguration.getSysParams().getProperty("resource.storage.relativePath");   
  36.         }   
  37.         catch(Exception e){/*do as default value*/}   
  38.         try {   
  39.             this.ftpClient =FtpClient.create((InetSocketAddress)this.ftpServerAddress);   
  40.         } catch (FtpProtocolException | IOException e) {   
  41.             e.printStackTrace();   
  42.         }   
  43.     }   
  44.        
  45.     public static long getSerialversionuid() {   
  46.         return serialVersionUID;   
  47.     }   
  48.    
  49.     private void checkConnection(){   
  50.         try {   
  51.             if(!ftpClient.isConnected())   
  52.                 this.ftpClient.connect(this.ftpServerAddress);   
  53.             if(!ftpClient.isLoggedIn())   
  54.             {   
  55.                 try{this.password = WebConfigura-tion.getSysParams().getProperty("resource.ftp.password");}catch(Exception e){}   
  56.                 ftpClient.login(this.ftpUser, this.password.toCharArray());   
  57.             }   
  58.         } catch (FtpProtocolException e) {   
  59.             e.printStackTrace();   
  60.         } catch (IOException e) {   
  61.             e.printStackTrace();   
  62.         }   
  63.     }   
  64.        
  65.     private void gotoDirectory(String dir,Boolean write){   
  66.         if(dir==null||dir.trim().length()==0)return;   
  67.         if(write==null)write=false;   
  68.         try {   
  69.             dir = dir.replaceAll("\\\\+""/");   
  70.             if(dir.startsWith("/")){   
  71.                 this.checkConnection();   
  72.                 ftpClient.reInit();   
  73.                 dir=(this.releateRootPath+dir).replaceAll("/+""/");   
  74.                 if(dir.startsWith("/"))dir=dir.substring(1);   
  75.             }   
  76.             String[] dirs = dir.split("/");   
  77.             this.checkConnection();   
  78.             for(String dire:dirs){   
  79.                 if(write)try{ftpClient.makeDirectory(dire);}   
  80.                 catch(sun.net.ftp.FtpProtocolException fpe){   
  81.                     if(!fpe.getMessage().contains("Cannot create a file when that file already exists"))   
  82.                         throw fpe;}   
  83.                 ftpClient.changeDirectory(dire);   
  84.             }   
  85.         } catch (FtpProtocolException | IOException e) {   
  86.             if(e instanceof FtpProtocolException && e.getMessage().contains("The sys-tem cannot find the file specified"));   
  87.         }   
  88.     }   
  89.     @Override   
  90.     public boolean isExisting(String key) throws Exception {   
  91.         if(key==null)   
  92.             return false;   
  93.         try{   
  94.             key =('/'+key.replaceAll("\\\\+""/")).replaceAll("/+""/");   
  95.             int lastIdx = key.lastIndexOf('/');   
  96.             this.gotoDirectory(key.substring(0,lastIdx), null);   
  97.             String fileName = key.substring(lastIdx+1);   
  98.             InputStream is =ftpClient.nameList(fileName);   
  99.             byte[] testContent = FileCopyUtils.copyToByteArray(is);   
  100.             if(testContent!=null&&testContent.length>0)   
  101.                 return new String(testContent).trim().equals(fileName);   
  102.             else return false;   
  103.         }catch(Exception e){   
  104.             if(e instanceof sun.net.ftp.FtpProtocolException && e.getMessage().contains("The system cannot find the file specified"))   
  105.                 return false;   
  106.             else throw e;   
  107.         }   
  108.     }   
  109.    
  110.     @SuppressWarnings("unchecked")   
  111.     @Override   
  112.     public void storeResource(String key, Object data) throws Exception {   
  113.         if(key==null||key.trim().length()==0||data==nullreturn;   
  114.         @SuppressWarnings("rawtypes")   
  115.         Class dataType = data.getClass();   
  116.         for(DataType supportedType: DataType.values()){   
  117.             if(supportedType.getDataType().isAssignableFrom(dataType))   
  118.             {   
  119.                 OutputStream os = null;   
  120.                 try{   
  121.                     key =('/'+key.replaceAll("\\\\+""/")).replaceAll("/+""/");   
  122.                     int lastIdx = key.lastIndexOf('/');   
  123.                     this.gotoDirectory(key.substring(0,lastIdx), true);   
  124.                     os =ftpClient.putFileStream(key.substring(lastIdx+1));   
  125.                     switch(supportedType){   
  126.                     case Base64:data =(Object) new BASE64Decoder().decodeBuffer((String)data);   
  127.                     case ByteArray:data = (Object)new ByteArrayIn-putStream((byte[])data);   
  128.                     case InputStream:FileCopyUtils.copy((InputStream)data, os);   
  129.                     default:return;   
  130.                     }   
  131.                 }catch(Exception e){}   
  132.             }   
  133.         }   
  134.         throw new Exception("Data Type is not supported");   
  135.            
  136.     }   
  137.    
  138.     @SuppressWarnings("unchecked")   
  139.     @Override   
  140.     public <Form> Form achieveResource(String key, Class<Form> clasze)   
  141.             throws Exception {   
  142.         if(key==null)return null;   
  143.         if(clasze==null)return (Form) achieveResource(key,InputStream.class);   
  144.         for(DataType supportedType: DataType.values()){   
  145.             if(clasze.equals(supportedType.getDataType()))   
  146.             {   
  147.                 InputStream is =null;   
  148.                 try{   
  149.                     key =('/'+key.replaceAll("\\\\+""/")).replaceAll("/+""/");   
  150.                     int lastIdx = key.lastIndexOf('/');   
  151.                     this.gotoDirectory(key.substring(0,lastIdx), null);   
  152.                     is =ftpClient.getFileStream(key.substring(lastIdx+1));   
  153.                     switch(supportedType){   
  154.                     case InputStream:return (Form)is;   
  155.                     case ByteArray:return (Form)FileCopyUtils.copyToByteArray(is);   
  156.                     case Base64:return (Form)new BASE64Encoder().encode(FileCopyUtils.copyToByteArray(is));   
  157.                     }   
  158.                 }catch(Exception e){}   
  159.             }   
  160.         }   
  161.         throw new Exception("Data Type is not supported");   
  162.     }   
  163.    
  164.     @Override   
  165.     public void removeResource(String key) throws Exception {   
  166.         try{   
  167.             key =('/'+key.replaceAll("\\\\+""/")).replaceAll("/+""/");   
  168.             int lastIdx = key.lastIndexOf('/');   
  169.             this.gotoDirectory(key.substring(0,lastIdx), true);   
  170.             String resName =key.substring(lastIdx+1);   
  171.             ftpClient.deleteFile(resName);   
  172.             String preName = key.substring(1,lastIdx);   
  173.             String dirs[] = preName.split("/");   
  174.             for(int i=dirs.length-1;i>-1;i--)   
  175.             {   
  176.                 ftpClient.changeToParentDirectory();   
  177.                 ftpClient.removeDirectory(dirs[i]);   
  178.             }   
  179.         }   
  180.         catch(Exception e){   
  181.             e.printStackTrace();   
  182.         }   
  183.     }   
  184.    
  185. }   

        FTP的安装与配置就不多说了,网络上随处可见,Windows 里把IIS的FTP服务打开,Linux用相应的源管理软件安装个ftpd 或vsftpd, pure-ftpd都可以。配置好之后在sysParam里填加上相应的properties

 

 
  
  1. resource.storage.relativePath=/FileStorage   
  2. resource.ftp.url=ftp://[ftpusername]@[hostname{:pot}]/{为该应用配置的路径}   
  3. resource.ftp.password=ftppasswordvalue   

      在单元测试类中通过改变@Resource的name值注入不同的实现类,分别测试,成功。