コード例 #1
1
ファイル: Util.java プロジェクト: saruna/incubator-trafodion
  static void toHexString(String header, ByteBuffer buf) {
    sb.delete(0, sb.length());

    for (int index = 0; index < buf.limit(); index++) {
      String hex = Integer.toHexString(0x0100 + (buf.get(index) & 0x00FF)).substring(1);
      sb.append((hex.length() < 2 ? "0" : "") + hex + " ");
    }
    LOG.debug(
        "hex->"
            + header
            + ": position,limit,capacity "
            + buf.position()
            + ","
            + buf.limit()
            + ","
            + buf.capacity());
    LOG.debug("hex->" + sb.toString());
  }
コード例 #2
0
 private void recv(SocketChannel sc, ClientInfo ci) throws IOException {
   ci.channel.read(ci.inBuf);
   ByteBuffer tmpBuf = ci.inBuf.duplicate();
   tmpBuf.flip();
   int bytesProcessed = 0;
   boolean doneLoop = false;
   while (!doneLoop) {
     byte b;
     try {
       b = tmpBuf.get();
     } catch (BufferUnderflowException bue) {
       // Processed all data in buffer
       ci.inBuf.clear();
       doneLoop = true;
       break;
     }
     switch (b) {
       case TypeServerConstants.WELCOME:
         bytesProcessed++;
         break;
       case TypeServerConstants.GET_STRING_REQUEST:
         bytesProcessed++;
         if (ci.outputPending) {
           // Client is backed up. We can't append to
           // the byte buffer because it's in the wrong
           // state. We could allocate another buffer
           // here and change our send method to know
           // about multiple buffers, but we'll just
           // assume that the client is dead
           break;
         }
         ci.outBuf.put(TypeServerConstants.GET_STRING_RESPONSE);
         ByteBuffer strBuf = encoder.encode(testString);
         ci.outBuf.putShort((short) strBuf.remaining());
         ci.outBuf.put(strBuf);
         ci.outBuf.flip();
         send(sc, ci);
         break;
       case TypeServerConstants.GET_STRING_RESPONSE:
         int startPos = tmpBuf.position();
         try {
           int nBytes = tmpBuf.getInt();
           byte[] buf = new byte[nBytes];
           tmpBuf.get(buf);
           bytesProcessed += buf.length + 5;
           String s = new String(buf);
           // Send the string to the GUI
           break;
         } catch (BufferUnderflowException bue) {
           // Processed all available data
           ci.inBuf.position(ci.inBuf.position() + bytesProcessed);
           doneLoop = true;
         }
         break;
     }
   }
 }
コード例 #3
0
  /** {@inheritDoc} */
  @Nullable
  @Override
  public GridClientMessage decode(GridNioSession ses, ByteBuffer buf)
      throws IOException, GridException {
    ParserState state = ses.removeMeta(PARSER_STATE_META_NAME);

    if (state == null) state = new ParserState();

    PacketType type = state.packetType();

    if (type == null) {
      byte hdr = buf.get(buf.position());

      switch (hdr) {
        case MEMCACHE_REQ_FLAG:
          state.packet(new GridTcpRestPacket());
          state.packetType(PacketType.MEMCACHE);

          break;
        case GRIDGAIN_REQ_FLAG:
          // Skip header.
          buf.get();

          state.packetType(PacketType.GRIDGAIN);

          break;

        default:
          throw new IOException(
              "Failed to parse incoming packet (invalid packet start) [ses="
                  + ses
                  + ", b="
                  + Integer.toHexString(hdr & 0xFF)
                  + ']');
      }
    }

    GridClientMessage result = null;

    switch (state.packetType()) {
      case MEMCACHE:
        result = parseMemcachePacket(ses, buf, state);

        break;
      case GRIDGAIN:
        result = parseCustomPacket(ses, buf, state);

        break;
    }

    if (result == null)
      // Packet was not fully parsed yet.
      ses.addMeta(PARSER_STATE_META_NAME, state);

    return result;
  }
コード例 #4
0
ファイル: Util.java プロジェクト: saruna/incubator-trafodion
 static byte[] extractByteString(ByteBuffer buf) {
   int len = buf.getInt();
   byte[] str = null;
   if (len > 0) {
     str = new byte[len];
     buf.get(str, 0, len);
     buf.get(); // trailing null
   } else str = new byte[0];
   return str;
 }
コード例 #5
0
ファイル: Util.java プロジェクト: saruna/incubator-trafodion
 static String extractString(ByteBuffer buf) throws java.io.UnsupportedEncodingException {
   int len = buf.getInt();
   byte[] str = null;
   if (len > 0) {
     str = new byte[len - 1];
     ;
     buf.get(str, 0, len - 1);
     buf.get(); // trailing null
   } else str = new byte[0];
   return new String(str, "UTF-8");
 }
コード例 #6
0
ファイル: TCPSock.java プロジェクト: sherwinyu/class
  /**
   * sends data from buffer.
   *
   * <p>precondition: sendbb is in put mode post condition: sendbb is in put mode
   */
  private void sendFromBuffer() {
    aa(this, isSender(), "nonsender can't write");
    aa(this, isConnected() || isClosurePending(), "needs to be established can't write");

    // switch sendbb to get mode
    sendbb.flip();
    p(this, 3, "Sending from buffer. bb flipped.");
    int payloadLength = Math.min(Transport.MAX_PAYLOAD_SIZE, sendbb.limit());
    p(this, 4, "Max Payload size: " + Transport.MAX_PAYLOAD_SIZE);
    p(this, 4, "payloadlen: " + payloadLength);
    dumpState(4);

    if (roomForPacket(payloadLength) && payloadLength > 0) {
      byte[] payload = new byte[payloadLength];
      sendbb.get(payload);

      Transport t = makeTransport(Transport.DATA, seqNum, payload);
      tcpMan.sendData(this.tsid, t);

      p(this, 3, "Write: converting to packet: " + TCPManager.bytesToString(payload));

      // only increment the seqNum if a packet is sent
      seqNum += payloadLength;
    }

    // switch back to put mode
    sendbb.compact();
    dumpState(4);
    if (isClosurePending() && sendbb.position() == 0) release();
  }
コード例 #7
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;
 }
コード例 #8
0
ファイル: Util.java プロジェクト: saruna/incubator-trafodion
 static byte[] extractByteArray(ByteBuffer buf) {
   int len = buf.getInt();
   if (len > 0) {
     byte[] a = new byte[len];
     buf.get(a, 0, len);
     return a;
   } else return new byte[0];
 }
コード例 #9
0
 public final void unserialise(final byte[] data) {
   final ByteBuffer bb = ByteBuffer.wrap(data);
   this.m_id = bb.getInt();
   this.m_isChallengeGoal = (bb.get() == 1);
   try {
     final byte[] targetPosition = new byte[bb.getInt()];
     bb.get(targetPosition);
     this.m_targetPosition = new String(targetPosition, "UTF-8").intern();
     this.m_isCountDownJauge = (bb.get() == 1);
     this.m_jaugeMaxValue = bb.getInt();
     final byte[] jaugeVarName = new byte[bb.getInt()];
     bb.get(jaugeVarName);
     this.m_jaugeVarName = new String(jaugeVarName, "UTF-8").intern();
   } catch (UnsupportedEncodingException e) {
     ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e);
   }
 }
コード例 #10
0
ファイル: Error_t.java プロジェクト: adoggie/Koala-Messaging
 public boolean unmarshall(ByteBuffer d) {
   boolean r = false;
   try {
     byte v_1 = d.get();
     this.succ = v_1 == 0 ? false : true;
     this.code = d.getInt();
     int v_2 = d.getInt();
     byte[] _sb_3 = new byte[v_2];
     d.get(_sb_3);
     this.msg = new String(_sb_3);
   } catch (Exception e) {
     tce.RpcCommunicator.instance().getLogger().error(e.getMessage());
     r = false;
     return r;
   }
   return true;
 }
コード例 #11
0
ファイル: NCCPConnection.java プロジェクト: WU-ARL/RLI
 public static byte[] getNBOPort(short p) {
   ByteBuffer buf = ByteBuffer.allocate(2);
   buf.putShort((short) p);
   buf.order(ByteOrder.BIG_ENDIAN);
   buf.rewind();
   byte[] rtn = new byte[2];
   buf.get(rtn);
   return rtn;
 }
コード例 #12
0
 public final void unserialise(final byte[] data) {
   final ByteBuffer bb = ByteBuffer.wrap(data);
   this.m_id = bb.getInt();
   this.m_order = bb.get();
   this.m_gfx = bb.getInt();
   final byte[] cdata = new byte[bb.getInt()];
   bb.get(cdata);
   try {
     this.m_criterion = new String(cdata, "UTF-8").intern();
   } catch (UnsupportedEncodingException e) {
     ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e);
   }
   this.m_success = (bb.get() == 1);
   this.m_itemId = bb.getInt();
   this.m_itemQty = bb.getShort();
   this.m_xp = bb.getInt();
   this.m_kama = bb.getInt();
   this.m_guildPoints = bb.getInt();
 }
