1
2
3
4
5
6
7
8
9
10
11 package org.mule.transport.ftp;
12
13 import org.mule.DefaultMuleMessage;
14 import org.mule.api.MuleMessage;
15 import org.mule.api.endpoint.EndpointURI;
16 import org.mule.api.endpoint.InboundEndpoint;
17 import org.mule.transport.AbstractMessageRequester;
18 import org.mule.transport.file.FileConnector;
19
20 import java.io.FilenameFilter;
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.List;
24
25 import org.apache.commons.io.output.ByteArrayOutputStream;
26 import org.apache.commons.net.ftp.FTPClient;
27 import org.apache.commons.net.ftp.FTPFile;
28 import org.apache.commons.net.ftp.FTPReply;
29
30 public class FtpMessageRequester extends AbstractMessageRequester
31 {
32 protected final FtpConnector connector;
33
34 public FtpMessageRequester(InboundEndpoint endpoint)
35 {
36 super(endpoint);
37 this.connector = (FtpConnector) endpoint.getConnector();
38 }
39
40 protected void doDispose()
41 {
42
43 }
44
45 protected void doConnect() throws Exception
46 {
47
48
49 }
50
51 protected void doDisconnect() throws Exception
52 {
53 try
54 {
55 EndpointURI uri = endpoint.getEndpointURI();
56 FTPClient client = connector.getFtp(uri);
57 connector.destroyFtp(uri, client);
58 }
59 catch (Exception e)
60 {
61
62 }
63 }
64
65
66
67
68
69
70
71
72
73
74
75
76 protected MuleMessage doRequest(long timeout) throws Exception
77 {
78 FTPClient client = null;
79 try
80 {
81 client = connector.createFtpClient(endpoint);
82
83 FilenameFilter filenameFilter = null;
84 if (endpoint.getFilter() instanceof FilenameFilter)
85 {
86 filenameFilter = (FilenameFilter) endpoint.getFilter();
87 }
88
89 FTPFile[] files = client.listFiles();
90 if (!FTPReply.isPositiveCompletion(client.getReplyCode()))
91 {
92 throw new IOException("Ftp error: " + client.getReplyCode());
93 }
94 if (files == null || files.length == 0)
95 {
96 return null;
97 }
98 List fileList = new ArrayList();
99 FTPFile file = null;
100 for (int i = 0; i < files.length; i++)
101 {
102 file = files[i];
103 if (file.isFile())
104 {
105 if (filenameFilter == null || filenameFilter.accept(null, file.getName()))
106 {
107 if (connector.validateFile(file))
108 {
109 fileList.add(file);
110
111 break;
112 }
113 }
114 }
115 }
116 if (fileList.size() == 0)
117 {
118 return null;
119 }
120
121 ByteArrayOutputStream baos = new ByteArrayOutputStream();
122 if (!client.retrieveFile(file.getName(), baos))
123 {
124 throw new IOException("Ftp error: " + client.getReplyCode());
125 }
126
127 MuleMessage reply = new DefaultMuleMessage(connector.getMessageAdapter(baos.toByteArray()));
128 reply.setProperty(FileConnector.PROPERTY_ORIGINAL_FILENAME, file.getName());
129 reply.setProperty(FileConnector.PROPERTY_FILE_SIZE, new Long(file.getSize()));
130 return reply;
131 }
132 finally
133 {
134 logger.debug("leaving doRequest()");
135 connector.releaseFtp(endpoint.getEndpointURI(), client);
136 }
137 }
138 }