private static CharBuffer allocate(CharBuffer buffer, int length) {
   if (buffer == null) {
     length = Math.max(length * 3 / 2, DEFAULT_BUFFER_CAPACITY);
     return CharBuffer.allocate(length);
   }
   if (buffer.remaining() < length) {
     CharBuffer expandedBuffer = CharBuffer.allocate((buffer.position() + length) * 3 / 2);
     buffer.flip();
     expandedBuffer.put(buffer);
     return expandedBuffer;
   }
   return buffer;
 }
  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();
  }
  /**
   * Read a 'n' bytes from buffer into a String where n is the framesize - offset so therefore
   * cannot use this if there are other objects after it because it has no delimiter.
   *
   * <p>Must take into account the text encoding defined in the Encoding Object ID3 Text Frames
   * often allow multiple strings seperated by the null char appropriate for the encoding.
   *
   * @param arr this is the buffer for the frame
   * @param offset this is where to start reading in the buffer for this field
   * @throws NullPointerException
   * @throws IndexOutOfBoundsException
   */
  public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException {
    logger.finest("Reading from array from offset:" + offset);

    // Get the Specified Decoder
    String charSetName = getTextEncodingCharSet();
    CharsetDecoder decoder = Charset.forName(charSetName).newDecoder();
    decoder.reset();

    // Decode sliced inBuffer
    ByteBuffer inBuffer;
    // #302 [dallen] truncating array manually since the decoder.decode() does not honor the offset
    // in the in buffer
    byte[] truncArr = new byte[arr.length - offset];
    System.arraycopy(arr, offset, truncArr, 0, truncArr.length);
    inBuffer = ByteBuffer.wrap(truncArr);

    CharBuffer outBuffer = CharBuffer.allocate(arr.length - offset);
    CoderResult coderResult = decoder.decode(inBuffer, outBuffer, true);
    if (coderResult.isError()) {
      logger.warning("Decoding error:" + coderResult.toString());
    }
    decoder.flush(outBuffer);
    outBuffer.flip();

    // If using UTF16 with BOM we then search through the text removing any BOMs that could exist
    // for multiple values, BOM could be Big Endian or Little Endian
    if (charSetName.equals(TextEncoding.CHARSET_UTF_16)) {
      value = outBuffer.toString().replace("\ufeff", "").replace("\ufffe", "");
    } else {
      value = outBuffer.toString();
    }
    // SetSize, important this is correct for finding the next datatype
    setSize(arr.length - offset);
    logger.config("Read SizeTerminatedString:" + value + " size:" + size);
  }
 private static String readFromFile(File file) throws IOException {
   Reader reader = new FileReader(file);
   CharBuffer charBuffer = CharBuffer.allocate(MAX_TEST_DATA_FILE_SIZE);
   reader.read(charBuffer);
   charBuffer.position(0);
   return charBuffer.toString().trim();
 }
  @JRubyMethod
  public IRubyObject convert(ThreadContext context, IRubyObject srcBuffer) {
    if (!(srcBuffer instanceof RubyString)) {
      throw context.runtime.newTypeError(srcBuffer, context.runtime.getString());
    }

    RubyString srcString = (RubyString) srcBuffer;

    ByteList srcBL = srcString.getByteList();

    if (srcBL.getRealSize() == 0) return context.runtime.newSymbol("source_buffer_empty");

    ByteBuffer srcBB = ByteBuffer.wrap(srcBL.getUnsafeBytes(), srcBL.begin(), srcBL.getRealSize());
    try {
      CharBuffer srcCB =
          CharBuffer.allocate((int) (srcDecoder.maxCharsPerByte() * srcBL.getRealSize()) + 1);
      CoderResult decodeResult = srcDecoder.decode(srcBB, srcCB, true);
      srcCB.flip();

      ByteBuffer destBB =
          ByteBuffer.allocate((int) (destEncoder.maxBytesPerChar() * srcCB.limit()) + 1);
      CoderResult encodeResult = destEncoder.encode(srcCB, destBB, true);
      destBB.flip();

      byte[] destBytes = new byte[destBB.limit()];
      destBB.get(destBytes);

      srcDecoder.reset();
      destEncoder.reset();

      return context.runtime.newString(new ByteList(destBytes, destEncoding.getEncoding(), false));
    } catch (Exception e) {
      throw context.runtime.newRuntimeError(e.getLocalizedMessage());
    }
  }
