Пример #1
0
  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);
    }
  }
Пример #2
0
    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);
      }
    }
Пример #3
0
    private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
      char[] sa = src.array();
      int sp = src.arrayOffset() + src.position();
      int sl = src.arrayOffset() + src.limit();
      assert (sp <= sl);
      sp = (sp <= sl ? sp : sl);
      byte[] da = dst.array();
      int dp = dst.arrayOffset() + dst.position();
      int dl = dst.arrayOffset() + dst.limit();
      assert (dp <= dl);
      dp = (dp <= dl ? dp : dl);

      try {
        while (sp < sl) {
          char c = sa[sp];
          if (c < 0x80) {
            if (dp >= dl) return CoderResult.OVERFLOW;
            da[dp] = (byte) c;
            sp++;
            dp++;
            continue;
          }
          if (sgp.parse(c, sa, sp, sl) < 0) return sgp.error();
          return sgp.unmappableResult();
        }
        return CoderResult.UNDERFLOW;
      } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
      }
    }
Пример #4
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;
 }
Пример #5
0
  @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;
  }
Пример #6
0
 protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
   int mark = src.position();
   if (!doneBOM && src.hasRemaining()) {
     if (dst.remaining() < 4) return CoderResult.OVERFLOW;
     put(BOM_BIG, dst);
     doneBOM = true;
   }
   try {
     while (src.hasRemaining()) {
       char c = src.get();
       if (!Character.isSurrogate(c)) {
         if (dst.remaining() < 4) return CoderResult.OVERFLOW;
         mark++;
         put(c, dst);
       } else if (Character.isHighSurrogate(c)) {
         if (!src.hasRemaining()) return CoderResult.UNDERFLOW;
         char low = src.get();
         if (Character.isLowSurrogate(low)) {
           if (dst.remaining() < 4) return CoderResult.OVERFLOW;
           mark += 2;
           put(Character.toCodePoint(c, low), dst);
         } else {
           return CoderResult.malformedForLength(1);
         }
       } else {
         // assert Character.isLowSurrogate(c);
         return CoderResult.malformedForLength(1);
       }
     }
     return CoderResult.UNDERFLOW;
   } finally {
     src.position(mark);
   }
 }
Пример #7
0
    private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
      byte[] sa = src.array();
      int sp = src.arrayOffset() + src.position();
      int sl = src.arrayOffset() + src.limit();
      assert (sp <= sl);
      sp = (sp <= sl ? sp : sl);
      char[] da = dst.array();
      int dp = dst.arrayOffset() + dst.position();
      int dl = dst.arrayOffset() + dst.limit();
      assert (dp <= dl);
      dp = (dp <= dl ? dp : dl);

      try {
        while (sp < sl) {
          byte b = sa[sp];
          if (b >= 0) {
            if (dp >= dl) return CoderResult.OVERFLOW;
            da[dp++] = (char) b;
            sp++;
            continue;
          }
          return CoderResult.malformedForLength(1);
        }
        return CoderResult.UNDERFLOW;
      } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
      }
    }
Пример #8
0
  private void unescape() {
    int len = buffer.position();
    buffer.position(0);
    Matcher m = pattern.matcher(buffer);
    int pos = 0;
    StringBuilder tmp = new StringBuilder(len);
    String seq = null;
    while (m.find(pos)) {
      // Copy any previous text
      if (m.start() > pos) {
        // Get text before
        tmp.append(buffer.subSequence(pos, m.start()));
      }
      pos = m.end();

      // Treat the escape sequence
      seq = m.group();
      int value = -1;
      int uIndex = seq.indexOf('u');
      if (seq.indexOf('x') == 2) {
        // Hexadecimal NCR "&#xHHH;"
        value = Integer.parseInt(seq.substring(3, seq.length() - 1), 16);
      } else if ((uIndex == 1) && (seq.charAt(uIndex - 1) == '\\')) {
        // Java style "\ and uHHH"
        value = Integer.parseInt(seq.substring(2), 16);
      } else if (seq.indexOf('#') == 1) {
        // Decimal NCR "&#DDD;"
        value = Integer.parseInt(seq.substring(2, seq.length() - 1));
      } else {
        // Character entity reference: &NAME;
        seq = seq.substring(1, seq.length() - 1);
        // Unidentified is -1: leave it like that
        value = entities.lookupName(seq);
      }

      // Append the parsed escape
      if (value < 128) {
        // Unknown pattern or ASCII values: Keep it as it
        // (so <, &, ", etc.. stay escaped)
        tmp.append(m.group());
      } else {
        tmp.append((char) value);
      }
    }

    // Copy last part and re-build the buffer
    if (seq != null) { // We had at least one match
      if (pos < len) {
        // Get text before
        tmp.append(buffer.subSequence(pos, len));
      }
      // Reset the buffer
      buffer.clear();
      buffer.append(tmp.toString(), 0, tmp.length());
    } else { // Else: nothing to un-escape
      buffer.position(len);
    }
  }
