コード例 #1
0
 /**
  * Writes the SOCKS "connect" bytes, differentiating between SOCKS 4 and 4A; the former sends an
  * IPv4 address, the latter the full domain name.
  */
 private void writeSocks4Connect() {
   HttpDestination destination =
       (HttpDestination) context.get(HttpClientTransport.HTTP_DESTINATION_CONTEXT_KEY);
   String host = destination.getHost();
   short port = (short) destination.getPort();
   Matcher matcher = IPv4_PATTERN.matcher(host);
   if (matcher.matches()) {
     // SOCKS 4
     ByteBuffer buffer = ByteBuffer.allocate(9);
     buffer.put((byte) 4).put((byte) 1).putShort(port);
     for (int i = 1; i <= 4; ++i) buffer.put((byte) Integer.parseInt(matcher.group(i)));
     buffer.put((byte) 0);
     buffer.flip();
     getEndPoint().write(this, buffer);
   } else {
     // SOCKS 4A
     byte[] hostBytes = host.getBytes(StandardCharsets.UTF_8);
     ByteBuffer buffer = ByteBuffer.allocate(9 + hostBytes.length + 1);
     buffer.put((byte) 4).put((byte) 1).putShort(port);
     buffer.put((byte) 0).put((byte) 0).put((byte) 0).put((byte) 1).put((byte) 0);
     buffer.put(hostBytes).put((byte) 0);
     buffer.flip();
     getEndPoint().write(this, buffer);
   }
 }
コード例 #2
0
  public boolean transmit(SocketChannel ch) throws IOException {
    if (buf == null) {
      byte[] data = serializeBinary(this);
      int len = data.length;
      buf = ByteBuffer.allocateDirect(len + 4);

      buf.put((byte) ((len >> 24) & 0xFF));
      buf.put((byte) ((len >> 16) & 0xFF));
      buf.put((byte) ((len >> 8) & 0xFF));
      buf.put((byte) ((len) & 0xFF));
      buf.put(data);
      buf.flip();
    }

    if (ch.write(buf) < 0) {
      throw new IOException("Server went down");
    }

    if (buf.hasRemaining()) {
      return false;
    } else {
      buf.flip();
      return true;
    }
  }
コード例 #3
0
 private ByteBuffer loadResource(URL url) throws IOException {
   InputStream stream = null;
   try {
     stream = url.openStream();
     int initialBufferCapacity = Math.min(0x40000, stream.available() + 1);
     if (initialBufferCapacity <= 2) initialBufferCapacity = 0x10000;
     else initialBufferCapacity = Math.max(initialBufferCapacity, 0x200);
     ByteBuffer buf = ByteBuffer.allocate(initialBufferCapacity);
     while (true) {
       if (!buf.hasRemaining()) {
         ByteBuffer newBuf = ByteBuffer.allocate(2 * buf.capacity());
         buf.flip();
         newBuf.put(buf);
         buf = newBuf;
       }
       int len = stream.read(buf.array(), buf.position(), buf.remaining());
       if (len <= 0) break;
       buf.position(buf.position() + len);
     }
     buf.flip();
     return buf;
   } finally {
     if (stream != null) stream.close();
   }
 }