コード例 #13
0
ファイル: TCPSock.java プロジェクト: sherwinyu/class
  /**
   * Read from the socket up to len bytes into the buffer buf starting at position pos.
   *
   * @param buf byte[] the buffer
   * @param pos int starting position in buffer
   * @param len int number of bytes to read
   * @return int on success, the number of bytes read, which may be smaller than len; on failure, -1
   */
  public int read(byte[] buf, int pos, int len) {
    aa(this, isReceiver(), "nonreceiver socket reading");
    aa(this, state == State.ESTABLISHED, "attempting to read from closed socket");

    recvbb.flip();
    int bytesCopied = Math.min(recvbb.limit(), len);
    recvbb.get(buf, pos, bytesCopied);
    recvbb.compact();

    return bytesCopied;
  }
コード例 #14
0
  static void testMixed(Charset cs) throws Throwable {
    CharsetDecoder dec =
        cs.newDecoder()
            .onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);
    CharsetEncoder enc =
        cs.newEncoder()
            .onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);
    List<Integer> cps = new ArrayList<>(0x10000);
    int off = 0;
    int cp = 0;
    while (cp < 0x10000) {
      if (enc.canEncode((char) cp)) {
        cps.add(cp);
      }
      cp++;
    }
    Collections.shuffle(cps);
    char[] bmpCA = new char[cps.size()];
    for (int i = 0; i < cps.size(); i++) bmpCA[i] = (char) (int) cps.get(i);
    String bmpStr = new String(bmpCA);
    // getBytes(csn);
    byte[] bmpBA = bmpStr.getBytes(cs.name());
    ByteBuffer bf = enc.reset().encode(CharBuffer.wrap(bmpCA));
    byte[] baNIO = new byte[bf.limit()];
    bf.get(baNIO, 0, baNIO.length);
    if (!Arrays.equals(bmpBA, baNIO)) {
      throw new RuntimeException("getBytes(csn) failed  -> " + cs.name());
    }

    // getBytes(cs);
    bmpBA = bmpStr.getBytes(cs);
    if (!Arrays.equals(bmpBA, baNIO))
      throw new RuntimeException("getBytes(cs) failed  -> " + cs.name());

    // new String(csn);
    String strSC = new String(bmpBA, cs.name());
    String strNIO = dec.reset().decode(ByteBuffer.wrap(bmpBA)).toString();
    if (!strNIO.equals(strSC)) {
      throw new RuntimeException("new String(csn) failed  -> " + cs.name());
    }

    // new String(cs);
    strSC = new String(bmpBA, cs);
    if (!strNIO.equals(strSC)) throw new RuntimeException("new String(cs) failed  -> " + cs.name());
  }
