Search code examples
javaspringspring-integrationspring-integration-sftp

spring SFTP create file in remote from byte[]


how to create an file in remote directory from byte[], as there is send() methods available in PollableChannel. from below code able to send file to remote, but it's creating an file in local machine. how to avoid creating file in local machine?

PollableChannel remoteFileChannel = context.getBean("outputChannel", PollableChannel.class); 

Message<byte[]> sendFile = MessageBuilder.withPayload("hi how are you".getBytes()).build();

remoteFileChannel.send(sendFile);

spring sftp configuration:

<bean id="sftpSessionFactory"
        class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory"
        p:host="${sftp.host}"
        p:port="${sftp.port}"
        p:user="${sftp.username}"
        p:password="${sftp.password}"
        p:allowUnknownKeys="${sftp.allowUnknownKeys}" />

<int:channel id="outputChannel">
        <int:queue />
</int:channel>

<int-sftp:outbound-channel-adapter id="outboundAdapter"
        session-factory="sftpSessionFactory"
        channel="outputChannel"
        charset="UTF-8"
        remote-directory="${sftp.remotedir}"
        remote-filename-generator="randomFileNameGenerator" /> 

how to create an file with random name and write bytes into it?

I have tried with custom file name generator class:

@Component("randomFileNameGenerator")
public class RandomFileNameGenerator implements FileNameGenerator {

    @Override
    public String generateFileName(Message<?> msg) {
        long number = (long) Math.floor(Math.random() * 90000000L) + 1000000L;
        String fileName = String.format("%d.txt", number);
        return fileName;
    }

}

where the filename was not setting, creating file with name like "adas-asdfsadf-545sadf.msg". can any one point me where am doing wrong


Solution

  • First of all you don't show your Spring Integration configuration.

    From other hand it isn't clear why you say " it's creating an file", if it looks like code is yours. So, that is you who create a file.

    There are out-of-the-box components like <int-sftp:outbound-channel-adapter> and <int-sftp:outbound-gateway>, which definitely can address your goal.

    Both of them are based on the RemoteFileTemplate.send() operation which handles byte[] payload very well.

    See more info in the Reference Manual and Samples.

    UPDATE

    how to create an file with random name and write bytes into it?

    Seems for me we have just fixed with you the byte[] question.

    Re. "random name". Looks like you go right way: the remote-filename-generator="fileNameGenerator" is exactly for that task. See FileNameGenerator strategy and its implementations in the Framework. You can utilize your randomize function in your custom implementation and refer it from that channel-adapter definition.