Exemple #6
0
  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);
  }
Exemple #7
0
 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);
 }
Exemple #8
0
 static boolean check(CharsetDecoder dec, byte[] bytes, boolean direct, int[] flow) {
   int inPos = flow[0];
   int inLen = flow[1];
   int outPos = flow[2];
   int outLen = flow[3];
   int expedInPos = flow[4];
   int expedOutPos = flow[5];
   CoderResult expedCR = (flow[6] == 0) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW;
   ByteBuffer bbf;
   CharBuffer cbf;
   if (direct) {
     bbf = ByteBuffer.allocateDirect(inPos + bytes.length);
     cbf = ByteBuffer.allocateDirect((outPos + outLen) * 2).asCharBuffer();
   } else {
     bbf = ByteBuffer.allocate(inPos + bytes.length);
     cbf = CharBuffer.allocate(outPos + outLen);
   }
   bbf.position(inPos);
   bbf.put(bytes).flip().position(inPos).limit(inPos + inLen);
   cbf.position(outPos);
   dec.reset();
   CoderResult cr = dec.decode(bbf, cbf, false);
   if (cr != expedCR || bbf.position() != expedInPos || cbf.position() != expedOutPos) {
     System.out.printf("Expected(direct=%5b): [", direct);
     for (int i : flow) System.out.print(" " + i);
     System.out.println(
         "]  CR=" + cr + ", inPos=" + bbf.position() + ", outPos=" + cbf.position());
     return false;
   }
   return true;
 }
Exemple #9
0
 private void fillByteBuffer(Reader reader) throws IOException {
   CharBuffer cbuf = CharBuffer.allocate(DEFAULT_CHAR_BUFFER_SIZE);
   ByteBuffer bbuf = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE);
   List<byte[]> list = new ArrayList<byte[]>();
   while (true) {
     cbuf.clear();
     int size = reader.read(cbuf);
     if (size <= 0) {
       break;
     }
     cbuf.limit(cbuf.position());
     cbuf.rewind();
     boolean eof = false;
     while (!eof) {
       CoderResult cr = encoder.encode(cbuf, bbuf, eof);
       if (cr.isError()) {
         cr.throwException();
       } else if (cr.isUnderflow()) {
         appendBytes(list, bbuf);
         eof = true;
       } else if (cr.isOverflow()) {
         appendBytes(list, bbuf);
         bbuf.clear();
       }
     }
   }
   getByteArray(list);
 }
Exemple #10
0
 /** @param input */
 public MailtoFilter(final TokenStream input) {
   super(input);
   termAtt = this.addAttribute(CharTermAttribute.class);
   typeAtt = this.addAttribute(TypeAttribute.class);
   posIncrAtt = this.addAttribute(PositionIncrementAttribute.class);
   termBuffer = CharBuffer.allocate(256);
 }
 @NotNull
 public static IndexedCollection<Character> ofCharacter(
     @NotNull Collection<Character> intCollection) {
   CharBuffer vals = CharBuffer.allocate(intCollection.size());
   intCollection.forEach(vals::put);
   vals.flip();
   return new CharacterBufferCollection(vals);
 }
Exemple #12
0
 // 将字符转为字节(编码)
 public static byte[] getBytes(char[] chars) {
   Charset cs = Charset.forName("UTF-8");
   CharBuffer cb = CharBuffer.allocate(chars.length);
   cb.put(chars);
   cb.flip();
   ByteBuffer bb = cs.encode(cb);
   return bb.array();
 }
 public ReaderInputStream(Reader reader1, CharsetEncoder charsetencoder, int i) {
   reader = reader1;
   encoder = charsetencoder;
   encoderIn = CharBuffer.allocate(i);
   encoderIn.flip();
   encoderOut = ByteBuffer.allocate(128);
   encoderOut.flip();
 }