コード例 #15
0
  /**
   * Gets a Reader for a text flavor, decoded, if necessary, for the expected charset (encoding).
   * The supported representation classes are <code>java.io.Reader</code>, <code>java.lang.String
   * </code>, <code>java.nio.CharBuffer</code>, <code>[C</code>, <code>java.io.InputStream</code>,
   * <code>java.nio.ByteBuffer</code>, and <code>[B</code>.
   *
   * <p>Because text flavors which do not support the charset parameter are encoded in a
   * non-standard format, this method should not be called for such flavors. However, in order to
   * maintain backward-compatibility, if this method is called for such a flavor, this method will
   * treat the flavor as though it supports the charset parameter and attempt to decode it
   * accordingly. See <code>selectBestTextFlavor</code> for a list of text flavors which do not
   * support the charset parameter.
   *
   * @param transferable the <code>Transferable</code> whose data will be requested in this flavor
   * @return a <code>Reader</code> to read the <code>Transferable</code>'s data
   * @exception IllegalArgumentException if the representation class is not one of the seven listed
   *     above
   * @exception IllegalArgumentException if the <code>Transferable</code> has <code>null</code> data
   * @exception NullPointerException if the <code>Transferable</code> is <code>null</code>
   * @exception UnsupportedEncodingException if this flavor's representation is <code>
   *     java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or <code>[B</code> and this
   *     flavor's encoding is not supported by this implementation of the Java platform
   * @exception UnsupportedFlavorException if the <code>Transferable</code> does not support this
   *     flavor
   * @exception IOException if the data cannot be read because of an I/O error
   * @see #selectBestTextFlavor
   * @since 1.3
   */
  public Reader getReaderForText(Transferable transferable)
      throws UnsupportedFlavorException, IOException {
    Object transferObject = transferable.getTransferData(this);
    if (transferObject == null) {
      throw new IllegalArgumentException("getTransferData() returned null");
    }

    if (transferObject instanceof Reader) {
      return (Reader) transferObject;
    } else if (transferObject instanceof String) {
      return new StringReader((String) transferObject);
    } else if (transferObject instanceof CharBuffer) {
      CharBuffer buffer = (CharBuffer) transferObject;
      int size = buffer.remaining();
      char[] chars = new char[size];
      buffer.get(chars, 0, size);
      return new CharArrayReader(chars);
    } else if (transferObject instanceof char[]) {
      return new CharArrayReader((char[]) transferObject);
    }

    InputStream stream = null;

    if (transferObject instanceof InputStream) {
      stream = (InputStream) transferObject;
    } else if (transferObject instanceof ByteBuffer) {
      ByteBuffer buffer = (ByteBuffer) transferObject;
      int size = buffer.remaining();
      byte[] bytes = new byte[size];
      buffer.get(bytes, 0, size);
      stream = new ByteArrayInputStream(bytes);
    } else if (transferObject instanceof byte[]) {
      stream = new ByteArrayInputStream((byte[]) transferObject);
    }

    if (stream == null) {
      throw new IllegalArgumentException(
          "transfer data is not Reader, String, CharBuffer, char array, InputStream, ByteBuffer, or byte array");
    }

    String encoding = getParameter("charset");
    return (encoding == null)
        ? new InputStreamReader(stream)
        : new InputStreamReader(stream, encoding);
  }
コード例 #16
0
  /** {@inheritDoc} */
  @Nullable
  @Override
  public Object decode(GridNioSession ses, ByteBuffer buf) throws IOException, GridException {
    GridTcpCommunicationMessageAdapter msg = ses.removeMeta(MSG_META_KEY);
    UUID nodeId = ses.meta(GridNioServer.DIFF_VER_NODE_ID_META_KEY);

    if (msg == null && buf.hasRemaining())
      msg = GridTcpCommunicationMessageFactory.create(buf.get());

    boolean finished = false;

    if (buf.hasRemaining()) finished = msgReader.read(nodeId, msg, buf);

    if (finished) return msg;
    else {
      ses.addMeta(MSG_META_KEY, msg);

      return null;
    }
  }
コード例 #17
0
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
コード例 #18
0
  /**
   * Parses custom packet serialized by hessian marshaller.
   *
   * @param ses Session.
   * @param buf Buffer containing not parsed bytes.
   * @param state Parser state.
   * @return Parsed message.
   * @throws IOException If packet parsing or deserialization failed.
   */
  @Nullable
  private GridClientMessage parseCustomPacket(GridNioSession ses, ByteBuffer buf, ParserState state)
      throws IOException {
    assert state.packetType() == PacketType.GRIDGAIN;
    assert state.packet() == null;

    ByteArrayOutputStream tmp = state.buffer();

    int len = state.index();

    while (buf.remaining() > 0) {
      byte b = buf.get();

      if (len == 0) {
        tmp.write(b);

        if (tmp.size() == 4) {
          len = U.bytesToInt(tmp.toByteArray(), 0);

          tmp.reset();

          if (len == 0) return PING_MESSAGE;
          else if (len < 0)
            throw new IOException(
                "Failed to parse incoming packet (invalid packet length) [ses="
                    + ses
                    + ", len="
                    + len
                    + ']');

          state.index(len);
        }
      } else {
        tmp.write(b);

        if (tmp.size() == len) return marshaller.unmarshal(tmp.toByteArray());
      }
    }

    return null;
  }
