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.MuleContext;
15 import org.mule.transport.AbstractMuleMessageFactory;
16 import org.mule.transport.file.FileConnector;
17
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.text.MessageFormat;
22
23 import org.apache.commons.net.ftp.FTPClient;
24 import org.apache.commons.net.ftp.FTPFile;
25
26 public class FtpMuleMessageFactory extends AbstractMuleMessageFactory
27 {
28
29 private FTPClient ftpClient;
30 private boolean streaming;
31
32 public FtpMuleMessageFactory(MuleContext context)
33 {
34 super(context);
35 }
36
37 @Override
38 protected Object extractPayload(Object transportMessage, String encoding) throws Exception
39 {
40 FTPFile file = (FTPFile) transportMessage;
41 if (streaming)
42 {
43 InputStream stream = ftpClient.retrieveFileStream(file.getName());
44 if (stream == null)
45 {
46 throw new IOException(MessageFormat.format("Failed to retrieve file {0}. Ftp error: {1}",
47 file.getName(), ftpClient.getReplyCode()));
48 }
49 return stream;
50 }
51 else
52 {
53 ByteArrayOutputStream baos = new ByteArrayOutputStream();
54 if (!ftpClient.retrieveFile(file.getName(), baos))
55 {
56 throw new IOException(MessageFormat.format("Failed to retrieve file {0}. Ftp error: {1}",
57 file.getName(), ftpClient.getReplyCode()));
58 }
59 byte[] bytes = baos.toByteArray();
60 if (bytes.length > 0)
61 {
62 return bytes;
63 }
64 else
65 {
66 throw new IOException("File " + file.getName() + " is empty (zero bytes)");
67 }
68 }
69 }
70
71 @Override
72 protected Class<?>[] getSupportedTransportMessageTypes()
73 {
74 return new Class[]{FTPFile.class};
75 }
76
77 @Override
78 protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception
79 {
80 super.addProperties(message, transportMessage);
81
82 FTPFile file = (FTPFile) transportMessage;
83 message.setOutboundProperty(FileConnector.PROPERTY_ORIGINAL_FILENAME, file.getName());
84 message.setOutboundProperty(FileConnector.PROPERTY_FILE_SIZE, file.getSize());
85 message.setOutboundProperty(FileConnector.PROPERTY_FILE_TIMESTAMP, file.getTimestamp());
86 }
87
88 public void setFtpClient(FTPClient ftpClient)
89 {
90 this.ftpClient = ftpClient;
91 }
92
93 public void setStreaming(boolean streaming)
94 {
95 this.streaming = streaming;
96 }
97
98 }