下面列出了java.nio.CharBuffer#wrap ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void flush() throws IOException {
//Log.i("PackageManager", "flush mPos=" + mPos);
if (mPos > 0) {
if (mOutputStream != null) {
CharBuffer charBuffer = CharBuffer.wrap(mText, 0, mPos);
CoderResult result = mCharset.encode(charBuffer, mBytes, true);
while (true) {
if (result.isError()) {
throw new IOException(result.toString());
} else if (result.isOverflow()) {
flushBytes();
result = mCharset.encode(charBuffer, mBytes, true);
continue;
}
break;
}
flushBytes();
mOutputStream.flush();
} else {
mWriter.write(mText, 0, mPos);
mWriter.flush();
}
mPos = 0;
}
}
String toString(byte[] ba, int length) {
CharsetDecoder cd = decoder().reset();
int len = (int)(length * cd.maxCharsPerByte());
char[] ca = new char[len];
if (len == 0)
return new String(ca);
ByteBuffer bb = ByteBuffer.wrap(ba, 0, length);
CharBuffer cb = CharBuffer.wrap(ca);
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
cr = cd.flush(cb);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
return new String(ca, 0, cb.position());
}
String toString(byte[] ba, int length) {
CharsetDecoder cd = decoder().reset();
int len = (int)(length * cd.maxCharsPerByte());
char[] ca = new char[len];
if (len == 0)
return new String(ca);
// UTF-8 only for now. Other ArrayDeocder only handles
// CodingErrorAction.REPLACE mode. ZipCoder uses
// REPORT mode.
if (isUTF8 && cd instanceof ArrayDecoder) {
int clen = ((ArrayDecoder)cd).decode(ba, 0, length, ca);
if (clen == -1) // malformed
throw new IllegalArgumentException("MALFORMED");
return new String(ca, 0, clen);
}
ByteBuffer bb = ByteBuffer.wrap(ba, 0, length);
CharBuffer cb = CharBuffer.wrap(ca);
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
cr = cd.flush(cb);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
return new String(ca, 0, cb.position());
}
/**
* Convert a char array into a byte array
*
* @param chars
* @return
*/
private byte[] toBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName(WFImplConstant.DEFAULT_CHARSET).encode(charBuffer);
byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000');
Arrays.fill(byteBuffer.array(), (byte) 0);
return bytes;
}
static byte[] toBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000'); // clear the cleartext
Arrays.fill(byteBuffer.array(), (byte) 0); // clear the ciphertext
return bytes;
}
static byte[] encode(Charset cs, char[] ca, int off, int len) {
CharsetEncoder ce = cs.newEncoder();
int en = scale(len, ce.maxBytesPerChar());
byte[] ba = new byte[en];
if (len == 0)
return ba;
boolean isTrusted = false;
if (System.getSecurityManager() != null) {
if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
ca = Arrays.copyOfRange(ca, off, off + len);
off = 0;
}
}
ce.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.reset();
if (ce instanceof ArrayEncoder) {
int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
return safeTrim(ba, blen, cs, isTrusted);
} else {
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca, off, len);
try {
CoderResult cr = ce.encode(cb, bb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = ce.flush(bb);
if (!cr.isUnderflow())
cr.throwException();
} catch (CharacterCodingException x) {
throw new Error(x);
}
return safeTrim(ba, bb.position(), cs, isTrusted);
}
}
public static ByteBuffer toByteBuffer(Type type, Object value) {
switch (type.typeId()) {
case BOOLEAN:
return ByteBuffer.allocate(1).put(0, (Boolean) value ? (byte) 0x01 : (byte) 0x00);
case INTEGER:
case DATE:
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(0, (int) value);
case LONG:
case TIME:
case TIMESTAMP:
return ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(0, (long) value);
case FLOAT:
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(0, (float) value);
case DOUBLE:
return ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putDouble(0, (double) value);
case STRING:
CharBuffer buffer = CharBuffer.wrap((CharSequence) value);
try {
return ENCODER.get().encode(buffer);
} catch (CharacterCodingException e) {
throw new RuntimeIOException(e, "Failed to encode value as UTF-8: " + value);
}
case UUID:
UUID uuid = (UUID) value;
return ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)
.putLong(0, uuid.getMostSignificantBits())
.putLong(1, uuid.getLeastSignificantBits());
case FIXED:
case BINARY:
return (ByteBuffer) value;
case DECIMAL:
return ByteBuffer.wrap(((BigDecimal) value).unscaledValue().toByteArray());
default:
throw new UnsupportedOperationException("Cannot serialize type: " + type);
}
}
public static InputStream prepareInputStream(char[] chars, Charset charset) {
CharBuffer wrapped = CharBuffer.wrap(chars);
ByteBuffer buffer = charset.encode(wrapped);
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
return prepareInputStream(bytes);
}
char[] decode(byte[] ba, int off, int len) {
int en = scale(len, cd.maxCharsPerByte());
char[] ca = new char[en];
if (len == 0)
return ca;
if (cd instanceof ArrayDecoder) {
int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
return safeTrim(ca, clen, cs, isTrusted);
} else {
cd.reset();
ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
CharBuffer cb = CharBuffer.wrap(ca);
try {
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = cd.flush(cb);
if (!cr.isUnderflow())
cr.throwException();
} catch (CharacterCodingException x) {
// Substitution is always enabled,
// so this shouldn't happen
throw new Error(x);
}
return safeTrim(ca, cb.position(), cs, isTrusted);
}
}
private static byte[] getPasswordBytes(char[] passwd) {
Charset utf8 = Charset.forName("UTF-8");
CharBuffer cb = CharBuffer.wrap(passwd);
ByteBuffer bb = utf8.encode(cb);
int len = bb.limit();
byte[] passwdBytes = new byte[len];
bb.get(passwdBytes, 0, len);
return passwdBytes;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
synchronized (lock) {
CharBuffer input = CharBuffer.wrap(cbuf);
input.limit(off + len).position(off);
flushLeftOver(input);
for (;;) {
CoderResult cr = _encoder.encode(input, _buffer, false);
if (cr.isUnderflow()) {
if (input.hasRemaining()) {
if (_leftOverBuffer == null) {
_leftOverBuffer = CharBuffer.allocate(LEFT_OVER_BUFFER);
}
_leftOverBuffer.put(input);
_hasLeftOver = true;
}
return;
}
if (cr.isOverflow()) {
flushBufferToWriter();
}
}
}
}
public ExpressionTokenizer(String expression) {
assertNotNull(expression);
this.expression = expression;
buf = CharBuffer.wrap(expression);
duplicatedBuf = buf.duplicate();
peek();
}
public void sendStringByCompletion(String text, SendHandler handler) {
if (text == null) {
throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullData"));
}
if (handler == null) {
throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullHandler"));
}
stateMachine.textStart();
TextMessageSendHandler tmsh = new TextMessageSendHandler(handler,
CharBuffer.wrap(text), true, encoder, encoderBuffer, this);
tmsh.write();
// TextMessageSendHandler will update stateMachine when it completes
}
static byte[] encode(Charset cs, char[] ca, int off, int len) {
CharsetEncoder ce = cs.newEncoder();
int en = scale(len, ce.maxBytesPerChar());
byte[] ba = new byte[en];
if (len == 0)
return ba;
boolean isTrusted = false;
if (System.getSecurityManager() != null) {
if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
ca = Arrays.copyOfRange(ca, off, off + len);
off = 0;
}
}
ce.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.reset();
if (ce instanceof ArrayEncoder) {
int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
return safeTrim(ba, blen, cs, isTrusted);
} else {
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca, off, len);
try {
CoderResult cr = ce.encode(cb, bb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = ce.flush(bb);
if (!cr.isUnderflow())
cr.throwException();
} catch (CharacterCodingException x) {
throw new Error(x);
}
return safeTrim(ba, bb.position(), cs, isTrusted);
}
}
char[] decode(byte[] ba, int off, int len) {
int en = scale(len, cd.maxCharsPerByte());
char[] ca = new char[en];
if (len == 0)
return ca;
if (cd instanceof ArrayDecoder) {
int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
return safeTrim(ca, clen, cs, isTrusted);
} else {
cd.reset();
ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
CharBuffer cb = CharBuffer.wrap(ca);
try {
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = cd.flush(cb);
if (!cr.isUnderflow())
cr.throwException();
} catch (CharacterCodingException x) {
// Substitution is always enabled,
// so this shouldn't happen
throw new Error(x);
}
return safeTrim(ca, cb.position(), cs, isTrusted);
}
}
@Test
public void testTimeoutZero() throws InterruptedException {
MessageQueue q = new MessageQueue(false);
NatsMessage expected = new NatsMessage(CharBuffer.wrap("PING"));
q.push(expected);
NatsMessage msg = q.pop(Duration.ZERO);
assertNotNull(msg);
}
private int unicodeToNative(char unicode, byte ebyte[])
{
int index = 0;
byte tmpByte[];
char convChar[] = {unicode};
byte convByte[] = new byte[4];
int converted;
try{
CharBuffer cc = CharBuffer.wrap(convChar);
ByteBuffer bb = ByteBuffer.allocate(4);
ISOEncoder.encode(cc, bb, true);
bb.flip();
converted = bb.remaining();
bb.get(convByte,0,converted);
} catch(Exception e) {
return -1;
}
if (converted == 2) {
if (!SODesDefined) {
newSODesDefined = true;
ebyte[0] = ISO_ESC;
tmpByte = SODesig.getBytes();
System.arraycopy(tmpByte,0,ebyte,1,tmpByte.length);
index = tmpByte.length+1;
}
if (!shiftout) {
newshiftout = true;
ebyte[index++] = ISO_SO;
}
ebyte[index++] = (byte)(convByte[0] & 0x7f);
ebyte[index++] = (byte)(convByte[1] & 0x7f);
} else {
if(convByte[0] == SS2) {
if (convByte[1] == PLANE2) {
if (!SS2DesDefined) {
newSS2DesDefined = true;
ebyte[0] = ISO_ESC;
tmpByte = SS2Desig.getBytes();
System.arraycopy(tmpByte, 0, ebyte, 1, tmpByte.length);
index = tmpByte.length+1;
}
ebyte[index++] = ISO_ESC;
ebyte[index++] = ISO_SS2_7;
ebyte[index++] = (byte)(convByte[2] & 0x7f);
ebyte[index++] = (byte)(convByte[3] & 0x7f);
} else if (convByte[1] == PLANE3) {
if(!SS3DesDefined){
newSS3DesDefined = true;
ebyte[0] = ISO_ESC;
tmpByte = SS3Desig.getBytes();
System.arraycopy(tmpByte, 0, ebyte, 1, tmpByte.length);
index = tmpByte.length+1;
}
ebyte[index++] = ISO_ESC;
ebyte[index++] = ISO_SS3_7;
ebyte[index++] = (byte)(convByte[2] & 0x7f);
ebyte[index++] = (byte)(convByte[3] & 0x7f);
}
}
}
return index;
}
private int unicodeToNative(char unicode, byte ebyte[])
{
int index = 0;
byte tmpByte[];
char convChar[] = {unicode};
byte convByte[] = new byte[4];
int converted;
try{
CharBuffer cc = CharBuffer.wrap(convChar);
ByteBuffer bb = ByteBuffer.allocate(4);
ISOEncoder.encode(cc, bb, true);
bb.flip();
converted = bb.remaining();
bb.get(convByte,0,converted);
} catch(Exception e) {
return -1;
}
if (converted == 2) {
if (!SODesDefined) {
newSODesDefined = true;
ebyte[0] = ISO_ESC;
tmpByte = SODesig.getBytes();
System.arraycopy(tmpByte,0,ebyte,1,tmpByte.length);
index = tmpByte.length+1;
}
if (!shiftout) {
newshiftout = true;
ebyte[index++] = ISO_SO;
}
ebyte[index++] = (byte)(convByte[0] & 0x7f);
ebyte[index++] = (byte)(convByte[1] & 0x7f);
} else {
if(convByte[0] == SS2) {
if (convByte[1] == PLANE2) {
if (!SS2DesDefined) {
newSS2DesDefined = true;
ebyte[0] = ISO_ESC;
tmpByte = SS2Desig.getBytes();
System.arraycopy(tmpByte, 0, ebyte, 1, tmpByte.length);
index = tmpByte.length+1;
}
ebyte[index++] = ISO_ESC;
ebyte[index++] = ISO_SS2_7;
ebyte[index++] = (byte)(convByte[2] & 0x7f);
ebyte[index++] = (byte)(convByte[3] & 0x7f);
} else if (convByte[1] == PLANE3) {
if(!SS3DesDefined){
newSS3DesDefined = true;
ebyte[0] = ISO_ESC;
tmpByte = SS3Desig.getBytes();
System.arraycopy(tmpByte, 0, ebyte, 1, tmpByte.length);
index = tmpByte.length+1;
}
ebyte[index++] = ISO_ESC;
ebyte[index++] = ISO_SS3_7;
ebyte[index++] = (byte)(convByte[2] & 0x7f);
ebyte[index++] = (byte)(convByte[3] & 0x7f);
}
}
}
return index;
}
/**
* Concatenate normalized strings, making sure that the result is normalized
* as well.
*
* If both the left and the right strings are in
* the normalization form according to "mode",
* then the result will be
*
* <code>
* dest=normalize(left+right, mode)
* </code>
*
* With the input strings already being normalized,
* this function will use next() and previous()
* to find the adjacent end pieces of the input strings.
* Only the concatenation of these end pieces will be normalized and
* then concatenated with the remaining parts of the input strings.
*
* It is allowed to have dest==left to avoid copying the entire left string.
*
* @param left Left source array, may be same as dest.
* @param leftStart start in the left array.
* @param leftLimit limit in the left array (==length)
* @param right Right source array.
* @param rightStart start in the right array.
* @param rightLimit limit in the right array (==length)
* @param dest The output buffer; can be null if destStart==destLimit==0
* for pure preflighting.
* @param destStart start in the destination array
* @param destLimit limit in the destination array (==length)
* @param mode The normalization mode.
* @param options The normalization options, ORed together (0 for no options).
* @return Length of output (number of chars) when successful or
* IndexOutOfBoundsException
* @exception IndexOutOfBoundsException whose message has the string
* representation of destination capacity required.
* @see #normalize
* @see #next
* @see #previous
* @exception IndexOutOfBoundsException if target capacity is less than the
* required length
* @deprecated ICU 56 Use {@link Normalizer2} instead.
*/
@Deprecated
public static int concatenate(char[] left, int leftStart, int leftLimit,
char[] right, int rightStart, int rightLimit,
char[] dest, int destStart, int destLimit,
Normalizer.Mode mode, int options) {
if(dest == null) {
throw new IllegalArgumentException();
}
/* check for overlapping right and destination */
if (right == dest && rightStart < destLimit && destStart < rightLimit) {
throw new IllegalArgumentException("overlapping right and dst ranges");
}
/* allow left==dest */
StringBuilder destBuilder=new StringBuilder(leftLimit-leftStart+rightLimit-rightStart+16);
destBuilder.append(left, leftStart, leftLimit-leftStart);
CharBuffer rightBuffer=CharBuffer.wrap(right, rightStart, rightLimit-rightStart);
mode.getNormalizer2(options).append(destBuilder, rightBuffer);
int destLength=destBuilder.length();
if(destLength<=(destLimit-destStart)) {
destBuilder.getChars(0, destLength, dest, destStart);
return destLength;
} else {
throw new IndexOutOfBoundsException(Integer.toString(destLength));
}
}
/**
* Concatenate normalized strings, making sure that the result is normalized
* as well.
*
* If both the left and the right strings are in
* the normalization form according to "mode",
* then the result will be
*
* <code>
* dest=normalize(left+right, mode)
* </code>
*
* With the input strings already being normalized,
* this function will use next() and previous()
* to find the adjacent end pieces of the input strings.
* Only the concatenation of these end pieces will be normalized and
* then concatenated with the remaining parts of the input strings.
*
* It is allowed to have dest==left to avoid copying the entire left string.
*
* @param left Left source array, may be same as dest.
* @param leftStart start in the left array.
* @param leftLimit limit in the left array (==length)
* @param right Right source array.
* @param rightStart start in the right array.
* @param rightLimit limit in the right array (==length)
* @param dest The output buffer; can be null if destStart==destLimit==0
* for pure preflighting.
* @param destStart start in the destination array
* @param destLimit limit in the destination array (==length)
* @param mode The normalization mode.
* @param options The normalization options, ORed together (0 for no options).
* @return Length of output (number of chars) when successful or
* IndexOutOfBoundsException
* @exception IndexOutOfBoundsException whose message has the string
* representation of destination capacity required.
* @see #normalize
* @see #next
* @see #previous
* @exception IndexOutOfBoundsException if target capacity is less than the
* required length
* @deprecated ICU 56 Use {@link Normalizer2} instead.
* @hide original deprecated declaration
*/
@Deprecated
public static int concatenate(char[] left, int leftStart, int leftLimit,
char[] right, int rightStart, int rightLimit,
char[] dest, int destStart, int destLimit,
Normalizer.Mode mode, int options) {
if(dest == null) {
throw new IllegalArgumentException();
}
/* check for overlapping right and destination */
if (right == dest && rightStart < destLimit && destStart < rightLimit) {
throw new IllegalArgumentException("overlapping right and dst ranges");
}
/* allow left==dest */
StringBuilder destBuilder=new StringBuilder(leftLimit-leftStart+rightLimit-rightStart+16);
destBuilder.append(left, leftStart, leftLimit-leftStart);
CharBuffer rightBuffer=CharBuffer.wrap(right, rightStart, rightLimit-rightStart);
mode.getNormalizer2(options).append(destBuilder, rightBuffer);
int destLength=destBuilder.length();
if(destLength<=(destLimit-destStart)) {
destBuilder.getChars(0, destLength, dest, destStart);
return destLength;
} else {
throw new IndexOutOfBoundsException(Integer.toString(destLength));
}
}