Reputation: 3
I'm implementing a service using Spring boot to download a single pattern-based file from an ftp server. The file name in the pattern changes based on the client's request parameters. And the file shouldn't be saved locally.
I'm new to this and I couldn't find a good explanation on how to achieve this using FtpOutboundGateway and Java config. Please help.
Here's some sample to show where I was taking this:
FtpOutboundGateway bean:
@Bean
@ServiceActivator(inputChannel = "requestChannel")
public FtpOutboundGateway ftpFileGateway() {
FtpOutboundGateway ftpOutboundGateway =
new FtpOutboundGateway(ftpSessionFactory(), "get", "'Ready_Downloads/'");
ftpOutboundGateway.setOptions("-P -stream");
ftpOutboundGateway.setOutputChannelName("downloadChannel");
return ftpOutboundGateway;
}
Use of autowired OutboundGateway ftpFileGateway bean in service endpoint:
@RequestMapping(value="/getFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] downloadFile(@RequestPart Map<String, String> fileDetails) throws Exception
{
String filename = fileDetails.get("filename");
FtpSimplePatternFileListFilter filter = new FtpSimplePatternFileListFilter( "*"+filename+"*");
ftpFileGateway.setFilter(filter);
//then what?...
}
I'm assuming I might need to use the input and output message channels, just not sure on how to proceed.
Upvotes: 0
Views: 1045
Reputation: 174514
You shouldn't mutate the gateway for each request; it's not thread-safe.
You don't need a filter at all; simply send the fileName
as the payload of the message sent to the get
gateway and set the gateway expression to...
new FtpOutboundGateway(ftpSessionFactory(), "get",
"'Ready_Downloads/' + payload"
EDIT
@SpringBootApplication
public class So49516152Application {
public static void main(String[] args) {
SpringApplication.run(So49516152Application.class, args);
}
@Bean
public ApplicationRunner runner (Gate gate) {
return args -> {
InputStream is = gate.get("bar.txt");
File file = new File("/tmp/bar.txt");
FileOutputStream os = new FileOutputStream(file);
FileCopyUtils.copy(is, os);
System.out.println("Copied: " + file.getAbsolutePath());
};
}
@ServiceActivator(inputChannel = "ftpGet")
@Bean
public FtpOutboundGateway getGW() {
FtpOutboundGateway gateway = new FtpOutboundGateway(sf(), "get", "'foo/' + payload");
gateway.setOption(Option.STREAM);
return gateway;
}
@Bean
public DefaultFtpSessionFactory sf() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost("...");
sf.setUsername("...");
sf.setPassword("...");
return sf;
}
@MessagingGateway(defaultRequestChannel = "ftpGet")
public interface Gate {
InputStream get(String fileName);
}
}
Upvotes: 1