1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
|
|
10 |
|
|
11 |
|
|
12 |
|
|
13 |
|
|
14 |
|
|
15 |
|
|
16 |
|
|
17 |
|
|
18 |
|
package org.apache.camel.component.file.remote; |
19 |
|
|
20 |
|
import org.apache.camel.Exchange; |
21 |
|
import org.apache.camel.RuntimeCamelException; |
22 |
|
import org.apache.commons.net.ftp.FTPClient; |
23 |
|
|
24 |
|
import java.io.IOException; |
25 |
|
import java.io.InputStream; |
26 |
|
|
27 |
|
public class FtpProducer extends RemoteFileProducer<RemoteFileExchange> { |
28 |
|
FtpEndpoint endpoint; |
29 |
|
private final FTPClient client; |
30 |
|
|
31 |
|
public FtpProducer(FtpEndpoint endpoint, FTPClient client) { |
32 |
1 |
super(endpoint); |
33 |
1 |
this.endpoint = endpoint; |
34 |
1 |
this.client = client; |
35 |
1 |
} |
36 |
|
|
37 |
|
public void process(Exchange exchange) throws Exception { |
38 |
1 |
process(endpoint.toExchangeType(exchange)); |
39 |
1 |
} |
40 |
|
|
41 |
|
public void process(RemoteFileExchange exchange) throws Exception { |
42 |
|
final String fileName; |
43 |
1 |
InputStream payload = exchange.getIn().getBody(InputStream.class); |
44 |
1 |
final String endpointFile = endpoint.getConfiguration().getFile(); |
45 |
1 |
client.changeWorkingDirectory(endpointFile); |
46 |
1 |
if (endpointFile == null) { |
47 |
0 |
throw new NullPointerException("Null Endpoint File"); |
48 |
|
} |
49 |
|
else { |
50 |
1 |
if (endpoint.getConfiguration().isDirectory()) { |
51 |
1 |
fileName = endpointFile + "/" + exchange.getIn().getMessageId(); |
52 |
1 |
} |
53 |
|
else { |
54 |
0 |
fileName = endpointFile; |
55 |
|
} |
56 |
|
} |
57 |
1 |
buildDirectory(client, fileName.substring(0, fileName.lastIndexOf('/'))); |
58 |
1 |
final boolean success = client.storeFile(fileName, payload); |
59 |
1 |
if (success) { |
60 |
|
|
61 |
1 |
} |
62 |
|
else { |
63 |
0 |
throw new RuntimeCamelException("error sending file"); |
64 |
|
} |
65 |
1 |
} |
66 |
|
|
67 |
|
@Override |
68 |
|
protected void doStart() throws Exception { |
69 |
1 |
super.doStart(); |
70 |
|
|
71 |
|
|
72 |
|
|
73 |
1 |
} |
74 |
|
|
75 |
|
@Override |
76 |
|
protected void doStop() throws Exception { |
77 |
1 |
client.disconnect(); |
78 |
1 |
super.doStop(); |
79 |
1 |
} |
80 |
|
|
81 |
|
protected static boolean buildDirectory(FTPClient ftpClient, String dirName) throws IOException { |
82 |
1 |
boolean atLeastOneSuccess = false; |
83 |
1 |
final StringBuilder sb = new StringBuilder(dirName.length()); |
84 |
1 |
final String[] dirs = dirName.split("\\/"); |
85 |
6 |
for (String dir : dirs) { |
86 |
5 |
sb.append('/').append(dir); |
87 |
5 |
final boolean success = ftpClient.makeDirectory(sb.toString()); |
88 |
5 |
System.out.println(sb.toString() + " = " + success); |
89 |
5 |
if (!atLeastOneSuccess && success) { |
90 |
1 |
atLeastOneSuccess = true; |
91 |
|
} |
92 |
|
} |
93 |
1 |
return atLeastOneSuccess; |
94 |
|
} |
95 |
|
} |