Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Implementing SFTP Server Connection with Java Singleton Pattern

Notes Apr 30 9

SFTP Server Connection Using Singleton Pattern in Java

The singleton design pattern ensures a class has only one instance while providing global access to that instance. This pattern is particularly useful for managign resources like SFTP server connections.

Singleton Implementation

import com.jcraft.jsch.*;

public class SftpConnector {
    private static SftpConnector connector;
    private Session session;

    private SftpConnector() {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession("username", "hostname", 22);
            session.setPassword("password");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    public static synchronized SftpConnector getConnection() {
        if (connector == null) {
            connector = new SftpConnector();
        }
        return connector;
    }

    public Session getSession() {
        return session;
    }
}

File Transfer Operations

import com.jcraft.jsch.ChannelSftp;

public class SftpFileHandler {
    public void upload(String localPath, String remotePath) {
        try {
            ChannelSftp channel = (ChannelSftp) SftpConnector
                .getConnection()
                .getSession()
                .openChannel("sftp");
            channel.connect();
            channel.put(localPath, remotePath);
            channel.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Tags: Java

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Spring Boot MyBatis with Two MySQL DataSources Using Druid

Required dependencies application.properties: define two data sources and poooling Java configuration for both data sources MyBatis mappers for each data source Controller endpoints to verify both co...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.