Exemple #14
0
 private void ensureCharBuffRemaining(final int size) {
   if (charBuff.remaining() < size) {
     final int cpcty = (charBuff.capacity() + size) * 2;
     final java.nio.CharBuffer newChBuf = java.nio.CharBuffer.allocate(cpcty);
     newChBuf.put(charBuff);
     charBuff = newChBuf;
   }
 }
 private void testControlCharsBuffer(boolean remove, String input, String output)
     throws Exception {
   try (Reader reader = new OverrunReader(new StringReader(input), -1, false, remove)) {
     CharBuffer buff = CharBuffer.allocate(10);
     Assert.assertEquals(output.length(), reader.read(buff));
     buff.flip();
     Assert.assertEquals(output, buff.toString());
   }
 }
  /**
   * Creates an instance that reads bytes from <code>delegate</code> that represent characters in
   * the "from" character set, and returning them to the caller as characters in the "to" character
   * set. Any characters that cannot be represented in the "to" character set will be ignored.
   */
  public TranslatingInputStream(InputStream delegate, Charset from, Charset to) {
    _delegate = new InputStreamReader(delegate, from);
    _encoder = to.newEncoder();
    _charBuf = CharBuffer.allocate(2);
    _byteBuf = ByteBuffer.allocate(4);

    // this will force first call to read() to pull a byte from source
    _byteBuf.limit(0);
  }
 public WsOutbound(
     UpgradeOutbound upgradeOutbound,
     StreamInbound streamInbound,
     int byteBufferSize,
     int charBufferSize) {
   this.upgradeOutbound = upgradeOutbound;
   this.streamInbound = streamInbound;
   this.bb = ByteBuffer.allocate(byteBufferSize);
   this.cb = CharBuffer.allocate(charBufferSize);
 }
Exemple #18
0
  private static String decode(ByteBuffer bb, CharsetDecoder decoder) {
    CharBuffer cb = CharBuffer.allocate(128);

    CoderResult result = decoder.decode((ByteBuffer) bb.flip(), cb, true /* endOfInput */);
    if (result.isError()) {
      throw new IllegalArgumentException("Malformed UTF-8!");
    }

    return ((CharBuffer) cb.flip()).toString();
  }
 /** Create a new WriterOutputStream which writes to the given writer. */
 public WriterOutputStream(Writer writer) {
   this.writer = writer;
   decoder.reset();
   decoder.onMalformedInput(CodingErrorAction.REPLACE);
   decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
   inBuffer = ByteBuffer.allocate(4096);
   inBuffer.clear();
   outBuffer = CharBuffer.allocate(4096);
   outBuffer.clear();
 }
Exemple #20
0
    private void addCommand(String s) {
      CharBuffer buffer = CharBuffer.allocate(s.length() + 1);
      buffer.put(s);
      buffer.put('\n');
      buffer.flip();

      _command.compact();
      _encoder.encode(buffer, _command, true);
      _command.flip();
    }
