定長メッセージメッセージのグループパケットと解パケット単純パッケージ(Java実装)


実際のプロジェクトでは、異なるシステム間のデータ交換によく遭遇します.webserviceを使用するものもあります.一部では、socketメッセージを送信する方法で、送信する必要があるメッセージを特定のフォーマットの文字列またはXml形式のファイルに組み立て、socketプログラミングで相手のシステムに送信します.本論文では,定長文字列に組み立てることを主に論じた.
抽象的な任意の固定長メッセージパケット(MsgPackage)は、1つまたは複数のメッセージスライス(MsgPiece)から構成される.いずれのメッセージ・シートも、1つまたは複数のメッセージ・ドメイン(MsgField)から構成される.メッセージフィールドのプロパティには、ドメイン名、長さ、値、値の長さが定義した最大長より小さい場合、左揃えか右揃えか、残りはどの文字で入力されますか.
メッセージドメインクラス:
package socket.msg;

/**
 *    
 * @author Zhenwei.Zhang (2013-9-25)
 */
public class MsgField {
	
	public MsgField (String name, int length, char fillChar, FillSide fillSide) {
		this.name = name;
		this.length = length;
		this.fillChar = fillChar;
		this.fillSide = fillSide;
	}
	
	/**
	 *     
	 * @author Zhenwei.Zhang (2013-9-25)
	 */
	public enum FillSide {
		LEFT, RIGHT
	}

	/**     */
	private String name;
	/**    */
	private int length;
	/**      */
	private char fillChar;
	/**      */
	private FillSide fillSide;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public char getFillChar() {
		return fillChar;
	}

	public void setFillChar(char fillChar) {
		this.fillChar = fillChar;
	}

	public FillSide getFillSide() {
		return fillSide;
	}

	public void setFillSide(FillSide fillSide) {
		this.fillSide = fillSide;
	}

}
メッセージスライスクラス
package socket.msg;

import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import socket.msg.MsgField.FillSide;

/**
 *    ,              
 * @author Zhenwei.Zhang (2013-9-25)
 */
public abstract class MsgPiece {
	
	/**       */
	private List<MsgField> itemList = new LinkedList<MsgField>();
	
	public MsgPiece(MsgField[] items) {
		itemList = new LinkedList<MsgField>();
		for (int i = 0; i < items.length; i++) {
			itemList.add(items[i]);
		}
	}
	
	/**
	 *    
	 * @author Zhenwei.Zhang (2013-9-25)
	 * @param charsetName
	 * @return
	 * @throws Exception
	 */
	public byte[] pack(String charsetName) throws Exception {
		StringBuffer result = new StringBuffer();
		byte[] b = null;
		try {
			for (MsgField item : itemList) {
				PropertyDescriptor pd = new PropertyDescriptor(item.getName(), this.getClass());
				Method readMethod = pd.getReadMethod();
				Object gotVal = readMethod.invoke(this);
				String strFill = gotVal == null ? "" : gotVal.toString();
				result.append(this.autoFill(strFill, item.getFillChar(), item.getFillSide(), item.getLength(), charsetName));
			}
			b = result.toString().getBytes(charsetName);
		} catch (Exception e) {
			throw new Exception("     :" + e.getMessage(), e);
		}
		
		return b;
	}
	
	/**
	 *    
	 * @author Zhenwei.Zhang (2013-9-25)
	 * @param msg
	 * @param charsetName
	 * @throws Exception
	 */
	public void unPack(byte[] msg, String charsetName) throws Exception {
		if (msg.length != this.getLength()) {
			throw new Exception("     ,       !");
		}
		
		int index = 0;
		try {
			for (MsgField item : itemList) {
				String value = new String(msg, index, item.getLength(), charsetName);
				value = this.getRealVal(value, item.getFillSide(), item.getFillChar());
				
				PropertyDescriptor pd = new PropertyDescriptor(item.getName(), this.getClass());
				Method setMethod = pd.getWriteMethod();
				if (pd.getPropertyType().equals(byte.class) || pd.getPropertyType().equals(Byte.class)) {
					setMethod.invoke(this, Byte.parseByte(value));
				}else if (pd.getPropertyType().equals(short.class) || pd.getPropertyType().equals(Short.class)) {
					setMethod.invoke(this, Short.parseShort(value));
				}else if (pd.getPropertyType().equals(int.class) || pd.getPropertyType().equals(Integer.class)) {
					setMethod.invoke(this, Integer.parseInt(value));
				}else if (pd.getPropertyType().equals(long.class) || pd.getPropertyType().equals(Long.class)) {
					setMethod.invoke(this, Long.parseLong(value));
				}else if (pd.getPropertyType().equals(float.class) || pd.getPropertyType().equals(Float.class)) {
					setMethod.invoke(this, Float.parseFloat(value));
				}else if (pd.getPropertyType().equals(double.class) || pd.getPropertyType().equals(Double.class)) {
					setMethod.invoke(this, Double.parseDouble(value));
				}else if (pd.getPropertyType().equals(char.class) || pd.getPropertyType().equals(Character.class)) {
					setMethod.invoke(this, value.toCharArray()[0]);
				}else if (pd.getPropertyType().equals(boolean.class) || pd.getPropertyType().equals(Boolean.class)) {
					setMethod.invoke(this, Boolean.valueOf(value));
				}else {
					setMethod.invoke(this, value);
				}
				index += item.getLength();
			}
		} catch (Exception e) {
			throw new Exception("     :" + e.getMessage(), e);
		}
	}
	