コード例 #4
0
    @Override
    public EncryptedKeyVersion generateEncryptedKey(String encryptionKeyName)
        throws IOException, GeneralSecurityException {
      // Fetch the encryption key
      KeyVersion encryptionKey = keyProvider.getCurrentKey(encryptionKeyName);
      Preconditions.checkNotNull(
          encryptionKey, "No KeyVersion exists for key '%s' ", encryptionKeyName);
      // Generate random bytes for new key and IV

      CryptoCodec cc = CryptoCodec.getInstance(keyProvider.getConf());
      final byte[] newKey = new byte[encryptionKey.getMaterial().length];
      cc.generateSecureRandom(newKey);
      final byte[] iv = new byte[cc.getCipherSuite().getAlgorithmBlockSize()];
      cc.generateSecureRandom(iv);
      // Encryption key IV is derived from new key's IV
      final byte[] encryptionIV = EncryptedKeyVersion.deriveIV(iv);
      Encryptor encryptor = cc.createEncryptor();
      encryptor.init(encryptionKey.getMaterial(), encryptionIV);
      int keyLen = newKey.length;
      ByteBuffer bbIn = ByteBuffer.allocateDirect(keyLen);
      ByteBuffer bbOut = ByteBuffer.allocateDirect(keyLen);
      bbIn.put(newKey);
      bbIn.flip();
      encryptor.encrypt(bbIn, bbOut);
      bbOut.flip();
      byte[] encryptedKey = new byte[keyLen];
      bbOut.get(encryptedKey);
      return new EncryptedKeyVersion(
          encryptionKeyName,
          encryptionKey.getVersionName(),
          iv,
          new KeyVersion(encryptionKey.getName(), EEK, encryptedKey));
    }
コード例 #5
0
ファイル: Sender.java プロジェクト: Illarion-eV/Illarion-Java
  private void encodeCommand(@Nonnull AbstractCommand cmd) throws IOException {
    if (cmd.getId() != CommandList.CMD_KEEPALIVE) {
      log.debug("SND: {}", cmd);
    }

    buffer.clear();
    buffer.put((byte) cmd.getId());
    buffer.put((byte) (cmd.getId() ^ COMMAND_XOR_MASK));

    // keep some space for the length and the CRC
    int headerLenCRC = buffer.position();
    buffer.putShort((short) 0);
    buffer.putShort((short) 0);

    int startOfCmd = buffer.position();
    // encode command into net protocol
    cmd.encode(this);

    int length = buffer.position() - startOfCmd;
    buffer.flip();
    buffer.position(startOfCmd);
    int crc = NetComm.getCRC(buffer, length);
    buffer.position(headerLenCRC);
    buffer.putShort((short) length);
    buffer.putShort((short) crc);
    buffer.position(0);

    if (NetComm.isDumpingActive()) {
      NetComm.dump("snd => ", buffer);
      buffer.flip();
    }

    outChannel.write(buffer);
  }
コード例 #6
0
  @Test
  public void testRead() throws IOException {
    RegularFile file = regularFile(20);
    FileChannel channel = channel(file, READ);
    assertEquals(0, channel.position());

    ByteBuffer buf = buffer("1234567890");
    ByteBuffer buf2 = buffer("123457890");
    assertEquals(10, channel.read(buf));
    assertEquals(10, channel.position());

    buf.flip();
    assertEquals(10, channel.read(new ByteBuffer[] {buf, buf2}));
    assertEquals(20, channel.position());

    buf.flip();
    buf2.flip();
    file.write(20, new byte[10], 0, 10);
    assertEquals(10, channel.read(new ByteBuffer[] {buf, buf2}, 0, 2));
    assertEquals(30, channel.position());

    buf.flip();
    assertEquals(10, channel.read(buf, 5));
    assertEquals(30, channel.position());

    buf.flip();
    assertEquals(-1, channel.read(buf));
    assertEquals(30, channel.position());
  }
コード例 #7
0
ファイル: IOUtils.java プロジェクト: holmis83/jawr-main-repo
  /**
   * Copy the readable byte channel to the writable byte channel
   *
   * @param inChannel the readable byte channel
   * @param outChannel the writable byte channel
   * @throws IOException if an IOException occurs.
   */
  public static void copy(ReadableByteChannel inChannel, WritableByteChannel outChannel)
      throws IOException {

    if (inChannel instanceof FileChannel) {
      ((FileChannel) inChannel).transferTo(0, ((FileChannel) inChannel).size(), outChannel);
    } else {

      final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
      try {

        while (inChannel.read(buffer) != -1) {
          // prepare the buffer to be drained
          buffer.flip();
          // write to the channel, may block
          outChannel.write(buffer);
          // If partial transfer, shift remainder down
          // If buffer is empty, same as doing clear()
          buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
          outChannel.write(buffer);
        }
      } finally {
        IOUtils.close(inChannel);
        IOUtils.close(outChannel);
      }
    }
  }
