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.