Java unicode转换 [英] Java unicode conversion

查看:102
本文介绍了Java unicode转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Unicode转换的问题。主要问题是传递的String参数是不支持的字符。



以下是代码示例:



我有一个批处理脚本,将在服务器。

同时,应提供执行状态日志。此脚本包含一些日语字符,如下所述,实际上需要在日志中显示。我遇到了问题。



在这里,最顶层的字符串String command = sshcommand.getCommand();包含一些参数为字符串的远程命令。



我尝试过:



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;


/**
 * SSH Handler for ssh communication with servers Linux as well as Windows
 * @author ssharma365
 *
 */
public class SSHHandler {
	/**
	 * Enabling logger for this class
	 * 
	 */
	private static final Logger logger = LoggerFactory.getLogger(SSHHandler.class);

	/**
	 * Jsch channel
	 */
	private JSch jschSSHChannel;
	/**
	 * Remote machine User name
	 */
	private String strUserName;
	/**
	 * Remote machine server name or IP
	 */
	private String strConnectionIP;
	/**
	 * The port on which the remote machine will open the ssh communiction. by default 22
	 */
	private int intConnectionPort;
	/**
	 * Remote password for the above user
	 */
	private String strPassword;
	/*
	 * SSH session reference
	 */
	private Session sesConnection;
	/**
	 *  Time out 
	 */
	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 Cpf91cb("CPF91CB", 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()");
		/**
		 * YOU MUST CHANGE THE FOLLOWING FILE_NAME: A FILE IN THE DIRECTORY USER: LOGIN
		 * USER NAME PASSWORD: PASSWORD FOR THAT USER HOST: IP ADDRESS OF THE SSH SERVER
		 **/
		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 new Cpf91cb("CPF91CB", "Could not connect to the server :" + connectionIP + " with User:" + userName,e);
			throw e;
		}
		if (errorMessage != null) {
			logger.error("Could not connect to the server :" + connectionIP + " with User:" + userName + " message:"
					+ errorMessage);
			/*throw new Cpf91cb("CPF91CB", "Could not connect to the server :" + connectionIP + " with User:"
					+ userName + " message:" + errorMessage, new Exception(errorMessage));*/
			throw new Exception(errorMessage);
		}

		// call sendCommand for each command and the output
		// (without prompts) is returned
		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();
			// e.printStackTrace();
			logger.error(errorMessage);
			/*throw new Cpf91cb("CPF91CB", "Could not connect to the server :" + connectionIP + " with User:"
					+ userName + " message:" + errorMessage,new Exception(errorMessage));*/
			throw e;
		}
		// close only after all commands are sent
		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;
	}

	/**
	 * Get parameter value.
	 * 
	 * @param params
	 *            set of parameters
	 * @param paramKey
	 *            parameter key to retrieve value
	 * @param defaultValue
	 *            default value if value is null or not found
	 * @return
	 */
	@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;
	}

	/**
	 * Get parameter value.
	 * 
	 * @param params
	 *            set of parameters
	 * @param paramKey
	 *            parameter key to retrieve value
	 * @param defaultValue
	 *            default value if value is null or not found
	 * @return
	 */
	@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 )





问题似乎是由于字符串参数uft8Str带有一些不支持的字符。所以有人请帮帮我。

谢谢。



The problem seems due to the string parameter "uft8Str" which carries some unsupportive characters. So someone please help me out with this.
Thanks.

推荐答案

问题来自你的 sendCommand( )函数因为它没有返回有效的Java 字符串(UTF-16编码)。



接收的数据是字节。所以你必须使用字节缓冲区来接收。



从头开始的未经测试的例子:

The problem is sourced in your sendCommand() function because that does not return a valid Java String (UTF-16 encoded).

The received data are bytes. So you have to use a byte buffer for receiving.

Untested example from scratch:
// Assuming knowing the max. response length for simplicity
byte[] buffer = new byte[maxResponseLength];
int rxCount = 0;

// Receive data into buffer using and incrementing rxCount accordingly

// Create a Java String from the data.
// This requires knowing the encoding of the data which is probably UTF-8 
//  for responses from SSH servers.
String result = new String(buffer, 0, rxCount, "UTF8");

这篇关于Java unicode转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