1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
|
|
10 |
|
|
11 |
|
|
12 |
|
|
13 |
|
|
14 |
|
|
15 |
|
|
16 |
|
|
17 |
|
package org.apache.camel.component.file.remote; |
18 |
|
|
19 |
|
import java.io.IOException; |
20 |
|
import java.io.InputStream; |
21 |
|
|
22 |
|
import com.jcraft.jsch.ChannelSftp; |
23 |
|
import com.jcraft.jsch.SftpException; |
24 |
|
|
25 |
|
import org.apache.camel.Exchange; |
26 |
|
import org.apache.camel.RuntimeCamelException; |
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 |
|
} else { |
50 |
0 |
if (endpoint.getConfiguration().isDirectory()) { |
51 |
0 |
fileName = endpointFile + "/" + exchange.getIn().getMessageId(); |
52 |
0 |
} else { |
53 |
0 |
fileName = endpointFile; |
54 |
|
} |
55 |
|
} |
56 |
0 |
buildDirectory(channel, fileName.substring(0, fileName.lastIndexOf('/'))); |
57 |
|
try { |
58 |
0 |
channel.put(payload, fileName); |
59 |
0 |
} catch (SftpException e) { |
60 |
0 |
throw new RuntimeCamelException("error sending file", e); |
61 |
0 |
} |
62 |
0 |
} |
63 |
|
|
64 |
|
@Override |
65 |
|
protected void doStart() throws Exception { |
66 |
0 |
super.doStart(); |
67 |
|
|
68 |
|
|
69 |
|
|
70 |
|
|
71 |
|
|
72 |
0 |
} |
73 |
|
|
74 |
|
@Override |
75 |
|
protected void doStop() throws Exception { |
76 |
0 |
channel.disconnect(); |
77 |
0 |
super.doStop(); |
78 |
0 |
} |
79 |
|
|
80 |
|
protected static boolean buildDirectory(ChannelSftp sftpClient, String dirName) throws IOException { |
81 |
0 |
boolean atLeastOneSuccess = false; |
82 |
0 |
final StringBuilder sb = new StringBuilder(dirName.length()); |
83 |
0 |
final String[] dirs = dirName.split("\\/"); |
84 |
0 |
for (String dir : dirs) { |
85 |
0 |
sb.append('/').append(dir); |
86 |
|
try { |
87 |
0 |
sftpClient.mkdir(sb.toString()); |
88 |
0 |
if (!atLeastOneSuccess) { |
89 |
0 |
atLeastOneSuccess = true; |
90 |
|
} |
91 |
0 |
} catch (SftpException e) { |
92 |
|
|
93 |
0 |
} |
94 |
|
} |
95 |
0 |
return atLeastOneSuccess; |
96 |
|
} |
97 |
|
} |