Search code examples
javaspring-bootftpthymeleaf

How to convert FTP from Spring MVC to Spring Boot/Thymeleaf?


So I've been working on taking the logic from an older webapp and making a new Spring Boot application out of it. I've come to a stuck spot regarding an ftp connection and call. Since I don't have a bunch of experience with this, I'm curious if there is a better/more modern way to handle most of this ftp stuff using Spring Boot/Thymeleaf and ways to go ahead and set that up. Any advice/guidance would be fantastic.

This is the older code that I'd like to modernize a bit.

String serverName = getFtpServer();

// Connect to the server
try {
    ftp.connect(serverName);
    ftp.enterLocalPassiveMode();
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    e.printStackTrace();
    return false;
}

// Login to the server
try {
    ftp.login(userName, password);
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    e.printStackTrace();
    return false;
}

// Tell server that the file will have JCL records
try {
    ftp.site("filetype=jes");
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    e.printStackTrace();
    return false;
}

// Submit and run the JCL
try {
    System.out.println("TRYING TO START MAINFRAME JCL");
    submitJcl(filename, serverName);

    String replyText = ftp.getReplyString();
    System.out.println(replyText);
} catch (Exception e) {
    String replyText = ftp.getReplyString();
    System.out.println(replyText);
    e.printStackTrace();
    return false;
}

// Quit the server
try {
    ftp.quit();
} catch (Exception e) {
    e.printStackTrace();
}

Storing the file

private String submitJcl(String remoteFile, String serverName) throws IOException {
    String filePath = getFilePath();
    String result = "";
    String fileName = filePath + remoteFile;
    System.out.println("filePath = " + fileName);
    FileInputStream inputStream = new FileInputStream(fileName);
    ftp.storeFile(serverName, inputStream);

    return result;
}

Solution

  • For this I figured out that there may be better ways to change it into the newer ftp format for Spring Boot, but this still completely works.

    Changes I made to it regardless:

    • Consolidated the try/catch blocks into one.
    • Pushed the ftp stuff into its own function and then just called it inside the try/catch block
    • Changed all of the sys.out's to info.debugs.
    • Changed the way it gets the filePath to more of a relative path with the file stored within the system instead of user files.