コード例 #8
0
  @Override
  public int read(ScatteringByteChannel channel) throws IOException {
    int read = 0;
    if (sizeBuffer.hasRemaining()) {
      int num = channel.read(sizeBuffer);
      if (num < 0) {
        throw new IOException("end-of-stream reached");
      }
      read += num;
      if (sizeBuffer.hasRemaining()) {
        return read;
      } else {
        sizeBuffer.flip();
        size = sizeBuffer.getInt();
        contentBuffer = ByteBuffer.allocate(size);
      }
    }

    if (!sizeBuffer.hasRemaining()) {
      int num = channel.read(contentBuffer);
      if (num < 0) {
        throw new IOException("end-of-stream reached");
      }
      read += num;
      if (!contentBuffer.hasRemaining()) {
        contentBuffer.flip();
        complete = true;
      }
    }
    return read;
  }
コード例 #9
0
ファイル: client.java プロジェクト: sheldonj22/NetIO
  /**
   * examines buffer for a complete message
   *
   * @return the message or null
   */
  byte[] process() {

    running.put(b);
    // Read at leat 4 bytes - convert four bytes to expeceted bytes for first message
    if (begin && running.position() >= 4) {
      byte[] len = {running.get(0), running.get(1), running.get(2), running.get(3)};
      expectedBytes = client.byteArrayToInt(len);
      begin = false;
      running.flip();
      running.position(4);
      running.compact();

    } else {
    }
    ;

    if (running.position() >= this.expectedBytes) {
      running.flip();
      byte[] mess = new byte[expectedBytes];
      running.get(mess);
      running.position(expectedBytes);
      // out ("LIM: "+running.limit() +"   POS: "+running.position());
      running.compact();
      begin = true;
      // out("2-LIM: "+running.limit() +"   POS: "+running.position());

      return mess;
    } else return null;
  }
コード例 #10
0
ファイル: Server.java プロジェクト: gitter-badger/js-collider
    public int onMessageReceived(RetainableByteBuffer msg) {
      final int messages = ++m_messages;
      if (messages < REPLY_MESSAGES) {
        final ByteBuffer reply = ByteBuffer.allocateDirect(msg.remaining());
        msg.get(reply);
        reply.flip();
        final int rc = m_session.sendData(reply);
        if (rc < 0) throw new AssertionError();
        return 0;
      } else if (messages == REPLY_MESSAGES) {
        final int messageLength = msg.remaining();
        assert (messageLength >= 8);
        final ByteBuffer reply = ByteBuffer.allocateDirect(messageLength);
        msg.get(reply);
        reply.flip();
        reply.putInt(4, -1);

        int rc = m_session.sendData(reply);
        if (rc < 0) throw new AssertionError();

        rc = m_session.closeConnection();
        if (rc != 0) throw new AssertionError();

        rc = m_session.sendData(reply);
        if (rc != -1) throw new AssertionError();

        return -1;
      } else {
        /* Listener should not receive any messages
         * after Session.closeConnection() call.
         */
        throw new AssertionError();
      }
    }
コード例 #11
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());
  }
コード例 #12
0
  public static void writeParition()
      throws IOException, TableDoesNotExistException, InvalidPathException,
          FileAlreadyExistException, TException {
    RawTable rawTable = sTachyonClient.getRawTable(sTablePath);

    LOG.info("Writing data...");
    for (int column = 0; column < COLS; column++) {
      RawColumn rawColumn = rawTable.getRawColumn(column);
      if (!rawColumn.createPartition(0)) {
        CommonUtils.runtimeException(
            "Failed to create partition in table " + sTablePath + " under column " + column);
      }

      ByteBuffer buf = ByteBuffer.allocate(80);
      buf.order(ByteOrder.nativeOrder());
      for (int k = 0; k < 20; k++) {
        buf.putInt(k);
      }
      buf.flip();
      CommonUtils.printByteBuffer(LOG, buf);
      buf.flip();

      TachyonFile tFile = rawColumn.getPartition(0);
      OutStream os = tFile.createOutStream(sWriteType);
      os.write(buf);
      os.close();
    }
  }
