Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Implementing SFTP Server Connection with Java Singleton Pattern

Notes 1

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...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

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