1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
|
|
10 |
|
|
11 |
|
|
12 |
|
|
13 |
|
|
14 |
|
package org.apache.camel.component.file; |
15 |
|
|
16 |
|
import org.apache.camel.Exchange; |
17 |
|
import org.apache.camel.Producer; |
18 |
|
import org.apache.camel.impl.DefaultProducer; |
19 |
|
import org.apache.commons.logging.Log; |
20 |
|
import org.apache.commons.logging.LogFactory; |
21 |
|
|
22 |
|
import java.io.File; |
23 |
|
import java.io.RandomAccessFile; |
24 |
|
import java.nio.ByteBuffer; |
25 |
|
import java.nio.channels.FileChannel; |
26 |
|
|
27 |
|
|
28 |
|
|
29 |
|
|
30 |
|
|
31 |
|
|
32 |
|
public class FileProducer extends DefaultProducer { |
33 |
1 |
private static final transient Log log = LogFactory.getLog(FileProducer.class); |
34 |
|
private final FileEndpoint endpoint; |
35 |
|
|
36 |
|
public FileProducer(FileEndpoint endpoint) { |
37 |
1 |
super(endpoint); |
38 |
1 |
this.endpoint = endpoint; |
39 |
1 |
} |
40 |
|
|
41 |
|
|
42 |
|
|
43 |
|
|
44 |
|
|
45 |
|
public void process(Exchange exchange) { |
46 |
1 |
process(endpoint.toExchangeType(exchange)); |
47 |
1 |
} |
48 |
|
|
49 |
|
public void process(FileExchange exchange){ |
50 |
1 |
String fileName = exchange.getIn().getMessageId(); |
51 |
1 |
ByteBuffer payload=exchange.getIn().getBody(ByteBuffer.class); |
52 |
1 |
payload.flip(); |
53 |
1 |
File file = null; |
54 |
1 |
if(endpoint.getFile()!=null&&endpoint.getFile().isDirectory()){ |
55 |
|
|
56 |
1 |
file=new File(endpoint.getFile(),fileName); |
57 |
|
|
58 |
1 |
}else{ |
59 |
0 |
file=new File(fileName); |
60 |
|
} |
61 |
1 |
buildDirectory(file); |
62 |
|
try{ |
63 |
1 |
FileChannel fc=new RandomAccessFile(file,"rw").getChannel(); |
64 |
1 |
fc.position(fc.size()); |
65 |
1 |
fc.write(payload); |
66 |
1 |
fc.close(); |
67 |
0 |
}catch(Throwable e){ |
68 |
0 |
log.error("Failed to write to File: "+file,e); |
69 |
1 |
} |
70 |
1 |
} |
71 |
|
|
72 |
|
private void buildDirectory(File file) { |
73 |
1 |
String dirName = file.getAbsolutePath(); |
74 |
1 |
int index = dirName.lastIndexOf(File.separatorChar); |
75 |
1 |
if (index > 0) { |
76 |
1 |
dirName = dirName.substring(0,index); |
77 |
1 |
File dir = new File(dirName); |
78 |
1 |
dir.mkdirs(); |
79 |
|
} |
80 |
1 |
} |
81 |
|
} |