コード例 #13
0
ファイル: CopyUtil.java プロジェクト: RvonMassow/xDoc
 public String copy(String basePath, ImageRef source, String targetDirName) {
   try {
     ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
     Resource res = source.eResource();
     URI uri = source.eResource().getURI();
     URI inPath = URI.createURI(source.getPath()).resolve(uri);
     URI outPath =
         URI.createURI(source.getPath())
             .resolve(URI.createFileURI(new File(targetDirName).getAbsolutePath()));
     ReadableByteChannel inChannel =
         Channels.newChannel(res.getResourceSet().getURIConverter().createInputStream(inPath));
     WritableByteChannel outChannel =
         Channels.newChannel(res.getResourceSet().getURIConverter().createOutputStream(outPath));
     while (inChannel.read(buffer) != -1) {
       buffer.flip();
       outChannel.write(buffer);
       buffer.compact();
     }
     buffer.flip();
     while (buffer.hasRemaining()) {
       outChannel.write(buffer);
     }
     outChannel.close();
     return outPath.toFileString();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     logger.error(e);
     return null;
   }
 }
コード例 #14
0
  private boolean wrap() {
    SSLEngineResult wrapResult;

    try {
      wrapSrc.flip();
      wrapResult = engine.wrap(wrapSrc, wrapDst);
      wrapSrc.compact();
    } catch (SSLException exc) {
      this.onHandshakeFailure(exc);
      return false;
    }

    switch (wrapResult.getStatus()) {
      case OK:
        if (wrapDst.position() > 0) {
          wrapDst.flip();
          this.onOutboundData(wrapDst);
          wrapDst.compact();
        }
        break;

      case BUFFER_UNDERFLOW:
        // try again later
        break;

      case BUFFER_OVERFLOW:
        throw new IllegalStateException("failed to wrap");

      case CLOSED:
        this.onClosed();
        return false;
    }

    return true;
  }
コード例 #15
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);
      }
    }
  }
コード例 #16
0
  // 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();
  }
コード例 #17
0
  @Test
  public void testAppend() throws IOException {
    RegularFile file = regularFile(0);
    FileChannel channel = channel(file, WRITE, APPEND);
    assertEquals(0, channel.position());

    ByteBuffer buf = buffer("1234567890");
    ByteBuffer buf2 = buffer("1234567890");

    assertEquals(10, channel.write(buf));
    assertEquals(10, channel.position());

    buf.flip();
    channel.position(0);
    assertEquals(20, channel.write(new ByteBuffer[] {buf, buf2}));
    assertEquals(30, channel.position());

    buf.flip();
    buf2.flip();
    channel.position(0);
    assertEquals(20, channel.write(new ByteBuffer[] {buf, buf2}, 0, 2));
    assertEquals(50, channel.position());

    buf.flip();
    channel.position(0);
    assertEquals(10, channel.write(buf, 5));
    assertEquals(60, channel.position());

    buf.flip();
    channel.position(0);
    assertEquals(10, channel.transferFrom(new ByteBufferChannel(buf), 0, 10));
    assertEquals(70, channel.position());
  }
コード例 #18
0
  void isReadable(SelectionKey k) {
    EventableChannel ec = (EventableChannel) k.attachment();
    long b = ec.getBinding();

    if (ec.isWatchOnly()) {
      if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null);
    } else {
      myReadBuffer.clear();

      try {
        ec.readInboundData(myReadBuffer);
        myReadBuffer.flip();
        if (myReadBuffer.limit() > 0) {
          if (ProxyConnections != null) {
            EventableChannel target = ProxyConnections.get(b);
            if (target != null) {
              ByteBuffer myWriteBuffer = ByteBuffer.allocate(myReadBuffer.limit());
              myWriteBuffer.put(myReadBuffer);
              myWriteBuffer.flip();
              target.scheduleOutboundData(myWriteBuffer);
            } else {
              eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
            }
          } else {
            eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
          }
        }
      } catch (IOException e) {
        UnboundConnections.add(b);
      }
    }
  }
コード例 #19
0
ファイル: TesterA.java プロジェクト: jack-luj/NettyServer
 public static String getRegSuccessStr() {
   String start =
       "23 23 00 4D 01 55 D2 0F E7 13 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 BE E2 58 31 32 33 34 35 36 37 38 39 31 39 39 "; // 包头和size
   String[] replace = {"31", "32", "33", "34", "35", "36", "37", "38", "39"};
   // 根据注册校验结果,形成返回数据包
   StringBuilder sb = new StringBuilder();
   sb.append(start);
   // 随机生成vin
   for (int j = 0; j < 17; j++) {
     int max = 8;
     int min = 0;
     Random random = new Random();
     int s = random.nextInt(max) % (max - min + 1) + min;
     sb.append(replace[s] + " ");
   }
   ByteBuffer bb = ByteBuffer.allocate(1024);
   String byteString = sb.toString();
   String[] command = byteString.split(" ");
   byte[] abc = new byte[command.length];
   for (int i = 0; i < command.length; i++) {
     abc[i] = Integer.valueOf(command[i], 16).byteValue();
   }
   bb.put(abc);
   for (int i = 0; i < 15; i++) bb.put(Integer.valueOf("00", 16).byteValue());
   bb.flip();
   byte[] bodyData = getBytesFromByteBuffer(bb); // 不包含checkSum的字节数组
   ByteBuffer re = ByteBuffer.allocate(1024);
   re.put(bodyData);
   re.put(getCheckSum(bodyData));
   re.flip();
   return bytes2hex(getBytesFromByteBuffer(re));
 }
コード例 #20
0
ファイル: NeoStore.java プロジェクト: soluvas/neo4j
 private void insertRecord(int recordPosition, long value) throws IOException {
   try {
     FileChannel channel = getFileChannel();
     long previousPosition = channel.position();
     channel.position(RECORD_SIZE * recordPosition);
     int trail = (int) (channel.size() - channel.position());
     ByteBuffer trailBuffer = null;
     if (trail > 0) {
       trailBuffer = ByteBuffer.allocate(trail);
       channel.read(trailBuffer);
       trailBuffer.flip();
     }
     ByteBuffer buffer = ByteBuffer.allocate(RECORD_SIZE);
     buffer.put(Record.IN_USE.byteValue());
     buffer.putLong(value);
     buffer.flip();
     channel.position(RECORD_SIZE * recordPosition);
     channel.write(buffer);
     if (trail > 0) {
       channel.write(trailBuffer);
     }
     channel.position(previousPosition);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #21
0
  @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));
  }
コード例 #22
0
ファイル: CommonUtils.java プロジェクト: harveyfeng/tachyon
 public static ByteBuffer cloneByteBuffer(ByteBuffer buf) {
   ByteBuffer ret = ByteBuffer.allocate(buf.limit() - buf.position());
   ret.put(buf);
   ret.flip();
   buf.flip();
   return ret;
 }
コード例 #23
0
ファイル: MTSUtils.java プロジェクト: GreatArcStudios/jcodec
    public void readTsFile(SeekableByteChannel ch) throws IOException {
      ch.position(0);
      ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);

      for (long pos = ch.position(); ch.read(buf) != -1; pos = ch.position()) {
        buf.flip();
        while (buf.hasRemaining()) {
          ByteBuffer tsBuf = NIOUtils.read(buf, 188);
          pos += 188;
          Assert.assertEquals(0x47, tsBuf.get() & 0xff);
          int guidFlags = ((tsBuf.get() & 0xff) << 8) | (tsBuf.get() & 0xff);
          int guid = (int) guidFlags & 0x1fff;

          int payloadStart = (guidFlags >> 14) & 0x1;
          int b0 = tsBuf.get() & 0xff;
          int counter = b0 & 0xf;
          if ((b0 & 0x20) != 0) {
            NIOUtils.skip(tsBuf, tsBuf.get() & 0xff);
          }
          boolean sectionSyntax =
              payloadStart == 1 && (getRel(tsBuf, getRel(tsBuf, 0) + 2) & 0x80) == 0x80;
          if (sectionSyntax) {
            NIOUtils.skip(tsBuf, tsBuf.get() & 0xff);
          }
          if (!onPkt(guid, payloadStart == 1, tsBuf, pos - tsBuf.remaining())) return;
        }
        buf.flip();
      }
    }
コード例 #24
0
ファイル: EmbeddedOpenDS.java プロジェクト: casell/openam-all
 /**
  * Helper Method to Copy from one Byte Channel to another.
  *
  * @param from
  * @param to
  * @throws IOException
  */
 protected static void channelCopy(ReadableByteChannel from, WritableByteChannel to)
     throws IOException {
   ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
   try {
     // Read
     while (from.read(buffer) != -1) {
       buffer.flip();
       to.write(buffer);
       buffer.compact();
     }
     // Flip the Buffer
     buffer.flip();
     // Write
     while (buffer.hasRemaining()) {
       to.write(buffer);
     } // End of While Loop
   } finally {
     // Handle In Channel Closure
     if (from != null) {
       try {
         from.close();
       } catch (Exception ex) {
         // No handling required
       }
     }
     // Handle Out Channel Closure
     if (to != null) {
       try {
         to.close();
       } catch (Exception ex) {
         // No handling required
       }
     }
   } // End of Finally
 }
コード例 #25
0
  @Test
  public void testCleanNativeMem() throws Exception {
    ByteBuffer bb = ByteBuffer.allocateDirect(10240);
    bb.putInt(3344);
    bb.flip();
    int c = bb.getInt();
    assertEquals(3344, c);

    cleanNativeMem(bb);
    cleanNativeMem(bb);
    cleanNativeMem(bb);

    bb.flip();
    c = bb.getInt();
    if (3344 != c) {
      System.out.println("It's OK: " + c);
    }

    bb.clear();
    bb.putInt(6677);

    bb.flip();
    c = bb.getInt();
    assertEquals(6677, c);
  }
コード例 #26
0
  /**
   * Reads bytes from the socket.
   *
   * @param buf byte buffer receiving the bytes
   * @param offset offset into the buffer
   * @param length number of bytes to read
   * @return number of bytes read or -1
   * @exception throws ClientDisconnectException if the connection is dropped
   */
  @Override
  public int read(byte[] buf, int offset, int length) throws IOException {
    try {
      SocketChannel s = _s;

      if (s == null) {
        return -1;
      }

      int remaining = _readBuffer.remaining();
      if (remaining <= 0) {
        _readBuffer.clear();

        if (s.read(_readBuffer) < 0) {
          _readBuffer.flip();
          return -1;
        }

        _readBuffer.flip();

        remaining = _readBuffer.remaining();
      }

      int sublen = Math.min(remaining, length);

      _readBuffer.get(buf, offset, sublen);

      int readLength = sublen;

      if (readLength >= 0) {
        _totalReadBytes += readLength;
      }

      return readLength;
    } catch (InterruptedIOException e) {
      if (_throwReadInterrupts) throw e;

      log.log(Level.FINEST, e.toString(), e);
    } catch (IOException e) {
      if (_throwReadInterrupts) {
        throw e;
      }

      if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, e.toString(), e);
      } else {
        log.finer(e.toString());
      }
      // server/0611
      /*
      try {
        close();
      } catch (IOException e1) {
      }
      */
    }

    return -1;
  }