コード例 #19
0
 @Override
 public boolean unserialize(final ByteBuffer buffer) {
   final int contents_size = buffer.getShort() & 0xFFFF;
   this.contents.clear();
   this.contents.ensureCapacity(contents_size);
   for (int i = 0; i < contents_size; ++i) {
     final Content contents_element = new Content();
     final boolean contents_element_ok = contents_element.unserialize(buffer);
     if (!contents_element_ok) {
       return false;
     }
     this.contents.add(contents_element);
   }
   final boolean contentsSelection_present = buffer.get() == 1;
   if (contentsSelection_present) {
     this.contentsSelection = new ContentsSelection();
     final boolean contentsSelection_ok = this.contentsSelection.unserialize(buffer);
     if (!contentsSelection_ok) {
       return false;
     }
   } else {
     this.contentsSelection = null;
   }
   final int buyableContents_size = buffer.getShort() & 0xFFFF;
   this.buyableContents.clear();
   this.buyableContents.ensureCapacity(buyableContents_size);
   for (int j = 0; j < buyableContents_size; ++j) {
     final BuyableContent buyableContents_element = new BuyableContent();
     final boolean buyableContents_element_ok = buyableContents_element.unserialize(buffer);
     if (!buyableContents_element_ok) {
       return false;
     }
     this.buyableContents.add(buyableContents_element);
   }
   return true;
 }
コード例 #20
0
 private void readMessage(SelectionKey sk, SocketChannel readChannel, TcpAddress incomingAddress)
     throws IOException {
   // note that socket has been used
   SocketEntry entry = (SocketEntry) sockets.get(incomingAddress);
   if (entry != null) {
     entry.used();
     ByteBuffer readBuffer = entry.getReadBuffer();
     if (readBuffer != null) {
       readChannel.read(readBuffer);
       if (readBuffer.hasRemaining()) {
         readChannel.register(selector, SelectionKey.OP_READ, entry);
       } else {
         dispatchMessage(incomingAddress, readBuffer, readBuffer.capacity());
       }
       return;
     }
   }
   ByteBuffer byteBuffer = ByteBuffer.wrap(buf);
   byteBuffer.limit(messageLengthDecoder.getMinHeaderLength());
   long bytesRead = readChannel.read(byteBuffer);
   if (logger.isDebugEnabled()) {
     logger.debug("Reading header " + bytesRead + " bytes from " + incomingAddress);
   }
   MessageLength messageLength = new MessageLength(0, Integer.MIN_VALUE);
   if (bytesRead == messageLengthDecoder.getMinHeaderLength()) {
     messageLength = messageLengthDecoder.getMessageLength(ByteBuffer.wrap(buf));
     if (logger.isDebugEnabled()) {
       logger.debug("Message length is " + messageLength);
     }
     if ((messageLength.getMessageLength() > getMaxInboundMessageSize())
         || (messageLength.getMessageLength() <= 0)) {
       logger.error(
           "Received message length "
               + messageLength
               + " is greater than inboundBufferSize "
               + getMaxInboundMessageSize());
       synchronized (entry) {
         entry.getSocket().close();
         logger.info("Socket to " + entry.getPeerAddress() + " closed due to an error");
       }
     } else {
       byteBuffer.limit(messageLength.getMessageLength());
       bytesRead += readChannel.read(byteBuffer);
       if (bytesRead == messageLength.getMessageLength()) {
         dispatchMessage(incomingAddress, byteBuffer, bytesRead);
       } else {
         byte[] message = new byte[byteBuffer.limit()];
         byteBuffer.flip();
         byteBuffer.get(message, 0, byteBuffer.limit() - byteBuffer.remaining());
         entry.setReadBuffer(ByteBuffer.wrap(message));
       }
       readChannel.register(selector, SelectionKey.OP_READ, entry);
     }
   } else if (bytesRead < 0) {
     logger.debug("Socket closed remotely");
     sk.cancel();
     readChannel.close();
     TransportStateEvent e =
         new TransportStateEvent(
             DefaultTcpTransportMapping.this,
             incomingAddress,
             TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
             null);
     fireConnectionStateChanged(e);
   }
 }
