All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.tom.protocol.co.Row Maven / Gradle / Ivy

The newest version!
package cn.tom.protocol.co;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.tom.kit.Bits;
import cn.tom.kit.IoBuffer;


/**
 * 根据定义的Field 获取的 rows
 * 
 * @author tomsun
 *
 */
public class Row {

	private int length;

	private List data = new ArrayList<>();

	public Row() {

	}

	public Row setCell(Cell cell) {
		data.add(cell);
		length += cell.getLen() + 4;
		return this;
	}

	public void toBytes(IoBuffer buf) {
		if (data.size() > 0) {
			for (Cell c : data) {
				buf.writeInt(c.getLen());
				buf.writeBytes(c.getBs());
			}
		}
	}

	public List getData() {
		return data;
	}

	public int getLength() {
		return length;
	}

	public static class Cell {
		private int len;
		private byte[] bs;

		public Cell(Object obj) {
			this(toByteArray(obj));
		}

		public Cell(byte[] b) {
			this.bs = b;
			this.len = b.length;
		}

		public int getLen() {
			return len;
		}

		public void setLen(int len) {
			this.len = len;
		}

		public byte[] getBs() {
			return bs;
		}

		private static byte[] toByteArray(Object value) {
			byte[] array = null;

			if (value instanceof String) {
				array = ((String) value).getBytes();
			} else if (value instanceof Integer) {
				array = new byte[4];
				Bits.putInt(array, 0, (int) value);
			} else if (value instanceof Short) {
				array = new byte[2];
				Bits.putShort(array, 0, (short) value);
			} else if (value instanceof Character) {  //char 2 byte
				array = new byte[2];
				Bits.putChar(array, 0, (char)value);
			} else if (value instanceof Double) {
				array = new byte[8];
				Bits.putDouble(array, 0, (double) value);
			} else if (value instanceof Float) {
				array = new byte[4];
				Bits.putFloat(array, 0, (float) value);
			} else if (value instanceof Long) {
				array = new byte[8];
				Bits.putLong(array, 0, (long) value);
			} else if (value instanceof Boolean) {
				array = new byte[1];
				Bits.putBoolean(array, 0, (boolean) value);
			} else if (value instanceof java.sql.Timestamp) {
				array = new byte[8];
				Bits.putLong(array, 0, ((java.sql.Timestamp) value).getTime());
			} else if (value instanceof java.util.Date) {
				array = new byte[8];
				Bits.putLong(array, 0, ((java.util.Date) value).getTime());
			} else if (value instanceof BigDecimal) {
				array = new byte[8];
				Bits.putDouble(array, 0, ((BigDecimal) value).doubleValue());
			} else if (value instanceof byte[]) {
				array = (byte[]) value;
			}else{
				throw new RuntimeException("不支持的类型:" + value.getClass());
			}

			return array;
		}

	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy