Ejemplo n.º 1
0
    /** {@inheritDoc} */
    @Override
    protected void decode() {

      ByteBuffer framebytes =
          com.mikeduvall.redhorizon.util.ByteBufferFactory.createLittleEndianByteBuffer(
              width() * height());
      ByteBuffer colourbytes =
          com.mikeduvall.redhorizon.util.ByteBufferFactory.createLittleEndianByteBuffer(
              width() * height() * format().size);

      // Colour every decoded frame
      for (int i = 0; i < numImages(); i++) {
        framebytes.clear();
        try {
          inputchannel.read(framebytes);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
        framebytes.rewind();

        colourbytes.clear();
        ImageUtility.applyPalette(framebytes, colourbytes, wsapalette);
        try {
          outputchannel.write(colourbytes);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
Ejemplo n.º 2
0
  private void handle(SelectionKey key) throws IOException {
    // TODO Auto-generated method stub

    ServerSocketChannel server = null;
    SocketChannel client = null;
    String receiveText = null;
    int count = 0;

    if (key.isAcceptable()) {
      // client require accept events
      server = (ServerSocketChannel) key.channel();
      client = server.accept();
      client.configureBlocking(false);
      client.register(selector, SelectionKey.OP_READ);
    } else if (key.isReadable()) {
      // 如果是read事件,则直接读取
      client = (SocketChannel) key.channel();
      recBuffer.clear();
      count = client.read(recBuffer);
      if (count > 0) {
        recBuffer.flip();
        receiveText = decode.decode(recBuffer.asReadOnlyBuffer()).toString();
        System.out.println(client.toString() + ":" + receiveText);
        sendBuffer.clear();
        sendBuffer.put((sdf.format(new Date()) + "服务器收到你的消息").getBytes());
        sendBuffer.flip();
        client.write(sendBuffer);
        dispatch(client, receiveText);
        client = (SocketChannel) key.channel();
        client.register(selector, SelectionKey.OP_READ);
      }
    }
  }
Ejemplo n.º 3
0
    /**
     * writes the contents of the buffer to the socket
     *
     * @param socketChannel the socket to publish the buffer to
     * @param approxTime an approximation of the current time in millis
     * @throws IOException
     */
    private int writeBufferToSocket(
        @NotNull final SocketChannel socketChannel, final long approxTime) throws IOException {

      if (in.position() == 0) return 0;

      // if we still have some unwritten writer from last time
      lastSentTime = approxTime;
      out.limit((int) in.position());

      final int len = socketChannel.write(out);

      if (LOG.isDebugEnabled()) LOG.debug("bytes-written=" + len);

      if (out.remaining() == 0) {
        out.clear();
        in.clear();
      } else {
        out.compact();
        in.position(out.position());
        in.limit(in.capacity());
        out.clear();
      }

      return len;
    }
Ejemplo n.º 4
0
 private void _closeSocket() {
   synchronized (sendLock) {
     long interval = System.currentTimeMillis() - lastConnectTime;
     if (interval < connectWaitTime * 1000) {
       trace.trace("can not close socket within " + connectWaitTime + " sec");
       return;
     }
     try {
       try {
         socket.shutdownInput();
         socket.shutdownOutput();
       } catch (Exception e) {
       }
       socket.close();
     } catch (Exception e) {
     } finally {
       lastConnectTime = System.currentTimeMillis();
       connectWaitTime = 1;
       socket = null;
       listener.onClose(this);
       readBuffer.clear();
       sendBuffer.clear();
       if (State.STOPPING == _state || State.STOPPED == _state) {
         reader = null;
         return;
       }
       _state = State.STARTING;
     }
   }
 }
Ejemplo n.º 5
0
  private static void writeEntry(
      OutputStream os, Attributes.Name name, String value, CharsetEncoder encoder, ByteBuffer bBuf)
      throws IOException {
    byte[] out = name.getBytes();
    if (out.length > LINE_LENGTH_LIMIT) {
      throw new IOException(
          Messages.getString(
              "archive.33", name, Integer.valueOf(LINE_LENGTH_LIMIT))); // $NON-NLS-1$
    }

    os.write(out);
    os.write(VALUE_SEPARATOR);

    encoder.reset();
    bBuf.clear().limit(LINE_LENGTH_LIMIT - out.length - 2);

    CharBuffer cBuf = CharBuffer.wrap(value);
    CoderResult r;

    while (true) {
      r = encoder.encode(cBuf, bBuf, true);
      if (CoderResult.UNDERFLOW == r) {
        r = encoder.flush(bBuf);
      }
      os.write(bBuf.array(), bBuf.arrayOffset(), bBuf.position());
      os.write(LINE_SEPARATOR);
      if (CoderResult.UNDERFLOW == r) {
        break;
      }
      os.write(' ');
      bBuf.clear().limit(LINE_LENGTH_LIMIT - 1);
    }
  }
Ejemplo n.º 6
0
  private void upgradeRatings(BinaryFormat newFormat) throws IOException {
    Preconditions.checkArgument(
        newFormat.getRatingSize() > format.getRatingSize(), "new format is not wider than old");
    logger.info("upgrading {} ratings from {} to {}", index, format, newFormat);

    ByteBuffer oldBuffer = ByteBuffer.allocateDirect(format.getRatingSize());
    ByteBuffer newBuffer = ByteBuffer.allocateDirect(newFormat.getRatingSize());
    MutableRating scratch = new MutableRating();

    long oldPos = BinaryHeader.HEADER_SIZE + index * format.getRatingSize();
    Preconditions.checkState(channel.position() == oldPos, "channel is at the wrong position");
    long newPos = BinaryHeader.HEADER_SIZE + index * newFormat.getRatingSize();
    channel.position(newPos);
    // loop backwards, coping each rating to later in the file
    for (int i = index - 1; i >= 0; i--) {
      oldPos -= format.getRatingSize();
      newPos -= newFormat.getRatingSize();

      // read the old rating
      BinaryUtils.readBuffer(channel, oldBuffer, oldPos);
      oldBuffer.flip();
      format.readRating(oldBuffer, scratch);
      oldBuffer.clear();

      // write the new rating
      newFormat.renderRating(scratch, newBuffer);
      newBuffer.flip();
      BinaryUtils.writeBuffer(channel, newBuffer, newPos);
      newBuffer.clear();
    }
    assert oldPos == BinaryHeader.HEADER_SIZE;
    assert newPos == BinaryHeader.HEADER_SIZE;
    format = newFormat;
    ratingBuffer = ByteBuffer.allocateDirect(newFormat.getRatingSize());
  }
Ejemplo n.º 7
0
    public void memoryCopyParition() throws IOException {
      if (DEBUG_MODE) {
        mBuf.flip();
        CommonUtils.printByteBuffer(LOG, mBuf);
      }
      mBuf.flip();
      long sum = 0;
      String str = "th " + mMsg + " @ Worker ";

      if (mOneToMany) {
        ByteBuffer dst = null;
        RandomAccessFile file = null;
        if (mMemoryOnly) {
          dst = ByteBuffer.allocateDirect(FILE_BYTES);
        }
        for (int times = mLeft; times < mRight; times++) {
          long startTimeMs = System.currentTimeMillis();
          if (!mMemoryOnly) {
            file = new RandomAccessFile(FOLDER + (mWorkerId + BASE_FILE_NUMBER), "rw");
            dst = file.getChannel().map(MapMode.READ_WRITE, 0, FILE_BYTES);
          }
          dst.order(ByteOrder.nativeOrder());
          for (int k = 0; k < BLOCKS_PER_FILE; k++) {
            mBuf.array()[0] = (byte) (k + mWorkerId);
            dst.put(mBuf.array());
          }
          dst.clear();
          sum += dst.get(times);
          dst.clear();
          if (!mMemoryOnly) {
            file.close();
          }
          logPerIteration(startTimeMs, times, str, mWorkerId);
        }
      } else {
        ByteBuffer dst = null;
        RandomAccessFile file = null;
        if (mMemoryOnly) {
          dst = ByteBuffer.allocateDirect(FILE_BYTES);
        }
        for (int times = mLeft; times < mRight; times++) {
          long startTimeMs = System.currentTimeMillis();
          if (!mMemoryOnly) {
            file = new RandomAccessFile(FOLDER + (mWorkerId + BASE_FILE_NUMBER), "rw");
            dst = file.getChannel().map(MapMode.READ_WRITE, 0, FILE_BYTES);
          }
          dst.order(ByteOrder.nativeOrder());
          for (int k = 0; k < BLOCKS_PER_FILE; k++) {
            dst.get(mBuf.array());
          }
          sum += mBuf.get(times % 16);
          dst.clear();
          if (!mMemoryOnly) {
            file.close();
          }
          logPerIteration(startTimeMs, times, str, mWorkerId);
        }
      }
      Results[mWorkerId] = sum;
    }
 /**
  * Offset, rowStride, and pixelStride are given in bytes. Height and width are given in pixels.
  */
 private void writeByteBuffer(
     int width,
     int height,
     ByteBuffer pixels,
     OutputStream dngOutput,
     int pixelStride,
     int rowStride,
     long offset)
     throws IOException {
   if (width <= 0 || height <= 0) {
     throw new IllegalArgumentException(
         "Image with invalid width, height: (" + width + "," + height + ") passed to write");
   }
   long capacity = pixels.capacity();
   long totalSize = rowStride * height + offset;
   if (capacity < totalSize) {
     throw new IllegalArgumentException(
         "Image size " + capacity + " is too small (must be larger than " + totalSize + ")");
   }
   int minRowStride = pixelStride * width;
   if (minRowStride > rowStride) {
     throw new IllegalArgumentException(
         "Invalid image pixel stride, row byte width "
             + minRowStride
             + " is too large, expecting "
             + rowStride);
   }
   pixels.clear(); // Reset mark and limit
   nativeWriteImage(
       dngOutput, width, height, pixels, rowStride, pixelStride, offset, pixels.isDirect());
   pixels.clear();
 }
Ejemplo n.º 9
0
  private void begin(Writer writer, IndWriter indexer, int mode, int blockSize) {
    mDraw.checkErr();

    mActiveWriter = writer;
    mActiveIndexer = indexer;
    mActiveMode = mode;
    mVertBuf.clear();

    int bytes = mVertBuf.capacity();
    int vertBytes = writer.mVertWriter.bytesPerElem();
    mActiveCap = (bytes / (vertBytes * blockSize)) * blockSize;
    mActivePos = 0;

    writer.mProgram.bind(mDraw);
    writer.mVao.bind(mDraw);
    mVbo.bind(mDraw);

    if (indexer != null) {
      indexer.reset();
      mIndBuf.clear();
      mIbo.bind(mDraw);
    }

    DrawUtil.checkErr();
  }
  @Test
  public void test64kColumn() {
    // a byte buffer more than 64k
    ByteBuffer buffer = ByteBuffer.allocate(1024 * 65);
    buffer.clear();

    // read more than 64k
    for (int i = 0; i < 1024 * 64 / 4 + 1; i++) buffer.putInt(0);

    // for read
    buffer.flip();
    Column column = new Column(ByteBufferUtil.bytes("test"), buffer, 0);

    SecondaryIndexColumnSizeTest.MockRowIndex mockRowIndex =
        new SecondaryIndexColumnSizeTest.MockRowIndex();
    SecondaryIndexColumnSizeTest.MockColumnIndex mockColumnIndex =
        new SecondaryIndexColumnSizeTest.MockColumnIndex();

    assertTrue(mockRowIndex.validate(column));
    assertFalse(mockColumnIndex.validate(column));

    // test less than 64k value
    buffer.flip();
    buffer.clear();
    buffer.putInt(20);
    buffer.flip();

    assertTrue(mockRowIndex.validate(column));
    assertTrue(mockColumnIndex.validate(column));
  }
  @SuppressLint("Assert")
  @Override
  public boolean stepPipeline() {
    if (mIsEOS) return false;
    int trackIndex = mExtractor.getSampleTrackIndex();
    if (trackIndex < 0) {
      mBuffer.clear();
      mBufferInfo.set(0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
      mMuxer.writeSampleData(mSampleType, mBuffer, mBufferInfo);
      mIsEOS = true;
      return true;
    }
    if (trackIndex != mTrackIndex) return false;

    mBuffer.clear();
    int sampleSize = mExtractor.readSampleData(mBuffer, 0);
    assert sampleSize <= mBufferSize;
    boolean isKeyFrame = (mExtractor.getSampleFlags() & MediaExtractor.SAMPLE_FLAG_SYNC) != 0;
    int flags = isKeyFrame ? MediaCodec.BUFFER_FLAG_SYNC_FRAME : 0;
    mBufferInfo.set(0, sampleSize, mExtractor.getSampleTime(), flags);
    mMuxer.writeSampleData(mSampleType, mBuffer, mBufferInfo);
    mWrittenPresentationTimeUs = mBufferInfo.presentationTimeUs;

    mExtractor.advance();
    return true;
  }
  private void loadPartitionInMem(int pid, RunFileWriter wr, int[] buffs)
      throws HyracksDataException {
    RunFileReader r = wr.createReader();
    r.open();
    int counter = 0;
    ByteBuffer mBuff = null;
    reloadBuffer.clear();
    while (r.nextFrame(reloadBuffer)) {
      mBuff = memBuffs[buffs[counter]];
      if (mBuff == null) {
        mBuff = ctx.allocateFrame();
        memBuffs[buffs[counter]] = mBuff;
      }
      FrameUtils.copy(reloadBuffer, mBuff);
      counter++;
      reloadBuffer.clear();
    }

    int curNext = nextBuff[buffs[buffs.length - 1]];
    nextBuff[buffs[buffs.length - 1]] = END_OF_PARTITION;
    nextFreeBuffIx = curNext;

    r.close();
    pStatus.set(pid, false);
    buildRFWriters[pid] = null;
  }
Ejemplo n.º 13
0
  /** {@inheritDoc} */
  @Override
  public long write(final SelectionKey key) throws IOException {
    final DatagramChannel channel = (DatagramChannel) key.channel();
    final MessageBufferConsumer<ByteBuffer> chnIn = getChannelInput();
    long n = 0;
    long k = chnIn.remaining();
    for (; k >= 0; k--) {
      final SocketAddress address;
      try {
        final long sequence = chnIn.acquire();
        try {
          final ByteBuffer msg = chnIn.get(sequence);
          sendBuffer.clear();
          codec.put(msg, sendBuffer);
          msg.clear();
          sendBuffer.flip();
          address = (SocketAddress) chnIn.attachment(sequence);
        } finally {
          chnIn.release(sequence);
        }
      } catch (final InterruptedException e) {
        throw new IOException(e);
      }

      limiter.send(sendBuffer.remaining());

      do {
        n += channel.send(sendBuffer, address);
      } while (sendBuffer.remaining() > 0);
    }
    if (chnIn.remaining() == 0) {
      disableWriter();
    }
    return n;
  }
Ejemplo n.º 14
0
  public void tick() {
    soundBuffer.clear();

    //        targetAmplitude = (targetAmplitude - 1) * 0.9f + 1;
    //        targetAmplitude = (targetAmplitude - 1) * 0.9f + 1;
    synchronized (listenerMixer) {
      float maxAmplitude = listenerMixer.read(leftBuf, rightBuf, rate);
      //            if (maxAmplitude > targetAmplitude) targetAmplitude = maxAmplitude;
    }

    soundBuffer.clear();
    float gain = 32000;
    for (int i = 0; i < bufferSize; i++) {
      //            amplitude += (targetAmplitude - amplitude) / rate;
      //          amplitude = 1;
      //              float gain = 30000;
      int l = (int) (leftBuf[i] * gain);
      int r = (int) (rightBuf[i] * gain);
      if (l > 32767) l = 32767;
      if (r > 32767) r = 32767;
      if (l < -32767) l = -32767;
      if (r < -32767) r = -32767;
      soundBuffer.putShort((short) l);
      soundBuffer.putShort((short) r);
    }

    sdl.write(soundBuffer.array(), 0, bufferSize * 2 * 2);
  }
  public SelectionKey accept(Selector selector, SocketChannel socketChannel) throws IOException {
    writeBuffer.clear();
    readBuffer.clear();
    readBuffer.flip();
    currentObjectLength = 0;
    try {
      this.socketChannel = socketChannel;
      socketChannel.configureBlocking(false);
      Socket socket = socketChannel.socket();
      socket.setTcpNoDelay(true);

      selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);

      if (DEBUG) {
        debug(
            "kryonet",
            "Port "
                + socketChannel.socket().getLocalPort()
                + "/TCP connected to: "
                + socketChannel.socket().getRemoteSocketAddress());
      }

      lastReadTime = lastWriteTime = System.currentTimeMillis();

      return selectionKey;
    } catch (IOException ex) {
      close();
      throw ex;
    }
  }
  /* (non-Javadoc)
   * @see java.lang.Thread#run()
   */
  @Override
  public void run() {

    // loop until interrupt or reconnector count is -1 (to many retries)
    while (!isInterrupted() || reConnectCounter == -1) {
      try {

        if (inputStream == null) {
          reconnect();

        } else {
          int read = inputStream.read();
          if (read == -1) {
            logger.error("eBus read timeout occured, ignore it currently!");

            // reconnect
            // reconnect();

          } else {

            byte receivedByte = (byte) (read & 0xFF);

            // write received byte to input buffer
            inputBuffer.put(receivedByte);

            // the 0xAA byte is a end of a packet
            if (receivedByte == EBusTelegram.SYN) {
              onEBusSyncReceived();
            }
          }
        }

      } catch (IOException e) {
        logger.error("An IO exception has occured! Try to reconnect eBus connector ...", e);

        try {
          reconnect();
        } catch (IOException | InterruptedException e1) {
          logger.error(e.toString(), e);
        }

      } catch (BufferOverflowException e) {
        logger.error(
            "eBus telegram buffer overflow - not enough sync bytes received! Try to adjust eBus adapter.");
        inputBuffer.clear();

      } catch (Exception e) {
        logger.error(e.toString(), e);
        inputBuffer.clear();
      }
    }

    // disconnect the connector e.g. close serial port
    try {
      disconnect();
    } catch (IOException e) {
      logger.error(e.toString(), e);
    }
  }
  /** Recycle the processor. */
  @Override
  public void recycle(boolean socketClosing) {
    super.recycle(socketClosing);

    inputBuffer.clear();
    inputBuffer.limit(0);
    outputBuffer.clear();
  }
Ejemplo n.º 18
0
    /**
     * some more work is needed in read and write to handle the multiple fat availability we have to
     * correcly handle the exception to be sure that if we have at least a correct fat we get it -
     * gvt
     */
    private void read(long address) throws IOException {
      if (!isFree()) throw new IllegalArgumentException("cannot read a busy element");

      this.address.set(address);
      elem.clear();
      api.read(address * elementSize, elem);
      elem.clear();
    }
Ejemplo n.º 19
0
    public int readAndProcess() throws IOException, InterruptedException {
      while (true) {
        /*
         * Read at most one RPC. If the header is not read completely yet
         * then iterate until we read first RPC or until there is no data left.
         */
        int count = -1;
        if (dataLengthBuffer.remaining() > 0) {
          count = channelRead(channel, dataLengthBuffer);
          if (count < 0 || dataLengthBuffer.remaining() > 0) return count;
        }

        if (!headerRead) {
          dataLengthBuffer.flip();
          if (!HEADER.equals(dataLengthBuffer)) {
            // Warning is ok since this is not supposed to happen.
            LOG.warn("Incorrect header from " + hostAddress + ":" + remotePort);
            return -1;
          }
          dataLengthBuffer.clear();
          headerRead = true;
          continue;
        }

        if (data == null) {
          dataLengthBuffer.flip();
          dataLength = dataLengthBuffer.getInt();

          if (dataLength == Client.PING_CALL_ID) {
            dataLengthBuffer.clear();
            return 0; // ping message
          }
          data = ByteBuffer.allocate(dataLength);
          incRpcCount(); // Increment the rpc count
        }

        count = channelRead(channel, data);

        if (data.remaining() == 0) {
          dataLengthBuffer.clear();
          data.flip();
          if (protocolRead) {
            processData();
            data = null;
            return count;
          } else {
            processProtocol();
            protocolRead = true;
            data = null;

            // Authorizitation is intenionally left out

            continue;
          }
        }
        return count;
      }
    }
Ejemplo n.º 20
0
  public static void runTests() {
    try {

      // SHA1 sha1Jmule = new SHA1();
      MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1");
      SHA1 sha1Gudy = new SHA1();
      // SHA1Az shaGudyResume = new SHA1Az();

      ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);

      File dir = new File(dirname);
      File[] files = dir.listFiles();

      for (int i = 0; i < files.length; i++) {
        FileChannel fc = new RandomAccessFile(files[i], "r").getChannel();

        System.out.println("Testing " + files[i].getName() + " ...");

        while (fc.position() < fc.size()) {
          fc.read(buffer);
          buffer.flip();

          byte[] raw = new byte[buffer.limit()];
          System.arraycopy(buffer.array(), 0, raw, 0, raw.length);

          sha1Gudy.update(buffer);
          sha1Gudy.saveState();
          ByteBuffer bb = ByteBuffer.wrap(new byte[56081]);
          sha1Gudy.digest(bb);
          sha1Gudy.restoreState();

          sha1Sun.update(raw);

          buffer.clear();
        }

        byte[] sun = sha1Sun.digest();
        sha1Sun.reset();

        byte[] gudy = sha1Gudy.digest();
        sha1Gudy.reset();

        if (Arrays.equals(sun, gudy)) {
          System.out.println("  SHA1-Gudy: OK");
        } else {
          System.out.println("  SHA1-Gudy: FAILED");
        }

        buffer.clear();
        fc.close();
        System.out.println();
      }

    } catch (Throwable e) {
      Debug.printStackTrace(e);
    }
  }
Ejemplo n.º 21
0
  @Test
  public void testGentleCloseDuringHandshake() throws Exception {
    InetSocketAddress address = startServer(version, null);
    SslContextFactory sslContextFactory = newSslContextFactory();
    sslContextFactory.start();
    SSLEngine sslEngine = sslContextFactory.newSSLEngine(address);
    sslEngine.setUseClientMode(true);
    NextProtoNego.put(
        sslEngine,
        new NextProtoNego.ClientProvider() {
          @Override
          public boolean supports() {
            return true;
          }

          @Override
          public void unsupported() {}

          @Override
          public String selectProtocol(List<String> protocols) {
            return null;
          }
        });
    sslEngine.beginHandshake();

    ByteBuffer encrypted = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
    sslEngine.wrap(BufferUtil.EMPTY_BUFFER, encrypted);
    encrypted.flip();

    try (SocketChannel channel = SocketChannel.open(address)) {
      // Send ClientHello, immediately followed by TLS Close Alert and then by FIN
      channel.write(encrypted);
      sslEngine.closeOutbound();
      encrypted.clear();
      sslEngine.wrap(BufferUtil.EMPTY_BUFFER, encrypted);
      encrypted.flip();
      channel.write(encrypted);
      channel.shutdownOutput();

      // Read ServerHello from server
      encrypted.clear();
      int read = channel.read(encrypted);
      encrypted.flip();
      Assert.assertTrue(read > 0);
      // Cannot decrypt, as the SSLEngine has been already closed

      // Now if we read more, we should either read the TLS Close Alert, or directly -1
      encrypted.clear();
      read = channel.read(encrypted);
      // Sending a TLS Close Alert during handshake results in an exception when
      // unwrapping that the server react to by closing the connection abruptly.
      Assert.assertTrue(read < 0);
    }
  }
Ejemplo n.º 22
0
  private boolean processDataBinary() throws IOException {
    // Copy the available data to the buffer
    TransformationResult tr = transformation.getMoreData(opCode, fin, rsv, messageBufferBinary);
    while (!TransformationResult.END_OF_FRAME.equals(tr)) {
      // Frame not complete - what did we run out of?
      if (TransformationResult.UNDERFLOW.equals(tr)) {
        // Ran out of input data - get some more
        return false;
      }

      // Ran out of message buffer - flush it
      if (!usePartial()) {
        CloseReason cr =
            new CloseReason(
                CloseCodes.TOO_BIG,
                sm.getString(
                    "wsFrame.bufferTooSmall",
                    Integer.valueOf(messageBufferBinary.capacity()),
                    Long.valueOf(payloadLength)));
        throw new WsIOException(cr);
      }
      messageBufferBinary.flip();
      ByteBuffer copy = ByteBuffer.allocate(messageBufferBinary.limit());
      copy.put(messageBufferBinary);
      copy.flip();
      sendMessageBinary(copy, false);
      messageBufferBinary.clear();
      // Read more data
      tr = transformation.getMoreData(opCode, fin, rsv, messageBufferBinary);
    }

    // Frame is fully received
    // Send the message if either:
    // - partial messages are supported
    // - the message is complete
    if (usePartial() || !continuationExpected) {
      messageBufferBinary.flip();
      ByteBuffer copy = ByteBuffer.allocate(messageBufferBinary.limit());
      copy.put(messageBufferBinary);
      copy.flip();
      sendMessageBinary(copy, !continuationExpected);
      messageBufferBinary.clear();
    }

    if (continuationExpected) {
      // More data for this message expected, start a new frame
      newFrame();
    } else {
      // Message is complete, start a new message
      newMessage();
    }

    return true;
  }
Ejemplo n.º 23
0
 /**
  * Create a new ByteBuffer and copy all the content of {@code source} ByteBuffer to the new
  * ByteBuffer. The new ByteBuffer's limit and capacity will be source.capacity(), and its position
  * will be 0. Note that the state of {@code source} ByteBuffer won't be changed.
  */
 public static ByteBuffer copyByteBuffer(ByteBuffer source) {
   // Make a duplicate of the source ByteBuffer and read data from the
   // duplicate. This is to avoid affecting the source ByteBuffer's state.
   ByteBuffer temp = source.duplicate();
   // We want to copy all the data in the source ByteBuffer, not just the
   // remaining bytes.
   temp.clear();
   ByteBuffer result = ByteBuffer.allocate(temp.capacity());
   result.put(temp);
   result.clear();
   return result;
 }
Ejemplo n.º 24
0
 /**
  * Read size bytes from the reader at the current position
  *
  * @param reader the TarArchiveInputStream reader
  * @param size the number of bytes to read
  * @param data the buffer to store the content
  * @throws IOException
  */
 public static void getFile(
     final TarArchiveInputStream reader, long size, final StringBuilder data) throws IOException {
   bbuffer.clear();
   while (size > bbuffer.capacity()) {
     reader.read(bbuffer.array(), 0, bbuffer.capacity());
     size -= bbuffer.capacity();
     toAsciiString(data, bbuffer.capacity());
     bbuffer.clear();
   }
   reader.read(bbuffer.array(), 0, (int) size);
   toAsciiString(data, (int) size);
 }
Ejemplo n.º 25
0
    private void write() throws IOException {
      if (isFree()) throw new IllegalArgumentException("cannot write a free element");

      elem.clear();

      long addr = address.get() * elementSize;

      for (int i = 0; i < nrfats; i++) {
        api.write(addr, elem);
        addr += fatsize;
        elem.clear();
      }
    }
Ejemplo n.º 26
0
 @Override
 public void close() throws IOException {
   if (isMmap) {
     MmapUtils.unloadByteBuffer(chunkOffsetsBuffer);
     MmapUtils.unloadByteBuffer(bitsetBuffer);
     MmapUtils.unloadByteBuffer(rawDataBuffer);
     raf.close();
   } else {
     chunkOffsetsBuffer.clear();
     bitsetBuffer.clear();
     rawDataBuffer.clear();
   }
 }
 private void ping(int i) throws IOException {
   buffy.putInt(0, i);
   do {
     client.write(buffy);
   } while (buffy.hasRemaining());
   buffy.clear();
   buffy.putInt(0, 0);
   do {
     client.read(buffy);
   } while (buffy.hasRemaining());
   if (buffy.getInt(0) != i) throw new RuntimeException();
   buffy.clear();
 }
Ejemplo n.º 28
0
 void writeOut() {
   ByteBuffer byteBuffer = buffer.getBuffer();
   if (getOperationType() == OperationType.WRITE) {
     byteBuffer.clear();
     try {
       int count = getFileChannel().write(byteBuffer, position * recordSize);
       assert count == recordSize;
     } catch (IOException e) {
       throw new UnderlyingStorageException(
           "Unable to write record[" + position + "] @[" + position * recordSize + "]", e);
     }
   }
   byteBuffer.clear();
 }
  /**
   * Expand the underlying ByteBuffer and preserve content.
   *
   * @param requestSize Requested new size.
   */
  public synchronized void expand(int requestSize) {

    if (requestSize > mBuffer.capacity()) {

      ByteBuffer oldBuffer = mBuffer;
      int oldPosition = mBuffer.position();
      int newCapacity = ((requestSize / mGrowSize) + 1) * mGrowSize;
      mBuffer = ByteBuffer.allocateDirect(newCapacity);
      oldBuffer.clear();
      mBuffer.clear();
      mBuffer.put(oldBuffer);
      mBuffer.position(oldPosition);
    }
  }
Ejemplo n.º 30
0
  @Test
  public void testAbruptCloseDuringHandshake() throws Exception {
    InetSocketAddress address = startServer(version, null);
    SslContextFactory sslContextFactory = newSslContextFactory();
    sslContextFactory.start();
    SSLEngine sslEngine = sslContextFactory.newSSLEngine(address);
    sslEngine.setUseClientMode(true);
    NextProtoNego.put(
        sslEngine,
        new NextProtoNego.ClientProvider() {
          @Override
          public boolean supports() {
            return true;
          }

          @Override
          public void unsupported() {}

          @Override
          public String selectProtocol(List<String> protocols) {
            return null;
          }
        });
    sslEngine.beginHandshake();

    ByteBuffer encrypted = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
    sslEngine.wrap(BufferUtil.EMPTY_BUFFER, encrypted);
    encrypted.flip();

    try (SocketChannel channel = SocketChannel.open(address)) {
      // Send ClientHello, immediately followed by FIN (no TLS Close Alert)
      channel.write(encrypted);
      channel.shutdownOutput();

      // Read ServerHello from server
      encrypted.clear();
      int read = channel.read(encrypted);
      encrypted.flip();
      Assert.assertTrue(read > 0);
      ByteBuffer decrypted = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize());
      sslEngine.unwrap(encrypted, decrypted);

      // Now if we read more, we should either read the TLS Close Alert, or directly -1
      encrypted.clear();
      read = channel.read(encrypted);
      // Since we have close the connection abruptly, the server also does so
      Assert.assertTrue(read < 0);
    }
  }