public void setContent(byte[] cntnt) throws Exception { StringBuffer sb = new StringBuffer(isHTTP11 ? "HTTP/1.1" : "HTTP/1.0"); sb.append(OK_HDR); sb.append("Content-Type: "); sb.append(contentType); if (!isHTTP11 || !keepAlive || isMessages) { sb.append("\r\nConnection: close\r\nProxy-Connection: close"); } else { sb.append("\r\nConnection: Keep-Alive\r\nProxy-Connection: Keep-Alive"); sb.append("\r\nContent-Length: "); sb.append(cntnt.length); } sb.append("\r\n\r\n"); sb.trimToSize(); CharBuffer cb = CharBuffer.wrap(sb.toString()); ByteBuffer tempBuffer; try { tempBuffer = Charset.forName("iso-8859-1").newEncoder().encode(cb); } catch (CharacterCodingException cce) { Server.debug(this, "prepareForSending: ", cce, Server.MSG_ERROR, Server.LVL_MINOR); try { tempBuffer = ByteBuffer.wrap(cb.toString().getBytes(Server.srv.DEFAULT_CHARSET)); } catch (Exception e) { Server.debug(this, "prepareForSending: ", e, Server.MSG_ERROR, Server.LVL_MAJOR); throw e; } } this.buf = ByteBuffer.allocate(tempBuffer.capacity() + cntnt.length); this.buf.put(tempBuffer.array()); this.buf.put(cntnt); this.buf.flip(); }
/** * construct a HTTP-Redirect-Response * * @param dest the destination to redirect to */ public void setRedirectTo(String dest, String CookieDomain) { StringBuffer cntnt = new StringBuffer( "<html><head><title>redirection</title><head><body>Redirected to <a href=\""); cntnt.append(dest); cntnt.append("\">"); cntnt.append(dest); cntnt.append("</a>"); cntnt.append("</body></html>"); int len = cntnt.length(); StringBuffer sb = new StringBuffer(isHTTP11 ? "HTTP/1.1" : "HTTP/1.0"); sb.append(REDIRECT_HDR); sb.append(Server.srv.DEFAULT_CHARSET); sb.append("\r\nLocation: "); sb.append(dest); sb.append("\r\nContent-Length: "); sb.append(len); sb = appendCookie(sb, CookieDomain); sb.append("\r\n\r\n"); if ("iso-8859-1".equals(Server.srv.DEFAULT_CHARSET)) { sb.append(cntnt); sb.trimToSize(); prepareForSending(CharBuffer.wrap(sb.toString())); } else { CharBuffer hdrChar = CharBuffer.wrap(sb.toString()); cntnt.trimToSize(); prepareForSending(hdrChar, CharBuffer.wrap(cntnt)); } isRedirect = true; }
private void updateWithCharBuf() { final int reqSize = (int) charEncoder.maxBytesPerChar() * charBuff.position(); if (byteBuff.capacity() < reqSize) { byteBuff = java.nio.ByteBuffer.allocate(2 * reqSize); } // Make ready for read charBuff.flip(); final CoderResult cr = charEncoder.encode(charBuff, byteBuff, true); try { if (cr.isError()) cr.throwException(); // Make ready for read byteBuff.flip(); final byte[] byts = byteBuff.array(); final int len = byteBuff.remaining(); final int strt = byteBuff.arrayOffset(); digest.update(byts, strt, len); } catch (final CharacterCodingException e) { throw new OXFException(e); } catch (java.nio.BufferOverflowException e) { throw new OXFException(e); } catch (java.nio.BufferUnderflowException e) { throw new OXFException(e); } finally { // Make ready for write charBuff.clear(); byteBuff.clear(); } }
@Override protected void onTextMessage(CharBuffer message) throws IOException { String temp = message.toString(); JSONObject json = (JSONObject) JSONSerializer.toJSON(temp); String type = json.getString("type").toLowerCase().replaceAll(" ", ""); String location = json.getString("location"); String lat = json.getString("lat"); String lng = json.getString("lng"); String radius = json.getString("radius"); String keywords = json.getString("keywords"); String result = null; try { if (type.equals("overview")) result = getOverViewData(location, lat, lng, radius, keywords); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); JSONObject jsonResult = new JSONObject(); jsonResult.put("error", "true"); result = jsonResult.toString(); } if (result == null || result.equals("")) { JSONObject jsonResult = new JSONObject(); jsonResult.put("error", "true"); result = jsonResult.toString(); } Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharsetEncoder encoder = charset.newEncoder(); CharBuffer uCharBuffer = CharBuffer.wrap(result); ByteBuffer bbuf = encoder.encode(uCharBuffer); CharBuffer cbuf = decoder.decode(bbuf); getWsOutbound().writeTextMessage(cbuf); }
private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) { int mark = src.position(); try { while (src.hasRemaining()) { char c = src.get(); // AQUI HACE EL CAMBIO DE ALGUNOS CARACTERES if (c >= 0x0FF) { Character ch = s_codesTable.get((int) c); if (ch == null) { System.err.println( "Character without encoding in 'MyCharSet.properties' (" + (int) c + "): " + c); } else { c = ch; } } if (c < 0x0FF) { if (!dst.hasRemaining()) return CoderResult.OVERFLOW; dst.put((byte) c); mark++; continue; } if (sgp.parse(c, src) < 0) return sgp.error(); return sgp.unmappableResult(); } return CoderResult.UNDERFLOW; } finally { src.position(mark); } }
public void init(float vertices[], float normals[], float texcoords[], char indices[]) { int nbVertex = vertices.length / 3; mVertices = FloatBuffer.allocate(nbVertex * D3DMesh.nbFloatPerVertex); for (int i = 0; i < nbVertex; i++) { float px = vertices[i * 3]; float py = vertices[i * 3 + 1]; float pz = vertices[i * 3 + 2]; float nx = 0f; float ny = 0f; float nz = 0f; if (normals != null) { nx = normals[i * 3]; ny = normals[i * 3 + 1]; nz = normals[i * 3 + 2]; } float tx = 0f; float ty = 0f; if (texcoords != null) { tx = texcoords[i * 2]; ty = texcoords[i * 2 + 1]; } this.addPoint(px, py, pz, nx, ny, nz, tx, ty); } mVertices.position(0); mIndices = CharBuffer.allocate(indices.length); mIndices.put(indices); mIndices.position(0); }
public ByteBuffer flush(ByteBuffer dst) throws SVNException { if (myCharBuffer != null) { CoderResult result; while (true) { result = myDecoder.flush(myCharBuffer); if (result.isError()) { throwException(result); } if (result.isUnderflow()) { break; } } myCharBuffer.flip(); dst = allocate(dst, (int) (myEncoder.maxBytesPerChar() * myCharBuffer.remaining())); result = myEncoder.encode(myCharBuffer, dst, true); if (result.isError()) { throwException(result); } while (true) { result = myEncoder.flush(dst); if (result.isError()) { throwException(result); } if (result.isUnderflow()) { break; } } } reset(); return dst; }
public CharBuffer encodeHistCmd(Boolean activate, String[] names) { charBuffer.clear(); jsonWriter.startObject(); if (activate != null) { jsonWriter .writeString(FIELD.type.name(), TYPE.histCmd.name()) .next() .writeFieldName(FIELD.data.name()) .startObject() .writeBoolean(FIELD.activate.name(), activate) .next() .writeFieldName(FIELD.names.name()) .startArray(); if (names != null) { int i = 0; for (String name : names) { if (i > 0) jsonWriter.next(); jsonWriter.writeString(name); i++; } } jsonWriter.endArray().endObject(); } else { jsonWriter .writeString(FIELD.type.name(), TYPE.statCmd.name()) .next() .writeFieldName(FIELD.data.name()) .startObject() .writeBoolean(FIELD.hist.name(), true) .endObject(); } jsonWriter.endObject(); charBuffer.flip(); return charBuffer; }
// Check if the datagramsocket adaptor can send with a packet // that has not been initialized with an address; the legacy // datagram socket will send in this case private static void test2() throws Exception { DatagramChannel sndChannel = DatagramChannel.open(); sndChannel.socket().bind(null); InetSocketAddress sender = new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort()); DatagramChannel rcvChannel = DatagramChannel.open(); rcvChannel.socket().bind(null); InetSocketAddress receiver = new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort()); rcvChannel.connect(sender); sndChannel.connect(receiver); byte b[] = "hello".getBytes("UTF-8"); DatagramPacket pkt = new DatagramPacket(b, b.length); sndChannel.socket().send(pkt); ByteBuffer bb = ByteBuffer.allocate(256); rcvChannel.receive(bb); bb.flip(); CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb); if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed"); // Check that the pkt got set with the target address; // This is legacy behavior if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed"); rcvChannel.close(); sndChannel.close(); }
// Check if DatagramChannel.send while connected can include // address without throwing private static void test1() throws Exception { DatagramChannel sndChannel = DatagramChannel.open(); sndChannel.socket().bind(null); InetSocketAddress sender = new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort()); DatagramChannel rcvChannel = DatagramChannel.open(); rcvChannel.socket().bind(null); InetSocketAddress receiver = new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort()); rcvChannel.connect(sender); sndChannel.connect(receiver); ByteBuffer bb = ByteBuffer.allocate(256); bb.put("hello".getBytes()); bb.flip(); int sent = sndChannel.send(bb, receiver); bb.clear(); rcvChannel.receive(bb); bb.flip(); CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb); if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed"); rcvChannel.close(); sndChannel.close(); }
char[] decode(byte[] ba, int off, int len) { int en = (int) (cd.maxCharsPerByte() * len); char[] ca = new char[en]; if (len == 0) return ca; 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 trim(ca, cb.position()); }
@Override public final boolean incrementToken() throws IOException { if (isMailto) { termAtt.setEmpty(); // return the scheme + the mail part isMailto = false; posIncrAtt.setPositionIncrement(0); termAtt.copyBuffer(termBuffer.array(), 0, termBuffer.position()); return true; } if (input.incrementToken()) { final String type = typeAtt.type(); if (type.equals(TupleTokenizer.getTokenTypes()[TupleTokenizer.URI]) && this.isMailtoScheme()) { this.updateBuffer(); termBuffer.put(termAtt.buffer(), 0, termAtt.length()); // return only the mail part posIncrAtt.setPositionIncrement(1); termAtt.copyBuffer(termBuffer.array(), 7, termBuffer.position() - 7); } return true; } return false; }
@SuppressWarnings("unchecked") private void sendMessageText(boolean last) throws WsIOException { if (textMsgHandler instanceof WrappedMessageHandler) { long maxMessageSize = ((WrappedMessageHandler) textMsgHandler).getMaxMessageSize(); if (maxMessageSize > -1 && messageBufferText.remaining() > maxMessageSize) { throw new WsIOException( new CloseReason( CloseCodes.TOO_BIG, sm.getString( "wsFrame.messageTooBig", Long.valueOf(messageBufferText.remaining()), Long.valueOf(maxMessageSize)))); } } try { if (textMsgHandler instanceof MessageHandler.Partial<?>) { ((MessageHandler.Partial<String>) textMsgHandler) .onMessage(messageBufferText.toString(), last); } else { // Caller ensures last == true if this branch is used ((MessageHandler.Whole<String>) textMsgHandler).onMessage(messageBufferText.toString()); } } catch (Throwable t) { handleThrowableOnSend(t); } finally { messageBufferText.clear(); } }
/** * Receive as many items as possible from the given byte buffer to this buffer. * * <p>The <TT>receiveItems()</TT> method must not block the calling thread; if it does, all * message I/O in MP will be blocked. * * @param i Index of first item to receive, in the range 0 .. <TT>length</TT>-1. * @param num Maximum number of items to receive. * @param buffer Byte buffer. * @return Number of items received. */ protected int receiveItems(int i, int num, ByteBuffer buffer) { CharBuffer charbuffer = buffer.asCharBuffer(); int n = 0; int r = i / myColCount; int row = r + myLowerRow; int c = i % myColCount; int col = c + myLowerCol; int ncols = Math.min(myColCount - c, charbuffer.remaining()); while (r < myRowCount && ncols > 0) { char[] myMatrix_row = myMatrix[row]; while (c < ncols) { myMatrix_row[col] = myOp.op(myMatrix_row[col], charbuffer.get()); ++c; ++col; } n += ncols; ++r; ++row; c = 0; col = myLowerCol; ncols = Math.min(myColCount, charbuffer.remaining()); } buffer.position(buffer.position() + 2 * n); return n; }
/** * Adds the data to the buffer for textual data. If a binary message is currently in progress that * message will be completed and a new textual message started. If the buffer for textual data is * full, the buffer will be flushed and a new textual continuation fragment started. * * @param c The character to send to the client. * @throws IOException If a flush is required and an error occurs writing the WebSocket frame to * the client */ public void writeTextData(char c) throws IOException { try { synchronized (stateLock) { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); } } catch (IOException ioe) { // Any IOException is terminal. Make sure the Inbound side knows // that something went wrong. // The exception handling needs to be outside of the sync to avoid // possible deadlocks (e.g. BZ55524) when triggering the inbound // close as that will execute user code streamInbound.doOnClose(Constants23.getStatusClosedUnexpectedly()); throw ioe; } }
/** Decode the specified array of bytes according to * a charset selection. This function tries * to decode a string from the given byte array * with the following charsets (in preferred order): * <ul> * <li>the current charset returned by {@link Charset#defaultCharset()},</li> * <li>OEM United States: IBM437,</li> * <li>West European: ISO-8859-1,</li> * <li>one of the charst returned by {@link Charset#availableCharsets()}.</li> * </ul> * <p> * The IBM437 charset was added to support several specific files (Dbase files) * generated from a GIS. * * @param bytes is the array of bytes to decode. * @return the decoded string with the appropriate charset set. */ public static String decodeString(byte[] bytes) { Charset default_charset = Charset.defaultCharset(); Charset west_european = Charset.forName("ISO-8859-1"); //$NON-NLS-1$ Charset utf = Charset.forName("UTF-8"); //$NON-NLS-1$ String refBuffer = new String(bytes); CharBuffer buffer = decodeString(bytes,default_charset,refBuffer.length()); if ((buffer==null)&&(!default_charset.equals(west_european))) { buffer = decodeString(bytes,west_european,refBuffer.length()); } if ((buffer==null)&&(!default_charset.equals(utf))) { buffer = decodeString(bytes,utf,refBuffer.length()); } if (buffer==null) { // Decode until one of the available charset replied a value for (Charset charset : Charset.availableCharsets().values()) { buffer = decodeString(bytes,charset,refBuffer.length()); if (buffer!=null) break; } } // Use the default encoding if (buffer==null) return refBuffer; return buffer.toString(); }
private static String decode(Charset charset, byte[] b) { if (b == null) { return null; } final CharBuffer cb = charset.decode(ByteBuffer.wrap(b)); return new String(cb.array(), 0, cb.length()); }
/** * Attempts to read characters into the specified character buffer. The buffer is used as a * repository of characters as-is: the only changes made are the results of a put operation. No * flipping or rewinding of the buffer is performed. * * @param target the buffer to read characters into * @return The number of characters added to the buffer, or -1 if this source of characters is at * its end * @throws IOException if an I/O error occurs * @throws NullPointerException if target is null * @throws java.nio.ReadOnlyBufferException if target is a read only buffer * @since 1.5 */ public int read(java.nio.CharBuffer target) throws IOException { int len = target.remaining(); char[] cbuf = new char[len]; int n = read(cbuf, 0, len); if (n > 0) target.put(cbuf, 0, n); return n; }
public ByteBuffer convertChunk( byte[] b, int offset, int length, ByteBuffer dst, boolean endOfInput) throws SVNException { myInputByteBuffer = allocate(myInputByteBuffer, length); myInputByteBuffer.put(b, offset, length); myInputByteBuffer.flip(); myCharBuffer = allocate(myCharBuffer, (int) (myDecoder.maxCharsPerByte() * myInputByteBuffer.remaining())); CoderResult result = myDecoder.decode(myInputByteBuffer, myCharBuffer, endOfInput); if (result.isError()) { throwException(result); } else if (result.isUnderflow()) { myInputByteBuffer.compact(); } else { myInputByteBuffer.clear(); } myCharBuffer.flip(); dst = allocate(dst, (int) (myEncoder.maxBytesPerChar() * myCharBuffer.remaining())); result = myEncoder.encode(myCharBuffer, dst, false); if (result.isError()) { throwException(result); } else if (result.isUnderflow()) { myCharBuffer.compact(); } else { myCharBuffer.clear(); } return dst; }
@SuppressFBWarnings("SUA_SUSPICIOUS_UNINITIALIZED_ARRAY") public static String decode( final CharsetDecoder cd, final byte[] ba, final int off, final int len) { if (len == 0) { return ""; } int en = (int) (len * (double) cd.maxCharsPerByte()); char[] ca = Arrays.getCharsTmp(en); if (cd instanceof ArrayDecoder) { int clen = ((ArrayDecoder) cd).decode(ba, off, len, ca); return new String(ca, 0, clen); } 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) { throw new Error(x); } return new String(ca, 0, cb.position()); }
protected long computeEstimatedMemorySize() { long result = 0; if (!textArray.isDirect()) result += (Character.SIZE / 8) * textArray.capacity(); result += (Integer.SIZE / 8) * textIndexArray.length; result += (Double.SIZE / 8) * latlonArray.length; return result; }
private double interpolate_value( final UnstructuredVolumeObject volume, final int index0, final int index1) throws KVSException { Buffer buf = volume.values(); float[] coords = volume.coords(); final float value0 = this.substitute_plane_equation(new Vector3f(coords, 3 * index0)); final float value1 = this.substitute_plane_equation(new Vector3f(coords, 3 * index1)); final float ratio = kvs.core.util.Math.abs(value0 / (value1 - value0)); if (buf instanceof ByteBuffer) { ByteBuffer values = (ByteBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else if (buf instanceof ShortBuffer) { ShortBuffer values = (ShortBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else if (buf instanceof IntBuffer) { IntBuffer values = (IntBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else if (buf instanceof LongBuffer) { LongBuffer values = (LongBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else if (buf instanceof FloatBuffer) { FloatBuffer values = (FloatBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else if (buf instanceof DoubleBuffer) { DoubleBuffer values = (DoubleBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else if (buf instanceof CharBuffer) { CharBuffer values = (CharBuffer) buf; return (values.get(index0) + ratio * (values.get(index1) - values.get(index0))); } else { throw new KVSException("Unsupported data type"); } }
public void handle(HttpExchange exchange) throws IOException { InputStream is = exchange.getRequestBody(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String requestMethod = exchange.getRequestMethod(); CharBuffer cb = CharBuffer.allocate(256); // read characters into a char buffer in.read(cb); // flip the char buffer cb.flip(); // print the char buffer Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "application/json"); responseHeaders.set("Access-Control-Allow-Origin", "http://minecraft-social.de"); exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); responseBody.write(getOnlineUser().getBytes()); responseBody.close(); }
public void createBufferObjects(GL gl) { checkGLError(gl); // Generate a the vertex and element buffer IDs int[] vboIds = new int[2]; GL11 gl11 = (GL11) gl; gl11.glGenBuffers(2, vboIds, 0); mVertexBufferObjectId = vboIds[0]; mElementBufferObjectId = vboIds[1]; // Upload the vertex data gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertexBufferObjectId); mVertexByteBuffer.position(0); gl11.glBufferData( GL11.GL_ARRAY_BUFFER, mVertexByteBuffer.capacity(), mVertexByteBuffer, GL11.GL_STATIC_DRAW); gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mElementBufferObjectId); mIndexBuffer.position(0); gl11.glBufferData( GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer.capacity() * CHAR_SIZE, mIndexBuffer, GL11.GL_STATIC_DRAW); // We don't need the in-memory data any more mVertexBuffer = null; mVertexByteBuffer = null; mIndexBuffer = null; checkGLError(gl); }
@Override public boolean incrementToken() throws IOException { if (!terms.isEmpty()) { char[] buffer = terms.poll(); termAttribute.setEmpty(); termAttribute.copyBuffer(buffer, 0, buffer.length); posIncAttr.setPositionIncrement(1); return true; } if (!input.incrementToken()) { return false; } else { final char term[] = termAttribute.buffer(); final int length = termAttribute.length(); int k = 0; for (; k < length; k++) { if (term[k] == tokenDelimiter) { break; } } LinkedList<CharBuffer> buffers = permuteTerms(term, 0, length); Iterator iter = buffers.iterator(); while (iter.hasNext()) { CharBuffer cb = (CharBuffer) iter.next(); terms.add(cb.array()); } // we return true and leave the original token unchanged return true; } }
private ByteBuffer processAsciiCommand(ByteBuffer buffer, Cache cache) { CharBuffer flb = getFirstLineBuffer(); getAsciiDecoder().reset(); getAsciiDecoder().decode(buffer, flb, false); flb.flip(); String firstLine = getFirstLine(); String[] firstLineElements = firstLine.split(" "); assert "decr".equals(firstLineElements[0]); String key = firstLineElements[1]; String decrByStr = stripNewline(firstLineElements[2]); Long decrBy = Long.parseLong(decrByStr); boolean noReply = firstLineElements.length > 3; Region<Object, ValueWrapper> r = getMemcachedRegion(cache); String reply = Reply.NOT_FOUND.toString(); ByteBuffer newVal = ByteBuffer.allocate(8); while (true) { ValueWrapper oldValWrapper = r.get(key); if (oldValWrapper == null) { break; } newVal.clear(); byte[] oldVal = oldValWrapper.getValue(); long oldLong = getLongFromByteArray(oldVal); long newLong = oldLong - decrBy; newVal.putLong(newLong); ValueWrapper newValWrapper = ValueWrapper.getWrappedValue(newVal.array(), 0 /*flags*/); if (r.replace(key, oldValWrapper, newValWrapper)) { reply = newLong + "\r\n"; break; } } return noReply ? null : asciiCharset.encode(reply); }
public String getPayloadTracingString() { if (null == payload || 0 == payload.length) return "no payload"; boolean text = true; for (byte b : payload) { if (' ' > b) { switch (b) { case '\t': case '\n': case '\r': continue; } text = false; break; } } if (text) { CharsetDecoder decoder = CoAP.UTF8_CHARSET.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); ByteBuffer in = ByteBuffer.wrap(payload); CharBuffer out = CharBuffer.allocate(24); CoderResult result = decoder.decode(in, out, true); decoder.flush(out); out.flip(); if (CoderResult.OVERFLOW == result) { return "\"" + out + "\".. " + payload.length + " bytes"; } else if (!result.isError()) { return "\"" + out + "\""; } } return Utils.toHexText(payload, 256); }
private byte[] encodeImpl(CharBuffer in) { Charset cs = charset(); if (!(cs instanceof IOSCharset)) { throw new UnsupportedCharsetException(cs.name()); } char[] chars; int i; if (inBuffer != null) { i = inBuffer.length; chars = new char[i + in.remaining()]; System.arraycopy(inBuffer, 0, chars, 0, inBuffer.length); inBuffer = null; } else { if (((IOSCharset) cs).nsEncoding() == /* NSUnicodeStringEncoding */ 10L) { // Prepend required BOM for Java's big-endian encoding default. chars = new char[in.remaining() + 1]; chars[0] = (char) 0xFEFF; i = 1; } else { i = 0; chars = new char[in.remaining()]; } } in.get(chars, i, chars.length - i); byte[] bytes = encode(chars, ((IOSCharset) cs).nsEncoding()); if (bytes.length == 0) { inBuffer = chars; } else { inBuffer = null; } return bytes; }
public static void main(String[] args) { ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 'a'}); bb.rewind(); printnb("Byte Buffer "); while (bb.hasRemaining()) printnb(bb.position() + " -> " + bb.get() + ", "); print(); CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer(); printnb("Char Buffer "); while (cb.hasRemaining()) printnb(cb.position() + " -> " + cb.get() + ", "); print(); FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer(); printnb("Float Buffer "); while (fb.hasRemaining()) printnb(fb.position() + " -> " + fb.get() + ", "); print(); IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer(); printnb("Int Buffer "); while (ib.hasRemaining()) printnb(ib.position() + " -> " + ib.get() + ", "); print(); LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer(); printnb("Long Buffer "); while (lb.hasRemaining()) printnb(lb.position() + " -> " + lb.get() + ", "); print(); ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer(); printnb("Short Buffer "); while (sb.hasRemaining()) printnb(sb.position() + " -> " + sb.get() + ", "); print(); DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer(); printnb("Double Buffer "); while (db.hasRemaining()) printnb(db.position() + " -> " + db.get() + ", "); }
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) { int mark = src.position(); if (needsMark) { if (dst.remaining() < 2) return CoderResult.OVERFLOW; put(BYTE_ORDER_MARK, dst); needsMark = false; } try { while (src.hasRemaining()) { char c = src.get(); if (!Surrogate.is(c)) { if (dst.remaining() < 2) return CoderResult.OVERFLOW; mark++; put(c, dst); continue; } int d = sgp.parse(c, src); if (d < 0) return sgp.error(); if (dst.remaining() < 4) return CoderResult.OVERFLOW; mark += 2; put(Surrogate.high(d), dst); put(Surrogate.low(d), dst); } return CoderResult.UNDERFLOW; } finally { src.position(mark); } }