下面列出了怎么用java.nio.BufferUnderflowException的API类实例代码及写法,或者点击链接到github查看源代码。
private static TypeAnnotation parseTypeAnnotation(ByteBuffer buf,
ConstantPool cp,
AnnotatedElement baseDecl,
Class<?> container) {
try {
TypeAnnotationTargetInfo ti = parseTargetInfo(buf);
LocationInfo locationInfo = LocationInfo.parseLocationInfo(buf);
Annotation a = AnnotationParser.parseAnnotation(buf, cp, container, false);
if (ti == null) // Inside a method for example
return null;
return new TypeAnnotation(ti, locationInfo, a, baseDecl);
} catch (IllegalArgumentException | // Bad type in const pool at specified index
BufferUnderflowException e) {
throw new AnnotationFormatError(e);
}
}
private static void expunge(Path p, KerberosTime currTime)
throws IOException {
Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
try (SeekableByteChannel oldChan = Files.newByteChannel(p);
SeekableByteChannel newChan = createNoClose(p2)) {
long timeLimit = currTime.getSeconds() - readHeader(oldChan);
while (true) {
try {
AuthTime at = AuthTime.readFrom(oldChan);
if (at.ctime > timeLimit) {
ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
newChan.write(bb);
}
} catch (BufferUnderflowException e) {
break;
}
}
}
makeMine(p2);
Files.move(p2, p,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
/**
* Decodes a series of events from the ByteBuffer. Handles event values and
* types as bytes.
*
* @param buffer
* @return
* @throws ClientException
*/
public static Event[] decodeEvents(final ByteBuffer buffer)
throws ClientException {
final ArrayList<Event> events = new ArrayList<Event>();
int nEvents = 0;
// Read events while bytes remain in the buffer.
try {
while (buffer.position() < buffer.capacity()) {
events.add(decodeEvent(buffer));
nEvents++;
}
} catch (final BufferUnderflowException e) {
throw new ClientException("Malformed event message");
}
return events.toArray(new Event[nEvents]);
}
@Override
void dispatch(byte handshakeType, ByteBuffer fragment) throws IOException {
SSLConsumer consumer = handshakeConsumers.get(handshakeType);
if (consumer == null) {
throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unexpected post-handshake message: " +
SSLHandshake.nameOf(handshakeType));
}
try {
consumer.consume(this, fragment);
} catch (UnsupportedOperationException unsoe) {
throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unsupported post-handshake message: " +
SSLHandshake.nameOf(handshakeType), unsoe);
} catch (BufferUnderflowException | BufferOverflowException be) {
throw conContext.fatal(Alert.DECODE_ERROR,
"Illegal handshake message: " +
SSLHandshake.nameOf(handshakeType), be);
}
}
/**
* Reads color table as 256 RGB integer values
*
* @param ncolors int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
*/
protected int[] readColorTable(int ncolors) {
int nbytes = 3 * ncolors;
int[] tab = null;
byte[] c = new byte[nbytes];
try {
rawData.get(c);
tab = new int[256]; // max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors) {
int r = ((int) c[j++]) & 0xff;
int g = ((int) c[j++]) & 0xff;
int b = ((int) c[j++]) & 0xff;
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
}
} catch (BufferUnderflowException e) {
Log.w(TAG, "Format Error Reading Color Table", e);
status = STATUS_FORMAT_ERROR;
}
return tab;
}
private static void expunge(Path p, KerberosTime currTime)
throws IOException {
Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
try (SeekableByteChannel oldChan = Files.newByteChannel(p);
SeekableByteChannel newChan = createNoClose(p2)) {
long timeLimit = currTime.getSeconds() - readHeader(oldChan);
while (true) {
try {
AuthTime at = AuthTime.readFrom(oldChan);
if (at.ctime > timeLimit) {
ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
newChan.write(bb);
}
} catch (BufferUnderflowException e) {
break;
}
}
}
makeMine(p2);
Files.move(p2, p,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
}
private static byte[] getBytes(int index, int len, ByteBuffer buffer) {
if (index < 0 || index > buffer.limit()) {
throw new IndexOutOfBoundsException();
}
if (len < 0) {
throw new IllegalArgumentException("len must be >= 0");
}
if (len > buffer.limit() - index) {
throw new BufferUnderflowException();
}
byte[] buf = new byte[len];
if (len > 0) {
System.arraycopy(buffer.array(), index, buf, 0, len);
}
return buf;
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
private int nextTokenType(ByteBuffer bb) {
try {
byte b = skip(bb);
while (true) {
if (b == (byte)'/') { // PS defined name follows.
return PSNAMETOKEN;
} else if (b == (byte)'(') { // PS string follows
return PSSTRINGTOKEN;
} else if ((b == (byte)'\r') || (b == (byte)'\n')) {
b = skip(bb);
} else {
b = bb.get();
}
}
} catch (BufferUnderflowException e) {
return PSEOFTOKEN;
}
}
/** Parse the constant pool of the class
* calling a method visit* each time a constant pool entry is parsed.
*
* The order of the calls to visit* is not guaranteed to be the same
* than the order of the constant pool entry in the bytecode array.
*
* @param visitor
* @throws InvalidConstantPoolFormatException
*/
public void parse(ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException {
ByteBuffer buffer = ByteBuffer.wrap(classFile);
buffer.position(getStartOffset()); //skip header
Object[] values = new Object[getLength()];
try {
parseConstantPool(buffer, values, visitor);
} catch(BufferUnderflowException e) {
throw new InvalidConstantPoolFormatException(e);
}
if (endOffset == 0) {
endOffset = buffer.position();
secondHeader = new char[4];
for (int i = 0; i < secondHeader.length; i++) {
secondHeader[i] = (char) getUnsignedShort(buffer);
}
}
resolveConstantPool(values, visitor);
}
private static void expunge(Path p, KerberosTime currTime)
throws IOException {
Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
try (SeekableByteChannel oldChan = Files.newByteChannel(p);
SeekableByteChannel newChan = createNoClose(p2)) {
long timeLimit = currTime.getSeconds() - readHeader(oldChan);
while (true) {
try {
AuthTime at = AuthTime.readFrom(oldChan);
if (at.ctime > timeLimit) {
ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
newChan.write(bb);
}
} catch (BufferUnderflowException e) {
break;
}
}
}
makeMine(p2);
Files.move(p2, p,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
private static TypeAnnotation parseTypeAnnotation(ByteBuffer buf,
ConstantPool cp,
AnnotatedElement baseDecl,
Class<?> container) {
try {
TypeAnnotationTargetInfo ti = parseTargetInfo(buf);
LocationInfo locationInfo = LocationInfo.parseLocationInfo(buf);
Annotation a = AnnotationParser.parseAnnotation(buf, cp, container, false);
if (ti == null) // Inside a method for example
return null;
return new TypeAnnotation(ti, locationInfo, a, baseDecl);
} catch (IllegalArgumentException | // Bad type in const pool at specified index
BufferUnderflowException e) {
throw new AnnotationFormatError(e);
}
}
private void processBuffer(final ReaderRegistry<String> registry, final IValueDeserializer deserializer,
final OutputPort<IMonitoringRecord> outputPort) throws IOException {
this.buffer.flip();
try {
/** Needs at least an record id. */
while ((this.buffer.position() + 4) <= this.buffer.limit()) {
this.buffer.mark();
final IMonitoringRecord record = this.deserializeRecord(registry, deserializer);
if (record == null) {
return;
} else {
outputPort.send(record);
}
}
this.buffer.mark();
this.buffer.compact();
} catch (final BufferUnderflowException ex) {
RecordFromBinaryFileCreator.LOGGER.warn("Unexpected buffer underflow. Resetting and compacting buffer.", ex);
this.buffer.reset();
this.buffer.compact();
throw ex;
}
}
private static int csize(int p) throws Exception {
try (SeekableByteChannel chan = Files.newByteChannel(
Paths.get(dfl(p)), StandardOpenOption.READ)) {
chan.position(6);
int cc = 0;
while (true) {
try {
if (AuthTime.readFrom(chan) != null) cc++;
} catch (BufferUnderflowException e) {
break;
}
}
return cc;
} catch (IOException ioe) {
return 0;
}
}
public boolean skipToTag(int tag) {
try {
HeadData hd = new HeadData();
while (true) {
int len = peakHead(hd);
if (hd.type == TarsStructBase.STRUCT_END) {
return false;
}
if (tag <= hd.tag) return tag == hd.tag;
skip(len);
skipField(hd.type);
}
} catch (TarsDecodeException | BufferUnderflowException e) {
}
return false;
}
private static void expunge(Path p, KerberosTime currTime)
throws IOException {
Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
try (SeekableByteChannel oldChan = Files.newByteChannel(p);
SeekableByteChannel newChan = createNoClose(p2)) {
long timeLimit = currTime.getSeconds() - readHeader(oldChan);
while (true) {
try {
AuthTime at = AuthTime.readFrom(oldChan);
if (at.ctime > timeLimit) {
ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
newChan.write(bb);
}
} catch (BufferUnderflowException e) {
break;
}
}
}
makeMine(p2);
Files.move(p2, p,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
/**
* Checks bounds for a slice.
*/
protected long checkSlice(long offset, long length) {
checkOffset(offset);
if (limit == -1) {
if (offset + length > capacity) {
if (capacity < maxCapacity) {
capacity(calculateCapacity(offset + length));
} else {
throw new BufferUnderflowException();
}
}
} else {
if (offset + length > limit)
throw new BufferUnderflowException();
}
return offset(offset);
}
@Override
public final void readBytes(byte[] b, int offset, int len) throws IOException {
try {
guard.getBytes(curBuf, b, offset, len);
} catch (BufferUnderflowException e) {
int curAvail = curBuf.remaining();
while (len > curAvail) {
guard.getBytes(curBuf, b, offset, curAvail);
len -= curAvail;
offset += curAvail;
curBufIndex++;
if (curBufIndex >= buffers.length) {
throw new EOFException("read past EOF: " + this);
}
setCurBuf(buffers[curBufIndex]);
curBuf.position(0);
curAvail = curBuf.remaining();
}
guard.getBytes(curBuf, b, offset, len);
} catch (NullPointerException npe) {
throw new AlreadyClosedException("Already closed: " + this);
}
}
private static TypeAnnotation parseTypeAnnotation(ByteBuffer buf,
ConstantPool cp,
AnnotatedElement baseDecl,
Class<?> container) {
try {
TypeAnnotationTargetInfo ti = parseTargetInfo(buf);
LocationInfo locationInfo = LocationInfo.parseLocationInfo(buf);
Annotation a = AnnotationParser.parseAnnotation(buf, cp, container, false);
if (ti == null) // Inside a method for example
return null;
return new TypeAnnotation(ti, locationInfo, a, baseDecl);
} catch (IllegalArgumentException | // Bad type in const pool at specified index
BufferUnderflowException e) {
throw new AnnotationFormatError(e);
}
}
@Override
public void getEncodedData(PacketBuffer packetBuffer) throws BufferUnderflowException {
if (mBufferedFrames < mFramesPerPacket) {
throw new BufferUnderflowException();
}
for (int x = 0; x < mBufferedFrames; x++) {
byte[] frame = mBuffer[x];
int head = frame.length;
if(x < mBufferedFrames - 1)
head |= 0x80;
packetBuffer.append(head);
packetBuffer.append(frame, frame.length);
}
mBufferedFrames = 0;
}
private static int csize(int p) throws Exception {
try (SeekableByteChannel chan = Files.newByteChannel(
Paths.get(dfl(p)), StandardOpenOption.READ)) {
chan.position(6);
int cc = 0;
while (true) {
try {
if (AuthTime.readFrom(chan) != null) cc++;
} catch (BufferUnderflowException e) {
break;
}
}
return cc;
} catch (IOException ioe) {
return 0;
}
}
@Test
public void testGetByteWithOneArrayWithManyElements() {
CompositeReadableBuffer buffer = new CompositeReadableBuffer();
buffer.append(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
assertEquals(10, buffer.remaining());
assertTrue(buffer.hasRemaining());
assertEquals(0, buffer.position());
for (int i = 0; i < 10; ++i) {
assertEquals(i, buffer.get());
assertEquals(i + 1, buffer.position());
}
assertEquals(0, buffer.remaining());
assertEquals(10, buffer.position());
try {
buffer.get();
fail("Should not be able to read past end");
} catch (BufferUnderflowException e) {}
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
@Override
public final void readBytes(byte[] b, int offset, int len) throws IOException {
try {
curBuf.get(b, offset, len);
} catch (BufferUnderflowException e) {
int curAvail = curBuf.remaining();
while (len > curAvail) {
curBuf.get(b, offset, curAvail);
len -= curAvail;
offset += curAvail;
curBufIndex++;
if (curBufIndex >= buffers.length) {
throw new EOFException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.position(0);
curAvail = curBuf.remaining();
}
curBuf.get(b, offset, len);
} catch (NullPointerException npe) {
throw new AlreadyClosedException("Already closed: " + this);
}
}
private void verifyPFB(ByteBuffer bb) throws FontFormatException {
int pos = 0;
while (true) {
try {
int segType = bb.getShort(pos) & 0xffff;
if (segType == 0x8001 || segType == 0x8002) {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segLen = bb.getInt(pos+2);
bb.order(ByteOrder.BIG_ENDIAN);
if (segLen <= 0) {
throw new FontFormatException("bad segment length");
}
pos += segLen+6;
} else if (segType == 0x8003) {
return;
} else {
throw new FontFormatException("bad pfb file");
}
} catch (BufferUnderflowException bue) {
throw new FontFormatException(bue.toString());
} catch (Exception e) {
throw new FontFormatException(e.toString());
}
}
}
@Override
public Handshakedata translateHandshake( ByteBuffer buf ) throws InvalidHandshakeException {
HandshakeBuilder bui = translateHandshakeHttp( buf, role );
// the first drafts are lacking a protocol number which makes them difficult to distinguish. Sec-WebSocket-Key1 is typical for draft76
if( ( bui.hasFieldValue( "Sec-WebSocket-Key1" ) || role == Role.CLIENT ) && !bui.hasFieldValue( "Sec-WebSocket-Version" ) ) {
byte[] key3 = new byte[ role == Role.SERVER ? 8 : 16 ];
try {
buf.get( key3 );
} catch ( BufferUnderflowException e ) {
throw new IncompleteHandshakeException( buf.capacity() + 16 );
}
bui.setContent( key3 );
}
return bui;
}