	/**
	 *       
	 * @author Zhenwei.Zhang (2013-9-25)
	 * @return
	 */
	public int getLength() {
		int length = 0;
		for (MsgField item : itemList) {
			length += item.getLength();
		}
		return length;
	}
	
	/**
	 *               ,      
	 * @author Zhenwei.Zhang (2013-9-26)
	 * @param value
	 * @param fillChar     
	 * @param side     
	 * @param totalLen       
	 * @param charsetName   
	 * @return
	 */
	private String autoFill(String value, char fillChar, FillSide side, int totalLen, String charsetName) {
		try {
			if (value == null) {
				value = "";
			}
			StringBuffer sbuffBuffer = new StringBuffer();
			//         ,  
			if (value.getBytes(charsetName).length > totalLen) {
				byte[] data = new byte[totalLen];
				System.arraycopy(value.getBytes(charsetName), 0, data, 0, totalLen);
				sbuffBuffer.append(new String(data, charsetName));
				return sbuffBuffer.toString();
			}
			if (side == socket.msg.MsgField.FillSide.RIGHT) {
				sbuffBuffer.append(value);
			}
			for (int i = value.getBytes(charsetName).length; i < totalLen; i++) {
				sbuffBuffer.append(fillChar);
			}
			if (side == socket.msg.MsgField.FillSide.LEFT) {
				sbuffBuffer.append(value);
			}
			return sbuffBuffer.toString();
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("     " + charsetName + "  ");
		}
	}
	
	/**
	 *          
	 * @author Zhenwei.Zhang (2013-9-26)
	 * @param value
	 * @param side     
	 * @param fillChar     
	 * @return
	 * @throws Exception
	 */
	private String getRealVal(String value, FillSide side, char fillChar) throws Exception {
		char[] chars = value.toCharArray();
		if (FillSide.LEFT == side) {
			int index = 0;
			for (int i = 0; i < chars.length; i++) {
				if (fillChar == chars[i]) {
					index ++;
				} else {
					continue;
				}
			}
			return value.substring(index);
		} else if (FillSide.RIGHT == side) {
			int index = chars.length - 1;
			for (int i = index; i >= 0; i--) {
				if (fillChar == chars[i]) {
					index --;
				} else {
					continue;
				}
			}
			return value.substring(0, index + 1);
		} else {
			throw new Exception("       ");
		}
	}

}
メッセージ・パッケージ・クラス:
package socket.msg;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 *    ,        
 * @author Zhenwei.Zhang (2013-10-12)
 */
public abstract class MsgPackage {
	
	/**           */
	String[] pieces = null;
	
	public MsgPackage(String... pieName) {
		pieces = pieName;
	}
	
	/**
	 *   
	 * @author Zhenwei.Zhang (2013-9-26)
	 * @param charsetName
	 * @return
	 * @throws Exception
	 */
	public byte[] pack(String charsetName) throws Exception {
		int index = 0;
		byte[] result = new byte[this.getLength()];
		for (String p : pieces) {
			PropertyDescriptor pd = new PropertyDescriptor(p, this.getClass());
			Method getterMethod = pd.getReadMethod();
			MsgPiece piece = (MsgPiece)getterMethod.invoke(this);
			if (piece == null) { //           
				piece = (MsgPiece) pd.getPropertyType().newInstance();
			}
			byte[] t = piece.pack(charsetName);
			System.arraycopy(t, 0, result, index, t.length);
			index += t.length;
		}
		return result;
	}
	