コード例 #21
0
ファイル: HCIOTest.java プロジェクト: elambert/honeycomb
  public static void main(String[] argv) {
    if (argv.length != 3) {
      usage();
    }

    String tempFile = argv[0];
    String testFile = argv[1];
    int fileSize = Integer.valueOf(argv[2]).intValue();
    int exitcode = 0;
    int numRead;
    int numThisBuf;
    int numWritten;

    if ((fileSize <= 0) || (fileSize % 4096 != 0)) {
      System.out.println("Error: size is not a multiple of 4096!!!!!!");
      System.out.println();
      usage();
    }

    try {
      int bufSize = 4096;
      byte[] inBytes = new byte[bufSize];
      byte[] outBytes = new byte[bufSize];
      Random ioRandom = new Random(2006);
      ioRandom.nextBytes(outBytes);
      ByteBuffer inBuf = ByteBuffer.allocate(bufSize);
      ByteBuffer outBuf = ByteBuffer.wrap(outBytes);

      //
      // Loop forever
      //
      while (true) {
        //
        // Write the temporary file
        //
        FileOutputStream fos = new FileOutputStream(tempFile);
        FileChannel foc = fos.getChannel();
        numWritten = 0;
        while (numWritten < fileSize) {
          outBuf.clear(); // sets limit to capacity & position to zero
          while (outBuf.hasRemaining()) {
            numWritten += foc.write(outBuf);
          }
        }

        //
        // Move to permanent location
        //
        FileChannel srcChannel = new FileInputStream(tempFile).getChannel();
        FileChannel dstChannel = new FileOutputStream(testFile).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
        boolean success = (new File(tempFile)).delete();
        if (!success) {
          System.out.println("Warning: unable to delete temporary file");
        }

        //
        // Read and compare
        //
        FileInputStream fis = new FileInputStream(testFile);
        FileChannel fic = fis.getChannel();

        for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) {
          inBuf.rewind(); // Set the buffer position to 0
          numThisBuf = fic.read(inBuf);
          while (numThisBuf < bufSize) {
            numThisBuf += fic.read(inBuf);
          }
          numRead += bufSize;
          inBuf.rewind(); // Set the buffer position to 0
          inBuf.get(inBytes);
          boolean same = Arrays.equals(inBytes, outBytes);
          if (same = false) {
            System.out.println("Data read does not equal data written at " + numRead + " bytes");
          }
        }
      }

    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace(System.err);
      exitcode = 1;
      // break;
    } catch (SecurityException se) {
      se.printStackTrace(System.err);
      exitcode = 1;
      // break;
    } catch (Throwable t) {
      t.printStackTrace(System.err);
      exitcode = 1;
    }

    System.exit(exitcode);
  }
コード例 #22
0
  /**
   * Handles control packet.
   *
   * @param data raw packet data that arrived on control PPID.
   * @param sid SCTP stream id on which the data has arrived.
   */
  private synchronized void onCtrlPacket(byte[] data, int sid) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(data);
    int messageType = /* 1 byte unsigned integer */ 0xFF & buffer.get();

    if (messageType == MSG_CHANNEL_ACK) {
      if (logger.isDebugEnabled()) {
        logger.debug(getEndpoint().getID() + " ACK received SID: " + sid);
      }
      // Open channel ACK
      WebRtcDataStream channel = channels.get(sid);
      if (channel != null) {
        // Ack check prevents from firing multiple notifications
        // if we get more than one ACKs (by mistake/bug).
        if (!channel.isAcknowledged()) {
          channel.ackReceived();
          notifyChannelOpened(channel);
        } else {
          logger.warn("Redundant ACK received for SID: " + sid);
        }
      } else {
        logger.error("No channel exists on sid: " + sid);
      }
    } else if (messageType == MSG_OPEN_CHANNEL) {
      int channelType = /* 1 byte unsigned integer */ 0xFF & buffer.get();
      int priority = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      long reliability = /* 4 bytes unsigned integer */ 0xFFFFFFFFL & buffer.getInt();
      int labelLength = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      int protocolLength = /* 2 bytes unsigned integer */ 0xFFFF & buffer.getShort();
      String label;
      String protocol;

      if (labelLength == 0) {
        label = "";
      } else {
        byte[] labelBytes = new byte[labelLength];

        buffer.get(labelBytes);
        label = new String(labelBytes, "UTF-8");
      }
      if (protocolLength == 0) {
        protocol = "";
      } else {
        byte[] protocolBytes = new byte[protocolLength];

        buffer.get(protocolBytes);
        protocol = new String(protocolBytes, "UTF-8");
      }

      if (logger.isDebugEnabled()) {
        logger.debug(
            "!!! "
                + getEndpoint().getID()
                + " data channel open request on SID: "
                + sid
                + " type: "
                + channelType
                + " prio: "
                + priority
                + " reliab: "
                + reliability
                + " label: "
                + label
                + " proto: "
                + protocol);
      }

      if (channels.containsKey(sid)) {
        logger.error("Channel on sid: " + sid + " already exists");
      }

      WebRtcDataStream newChannel = new WebRtcDataStream(sctpSocket, sid, label, true);
      channels.put(sid, newChannel);

      sendOpenChannelAck(sid);

      notifyChannelOpened(newChannel);
    } else {
      logger.error("Unexpected ctrl msg type: " + messageType);
    }
  }