Exemple #21
0
  /**
   * Build a InMessage from an HttpServletrequest
   *
   * @param request The HttpservletRequest
   */
  public InMessage(HttpServletRequest request) {

    // TODO : Check this code : WSDL request are not well recorded !
    this.method = request.getMethod();
    // Set the headers
    this.headers = new Headers();
    Enumeration<String> headerNameEnum = request.getHeaderNames();
    while (headerNameEnum.hasMoreElements()) {
      String headerName = headerNameEnum.nextElement();
      this.headers.addHeader(new Header(headerName, request.getHeader(headerName)));
    }
    // Set protocol, server, port, path
    this.protocol = request.getProtocol().substring(0, request.getProtocol().indexOf('/'));
    this.protocolVersion = request.getProtocol().substring(request.getProtocol().indexOf('/') + 1);
    this.server = request.getServerName();
    this.port = request.getServerPort();
    this.path = request.getRequestURI();
    this.remoteHost = request.getRemoteHost();
    // this.completeUrl = request.getRequestURL().toString();
    // Set url parameters
    this.queryString = new QueryString();
    Enumeration<String> parametersNameEnum = request.getParameterNames();
    while (parametersNameEnum.hasMoreElements()) {
      String parameterName = parametersNameEnum.nextElement();
      for (String parameterValue : request.getParameterValues(parameterName)) {
        this.queryString.addQueryParam(new QueryParam(parameterName, parameterValue));
      }
    }
    this.messageContent = new MessageContent();
    StringBuffer requestBody = new StringBuffer();
    BufferedReader requestBodyReader = null;
    CharBuffer buffer = CharBuffer.allocate(512);
    try {
      requestBodyReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
      while (requestBodyReader.read(buffer) >= 0) {
        requestBody.append(buffer.flip());
        buffer.clear();
      }
      this.messageContent.setRawContent(requestBody.toString());
      this.messageContent.setSize(requestBody.length());
      this.messageContent.setMimeType(request.getContentType());
    } catch (Exception ex) {
      logger.warn("Error while reading request body !", ex);
    } finally {
      try {
        if (requestBodyReader != null) {
          requestBodyReader.close();
        }
      } catch (IOException ex) {
        // logger.warn("Error while closing the requestBodyReader !",
        // ex);
      }
    }
    this.comment = "";
  }
 public static void main(String[] args) throws Exception {
   // 申请CharBuffer空间
   CharBuffer charBuffer = CharBuffer.allocate(100);
   while (fillBuffer(charBuffer)) {
     // 倒转CharBuffer,由写变为读
     charBuffer.flip();
     drainBuffer(charBuffer);
     // 清除CharBuffer,位置重置
     charBuffer.clear();
   }
 }
Exemple #23
0
 private void startBuffer(ZipEntry ze) {
   String name = ze.getName();
   if (name.startsWith("/store")) {
     store = Store.open(true);
   } else if (name.startsWith("/accessLog")) {
     Charset c = Charset.forName("utf-8");
     charsetDecoder = c.newDecoder();
     // accessLogをjson化したものなので無制限に大きくならない
     charBuffer = CharBuffer.allocate(4096);
   }
 }
 public static String a(Readable readable) {
   StringBuilder stringBuilder = new StringBuilder();
   CharSequence allocate = CharBuffer.allocate(2048);
   while (true) {
     int read = readable.read(allocate);
     if (read == -1) {
       return stringBuilder.toString();
     }
     allocate.flip();
     stringBuilder.append(allocate, 0, read);
   }
 }
 /**
  * Wraps the passed key in a CharBuffer
  *
  * @param key The key to wrap
  * @return The CharBuffer wrapped key
  */
 protected CharBuffer wrap(CharSequence key) {
   CharBuffer cb = null;
   if (!offHeap) {
     cb = ((CharBuffer) CharBuffer.allocate(key.length()).append(key).flip()).asReadOnlyBuffer();
   } else {
     cb =
         ((CharBuffer)
                 ByteBuffer.allocateDirect(key.length() * 2).asCharBuffer().append(key).flip())
             .asReadOnlyBuffer();
   }
   return cb;
 }
Exemple #26
0
  /** Decode a string into a ByteBuffer */
  public static String fromByteBuffer(ByteBuffer bb, CharsetDecoder dec) {
    if (bb.remaining() == 0) return "";

    dec.reset();
    CharBuffer cBuff = CharBuffer.allocate(bb.remaining());
    CoderResult r = dec.decode(bb, cBuff, true);
    if (r.isOverflow()) throw new InternalErrorException("fromByteBuffer: decode overflow (1)");
    r = dec.flush(cBuff);
    if (r.isOverflow()) throw new InternalErrorException("fromByteBuffer: decode overflow (2)");
    cBuff.flip();
    return cBuff.toString();
  }