コード例 #27
0
  protected boolean handleSSLHandshake2() throws IOException {
    // We need to make sure the handshake process finished as a whole
    //		boolean proceed = false;
    SSLEngineResult engineResult = null;
    isHanshakeDone = false;
    while (true) {
      switch (engine.getHandshakeStatus()) {
        case NOT_HANDSHAKING:
        case FINISHED:
          isHanshakeDone = true;
          return true;
        case NEED_TASK:
          Executor exec = Executors.newSingleThreadExecutor();
          Runnable task;
          while ((task = engine.getDelegatedTask()) != null) {
            exec.execute(task);
          }
          continue;
        case NEED_WRAP:
          // We need to call a wrap on the engine
          appSendBuffer.flip();
          engineResult = engine.wrap(appSendBuffer, netSendBuffer);
          appSendBuffer.compact();
          if (engineResult.getStatus() == Status.BUFFER_OVERFLOW
              || engineResult.getStatus()
                  == Status
                      .OK) { // The enigne sys we need to flush the current buffer into the network
            // So just set the selector to the write mode
            channel.register(selector, SelectionKey.OP_WRITE);
            selector.wakeup();
            // System.out.println("Handshake wants to do a write ");
            return false;
          } else if (engineResult.getStatus() == Status.CLOSED) {
            throw new IOException("Connection closed");
          } else {
            continue;
          }

        case NEED_UNWRAP:
          // We need to call unwarap method of the engine
          netRecvBuffer.flip();
          engineResult = engine.unwrap(netRecvBuffer, appRecvBuffer);
          netRecvBuffer.compact();
          // System.out.println(engine.isInboundDone());
          if (engineResult.getStatus() == Status.BUFFER_UNDERFLOW) {
            if (!engine.isInboundDone()) {
              channel.register(selector, SelectionKey.OP_READ);
              selector.wakeup();
              // System.out.println("Handshake wants to do a read ");
              return false;
            } else continue;
          } else if (engineResult.getStatus() == Status.CLOSED) {
            throw new IOException("Connection closed");
          } else {
            continue;
          }
      }
    }
  }
コード例 #28
0
  public Object readObject(Connection connection) throws IOException {
    SocketChannel socketChannel = this.socketChannel;
    if (socketChannel == null) throw new SocketException("Connection is closed.");

    if (currentObjectLength == 0) {
      // Read the length of the next object from the socket.
      int lengthLength = serialization.getLengthLength();
      if (readBuffer.remaining() < lengthLength) {
        readBuffer.compact();
        int bytesRead = socketChannel.read(readBuffer);
        readBuffer.flip();
        if (bytesRead == -1) throw new SocketException("Connection is closed.");
        lastReadTime = System.currentTimeMillis();

        if (readBuffer.remaining() < lengthLength) return null;
      }
      currentObjectLength = serialization.readLength(readBuffer);

      if (currentObjectLength <= 0)
        throw new KryoNetException("Invalid object length: " + currentObjectLength);
      if (currentObjectLength > readBuffer.capacity())
        throw new KryoNetException(
            "Unable to read object larger than read buffer: " + currentObjectLength);
    }

    int length = currentObjectLength;
    if (readBuffer.remaining() < length) {
      // Fill the tcpInputStream.
      readBuffer.compact();
      int bytesRead = socketChannel.read(readBuffer);
      readBuffer.flip();
      if (bytesRead == -1) throw new SocketException("Connection is closed.");
      lastReadTime = System.currentTimeMillis();

      if (readBuffer.remaining() < length) return null;
    }
    currentObjectLength = 0;

    int startPosition = readBuffer.position();
    int oldLimit = readBuffer.limit();
    readBuffer.limit(startPosition + length);
    Object object;
    try {
      object = serialization.read(connection, readBuffer);
    } catch (Exception ex) {
      throw new KryoNetException("Error during deserialization.", ex);
    }

    readBuffer.limit(oldLimit);
    if (readBuffer.position() - startPosition != length)
      throw new KryoNetException(
          "Incorrect number of bytes ("
              + (startPosition + length - readBuffer.position())
              + " remaining) used to deserialize object: "
              + object);

    return object;
  }
コード例 #29
0
ファイル: Server.java プロジェクト: rikima/stratosphere
    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;
      }
    }
コード例 #30
0
ファイル: WsFrameBase.java プロジェクト: xiaobao2110/tomcat
  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;
  }