コード例 #23
0
  static void test(Charset cs, char[] bmpCA, byte[] sbBA) throws Throwable {
    String bmpStr = new String(bmpCA);
    CharsetDecoder dec =
        cs.newDecoder()
            .onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);
    CharsetEncoder enc =
        cs.newEncoder()
            .onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);

    // getBytes(csn);
    byte[] baSC = bmpStr.getBytes(cs.name());
    ByteBuffer bf = enc.reset().encode(CharBuffer.wrap(bmpCA));
    byte[] baNIO = new byte[bf.limit()];
    bf.get(baNIO, 0, baNIO.length);
    if (!Arrays.equals(baSC, baNIO))
      throw new RuntimeException("getBytes(csn) failed  -> " + cs.name());

    // getBytes(cs);
    baSC = bmpStr.getBytes(cs);
    if (!Arrays.equals(baSC, baNIO))
      throw new RuntimeException("getBytes(cs) failed  -> " + cs.name());

    // new String(csn);
    String strSC = new String(sbBA, cs.name());
    String strNIO = dec.reset().decode(ByteBuffer.wrap(sbBA)).toString();

    if (!strNIO.equals(strSC))
      throw new RuntimeException("new String(csn) failed  -> " + cs.name());

    // new String(cs);
    strSC = new String(sbBA, cs);
    if (!strNIO.equals(strSC)) throw new RuntimeException("new String(cs) failed  -> " + cs.name());

    // encode unmappable surrogates
    if (enc instanceof sun.nio.cs.ArrayEncoder && cs.contains(Charset.forName("ASCII"))) {
      if (cs.name().equals("UTF-8")
          || // utf8 handles surrogates
          cs.name().equals("CESU-8")) // utf8 handles surrogates
      return;
      enc.replaceWith(new byte[] {(byte) 'A'});
      sun.nio.cs.ArrayEncoder cae = (sun.nio.cs.ArrayEncoder) enc;

      String str = "ab\uD800\uDC00\uD800\uDC00cd";
      byte[] ba = new byte[str.length() - 2];
      int n = cae.encode(str.toCharArray(), 0, str.length(), ba);
      if (n != 6 || !"abAAcd".equals(new String(ba, cs.name())))
        throw new RuntimeException("encode1(surrogates) failed  -> " + cs.name());

      ba = new byte[str.length()];
      n = cae.encode(str.toCharArray(), 0, str.length(), ba);
      if (n != 6 || !"abAAcd".equals(new String(ba, 0, n, cs.name())))
        throw new RuntimeException("encode2(surrogates) failed  -> " + cs.name());
      str = "ab\uD800B\uDC00Bcd";
      ba = new byte[str.length()];
      n = cae.encode(str.toCharArray(), 0, str.length(), ba);
      if (n != 8 || !"abABABcd".equals(new String(ba, 0, n, cs.name())))
        throw new RuntimeException("encode3(surrogates) failed  -> " + cs.name());
      /* sun.nio.cs.ArrayDeEncoder works on the assumption that the
         invoker (StringCoder) allocates enough output buf, utf8
         and double-byte coder does not check the output buffer limit.
      ba = new byte[str.length() - 1];
      n = cae.encode(str.toCharArray(), 0, str.length(), ba);
      if (n != 7 || !"abABABc".equals(new String(ba, 0, n, cs.name()))) {
          throw new RuntimeException("encode4(surrogates) failed  -> "
                                     + cs.name());
      }
      */
    }
  }