Пример #9
0
 private ServiceBox<String> createStringBox(ServiceBox.Type type) {
   List<String> list = new ArrayList<String>();
   while (jsonReader.next()) {
     int len = jsonReader.stringLength();
     list.add(charBuffer.subSequence(0, len).toString());
     charBuffer.position(charBuffer.position() + len);
   }
   return new ServiceBox<String>(type, list);
 }
Пример #10
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);
    }
  }
Пример #11
0
 @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());
 }
Пример #12
0
 public static void main(String[] arguments) {
   try {
     // read byte data into a byte buffer
     String data = "friends.dat";
     FileInputStream inData = new FileInputStream(data);
     FileChannel inChannel = inData.getChannel();
     long inSize = inChannel.size();
     ByteBuffer source = ByteBuffer.allocate((int) inSize);
     inChannel.read(source, 0);
     source.position(0);
     System.out.println("Original byte data:");
     for (int i = 0; source.remaining() > 0; i++) {
       System.out.print(source.get() + " ");
     }
     // convert byte data into character data
     source.position(0);
     Charset ascii = Charset.forName("US-ASCII");
     CharsetDecoder toAscii = ascii.newDecoder();
     CharBuffer destination = toAscii.decode(source);
     destination.position(0);
     System.out.println("\n\nNew character data:");
     for (int i = 0; destination.remaining() > 0; i++) {
       System.out.print(destination.get());
     }
     System.out.println();
   } catch (FileNotFoundException fne) {
     System.out.println(fne.getMessage());
   } catch (IOException ioe) {
     System.out.println(ioe.getMessage());
   }
 }
Пример #13
0
 public char[] encode(byte[] data, String encoding) throws IOException {
   if (encoding == null) {
     encoding = DEFAULT_ENCODING;
   }
   if (!Charset.isSupported(encoding)) throw new IOException("Unsupported encoding " + encoding);
   Charset charset = Charset.forName(encoding);
   CharsetDecoder cd =
       charset
           .newDecoder()
           .onMalformedInput(CodingErrorAction.REPLACE)
           .onUnmappableCharacter(CodingErrorAction.REPLACE);
   int en = (int) (cd.maxCharsPerByte() * data.length);
   char[] ca = new char[en];
   ByteBuffer bb = ByteBuffer.wrap(data);
   CharBuffer cb = CharBuffer.wrap(ca);
   CoderResult cr = cd.decode(bb, cb, true);
   if (!cr.isUnderflow()) {
     cr.throwException();
   }
   cr = cd.flush(cb);
   if (!cr.isUnderflow()) {
     cr.throwException();
   }
   return trim(ca, cb.position());
 }
Пример #14
0
    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());
    }
 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();
 }
Пример #16
0
  /**
   * 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;
    }
  }
Пример #17
0
    private void endBuffer(ZipEntry ze) {
      if (ze == null) {
        return;
      }
      if (store != null) {
        store.close(); // 終了処理は別スレッドで実行中
        String digest = store.getDigest();
        logPersister.addDigest(addDigests, digest);
        store = null;
      } else if (charsetDecoder != null) {
        charBuffer.flip();
        charBuffer.array();
        String accessLogJson =
            new String(charBuffer.array(), charBuffer.position(), charBuffer.limit());
        charsetDecoder = null;
        charBuffer = null;
        AccessLog accessLog = AccessLog.fromJson(accessLogJson);
        if (accessLog == null) {
          return;
        }
        logPersister.addDigest(refDigests, accessLog.getRequestHeaderDigest());
        logPersister.addDigest(refDigests, accessLog.getRequestBodyDigest());
        logPersister.addDigest(refDigests, accessLog.getResponseHeaderDigest());
        logPersister.addDigest(refDigests, accessLog.getResponseBodyDigest());
        accessLog.setId(null);
        accessLog.setPersist(true);

        PersistenceManager pm = JdoUtil.getPersistenceManager();
        logPersister.executeInsert(pm, accessLog);
        if (pm.currentTransaction().isActive()) {
          pm.currentTransaction().rollback();
        }
      }
    }
Пример #18
0
 @Override
 public boolean onStdinCharsReady(CharBuffer buffer) {
   if (utf8Buffer.remaining() <= buffer.remaining()) {
     charsWritten += utf8Buffer.remaining();
     buffer.put(utf8Buffer);
     buffer.flip();
     return false;
   } else {
     charsWritten += buffer.remaining();
     buffer.put(utf8Buffer.subSequence(0, buffer.remaining()));
     buffer.flip();
     utf8Buffer.position(utf8Buffer.position() + buffer.remaining());
     stdinOverflow = true;
     return true;
   }
 }
    private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
      char[] sa = src.array();
      int sp = src.arrayOffset() + src.position();
      int sl = src.arrayOffset() + src.limit();

      byte[] da = dst.array();
      int dp = dst.arrayOffset() + dst.position();
      int dl = dst.arrayOffset() + dst.limit();
      int len = Math.min(dl - dp, sl - sp);

      while (len-- > 0) {
        char c = sa[sp];
        int b = encode(c);
        if (b == UNMAPPABLE_ENCODING) {
          if (Character.isSurrogate(c)) {
            if (sgp == null) sgp = new Surrogate.Parser();
            if (sgp.parse(c, sa, sp, sl) < 0) {
              return withResult(sgp.error(), src, sp, dst, dp);
            }
            return withResult(sgp.unmappableResult(), src, sp, dst, dp);
          }
          return withResult(CoderResult.unmappableForLength(1), src, sp, dst, dp);
        }
        da[dp++] = (byte) b;
        sp++;
      }
      return withResult(sp < sl ? CoderResult.OVERFLOW : CoderResult.UNDERFLOW, src, sp, dst, dp);
    }
    private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
      byte[] sa = src.array();
      int sp = src.arrayOffset() + src.position();
      int sl = src.arrayOffset() + src.limit();

      char[] da = dst.array();
      int dp = dst.arrayOffset() + dst.position();
      int dl = dst.arrayOffset() + dst.limit();

      CoderResult cr = CoderResult.UNDERFLOW;
      if ((dl - dp) < (sl - sp)) {
        sl = sp + (dl - dp);
        cr = CoderResult.OVERFLOW;
      }

      while (sp < sl) {
        char c = decode(sa[sp]);
        if (c == UNMAPPABLE_DECODING) {
          return withResult(CoderResult.unmappableForLength(1), src, sp, dst, dp);
        }
        da[dp++] = c;
        sp++;
      }
      return withResult(cr, src, sp, dst, dp);
    }
Пример #21
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);
 }
Пример #22
0
    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);
    }
Пример #23
0
  /** Recycle this <code>InputBuffer</code> for reuse. */
  public void recycle() {

    inputContentBuffer.tryDispose();
    inputContentBuffer = null;

    singleCharBuf.position(singleCharBuf.limit());

    connection = null;
    decoder = null;
    ctx = null;
    handler = null;

    processingChars = false;
    closed = false;
    contentRead = false;

    markPos = -1;
    readAheadLimit = -1;
    requestedSize = -1;
    readCount = 0;

    averageCharsPerByte = 1.0f;

    isWaitingDataAsynchronously = false;

    encoding = DEFAULT_HTTP_CHARACTER_ENCODING;
  }
