I am having a problem for the Unicode conversion. The main problem was the String parameter passed was something unsupported characters.
Here is the sample of the code:
I have a batch script which will be executed on a server.
By the meantime, execution status log should be provided. This script contains some Japanese character as mentioned below which actually need to be displayed as it is in the log. For which I am having a problem.
In this, the topmost string "String command = sshcommand.getCommand();" containssome "Remote command with parameters as string".
What I have tried:
package jp.co.kentaku.kikan.util.ssh;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.csc.qre.iseries.cl.CallCommand.ParamKey;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SSHHandler {
private static final Logger logger = LoggerFactory.getLogger(SSHHandler.class);
private JSch jschSSHChannel;
private String strUserName;
private String strConnectionIP;
private int intConnectionPort;
private String strPassword;
private Session sesConnection;
private int intTimeOut;
private void doCommonConstructorActions(String userName, String password, String connectionIP,
String knownHostsFileName) {
jschSSHChannel = new JSch();
try {
jschSSHChannel.setKnownHosts(knownHostsFileName);
} catch (JSchException jschX) {
logError(jschX.getMessage());
}
strUserName = userName;
strPassword = password;
strConnectionIP = connectionIP;
}
public SSHHandler(String userName, String password, String connectionIP, String knownHostsFileName) {
doCommonConstructorActions(userName, password, connectionIP, knownHostsFileName);
intConnectionPort = 22;
intTimeOut = 60000;
}
public String connect() throws Exception {
String errorMessage = null;
sesConnection = jschSSHChannel.getSession(strUserName, strConnectionIP, intConnectionPort);
sesConnection.setPassword(strPassword);
sesConnection.setConfig("StrictHostKeyChecking", "no");
sesConnection.connect(intTimeOut);
return errorMessage;
}
private String logError(String errorMessage) {
if (errorMessage != null) {
logger.error(strConnectionIP + ":" + intConnectionPort + " - " + errorMessage);
}
return errorMessage;
}
private String logWarning(String warnMessage) {
if (warnMessage != null) {
logger.error(strConnectionIP + ":" + intConnectionPort + " - " + warnMessage);
}
return warnMessage;
}
public String sendCommand(String command) throws Exception {
String errorMsg = null;
StringBuilder outputBuffer = new StringBuilder();
Channel channel = sesConnection.openChannel("exec");
((ChannelExec) channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
InputStream commandErrorOutput = ((ChannelExec) channel).getErrStream();
channel.connect();
int readByte = commandOutput.read();
while (readByte != 0xffffffff) {
outputBuffer.append((char) readByte);
readByte = commandOutput.read();
}
int readErrorByte = commandErrorOutput.read();
boolean error = false;
while (readErrorByte != 0xffffffff) {
error = true;
outputBuffer.append((char) readErrorByte);
readErrorByte = commandErrorOutput.read();
}
channel.disconnect();
int exitStatus = channel.getExitStatus();
if (error) {
errorMsg = outputBuffer.toString();
logger.error("Exception occured while executing the commnad:(" + command + ") exitStatus received:"
+ exitStatus + " Message:" + errorMsg);
logger.error("Message Id:CPF91CB Message:" + errorMsg);
throw new Exception(errorMsg);
}
return outputBuffer.toString();
}
public void close() {
sesConnection.disconnect();
}
public static void executeSSHCommand(SSHCommand sshcommand) throws Exception {
logger.info("Entering the executeSSHCommand()");
String command = sshcommand.getCommand();
String userName = sshcommand.getUserName();
String password = sshcommand.getPassword();
String connectionIP = sshcommand.getServerName();
String ccsid = sshcommand.getCcsid();
logger.info("Attempting connection to Server:" + connectionIP + " user:" + userName + " using password:"
+ password);
SSHHandler instance = new SSHHandler(userName, password, connectionIP, "");
String errorMessage = "";
try {
errorMessage = instance.connect();
logger.info("Established connection to Server:" + connectionIP + " user:" + userName + " using password:"
+ password);
} catch (Exception e) {
logger.error("Message ID : CPF91CB ; Message: Could not connect to Server:" + connectionIP + " user:"
+ userName + " using password:" + password);
throw e;
}
if (errorMessage != null) {
logger.error("Could not connect to the server :" + connectionIP + " with User:" + userName + " message:"
+ errorMessage);
throw new Exception(errorMessage);
}
String result = null;
try {
logger.info("Trying to execute command" + command + " on " + connectionIP);
result = instance.sendCommand(command);
logger.info("Executed command :" + command + " on Server:" + connectionIP + " user:" + userName
+ " using password:" + password);
logger.info("CHARSET found=" + ccsid);
if (ccsid != null && ccsid.equals("943")) {
logger.info("Lined up for conversion");
result = convertUTF8ToShiftJ(result);
}
logger.info("Command output : " + result);
} catch (Exception e) {
errorMessage = "Exception while executing the command:" + command + " on Server:" + connectionIP;
errorMessage = errorMessage + " message:" + e.getMessage();
logger.error(errorMessage);
throw e;
}
instance.close();
}
private static String convertUTF8ToShiftJ(String uft8Str) {
String shftJStr = null;
try {
byte[] b = uft8Str.getBytes(UTF_8);
shftJStr = new String(b, Charset.forName("SHIFT-JIS"));
logger.info("Converted to the string :" + shftJStr);
System.out.println(shftJStr);
} catch (Exception e) {
e.printStackTrace();
return uft8Str;
}
return shftJStr;
}
@SuppressWarnings("unchecked")
public static <T> T getParam(final Map<ParamKey, Object> params, final ParamKey paramKey, final T defaultValue) {
if (params == null) {
return defaultValue;
}
T value = (T) params.get(paramKey);
if (value == null) {
return defaultValue;
}
return value;
}
@SuppressWarnings("unchecked")
public static <T> T getParam(final Map<ParamKey, Object> params, final ParamKey paramKey) {
if (params == null) {
return null;
}
return (T) params.get(paramKey);
}
}
Output:
*** UX0025.SH ツ開ツ始ツ ツ(startedツ)
*** UX0025.SH ツ偲?ツ行ツ陳?ツ(executing...ツ)
*** UX0025.SH ツ終ツ猟ケツ ツ(endedツ ツ)
But Actually it supposed to be:
*** UX0025.SH 開始 (started)
*** UX0025.SH 実行中(executing...)
*** UX0025.SH 終了 (ended )
The problem seems due to the string parameter "uft8Str" which carries some unsupportive characters. So someone please help me out with this.
Thanks.