Exemple #1
1
  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());
  }
Exemple #2
0
 static boolean check(CharsetDecoder dec, byte[] bytes, boolean direct, int[] flow) {
   int inPos = flow[0];
   int inLen = flow[1];
   int outPos = flow[2];
   int outLen = flow[3];
   int expedInPos = flow[4];
   int expedOutPos = flow[5];
   CoderResult expedCR = (flow[6] == 0) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW;
   ByteBuffer bbf;
   CharBuffer cbf;
   if (direct) {
     bbf = ByteBuffer.allocateDirect(inPos + bytes.length);
     cbf = ByteBuffer.allocateDirect((outPos + outLen) * 2).asCharBuffer();
   } else {
     bbf = ByteBuffer.allocate(inPos + bytes.length);
     cbf = CharBuffer.allocate(outPos + outLen);
   }
   bbf.position(inPos);
   bbf.put(bytes).flip().position(inPos).limit(inPos + inLen);
   cbf.position(outPos);
   dec.reset();
   CoderResult cr = dec.decode(bbf, cbf, false);
   if (cr != expedCR || bbf.position() != expedInPos || cbf.position() != expedOutPos) {
     System.out.printf("Expected(direct=%5b): [", direct);
     for (int i : flow) System.out.print(" " + i);
     System.out.println(
         "]  CR=" + cr + ", inPos=" + bbf.position() + ", outPos=" + cbf.position());
     return false;
   }
   return true;
 }
