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 com.jcraft.jsch.ChannelSftp; |
21 |
|
import com.jcraft.jsch.SftpException; |
22 |
|
import org.apache.camel.Exchange; |
23 |
|
import org.apache.camel.RuntimeCamelException; |
24 |
|
|
25 |
|
import java.io.IOException; |
26 |
|
import java.io.InputStream; |
27 |
|
|
28 |
|
public class SftpProducer extends RemoteFileProducer<RemoteFileExchange> { |
29 |
|
SftpEndpoint endpoint; |
30 |
|
private final ChannelSftp channel; |
31 |
|
|
32 |
|
public SftpProducer(SftpEndpoint endpoint, ChannelSftp channelSftp) { |
33 |
0 |
super(endpoint); |
34 |
0 |
this.endpoint = endpoint; |
35 |
0 |
this.channel = channelSftp; |
36 |
0 |
} |
37 |
|
|
38 |
|
public void process(Exchange exchange) throws Exception { |
39 |
0 |
process(endpoint.toExchangeType(exchange)); |
40 |
0 |
} |
41 |
|
|
42 |
|
public void process(RemoteFileExchange exchange) throws Exception { |
43 |
|
final String fileName; |
44 |
0 |
InputStream payload = exchange.getIn().getBody(InputStream.class); |
45 |
0 |
final String endpointFile = endpoint.getConfiguration().getFile(); |
46 |
0 |
channel.cd(endpointFile); |
47 |
0 |
if (endpointFile == null) { |
48 |
0 |
throw new NullPointerException("Null Endpoint File"); |
49 |
|
} |
50 |
|
else { |
51 |
0 |
if (endpoint.getConfiguration().isDirectory()) { |
52 |
0 |
fileName = endpointFile + "/" + exchange.getIn().getMessageId(); |
53 |
0 |
} |
54 |
|
else { |
55 |
0 |
fileName = endpointFile; |
56 |
|
} |
57 |
|
} |
58 |
0 |
buildDirectory(channel, fileName.substring(0, fileName.lastIndexOf('/'))); |
59 |
|
try { |
60 |
0 |
channel.put(payload, fileName); |
61 |
|
} |
62 |
0 |
catch (SftpException e) { |
63 |
0 |
throw new RuntimeCamelException("error sending file", e); |
64 |
0 |
} |
65 |
0 |
} |
66 |
|
|
67 |
|
@Override |
68 |
|
protected void doStart() throws Exception { |
69 |
0 |
super.doStart(); |
70 |
|
|
71 |
|
|
72 |
|
|
73 |
0 |
} |
74 |
|
|
75 |
|
@Override |
76 |
|
protected void doStop() throws Exception { |
77 |
0 |
channel.disconnect(); |
78 |
0 |
super.doStop(); |
79 |
0 |
} |
80 |
|
|
81 |
|
protected static boolean buildDirectory(ChannelSftp sftpClient, String dirName) throws IOException { |
82 |
0 |
boolean atLeastOneSuccess = false; |
83 |
0 |
final StringBuilder sb = new StringBuilder(dirName.length()); |
84 |
0 |
final String[] dirs = dirName.split("\\/"); |
85 |
0 |
for (String dir : dirs) { |
86 |
0 |
sb.append('/').append(dir); |
87 |
|
try { |
88 |
0 |
sftpClient.mkdir(sb.toString()); |
89 |
0 |
if (!atLeastOneSuccess) { |
90 |
0 |
atLeastOneSuccess = true; |
91 |
|
} |
92 |
|
} |
93 |
0 |
catch (SftpException e) { |
94 |
|
|
95 |
0 |
} |
96 |
|
} |
97 |
0 |
return atLeastOneSuccess; |
98 |
|
} |
99 |
|
} |