下面列出了java.nio.ByteBuffer#getShort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static Object parseDoubleArray(int length,
ByteBuffer buf, ConstantPool constPool) {
double[] result = new double[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'D') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getDoubleAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Map<Class<? extends Annotation>, Annotation> parseAnnotations2(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container,
Class<? extends Annotation>[] selectAnnotationClasses) {
Map<Class<? extends Annotation>, Annotation> result =
new LinkedHashMap<Class<? extends Annotation>, Annotation>();
ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
int numAnnotations = buf.getShort() & 0xFFFF;
for (int i = 0; i < numAnnotations; i++) {
Annotation a = parseAnnotation2(buf, constPool, container, false, selectAnnotationClasses);
if (a != null) {
Class<? extends Annotation> klass = a.annotationType();
if (AnnotationType.getInstance(klass).retention() == RetentionPolicy.RUNTIME &&
result.put(klass, a) != null) {
throw new AnnotationFormatError(
"Duplicate annotation for class: "+klass+": " + a);
}
}
}
return result;
}
private static Object parseFloatArray(int length,
ByteBuffer buf, ConstantPool constPool) {
float[] result = new float[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'F') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getFloatAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private Map<String, String> decodeRequestAttachments(ByteBuffer buffer) throws IOException, ClassNotFoundException {
int size = buffer.getInt();
if (size <= 0) {
return null;
}
/*byte[] data = new byte[size];
buffer.get(data);
ByteBuffer attachBuffer = ByteBuffer.wrap(data);*/
short keySize;
byte[] keyContent;
int valSize;
byte[] valContent;
Map<String, String> attachments = new HashMap();
while (buffer.hasRemaining()) {
keySize = buffer.getShort();
keyContent = new byte[keySize];
buffer.get(keyContent);
valSize = buffer.getInt();
valContent = new byte[valSize];
buffer.get(valContent);
attachments.put(new String(keyContent, CHARSET_UTF8), new String(valContent, CHARSET_UTF8));
}
return attachments;
}
private static Map<Class<? extends Annotation>, Annotation> parseAnnotations2(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container,
Class<? extends Annotation>[] selectAnnotationClasses) {
Map<Class<? extends Annotation>, Annotation> result =
new LinkedHashMap<Class<? extends Annotation>, Annotation>();
ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
int numAnnotations = buf.getShort() & 0xFFFF;
for (int i = 0; i < numAnnotations; i++) {
Annotation a = parseAnnotation2(buf, constPool, container, false, selectAnnotationClasses);
if (a != null) {
Class<? extends Annotation> klass = a.annotationType();
if (AnnotationType.getInstance(klass).retention() == RetentionPolicy.RUNTIME &&
result.put(klass, a) != null) {
throw new AnnotationFormatError(
"Duplicate annotation for class: "+klass+": " + a);
}
}
}
return result;
}
public static HashMap<String, String> mapDeserialize(byte[] bytes) {
if (bytes == null || bytes.length <= 0)
return null;
HashMap<String, String> map = new HashMap<String, String>();
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
short keySize;
byte[] keyContent;
int valSize;
byte[] valContent;
while (byteBuffer.hasRemaining()) {
keySize = byteBuffer.getShort();
keyContent = new byte[keySize];
byteBuffer.get(keyContent);
valSize = byteBuffer.getInt();
valContent = new byte[valSize];
byteBuffer.get(valContent);
map.put(new String(keyContent, CHARSET_UTF8), new String(valContent, CHARSET_UTF8));
}
return map;
}
private static Object parseShortArray(int length,
ByteBuffer buf, ConstantPool constPool) {
short[] result = new short[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'S') {
int index = buf.getShort() & 0xFFFF;
result[i] = (short) constPool.getIntAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
/**
* Parses the primitive or String annotation member value indicated by
* the specified tag byte at the current position in the specified byte
* buffer, resolving constant reference in the specified constant pool.
* The cursor of the byte buffer must point to an annotation member value
* of the type indicated by the specified tag, as described in the
* RuntimeVisibleAnnotations_attribute:
*
* u2 const_value_index;
*/
private static Object parseConst(int tag,
ByteBuffer buf, ConstantPool constPool) {
int constIndex = buf.getShort() & 0xFFFF;
switch(tag) {
case 'B':
return Byte.valueOf((byte) constPool.getIntAt(constIndex));
case 'C':
return Character.valueOf((char) constPool.getIntAt(constIndex));
case 'D':
return Double.valueOf(constPool.getDoubleAt(constIndex));
case 'F':
return Float.valueOf(constPool.getFloatAt(constIndex));
case 'I':
return Integer.valueOf(constPool.getIntAt(constIndex));
case 'J':
return Long.valueOf(constPool.getLongAt(constIndex));
case 'S':
return Short.valueOf((short) constPool.getIntAt(constIndex));
case 'Z':
return Boolean.valueOf(constPool.getIntAt(constIndex) != 0);
case 's':
return constPool.getUTF8At(constIndex);
default:
throw new AnnotationFormatError(
"Invalid member-value tag in annotation: " + tag);
}
}
@Override
public int[] getIndexArray( final int size , final ByteBuffer wrapBuffer ) throws IOException{
int[] result = new int[size];
for( int i = 0 ; i < size ; i++ ){
result[i] = (int)( wrapBuffer.getShort() ) + min;
}
return result;
}
public static int[] readS16Enumeration(ByteBuffer b) {
int len = b.getShort() & 0xFFFF;
int[] a = new int[len];
for (int i = 0; i < len; ++i) {
a[i] = b.getShort();
}
return a;
}
/**
* Converts a variable length integer (https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer) to long
*
* @param varInt byte array containing variable length integer
*
* @return long corresponding to variable length integer
*
*/
public static long getVarInt(byte[] varInt) {
long result=0;
if (varInt.length==0) {
return result;
}
int unsignedByte=varInt[0] & 0xFF;
if (unsignedByte<0xFD) {
return unsignedByte;
}
int intSize=0;
if (unsignedByte==0xFD) {
intSize=3;
}
else if (unsignedByte==0xFE) {
intSize=5;
}
else if (unsignedByte==0XFF) {
intSize=9;
}
byte[] rawDataInt=reverseByteArray(Arrays.copyOfRange(varInt, 1, intSize));
ByteBuffer byteBuffer = ByteBuffer.wrap(rawDataInt);
if (intSize==3) {
result=byteBuffer.getShort();
}
else if (intSize==5) {
result=byteBuffer.getInt();
}
else if (intSize==9) {
result=byteBuffer.getLong(); // Need to handle sign - available only in JDK8
}
return result;
}
public static DnsHeader FromBytes(ByteBuffer buffer) {
DnsHeader header = new DnsHeader(buffer.array(), buffer.arrayOffset() + buffer.position());
header.ID = buffer.getShort();
header.Flags = DnsFlags.Parse(buffer.getShort());
header.QuestionCount = buffer.getShort();
header.ResourceCount = buffer.getShort();
header.AResourceCount = buffer.getShort();
header.EResourceCount = buffer.getShort();
return header;
}
private void testSingle(String hex) throws Exception {
byte[] data = Hex.decodeHex(hex.toCharArray());
ByteBuffer buffer = ByteBuffer.wrap(data);
int packetSize = buffer.getInt();
buffer.get(); // type
data = new byte[packetSize];
buffer.get(data);
buffer = ByteBuffer.wrap(data);
byte type = buffer.get();
long magic = Utils.unpack_dd(buffer);
long pid = Utils.unpack_dd(buffer);
long tid = Utils.unpack_dd(buffer);
long pc = Utils.unpack_dd(buffer);
short s1 = buffer.getShort();
String path = Utils.readCString(buffer);
long base = Utils.unpack_dd(buffer);
byte b1 = buffer.get();
long size = Utils.unpack_dd(buffer);
byte b2 = buffer.get();
long test = Utils.unpack_dd(buffer);
boolean dylib = buffer.get() == 1;
data = new byte[buffer.remaining()];
buffer.get(data);
Inspector.inspect(data, "type=" + type + ", magic=" + magic + ", pid=" + pid + ", tid=" + tid +
", pc=0x" + Long.toHexString(pc) + ", s1=" + s1 + ", path=" + path +
", base=0x" + Long.toHexString(base) + ", b1=" + b1 + ", size=0x" + Long.toHexString(size) + ", b2=" + b2 + ", test=0x" + Long.toHexString(test) +
", dylib=" + dylib);
}
public static Socket socks5rawSocketConnection(String networkHost, int networkPort, String socksHost, int socksPort)
throws IOException {
int bytesRead = 0;
boolean end = false;
String messageString = "";
final byte[] messageByte = new byte[1000];
Socket socket = new Socket();
socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
SocketAddress socksAddress = new InetSocketAddress(socksHost, socksPort);
socket.connect(socksAddress, CONNECT_TIMEOUT_MILLISECONDS);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.write((byte) 0x05);
outputStream.write((byte) 0x01);
outputStream.write((byte) 0x00);
outputStream.write((byte) 0x01);
outputStream.write(networkHost.getBytes());
outputStream.writeShort((short) networkPort);
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
messageByte[0] = inputStream.readByte();
messageByte[1] = inputStream.readByte();
if (messageByte[0] != (byte) 0x05 || messageByte[1] != (byte) 0x00) {
socket.close();
throw new IOException("SOCKS4a connect failed, got " + messageByte[0] + " - " + messageByte[1] +
", but expected 0x00 - 0x5a");
}
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);
int bytesToRead = byteBuffer.getShort();
LOG.info("About to read " + bytesToRead + " octets");
while (!end) {
bytesRead = inputStream.read(messageByte);
messageString += new String(messageByte, 0, bytesRead);
if (messageString.length() == bytesToRead) {
end = true;
}
}
return socket;
}
private void verifyPFA(ByteBuffer bb) throws FontFormatException {
if (bb.getShort() != 0x2521) { // 0x2521 is %!
throw new FontFormatException("bad pfa font");
}
// remind - additional verification needed?
}
/**
* Decode the encoded package into a object
*
* @param encodedPackage
* @return
* @throws PackageEncodeException
*/
public static KeepAliveRequest decodeTuple(final ByteBuffer encodedPackage) throws PackageEncodeException {
final short sequenceNumber = NetworkPackageDecoder.getRequestIDFromRequestPackage(encodedPackage);
final boolean decodeResult = NetworkPackageDecoder.validateRequestPackageHeader(encodedPackage, NetworkConst.REQUEST_TYPE_KEEP_ALIVE);
if(decodeResult == false) {
throw new PackageEncodeException("Unable to decode package");
}
final List<Tuple> tuples = new ArrayList<>();
final short tableLength = encodedPackage.getShort();
encodedPackage.get(); // Unused
encodedPackage.get(); // Unused
final int elements = encodedPackage.getInt();
final byte[] tableNameBytes = new byte[tableLength];
encodedPackage.get(tableNameBytes, 0, tableNameBytes.length);
final String tableName = new String(tableNameBytes);
for(int i = 0; i < elements; i++) {
final int keyLength = encodedPackage.getInt();
final byte[] keyBytes = new byte[keyLength];
encodedPackage.get(keyBytes, 0, keyBytes.length);
final String key = new String(keyBytes);
final int boundingBoxLength = encodedPackage.getInt();
final byte[] boundingBoxBytes = new byte[boundingBoxLength];
encodedPackage.get(boundingBoxBytes, 0, boundingBoxBytes.length);
final Hyperrectangle boundingBox = Hyperrectangle.fromByteArray(boundingBoxBytes);
final long version = encodedPackage.getLong();
final Tuple tuple = new Tuple(key, boundingBox, "".getBytes(), version);
tuples.add(tuple);
}
if(encodedPackage.remaining() != 0) {
throw new PackageEncodeException("Some bytes are left after decoding: " + encodedPackage.remaining());
}
return new KeepAliveRequest(sequenceNumber, tableName, tuples);
}
/**
* Skips the array value at the current position in the specified byte
* buffer. The cursor of the byte buffer must point to an array value
* struct.
*/
private static void skipArray(ByteBuffer buf) {
int length = buf.getShort() & 0xFFFF;
for (int i = 0; i < length; i++)
skipMemberValue(buf);
}
protected void init(int fIndex) throws FontFormatException {
int headerOffset = 0;
ByteBuffer buffer = readBlock(0, TTCHEADERSIZE);
try {
switch (buffer.getInt()) {
case ttcfTag:
buffer.getInt(); // skip TTC version ID
directoryCount = buffer.getInt();
if (fIndex >= directoryCount) {
throw new FontFormatException("Bad collection index");
}
fontIndex = fIndex;
buffer = readBlock(TTCHEADERSIZE+4*fIndex, 4);
headerOffset = buffer.getInt();
break;
case v1ttTag:
case trueTag:
case ottoTag:
break;
default:
throw new FontFormatException("Unsupported sfnt " +
getPublicFileName());
}
/* Now have the offset of this TT font (possibly within a TTC)
* After the TT version/scaler type field, is the short
* representing the number of tables in the table directory.
* The table directory begins at 12 bytes after the header.
* Each table entry is 16 bytes long (4 32-bit ints)
*/
buffer = readBlock(headerOffset+4, 2);
numTables = buffer.getShort();
directoryOffset = headerOffset+DIRECTORYHEADERSIZE;
ByteBuffer bbuffer = readBlock(directoryOffset,
numTables*DIRECTORYENTRYSIZE);
IntBuffer ibuffer = bbuffer.asIntBuffer();
DirectoryEntry table;
tableDirectory = new DirectoryEntry[numTables];
for (int i=0; i<numTables;i++) {
tableDirectory[i] = table = new DirectoryEntry();
table.tag = ibuffer.get();
/* checksum */ ibuffer.get();
table.offset = ibuffer.get();
table.length = ibuffer.get();
if (table.offset + table.length > fileSize) {
throw new FontFormatException("bad table, tag="+table.tag);
}
}
if (getDirectoryEntry(headTag) == null) {
throw new FontFormatException("missing head table");
}
if (getDirectoryEntry(maxpTag) == null) {
throw new FontFormatException("missing maxp table");
}
if (getDirectoryEntry(hmtxTag) != null
&& getDirectoryEntry(hheaTag) == null) {
throw new FontFormatException("missing hhea table");
}
initNames();
} catch (Exception e) {
if (FontUtilities.isLogging()) {
FontUtilities.getLogger().severe(e.toString());
}
if (e instanceof FontFormatException) {
throw (FontFormatException)e;
} else {
throw new FontFormatException(e.toString());
}
}
if (familyName == null || fullName == null) {
throw new FontFormatException("Font name not found");
}
/* The os2_Table is needed to gather some info, but we don't
* want to keep it around (as a field) so obtain it once and
* pass it to the code that needs it.
*/
ByteBuffer os2_Table = getTableBuffer(os_2Tag);
setStyle(os2_Table);
setCJKSupport(os2_Table);
}
private void readControlFrame() throws IOException {
if (mFrameLength >= Integer.MAX_VALUE) {
throw new IOException("Not support a frame length > " + Integer.MAX_VALUE);
}
WebSocketCallback callback = mCallback;
if (callback == null) {
return;
}
ByteBuffer byteBuffer;
if (mFrameLength > 0) {
byte[] frame = new byte[(int) mFrameLength];
readFully(frame);
if (!mClient) {
WebSocketProtocol.toggleMask(frame, mMaskKey);
}
byteBuffer = ByteBuffer.wrap(frame);
} else {
byteBuffer = ByteBuffer.allocate(0);
}
switch (mOpcode) {
case WebSocketProtocol.OPCODE_CONTROL_PING:
callback.onReadPing(readFully(byteBuffer));
break;
case WebSocketProtocol.OPCODE_CONTROL_PONG:
callback.onReadPong(readFully(byteBuffer));
break;
case WebSocketProtocol.OPCODE_CONTROL_CLOSE:
int code = WebSocketProtocol.CLOSE_NO_STATUS_CODE;
String reason = "";
long bufferSize = byteBuffer.remaining();
if (bufferSize == 1) {
throw new ProtocolException("Malformed close payload length of 1.");
} else if (bufferSize != 0) {
code = byteBuffer.getShort();
reason = new String(byteBuffer.array(), byteBuffer.position(), byteBuffer.remaining());
String codeExceptionMessage = WebSocketProtocol.closeCodeExceptionMessage(code);
if (codeExceptionMessage != null) {
throw new ProtocolException(codeExceptionMessage);
}
}
callback.onReadClose(code, reason);
break;
default:
throw new ProtocolException("Unknown control opcode: " + toHexString(mOpcode));
}
}
@Override
public void setBlockIndexNode( final BlockIndexNode parentNode , final ColumnBinary columnBinary , final int spreadIndex ) throws IOException{
BlockIndexNode currentNode = parentNode.getChildNode( columnBinary.columnName );
ByteBuffer wrapBuffer = ByteBuffer.wrap( columnBinary.binary , columnBinary.binaryStart , columnBinary.binaryLength );
switch( columnBinary.columnType ){
case BYTE:
byte byteValue = wrapBuffer.get();
currentNode.setBlockIndex( new ByteRangeBlockIndex( byteValue , byteValue ) );
break;
case SHORT:
short shortValue = wrapBuffer.getShort();
currentNode.setBlockIndex( new ShortRangeBlockIndex( shortValue , shortValue ) );
break;
case INTEGER:
int intValue = wrapBuffer.getInt();
currentNode.setBlockIndex( new IntegerRangeBlockIndex( intValue , intValue ) );
break;
case LONG:
long longValue = wrapBuffer.getLong();
currentNode.setBlockIndex( new LongRangeBlockIndex( longValue , longValue ) );
break;
case FLOAT:
float floatValue = wrapBuffer.getFloat();
currentNode.setBlockIndex( new FloatRangeBlockIndex( floatValue , floatValue ) );
break;
case DOUBLE:
double doubleValue = wrapBuffer.getDouble();
currentNode.setBlockIndex( new DoubleRangeBlockIndex( doubleValue , doubleValue ) );
break;
case STRING:
int stringLength = wrapBuffer.getInt();
byte[] stringBytes = new byte[stringLength];
wrapBuffer.get( stringBytes );
String string = new String( stringBytes , 0 , stringBytes.length , "UTF-8" );
currentNode.setBlockIndex( new StringRangeBlockIndex( string , string ) );
break;
default:
currentNode.disable();
break;
}
}