Пример #24
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);
  }
Пример #25
0
    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();
      }
    }
Пример #26
0
 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() + ", ");
 }
Пример #27
0
 static byte[] encode(char[] cc, Charset cs, boolean testDirect, Time t) throws Exception {
   ByteBuffer bbf;
   CharBuffer cbf;
   CharsetEncoder enc = cs.newEncoder();
   String csn = cs.name();
   if (testDirect) {
     bbf = ByteBuffer.allocateDirect(cc.length * 4);
     cbf = ByteBuffer.allocateDirect(cc.length * 2).asCharBuffer();
     cbf.put(cc).flip();
   } else {
     bbf = ByteBuffer.allocate(cc.length * 4);
     cbf = CharBuffer.wrap(cc);
   }
   CoderResult cr = null;
   long t1 = System.nanoTime() / 1000;
   for (int i = 0; i < iteration; i++) {
     cbf.rewind();
     bbf.clear();
     enc.reset();
     cr = enc.encode(cbf, bbf, true);
   }
   long t2 = System.nanoTime() / 1000;
   t.t = (t2 - t1) / iteration;
   if (cr != CoderResult.UNDERFLOW) {
     System.out.println("ENC-----------------");
     int pos = cbf.position();
     System.out.printf("  cr=%s, cbf.pos=%d, cc[pos]=%x%n", cr.toString(), pos, cc[pos] & 0xffff);
     throw new RuntimeException("Encoding err: " + csn);
   }
   byte[] bb = new byte[bbf.position()];
   bbf.flip();
   bbf.get(bb);
   return bb;
 }
Пример #28
0
 private void fillBuffer() throws IOException {
   if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) {
     encoderIn.compact();
     int i = encoderIn.position();
     int j = reader.read(encoderIn.array(), i, encoderIn.remaining());
     if (j == -1) {
       endOfInput = true;
     } else {
       encoderIn.position(i + j);
     }
     encoderIn.flip();
   }
   encoderOut.compact();
   lastCoderResult = encoder.encode(encoderIn, encoderOut, endOfInput);
   encoderOut.flip();
 }
Пример #29
0
 private void checkSplitSequence() {
   int len = buffer.position();
   buffer.position(0);
   // Search for the first & or \ in the last 10 (or less) characters
   prevBuf = null;
   int j = 0;
   for (int i = len - 1; ((i >= 0) && (j < 10)); i--) {
     if ((buffer.charAt(i) == '&') || (buffer.charAt(i) == '\\')) {
       prevBuf = buffer.subSequence(i, len).toString();
       len = i;
       break;
     }
     j++;
   }
   buffer.position(len);
   buffer.limit(len);
 }
Пример #30
0
    @Override
    public void onStdoutChars(CharBuffer buffer, boolean closed, CoderResult coderResult) {
      charsRead += buffer.remaining();
      decodedStdout.append(buffer);
      buffer.position(buffer.limit());

      if (charsRead == charsWritten) {
        nuProcess.closeStdin();
      }
    }