	/**
	 *   
	 * @author Zhenwei.Zhang (2013-9-26)
	 * @param msg
	 * @param charsetName
	 * @throws Exception
	 */
	public void unPack(byte[] msg, String charsetName) throws Exception {
		if (msg.length != this.getLength()) {
			throw new Exception("     ,        !");
		}

		int index = 0;
		for (String p : pieces) { //           ,  ,  
			PropertyDescriptor pd = new PropertyDescriptor(p, this.getClass());
			Method writeMethod = pd.getWriteMethod();
			MsgPiece piece = (MsgPiece) pd.getPropertyType().newInstance();
			byte[] t = new byte[piece.getLength()];
			System.arraycopy(msg, index, t, 0, t.length);
			piece.unPack(t, charsetName);
			writeMethod.invoke(this, piece);
			index += t.length;
		}
	}
	
	/**
	 *        
	 * @author Zhenwei.Zhang (2013-9-26)
	 * @return
	 * @throws Exception
	 */
	public int getLength() throws Exception {
		int length = 0;
		try {
			for (String p : pieces) {
				PropertyDescriptor pd = new PropertyDescriptor(p, this.getClass());
				Method getterMethod = pd.getReadMethod();
				MsgPiece piece = (MsgPiece)getterMethod.invoke(this);
				if (piece == null) {
					piece = (MsgPiece) pd.getPropertyType().newInstance();
				}
				length += piece.getLength();
			}
		} catch (Exception e) {
			throw new Exception("         :" + e.getMessage(), e);
		}
		return length;
	}
}

以下に、上記パッケージを用いた簡単な実装例を示す.
メッセージは、name、sex、Uage、amtなどのプロパティから構成され、メッセージはcontentプロパティから構成されるメッセージヘッダとメッセージボディから構成されることを定義します.
package socket.msg.test;

import socket.msg.MsgField;
import socket.msg.MsgPiece;
import socket.msg.MsgField.FillSide;

public class TestHead extends MsgPiece {
	
	private String name;
	private boolean sex;
	private int UAge;
	private String URL;
	private double amt;

	public int getUAge() {
		return UAge;
	}

	public void setUAge(int uAge) {
		UAge = uAge;
	}
	
	public double getAmt() {
		return amt;
	}

	public void setAmt(double amt) {
		this.amt = amt;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isSex() {
		return sex;
	}

	public void setSex(boolean sex) {
		this.sex = sex;
	}

	public String getURL() {
		return URL;
	}

	public void setURL(String uRL) {
		URL = uRL;
	}

	private static final MsgField[] items = new MsgField[]{
			new MsgField("name", 10, ' ', FillSide.RIGHT),
			new MsgField("sex", 10, '0', FillSide.LEFT),
			new MsgField("UAge", 10, '0', FillSide.LEFT),
			new MsgField("URL", 10, ' ', FillSide.RIGHT),
			new MsgField("amt", 10, '0', FillSide.LEFT)
		};
	
	public TestHead() {
		super(items);
	}
}
package socket.msg.test;

import socket.msg.MsgField;
import socket.msg.MsgPiece;
import socket.msg.MsgField.FillSide;

public class TestBody extends MsgPiece {
	
	private static final MsgField[] items = new MsgField[]{
		new MsgField("content", 20, ' ',FillSide.RIGHT),
	};
	
	public TestBody() {
		super(items);
	}
	
	private String content;

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}
package socket.msg.test;

import socket.msg.MsgPackage;

public class TestPackage extends MsgPackage {
	
	public TestPackage() {
		super("t1", "t2");
	}
	
	private TestHead t1;
	
	private TestBody t2;

	public TestHead getT1() {
		return t1;
	}

	public void setT1(TestHead t1) {
		this.t1 = t1;
	}

	public TestBody getT2() {
		return t2;
	}

	public void setT2(TestBody t2) {
		this.t2 = t2;
	}

}
テストクラス:
package socket.msg.test;

import java.io.UnsupportedEncodingException;

public class Test {

	/**
	 * @author Zhenwei.Zhang (2013-11-12)
	 * @param args
	 * @throws Exception 
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException, Exception {
		TestHead head = new  TestHead();
		head.setName("name");
		head.setAmt(12.121);
		head.setSex(false);
		head.setURL("http://asdsaaaaaaaaaaaaaaaaaaaaaaa");
		head.setUAge(111);
		
		TestBody body = new TestBody();
		body.setContent("content");
		
		TestPackage packagee = new TestPackage();
		packagee.setT1(head);
		packagee.setT2(body);
		
		System.out.println(new String(packagee.pack("GBK"), "GBK"));
		
		TestPackage packagee2 = new TestPackage();
		String str = "name      000000true0000000111http://asd000012.121content             ";
		packagee2.unPack(str.getBytes("GBK"), "GBK");
		System.out.println(packagee2.getT1().isSex());
	}

}