Exemple #27
0
  public void run() {
    byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
    charBuffer = CharBuffer.allocate(BUFFER_SIZE);

    /* for East Asian character widths */
    byte[] wideAttribute = new byte[BUFFER_SIZE];

    byteArray = byteBuffer.array();
    charArray = charBuffer.array();

    CoderResult result;

    int bytesRead = 0;
    byteBuffer.limit(0);
    int bytesToRead;
    int offset;
    int charWidth;

    EastAsianWidth measurer = EastAsianWidth.getInstance();

    try {
      while (true) {
        charWidth = bridge.charWidth;
        bytesToRead = byteBuffer.capacity() - byteBuffer.limit();
        offset = byteBuffer.arrayOffset() + byteBuffer.limit();
        bytesRead = transport.read(byteArray, offset, bytesToRead);

        if (bytesRead > 0) {
          byteBuffer.limit(byteBuffer.limit() + bytesRead);

          synchronized (this) {
            result = decoder.decode(byteBuffer, charBuffer, false);
          }

          if (result.isUnderflow() && byteBuffer.limit() == byteBuffer.capacity()) {
            byteBuffer.compact();
            byteBuffer.limit(byteBuffer.position());
            byteBuffer.position(0);
          }

          offset = charBuffer.position();

          measurer.measure(charArray, 0, offset, wideAttribute, bridge.defaultPaint, charWidth);
          buffer.putString(charArray, wideAttribute, 0, charBuffer.position());
          bridge.propagateConsoleText(charArray, charBuffer.position());
          charBuffer.clear();
          bridge.redraw();
        }
      }
    } catch (IOException e) {
      Log.e(TAG, "Problem while handling incoming data in relay thread", e);
    }
  }
  public void testCopyHeapCharBuffer() {
    String s = "abcde";
    CharBuffer buffer = CharBuffer.allocate(s.length());
    buffer.append(s);
    buffer.rewind();

    assertNotNull(CharArrayUtil.fromSequenceWithoutCopying(buffer));
    assertNotNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(0, 5)));
    // assertNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(0, 4))); // end index
    // is not checked
    assertNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(1, 5)));
    assertNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(1, 2)));
  }
  public LinkedList<CharBuffer> permuteTerms(char[] term, int offset, int end) {
    LinkedList<CharBuffer> buffers = new LinkedList<CharBuffer>();

    int i = offset;
    for (; i < end; i++) {
      if (term[i] == tokenDelimiter) {
        int k = offset;
        for (; k < i; k++) {
          if (term[k] == pipe) {
            break;
          }
        }
        LinkedList<CharBuffer> nextBuffers = permuteTerms(term, i + 1, end);
        Iterator iter = nextBuffers.iterator();
        while (iter.hasNext()) {
          CharBuffer formBuffer = CharBuffer.allocate(end - offset);
          formBuffer.put((CharBuffer) iter.next());
          /*if (k<i) {
              formBuffer.put(term, k+1, i-k);
              //formBuffer.put(term, offset, k-offset);
          }
          else {
              formBuffer.put(term, offset, i-offset);
              //formBuffer.put(term, offset, i-offset);
          }*/
          // formBuffer.put(' ');
          buffers.add(formBuffer);
        }

        return buffers;
      }
    }

    // i = length
    CharBuffer formBuffer = CharBuffer.allocate(2);
    formBuffer.put("hello", 0, 2);
    buffers.add(formBuffer);
    return buffers;
  }
Exemple #30
0
  public void copy(D3DMesh mesh) {
    mIndices = CharBuffer.allocate(mesh.mIndices.position());
    mVertices = FloatBuffer.allocate(mesh.mVertices.position());

    for (int j = 0; j < mIndices.capacity(); j++) mIndices.put(mesh.mIndices.get(j));

    for (int j = 0; j < mVertices.capacity(); j++) {
      mVertices.put(mesh.mVertices.get(j));
    }

    mIndices.position(0);
    mVertices.position(0);
  }