Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Remote Linux SFTP File Reader Utility

Tech 1
package com.example.networking;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class RemoteSshFileRetriever {
    private static final Logger logger = LoggerFactory.getLogger(RemoteSshFileRetriever.class);
    private static final int CONNECTION_TIMEOUT_MS = 20000;

    /**
     * Fetches a plain text file from a remote path and applies HTML escaping for display.
     */
    public static String pullFormattedFile(String targetHost, int servicePort, String loginAccount, String accessKey, String directoryPath, String documentName) throws Exception {
        Session connection = null;
        ChannelSftp transport = null;

        try {
            connection = initializeProtocolSession(targetHost, servicePort, loginAccount, accessKey);
            transport = activateSftpLayer(connection);

            ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
            String fullRoute = String.join("/", directoryPath, documentName);
            transport.get(fullRoute, dataBuffer);

            String rawPayload = new String(dataBuffer.toByteArray(), StandardCharsets.UTF_8);
            return sanitizeHtmlOutput(rawPayload);
        } catch (Exception failure) {
            logger.warn("SFTP operation aborted: {}", failure.getMessage());
            throw new IllegalStateException("Failed to extract remote payload", failure);
        } finally {
            terminateResources(transport, connection);
        }
    }

    private static Session initializeProtocolSession(String endpoint, int port, String user, String secret) {
        JSch client = new JSch();
        Session active = client.getSession(user, endpoint, port);
        active.setPassword(secret);
        active.setTimeout(CONNECTION_TIMEOUT_MS);

        Properties securitySettings = new Properties();
        securitySettings.put("StrictHostKeyChecking", "no");
        active.setConfig(securitySettings);
        active.connect();
        return active;
    }

    private static ChannelSftp activateSftpLayer(Session session) {
        try {
            ChannelSftp layer = (ChannelSftp) session.openChannel("sftp");
            layer.connect();
            return layer;
        } catch (Exception setupError) {
            throw new RuntimeException("SFTP initialization failed", setupError);
        }
    }

    private static void terminateResources(ChannelSftp channel, Session session) {
        if (channel != null && channel.isConnected()) channel.disconnect();
        if (session != null && session.isConnected()) session.disconnect();
    }

    private static String sanitizeHtmlOutput(String text) {
        return text.replace("\t", "    ")
                   .replaceAll("(\\r\\n|\\n|\\r)", "<br>");
    }
}

Operational Characteristics

  • Lifecycle Management: Utilizes explicit finally blocks to guarantee socket release, preventing connection pool exhaustion.
  • Encoding Standardization: Forces UTF-8 parsing to bypass platform-dependent default charset behavior.
  • Presentation Normalization: Converts whitespace control codes into semantic HTML entities optimized for browser viewing.
Tags: JavaJSch

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

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