コード例 #24
0
 @Override
 public void build(final ByteBuffer bb, final int id, final short version) {
   this.setGlobalId(id);
   if (version == 1) {
     this.m_id = bb.getInt();
     this.m_type = bb.get();
     this.m_userType = bb.get();
     this.m_autoTrigger = (bb.get() == 1);
     this.m_isChallenge = (bb.get() == 1);
     this.m_isChaos = (bb.get() == 1);
     this.m_duration = bb.getShort();
     this.m_minUsers = bb.getShort();
     this.m_maxUsers = bb.getShort();
     final long time = bb.getLong();
     if (time != 0L) {
       this.m_expirationDate = GameDate.fromLong(time);
     } else {
       this.m_expirationDate = null;
     }
     try {
       final byte[] bytes = new byte[bb.getInt()];
       bb.get(bytes);
       this.m_params = new String(bytes, "UTF-8").intern();
     } catch (UnsupportedEncodingException e) {
       ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e);
     }
     try {
       final int mappingLen = bb.getInt();
       this.m_varMapping = new String[mappingLen];
       for (int i = 0; i < mappingLen; ++i) {
         final byte[] bytes2 = new byte[bb.getInt()];
         bb.get(bytes2);
         this.m_varMapping[i] = new String(bytes2, "UTF-8").intern();
       }
     } catch (UnsupportedEncodingException e) {
       ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e);
     }
     try {
       final byte[] bytes = new byte[bb.getInt()];
       bb.get(bytes);
       this.m_joinCriterion = new String(bytes, "UTF-8").intern();
       final byte[] rewardEligibilityCriterion = new byte[bb.getInt()];
       bb.get(rewardEligibilityCriterion);
       this.m_rewardEligibilityCriterion =
           new String(rewardEligibilityCriterion, "UTF-8").intern();
     } catch (UnsupportedEncodingException e) {
       ScenarioBinaryStorable.m_logger.error((Object) "Exception", (Throwable) e);
     }
     for (int glen = bb.getInt(), i = 0; i < glen; ++i) {
       final byte[] gdata = new byte[bb.getInt()];
       bb.get(gdata);
       final ActionGroupStorable g = new ActionGroupStorable();
       g.unserialise(gdata);
       this.m_actionGroups.add(g);
     }
     for (int rlen = bb.getInt(), j = 0; j < rlen; ++j) {
       final byte[] rdata = new byte[bb.getInt()];
       bb.get(rdata);
       final RewardStorable r = new RewardStorable();
       r.unserialise(rdata);
       this.m_rewards.add(r);
     }
   } else {
     ScenarioBinaryStorable.m_logger.error(
         (Object)
             "Tentative de d\u00e9s\u00e9rialisation d'un objet avec une version non prise en charge");
   }
 }
コード例 #25
0
 @Override
 public boolean unserialize(final ByteBuffer buffer) {
   this.position = buffer.get();
   this.referenceId = buffer.getInt();
   return true;
 }
コード例 #26
0
  /**
   * Parses memcache protocol message.
   *
   * @param ses Session.
   * @param buf Buffer containing not parsed bytes.
   * @param state Current parser state.
   * @return Parsed packet.s
   * @throws IOException If packet cannot be parsed.
   * @throws GridException If deserialization error occurred.
   */
  @Nullable
  private GridClientMessage parseMemcachePacket(
      GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, GridException {
    assert state.packetType() == PacketType.MEMCACHE;
    assert state.packet() != null;
    assert state.packet() instanceof GridTcpRestPacket;

    GridTcpRestPacket req = (GridTcpRestPacket) state.packet();
    ByteArrayOutputStream tmp = state.buffer();
    int i = state.index();

    while (buf.remaining() > 0) {
      byte b = buf.get();

      if (i == 0) req.requestFlag(b);
      else if (i == 1) req.operationCode(b);
      else if (i == 2 || i == 3) {
        tmp.write(b);

        if (i == 3) {
          req.keyLength(U.bytesToShort(tmp.toByteArray(), 0));

          tmp.reset();
        }
      } else if (i == 4) req.extrasLength(b);
      else if (i >= 8 && i <= 11) {
        tmp.write(b);

        if (i == 11) {
          req.totalLength(U.bytesToInt(tmp.toByteArray(), 0));

          tmp.reset();
        }
      } else if (i >= 12 && i <= 15) {
        tmp.write(b);

        if (i == 15) {
          req.opaque(tmp.toByteArray());

          tmp.reset();
        }
      } else if (i >= HDR_LEN && i < HDR_LEN + req.extrasLength()) {
        tmp.write(b);

        if (i == HDR_LEN + req.extrasLength() - 1) {
          req.extras(tmp.toByteArray());

          tmp.reset();
        }
      } else if (i >= HDR_LEN + req.extrasLength()
          && i < HDR_LEN + req.extrasLength() + req.keyLength()) {
        tmp.write(b);

        if (i == HDR_LEN + req.extrasLength() + req.keyLength() - 1) {
          req.key(tmp.toByteArray());

          tmp.reset();
        }
      } else if (i >= HDR_LEN + req.extrasLength() + req.keyLength()
          && i < HDR_LEN + req.totalLength()) {
        tmp.write(b);

        if (i == HDR_LEN + req.totalLength() - 1) {
          req.value(tmp.toByteArray());

          tmp.reset();
        }
      }

      if (i == HDR_LEN + req.totalLength() - 1)
        // Assembled the packet.
        return assemble(ses, req);

      i++;
    }

    state.index(i);

    return null;
  }