Exemple #3
0
  /**
   * 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();
  }
Exemple #4
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;
 }
Exemple #5
0
 static void printBBInfo(ByteBuffer buf) {
   LOG.debug(
       "Info : position,limit,capacity "
           + buf.position()
           + ","
           + buf.limit()
           + ","
           + buf.capacity());
 }
 public NSOutputStream(ByteBuffer bytes) {
   super((SkipInit) null);
   if (bytes == null) {
     throw new NullPointerException("bytes");
   }
   long handle = NSData.getEffectiveAddress(bytes) + bytes.position();
   initObject(init(handle, bytes.remaining()));
   addStrongRef(bytes);
 }
 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;
     }
   }
 }
  /** {@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;
  }
  /**
   * Constructs a record instance from the given {@link java.nio.ByteBuffer}. The buffer's current
   * position must be the start of the record, and will be the start of the next record when the
   * constructor returns.
   *
   * @param shapeFile the parent {@link Shapefile}.
   * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from.
   * @throws IllegalArgumentException if any argument is null or otherwise invalid.
   * @throws gov.nasa.worldwind.exception.WWRuntimeException if the record's shape type does not
   *     match that of the shapefile.
   */
  public ShapefileRecord(Shapefile shapeFile, ByteBuffer buffer) {
    if (shapeFile == null) {
      String message = Logging.getMessage("nullValue.ShapefileIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (buffer == null) {
      String message = Logging.getMessage("nullValue.BufferIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    // Save the buffer's current position.
    int pos = buffer.position();
    try {
      this.readFromBuffer(shapeFile, buffer);
    } finally {
      // Move to the end of the record.
      buffer.position(pos + this.contentLengthInBytes + RECORD_HEADER_LENGTH);
    }
  }
Exemple #10
0
 /** Initiate closure of a connection (graceful shutdown) */
 public void close() {
   p(this, 3, "Close()");
   switch (sockType) {
     case SENDER:
       state = State.SHUTDOWN;
       if (sendbb.position() == 0) release();
       break;
     case RECEIVER:
       release();
       break;
     case WELCOME:
       release();
   }
 }
 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;
 }
Exemple #12
0
 static char[] decode(byte[] bb, Charset cs, boolean testDirect, Time t) throws Exception {
   String csn = cs.name();
   CharsetDecoder dec = cs.newDecoder();
   ByteBuffer bbf;
   CharBuffer cbf;
   if (testDirect) {
     bbf = ByteBuffer.allocateDirect(bb.length);
     cbf = ByteBuffer.allocateDirect(bb.length * 2).asCharBuffer();
     bbf.put(bb);
   } else {
     bbf = ByteBuffer.wrap(bb);
     cbf = CharBuffer.allocate(bb.length);
   }
   CoderResult cr = null;
   long t1 = System.nanoTime() / 1000;
   for (int i = 0; i < iteration; i++) {
     bbf.rewind();
     cbf.clear();
     dec.reset();
     cr = dec.decode(bbf, cbf, true);
   }
   long t2 = System.nanoTime() / 1000;
   t.t = (t2 - t1) / iteration;
   if (cr != CoderResult.UNDERFLOW) {
     System.out.println("DEC-----------------");
     int pos = bbf.position();
     System.out.printf(
         "  cr=%s, bbf.pos=%d, bb[pos]=%x,%x,%x,%x%n",
         cr.toString(),
         pos,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff);
     throw new RuntimeException("Decoding err: " + csn);
   }
   char[] cc = new char[cbf.position()];
   cbf.flip();
   cbf.get(cc);
   return cc;
 }
Exemple #13
0
  private synchronized DBMessage go(DBMessage msg, ByteDecoder decoder) throws IOException {

    if (_sock == null) _open();

    {
      ByteBuffer out = msg.prepare();
      while (out.remaining() > 0) _sock.write(out);
    }

    if (_pool != null) _pool._everWorked = true;

    if (decoder == null) return null;

    ByteBuffer response = decoder._buf;

    if (response.position() != 0) throw new IllegalArgumentException();

    int read = 0;
    while (read < DBMessage.HEADER_LENGTH) read += _read(response);

    int len = response.getInt(0);
    if (len <= DBMessage.HEADER_LENGTH)
      throw new IllegalArgumentException("db sent invalid length: " + len);

    if (len > response.capacity())
      throw new IllegalArgumentException(
          "db message size is too big (" + len + ") " + "max is (" + response.capacity() + ")");

    response.limit(len);
    while (read < len) read += _read(response);

    if (read != len) throw new RuntimeException("something is wrong");

    response.flip();
    return new DBMessage(response);
  }
  /**
   * method to extract the next monitor entry from the instrumentation memory. assumes that
   * nextEntry is the offset into the byte array at which to start the search for the next entry.
   * method leaves next entry pointing to the next entry or to the end of data.
   */
  protected Monitor getNextMonitorEntry() throws MonitorException {
    Monitor monitor = null;

    // entries are always 4 byte aligned.
    if ((nextEntry % 4) != 0) {
      throw new MonitorStructureException("Entry index not properly aligned: " + nextEntry);
    }

    // protect against a corrupted shared memory region.
    if ((nextEntry < 0) || (nextEntry > buffer.limit())) {
      throw new MonitorStructureException(
          "Entry index out of bounds: nextEntry = " + nextEntry + ", limit = " + buffer.limit());
    }

    // check for the end of the buffer
    if (nextEntry == buffer.limit()) {
      lognl("getNextMonitorEntry():" + " nextEntry == buffer.limit(): returning");
      return null;
    }

    buffer.position(nextEntry);

    int entryStart = buffer.position();
    int entryLength = buffer.getInt();

    // check for valid entry length
    if ((entryLength < 0) || (entryLength > buffer.limit())) {
      throw new MonitorStructureException("Invalid entry length: entryLength = " + entryLength);
    }

    // check if last entry occurs before the eof.
    if ((entryStart + entryLength) > buffer.limit()) {
      throw new MonitorStructureException(
          "Entry extends beyond end of buffer: "
              + " entryStart = "
              + entryStart
              + " entryLength = "
              + entryLength
              + " buffer limit = "
              + buffer.limit());
    }

    if (entryLength == 0) {
      // end of data
      return null;
    }

    int nameLength = buffer.getInt();
    int vectorLength = buffer.getInt();
    byte dataType = buffer.get();
    byte flags = buffer.get();
    Units u = Units.toUnits(buffer.get());
    Variability v = Variability.toVariability(buffer.get());
    boolean supported = (flags & 0x01) != 0;

    // defend against corrupt entries
    if ((nameLength <= 0) || (nameLength > entryLength)) {
      throw new MonitorStructureException("Invalid Monitor name length: " + nameLength);
    }

    if ((vectorLength < 0) || (vectorLength > entryLength)) {
      throw new MonitorStructureException("Invalid Monitor vector length: " + vectorLength);
    }

    // read in the perfData item name, casting bytes to chars. skip the
    // null terminator
    //
    byte[] nameBytes = new byte[nameLength - 1];
    for (int i = 0; i < nameLength - 1; i++) {
      nameBytes[i] = buffer.get();
    }

    // convert name into a String
    String name = new String(nameBytes, 0, nameLength - 1);

    if (v == Variability.INVALID) {
      throw new MonitorDataException(
          "Invalid variability attribute:" + " entry index = " + perfDataItem + " name = " + name);
    }
    if (u == Units.INVALID) {
      throw new MonitorDataException(
          "Invalid units attribute: " + " entry index = " + perfDataItem + " name = " + name);
    }

    int offset;
    if (vectorLength == 0) {
      // scalar Types
      if (dataType == BasicType.LONG.intValue()) {
        offset = entryStart + entryLength - 8; /* 8 = sizeof(long) */
        buffer.position(offset);
        LongBuffer lb = buffer.asLongBuffer();
        lb.limit(1);
        monitor = new PerfLongMonitor(name, u, v, supported, lb);
        perfDataItem++;
      } else {
        // bad data types.
        throw new MonitorTypeException(
            "Invalid Monitor type:"
                + " entry index = "
                + perfDataItem
                + " name = "
                + name
                + " type = "
                + dataType);
      }
    } else {
      // vector types
      if (dataType == BasicType.BYTE.intValue()) {
        if (u != Units.STRING) {
          // only byte arrays of type STRING are currently supported
          throw new MonitorTypeException(
              "Invalid Monitor type:"
                  + " entry index = "
                  + perfDataItem
                  + " name = "
                  + name
                  + " type = "
                  + dataType);
        }

        offset = entryStart + PERFDATA_NAME_OFFSET + nameLength;
        buffer.position(offset);
        ByteBuffer bb = buffer.slice();
        bb.limit(vectorLength);
        bb.position(0);

        if (v == Variability.CONSTANT) {
          monitor = new PerfStringConstantMonitor(name, supported, bb);
        } else if (v == Variability.VARIABLE) {
          monitor = new PerfStringVariableMonitor(name, supported, bb, vectorLength - 1);
        } else {
          // Monotonically increasing byte arrays are not supported
          throw new MonitorDataException(
              "Invalid variability attribute:"
                  + " entry index = "
                  + perfDataItem
                  + " name = "
                  + name
                  + " variability = "
                  + v);
        }
        perfDataItem++;
      } else {
        // bad data types.
        throw new MonitorTypeException(
            "Invalid Monitor type:"
                + " entry index = "
                + perfDataItem
                + " name = "
                + name
                + " type = "
                + dataType);
      }
    }

    // setup index to next entry for next iteration of the loop.
    nextEntry = entryStart + entryLength;
    return monitor;
  }
 public static TableInFirstNS getRootAsTableInFirstNS(ByteBuffer _bb, TableInFirstNS obj) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (obj.__init(_bb.getInt(_bb.position()) + _bb.position(), _bb));
 }
 public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (obj.__init(_bb.getInt(_bb.position()) + _bb.position(), _bb));
 }
 public static PathSELinuxGetLabelRequest getRootAsPathSELinuxGetLabelRequest(
     ByteBuffer _bb, PathSELinuxGetLabelRequest obj) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (obj.__init(_bb.getInt(_bb.position()) + _bb.position(), _bb));
 }
 public static FileCloseResponse getRootAsFileCloseResponse(
     ByteBuffer _bb, FileCloseResponse obj) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (obj.__init(_bb.getInt(_bb.position()) + _bb.position(), _bb));
 }
Exemple #19
0
 private int _read(ByteBuffer buf) throws IOException {
   int x = _in.read(buf.array(), buf.position(), buf.remaining());
   if (x < 0) throw new IOException("connection to server closed unexpectedly");
   buf.position(buf.position() + x);
   return x;
 }
 public static SetKernelRequest getRootAsSetKernelRequest(ByteBuffer _bb) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (new SetKernelRequest()).__init(_bb.getInt(_bb.position()) + _bb.position(), _bb);
 }
Exemple #21
0
 public long write(ByteBuffer bytes) {
   long handle = NSData.getEffectiveAddress(bytes) + bytes.position();
   return write(handle, bytes.remaining());
 }
 public static MbGetInstalledRomsResponse getRootAsMbGetInstalledRomsResponse(
     ByteBuffer _bb, MbGetInstalledRomsResponse obj) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (obj.__init(_bb.getInt(_bb.position()) + _bb.position(), _bb));
 }
Exemple #23
0
 public static Stat getRootAsStat(ByteBuffer _bb, Stat obj) {
   _bb.order(ByteOrder.LITTLE_ENDIAN);
   return (obj.__init(_bb.getInt(_bb.position()) + _bb.position(), _bb));
 }