@Override
  public void write(final byte[] b, final int off, final int len) throws IOException {
    if (anyAreSet(state, FLAG_CLOSED)) {
      throw UndertowServletMessages.MESSAGES.streamIsClosed();
    }
    if (listener == null) {
      Channels.writeBlocking(channel, ByteBuffer.wrap(b, off, len));
    } else {
      if (anyAreClear(state, FLAG_READY)) {
        throw UndertowServletMessages.MESSAGES.streamNotReady();
      }
      int res;
      ByteBuffer buffer = ByteBuffer.wrap(b);
      do {
        res = channel.write(buffer);
        if (res == 0) {

          ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
          copy.put(buffer);
          copy.flip();
          this.buffer = copy;
          state = state & ~FLAG_READY;
          channel.resumeWrites();
          return;
        }
      } while (buffer.hasRemaining());
    }
  }
 public void writeToChannel(WritableByteChannel channel) throws IOException {
   channel.write(ByteBuffer.wrap(new byte[] {version}));
   channel.write(ByteBuffer.wrap(Ints.toByteArray(totalSize)));
   channel.write(ByteBuffer.wrap(Ints.toByteArray(sizePer)));
   channel.write(ByteBuffer.wrap(new byte[] {compression.getId()}));
   baseLongBuffers.writeToChannel(channel);
 }
Ejemplo n.º 3
0
  /** Tests the method to fill the Reserved Expansion Field with a velocity value. */
  @Test
  public void testPrepareREForCat062() throws Exception {

    TrackVelocity trackVelocity = new TrackVelocity((short) 1, (short) 5, 5.5);
    REForCat062 re = new REForCat062((short) 62, 5, "description", new ArrayList<DataItem>());

    ByteBuffer buffer =
        REForCat062Container.getDefaultBuffer(re.getSubTypeDescriptor(), trackVelocity);

    byte[] bytes =
        new byte[] {
          0x6, // length
          0x20, // item indicator 00100000 (only the 3rd item is present)
          0x0, 0x1, 0x0, 0x5
        }; // values of the velocity

    Assert.assertEquals(ByteBuffer.wrap(bytes), buffer);

    // another test
    trackVelocity = new TrackVelocity((short) 2, (short) 7, 5.5);
    buffer = REForCat062Container.getDefaultBuffer(re.getSubTypeDescriptor(), trackVelocity);
    bytes[3] = 0x2;
    bytes[5] = 0x7;

    Assert.assertEquals(ByteBuffer.wrap(bytes), buffer);
  }
Ejemplo n.º 4
0
  public synchronized int writenonblock(ByteList buf) throws IOException, BadDescriptorException {
    checkWritable();
    ensureWrite();

    // Ruby ignores empty syswrites
    if (buf == null || buf.length() == 0) return 0;

    if (buffer.position() != 0 && !flushWrite(false)) return 0;

    if (descriptor.getChannel() instanceof SelectableChannel) {
      SelectableChannel selectableChannel = (SelectableChannel) descriptor.getChannel();
      synchronized (selectableChannel.blockingLock()) {
        boolean oldBlocking = selectableChannel.isBlocking();
        try {
          if (oldBlocking) {
            selectableChannel.configureBlocking(false);
          }
          return descriptor.write(ByteBuffer.wrap(buf.getUnsafeBytes(), buf.begin(), buf.length()));
        } finally {
          if (oldBlocking) {
            selectableChannel.configureBlocking(oldBlocking);
          }
        }
      }
    } else {
      // can't set nonblocking, so go ahead with it...not much else we can do
      return descriptor.write(ByteBuffer.wrap(buf.getUnsafeBytes(), buf.begin(), buf.length()));
    }
  }
Ejemplo n.º 5
0
 public synchronized List<Sample> getSamples() {
   if (samples == null) {
     samples = new ArrayList<Sample>();
     long lastEnd = 0;
     for (Line sub : subs) {
       long silentTime = sub.from - lastEnd;
       if (silentTime > 0) {
         samples.add(new SampleImpl(ByteBuffer.wrap(new byte[] {0, 0})));
       } else if (silentTime < 0) {
         throw new Error("Subtitle display times may not intersect");
       }
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       try {
         dos.writeShort(sub.text.getBytes("UTF-8").length);
         dos.write(sub.text.getBytes("UTF-8"));
         dos.close();
       } catch (IOException e) {
         throw new Error("VM is broken. Does not support UTF-8");
       }
       samples.add(new SampleImpl(ByteBuffer.wrap(baos.toByteArray())));
       lastEnd = sub.to;
     }
   }
   return samples;
 }
Ejemplo n.º 6
0
 void send(byte[] data) throws IOException {
   SocketChannel channel = (SocketChannel) key.channel();
   verboseLog("TCP write", data);
   byte[] lengthArray = new byte[2];
   lengthArray[0] = (byte) (data.length >>> 8);
   lengthArray[1] = (byte) (data.length & 0xFF);
   ByteBuffer[] buffers = new ByteBuffer[2];
   buffers[0] = ByteBuffer.wrap(lengthArray);
   buffers[1] = ByteBuffer.wrap(data);
   int nsent = 0;
   key.interestOps(SelectionKey.OP_WRITE);
   try {
     while (nsent < data.length + 2) {
       if (key.isWritable()) {
         long n = channel.write(buffers);
         if (n < 0) throw new EOFException();
         nsent += (int) n;
         if (nsent < data.length + 2 && System.currentTimeMillis() > endTime)
           throw new SocketTimeoutException();
       } else blockUntil(key, endTime);
     }
   } finally {
     if (key.isValid()) key.interestOps(0);
   }
 }
 public ByteBuffer encode(final String name) throws IOException {
   if (this.charset == null) { // i.e. use default charset, see no-args constructor
     return ByteBuffer.wrap(name.getBytes(de.getEncode()));
   } else {
     return ByteBuffer.wrap(name.getBytes(this.charset));
   }
 }
Ejemplo n.º 8
0
 /**
  * This utility method creates a list of Thrift TRowResult "struct" based on an Hbase RowResult
  * object. The empty list is returned if the input is null.
  *
  * @param in Hbase RowResult object
  * @param sortColumns This boolean dictates if row data is returned in a sorted order sortColumns
  *     = True will set TRowResult's sortedColumns member which is an ArrayList of TColumn struct
  *     sortColumns = False will set TRowResult's columns member which is a map of columnName and
  *     TCell struct
  * @return Thrift TRowResult array
  */
 public static List<TRowResult> rowResultFromHBase(Result[] in, boolean sortColumns) {
   List<TRowResult> results = new ArrayList<TRowResult>();
   for (Result result_ : in) {
     if (result_ == null || result_.isEmpty()) {
       continue;
     }
     TRowResult result = new TRowResult();
     result.row = ByteBuffer.wrap(result_.getRow());
     if (sortColumns) {
       result.sortedColumns = new ArrayList<TColumn>();
       for (Cell kv : result_.rawCells()) {
         result.sortedColumns.add(
             new TColumn(
                 ByteBuffer.wrap(
                     KeyValue.makeColumn(CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv))),
                 new TCell(ByteBuffer.wrap(CellUtil.cloneValue(kv)), kv.getTimestamp())));
       }
     } else {
       result.columns = new TreeMap<ByteBuffer, TCell>();
       for (Cell kv : result_.rawCells()) {
         result.columns.put(
             ByteBuffer.wrap(
                 KeyValue.makeColumn(CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv))),
             new TCell(ByteBuffer.wrap(CellUtil.cloneValue(kv)), kv.getTimestamp()));
       }
     }
     results.add(result);
   }
   return results;
 }
  @Override
  protected void eol(byte[] b, int len) throws IOException {
    String line = charset.decode(ByteBuffer.wrap(b, 0, len)).toString();
    // line = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(b, 0, len)).toString();

    // trim off CR/LF from the end
    line = trimEOL(line);

    Pattern patternWarnings = Pattern.compile(".*\\d+\\sWarning\\(s\\).*");
    Pattern patternErrors = Pattern.compile(".*\\d+\\sError\\(s\\).*");

    Matcher mWarnings = patternWarnings.matcher(line);
    Matcher mErrors = patternErrors.matcher(line);

    if (mWarnings.matches()) { // Match the number of warnings
      String[] part = line.split(" ");
      try {
        numberOfWarnings = Integer.parseInt(part[4]);
      } catch (NumberFormatException e) {

      }
    } else if (mErrors.matches()) { // Match the number of errors
      String[] part = line.split(" ");
      try {
        numberOfErrors = Integer.parseInt(part[4]);
      } catch (NumberFormatException e) {

      }
    }

    // Write to output
    // out.write(b, 0, len);
    out.write(sjis.decode(ByteBuffer.wrap(b, 0, len)).toString().getBytes(StandardCharsets.UTF_8));
  }
Ejemplo n.º 10
0
  @Test
  public void testToString() {
    String test1 = "你好äöüS§مندرين";
    String test2 = "";
    byte[] data3 = {1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
    String test3 = new String(data3, Helper.CHARSET_UTF8);
    byte[] data1 = test1.getBytes(Helper.CHARSET_UTF8);
    byte[] data2 = test2.getBytes(Helper.CHARSET_UTF8);
    ByteBuffer bb1 = ByteBuffer.wrap(data1);
    ByteBuffer bb2 = ByteBuffer.wrap(data2);
    ByteBuffer bb3 = ByteBuffer.wrap(data3);

    assertEquals(test1, ArrayHelper.toString(data1));
    assertEquals(test2, ArrayHelper.toString(data2));
    assertEquals(test3, ArrayHelper.toString(data3));
    assertEquals(test1, ArrayHelper.toString(bb1));
    assertEquals(test2, ArrayHelper.toString(bb2));
    assertEquals(test3, ArrayHelper.toString(bb3));

    bb1.position(3);
    bb3.position(3);
    assertEquals(test1, ArrayHelper.toString(bb1));
    assertEquals(test3, ArrayHelper.toString(bb3));
    assertFalse(test1.equals(ArrayHelper.toStringP(bb1)));
    assertFalse(test3.equals(ArrayHelper.toStringP(bb3)));
    String test =
        new String(new byte[] {4, 5, 6, 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1}, Helper.CHARSET_UTF8);
    assertTrue(test.equals(ArrayHelper.toStringP(bb3)));
    test = test1.substring(1);
    assertTrue(test.equals(ArrayHelper.toStringP(bb1)));
  }
Ejemplo n.º 11
0
 @Test
 public void testMd5() {
   System.out.println(
       ArrayHelper.toHexString(
           ArrayHelper.md5P(ByteBuffer.wrap("Wang_Bo.jpg".getBytes(Helper.CHARSET_UTF8)))));
   assertArrayEquals(
       new byte[] {
         (byte) 0x8e,
         (byte) 0xf9,
         (byte) 0x3b,
         (byte) 0x78,
         (byte) 0xdc,
         (byte) 0x67,
         (byte) 0x01,
         (byte) 0x9c,
         (byte) 0xd2,
         (byte) 0x63,
         (byte) 0xd1,
         (byte) 0x01,
         (byte) 0x16,
         (byte) 0xaa,
         (byte) 0x50,
         (byte) 0x05
       },
       ArrayHelper.md5P(ByteBuffer.wrap("Wang_Bo.jpg".getBytes(Helper.CHARSET_UTF8))));
 }
Ejemplo n.º 12
0
 @Test
 public void testReadAndWriteCaptureChannels() throws IOException {
   String blobName = "test-read-and-write-capture-channels-blob";
   BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build();
   byte[] stringBytes;
   BlobWriteChannel writer = storage.writer(blob);
   stringBytes = BLOB_STRING_CONTENT.getBytes(UTF_8);
   writer.write(ByteBuffer.wrap(BLOB_BYTE_CONTENT));
   RestorableState<BlobWriteChannel> writerState = writer.capture();
   BlobWriteChannel secondWriter = writerState.restore();
   secondWriter.write(ByteBuffer.wrap(stringBytes));
   secondWriter.close();
   ByteBuffer readBytes;
   ByteBuffer readStringBytes;
   BlobReadChannel reader = storage.reader(blob.blobId());
   reader.chunkSize(BLOB_BYTE_CONTENT.length);
   readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length);
   reader.read(readBytes);
   RestorableState<BlobReadChannel> readerState = reader.capture();
   BlobReadChannel secondReader = readerState.restore();
   readStringBytes = ByteBuffer.allocate(stringBytes.length);
   secondReader.read(readStringBytes);
   reader.close();
   secondReader.close();
   assertArrayEquals(BLOB_BYTE_CONTENT, readBytes.array());
   assertEquals(BLOB_STRING_CONTENT, new String(readStringBytes.array(), UTF_8));
   assertTrue(storage.delete(BUCKET, blobName));
 }
 /**
  * Reads the header and returns the length of the data part.
  *
  * @param inputStream
  * @return The length of the data part
  * @throws IOException, {@link SoftEndOfStreamException} if socket closes before any length data
  *     read.
  */
 protected int readHeader(InputStream inputStream) throws IOException {
   byte[] lengthPart = new byte[this.headerSize];
   int status = read(inputStream, lengthPart, true);
   if (status < 0) {
     throw new SoftEndOfStreamException("Stream closed between payloads");
   }
   int messageLength;
   switch (this.headerSize) {
     case HEADER_SIZE_INT:
       messageLength = ByteBuffer.wrap(lengthPart).getInt();
       if (messageLength < 0) {
         throw new IllegalArgumentException("Length header:" + messageLength + " is negative");
       }
       break;
     case HEADER_SIZE_UNSIGNED_BYTE:
       messageLength = ByteBuffer.wrap(lengthPart).get() & 0xff;
       break;
     case HEADER_SIZE_UNSIGNED_SHORT:
       messageLength = ByteBuffer.wrap(lengthPart).getShort() & 0xffff;
       break;
     default:
       throw new IllegalArgumentException("Bad header size:" + headerSize);
   }
   return messageLength;
 }
Ejemplo n.º 14
0
  @Override
  protected int readHeader(InputStream inputStream) throws IOException {
    byte[] lengthPart = new byte[this.headerSize];
    try {
      int status = read(inputStream, lengthPart, true);
      if (status < 0) {
        throw new SoftEndOfStreamException("Stream closed between payloads");
      }
      int messageLength;
      switch (this.headerSize) {
        case HEADER_SIZE_INT:
          messageLength = ByteBuffer.wrap(lengthPart).order(LITTLE_ENDIAN).getInt();
          if (messageLength < 0) {
            throw new IllegalArgumentException("Length header:" + messageLength + " is negative");
          }
          break;
        case HEADER_SIZE_UNSIGNED_BYTE:
          messageLength = ByteBuffer.wrap(lengthPart).order(LITTLE_ENDIAN).get() & 0xff;
          break;
        case HEADER_SIZE_UNSIGNED_SHORT:
          messageLength = ByteBuffer.wrap(lengthPart).order(LITTLE_ENDIAN).getShort() & 0xffff;
          break;
        default:
          throw new IllegalArgumentException("Bad header size:" + headerSize);
      }

      messageLength -= headerSize; // substract header size from data
      return messageLength;
    } catch (SoftEndOfStreamException e) {
      throw e;
    } catch (IOException | RuntimeException e) {
      publishEvent(e, lengthPart, -1);
      throw e;
    }
  }
Ejemplo n.º 15
0
  public int write(byte[] buf, int off, int len) throws IOException {
    if (!ready) {
      throw ISEnotusable;
    }
    int pos = 7;
    int current = len;

    // Force a blocking read.
    if (isComplete) {
      while (current > 0) {
        int digit = current % 16;
        current = current / 16;
        chunkLength[pos--] = HexUtils.HEX[digit];
      }

      OutputWriter.flushChannel(socketChannel, ByteBuffer.wrap(chunkLength, pos + 1, 9 - pos));
    }

    int nWrite = socketChannel.write(ByteBuffer.wrap(buf, off, len));
    if (nWrite == len) {
      isComplete = true;
      OutputWriter.flushChannel(socketChannel, ByteBuffer.wrap(chunkLength, 8, 2));
      OutputWriter.flushChannel(socketChannel, end.slice());
    } else {
      isComplete = false;
    }
    return nWrite;
  }
Ejemplo n.º 16
0
  private static byte[] createTCPMsg(int opcode) {
    ByteBuffer buffer = ByteBuffer.wrap(new byte[1]);

    switch (opcode) {
      case 0:
        buffer = ByteBuffer.wrap(new byte[1]);
        buffer.put((byte) 0x00);
        break;
      case 1:
        String userName = "******";
        buffer = ByteBuffer.wrap(new byte[userName.length() + 1]);
        buffer.put((byte) 0x01);
        buffer.put(userName.getBytes(StandardCharsets.UTF_8));
        break;
      case 2:
      case 3:
      case 4:
        buffer = ByteBuffer.wrap(new byte[17]);
        buffer.put((byte) opcode);
        buffer.putLong(userId.getMostSignificantBits());
        buffer.putLong(userId.getLeastSignificantBits());
        break;
    }

    return buffer.array();
  }
Ejemplo n.º 17
0
  public static String computeHash(InputStream stream, long length) throws IOException {
    int chunkSizeForFile = (int) Math.min(HASH_CHUNK_SIZE, length);

    // buffer that will contain the head and the tail chunk, chunks will overlap if length is
    // smaller than two chunks
    byte[] chunkBytes = new byte[(int) Math.min(2 * HASH_CHUNK_SIZE, length)];

    DataInputStream in = new DataInputStream(stream);

    // first chunk
    in.readFully(chunkBytes, 0, chunkSizeForFile);

    long position = chunkSizeForFile;
    long tailChunkPosition = length - chunkSizeForFile;

    // seek to position of the tail chunk, or not at all if length is smaller than two chunks
    while (position < tailChunkPosition && (position += in.skip(tailChunkPosition - position)) >= 0)
      ;

    // second chunk, or the rest of the data if length is smaller than two chunks
    in.readFully(chunkBytes, chunkSizeForFile, chunkBytes.length - chunkSizeForFile);

    long head = computeHashForChunk(ByteBuffer.wrap(chunkBytes, 0, chunkSizeForFile));
    long tail =
        computeHashForChunk(
            ByteBuffer.wrap(chunkBytes, chunkBytes.length - chunkSizeForFile, chunkSizeForFile));

    return String.format("%016x", length + head + tail);
  }
Ejemplo n.º 18
0
  @Test
  public void testLimits() throws DeploymentException {
    Server server = startServer(PingPongEndpoint.class);

    try {

      ClientManager client = createClient();
      final Session session =
          client.connectToServer(
              new Endpoint() {
                @Override
                public void onOpen(Session session, EndpointConfig config) {
                  // do nothing.
                }
              },
              ClientEndpointConfig.Builder.create().build(),
              getURI(PingPongEndpoint.class));

      session
          .getBasicRemote()
          .sendPing(
              ByteBuffer.wrap(
                  "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
                      .getBytes()));
      try {
        session
            .getBasicRemote()
            .sendPing(
                ByteBuffer.wrap(
                    "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
                        .getBytes()));
        fail();
      } catch (IllegalArgumentException e) {
        // ignore
      }
      session
          .getBasicRemote()
          .sendPong(
              ByteBuffer.wrap(
                  "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
                      .getBytes()));
      try {
        session
            .getBasicRemote()
            .sendPong(
                ByteBuffer.wrap(
                    "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456"
                        .getBytes()));
        fail();
      } catch (IllegalArgumentException e) {
        // ignore
      }

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage(), e);
    } finally {
      stopServer(server);
    }
  }
Ejemplo n.º 19
0
  @Override
  public ByteBuffer downloadChunk(String id) throws TException {
    TimeCacheMap<Object, Object> downloaders = data.getDownloaders();
    Object obj = downloaders.get(id);
    if (obj == null) {
      throw new TException("Could not find input stream for that id");
    }

    try {
      if (obj instanceof BufferFileInputStream) {
        BufferFileInputStream is = (BufferFileInputStream) obj;
        byte[] ret = is.read();
        if (ret != null) {
          downloaders.put(id, (BufferFileInputStream) is);
          return ByteBuffer.wrap(ret);
        }
      } else {
        throw new TException("Object isn't BufferFileInputStream for " + id);
      }
    } catch (IOException e) {
      LOG.error("BufferFileInputStream read failed when downloadChunk ", e);
      throw new TException(e);
    }
    byte[] empty = {};
    return ByteBuffer.wrap(empty);
  }
Ejemplo n.º 20
0
 public boolean get(OIDType type, Attribute<?> p) {
   Attribute<?> a = map.get(type);
   if (a == null) {
     return false;
   } else if (a instanceof AttributeValueAssertion) {
     if (p == null) {
       return false;
     } else {
       int idx = list.indexOf(a);
       ByteBuffer bb = ByteBuffer.wrap(((AttributeValueAssertion) a).getValue().getArray());
       bb.order(ByteOrder.BIG_ENDIAN);
       p.parse(bb);
       list.set(idx, p);
       map.put(type, p);
       recycle.add((AttributeValueAssertion) a);
       return true;
     }
   } else if (a.getValue() instanceof ByteArray) {
     int idx = list.indexOf(a);
     ByteArray ba = (ByteArray) a.getValue();
     p.parse(ByteBuffer.wrap(ba.getArray()).order(ByteOrder.BIG_ENDIAN));
     list.set(idx, p);
     map.put(type, p);
     return true;
   } else {
     return false;
   }
 }
Ejemplo n.º 21
0
  /*
   * Create and size the buffers appropriately.
   */
  private void createBuffers() {

    /*
     * We'll assume the buffer sizes are the same
     * between client and server.
     */
    SSLSession session = clientEngine.getSession();
    int appBufferMax = session.getApplicationBufferSize();
    int netBufferMax = session.getPacketBufferSize();

    /*
     * We'll make the input buffers a bit bigger than the max needed
     * size, so that unwrap()s following a successful data transfer
     * won't generate BUFFER_OVERFLOWS.
     *
     * We'll use a mix of direct and indirect ByteBuffers for
     * tutorial purposes only.  In reality, only use direct
     * ByteBuffers when they give a clear performance enhancement.
     */
    clientIn = ByteBuffer.allocate(appBufferMax + 50);
    serverIn = ByteBuffer.allocate(appBufferMax + 50);

    cTOs = ByteBuffer.allocateDirect(netBufferMax);
    sTOc = ByteBuffer.allocateDirect(netBufferMax);

    clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
    serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
  }
Ejemplo n.º 22
0
  /* (non-Javadoc)
   * @see chu.engine.Game#init(int, int, java.lang.String)
   */
  public void init(int width, int height, String name) {
    super.init(width, height, name);
    Player p1 = new Player("Player", (byte) 0);
    localPlayer = p1;
    ByteBuffer icon16, icon32;
    icon16 = icon32 = null;
    try {
      icon16 =
          ByteBuffer.wrap(
              TextureLoader.getTexture(
                      "PNG", ResourceLoader.getResourceAsStream("res/gui/icon16.png"))
                  .getTextureData());
      icon32 =
          ByteBuffer.wrap(
              TextureLoader.getTexture(
                      "PNG", ResourceLoader.getResourceAsStream("res/gui/icon32.png"))
                  .getTextureData());
    } catch (IOException e) {
      e.printStackTrace();
    }
    Display.setIcon(new ByteBuffer[] {icon16, icon32});
    FEResources.loadResources();
    FEResources.loadBitmapFonts();
    WeaponFactory.loadWeapons();
    UnitFactory.loadUnits();
    p1.getParty().setColor(Party.TEAM_BLUE);

    /* OpenGL final setup */
    glEnable(GL_LINE_SMOOTH);

    UnitFactory.getUnit("Lyn");
    connect = new ConnectStage();
    setCurrentStage(new TitleStage());
    SoundTrack.loop("main");
  }
Ejemplo n.º 23
0
  private void sendPacketOut(ConnectPoint outport, Ethernet payload, int sid) {

    IPv4 ipPacket = (IPv4) payload.getPayload();
    Ip4Address destIpAddress = Ip4Address.valueOf(ipPacket.getDestinationAddress());

    if (sid == -1
        || config.getSegmentId(payload.getDestinationMAC()) == sid
        || config.inSameSubnet(outport.deviceId(), destIpAddress)) {
      TrafficTreatment treatment =
          DefaultTrafficTreatment.builder().setOutput(outport.port()).build();
      OutboundPacket packet =
          new DefaultOutboundPacket(
              outport.deviceId(), treatment, ByteBuffer.wrap(payload.serialize()));
      srManager.packetService.emit(packet);
    } else {
      log.info("Send a MPLS packet as a ICMP response");
      TrafficTreatment treatment =
          DefaultTrafficTreatment.builder().setOutput(outport.port()).build();

      payload.setEtherType(Ethernet.MPLS_UNICAST);
      MPLS mplsPkt = new MPLS();
      mplsPkt.setLabel(sid);
      mplsPkt.setTtl(((IPv4) payload.getPayload()).getTtl());
      mplsPkt.setPayload(payload.getPayload());
      payload.setPayload(mplsPkt);

      OutboundPacket packet =
          new DefaultOutboundPacket(
              outport.deviceId(), treatment, ByteBuffer.wrap(payload.serialize()));

      srManager.packetService.emit(packet);
    }
  }
Ejemplo n.º 24
0
 private void init() throws IOException {
   if (xts != null) {
     return;
   }
   this.size = base.size() - HEADER_LENGTH;
   boolean newFile = size < 0;
   byte[] salt;
   if (newFile) {
     byte[] header = Arrays.copyOf(HEADER, BLOCK_SIZE);
     salt = MathUtils.secureRandomBytes(SALT_LENGTH);
     System.arraycopy(salt, 0, header, SALT_POS, salt.length);
     DataUtils.writeFully(base, 0, ByteBuffer.wrap(header));
     size = 0;
   } else {
     salt = new byte[SALT_LENGTH];
     DataUtils.readFully(base, SALT_POS, ByteBuffer.wrap(salt));
     if ((size & BLOCK_SIZE_MASK) != 0) {
       size -= BLOCK_SIZE;
     }
   }
   AES cipher = new AES();
   cipher.setKey(SHA256.getPBKDF2(encryptionKey, salt, HASH_ITERATIONS, 16));
   encryptionKey = null;
   xts = new XTS(cipher);
 }
Ejemplo n.º 25
0
 private Cell toOffheapCell(
     ByteBuffer valAndTagsBuffer, int vOffset, int tagsLenSerializationSize) {
   ByteBuffer tagsBuf = HConstants.EMPTY_BYTE_BUFFER;
   int tOffset = 0;
   if (this.includeTags) {
     if (this.tagCompressionContext == null) {
       tagsBuf = valAndTagsBuffer;
       tOffset = vOffset + this.valueLength + tagsLenSerializationSize;
     } else {
       tagsBuf = ByteBuffer.wrap(Bytes.copy(tagsBuffer, 0, this.tagsLength));
       tOffset = 0;
     }
   }
   return new OffheapDecodedCell(
       ByteBuffer.wrap(Bytes.copy(keyBuffer, 0, this.keyLength)),
       currentKey.getRowLength(),
       currentKey.getFamilyOffset(),
       currentKey.getFamilyLength(),
       currentKey.getQualifierOffset(),
       currentKey.getQualifierLength(),
       currentKey.getTimestamp(),
       currentKey.getTypeByte(),
       valAndTagsBuffer,
       vOffset,
       this.valueLength,
       memstoreTS,
       tagsBuf,
       tOffset,
       this.tagsLength);
 }
Ejemplo n.º 26
0
  @Test
  public void testGenerateParseOneByteAtATime() {
    DataGenerator generator = new DataGenerator(new HeaderGenerator());

    final List<DataFrame> frames = new ArrayList<>();
    Parser parser =
        new Parser(
            new Parser.Listener.Adapter() {
              @Override
              public void onData(DataFrame frame) {
                frames.add(frame);
              }
            },
            4096,
            8192);

    ByteBuffer data = ByteBuffer.wrap(largeContent);
    List<ByteBuffer> list = generator.generateData(13, data.slice(), true, data.remaining());

    for (ByteBuffer buffer : list) {
      while (buffer.hasRemaining()) {
        parser.parse(ByteBuffer.wrap(new byte[] {buffer.get()}));
      }
    }

    Assert.assertEquals(largeContent.length, frames.size());
  }
Ejemplo n.º 27
0
  /*
   * Reads BYTE image data organized as separate image planes.
   *
   */
  public byte[][] readPlanar8(
      int width,
      int height,
      int samplesPerPixel,
      long[] stripOffsets,
      long[] stripCounts,
      long rowsPerStrip)
      throws IOException {
    byte[][] data = new byte[samplesPerPixel][width * height];
    int band = 0;
    int offset = 0;
    int numRows = 0;

    ByteBuffer buff = ByteBuffer.wrap(data[band]);
    for (int i = 0; i < stripOffsets.length; i++) {
      this.theChannel.position(stripOffsets[i]);
      int len = (int) stripCounts[i];
      if ((offset + len) >= data[band].length) len = data[band].length - offset;
      buff.limit(offset + len);
      this.theChannel.read(buff);
      offset += stripCounts[i];
      numRows += rowsPerStrip;
      if (numRows >= height && band < (data.length - 1)) {
        buff = ByteBuffer.wrap(data[++band]);
        numRows = 0;
        offset = 0;
      }
    }

    return data;
  }
  @Override
  protected boolean parseAvcc(BoxHeader header) {
    byte[] data = new byte[(int) header.boxDataSize];
    try {
      if (mDataSource.readAt(mCurrentOffset, data, data.length) != data.length) {
        return false;
      }
    } catch (IOException e) {
      if (LOGS_ENABLED) Log.e(TAG, "Error while parsing 'avcc' box", e);
      return false;
    }

    if (mIsMarlinProtected) {
      ByteBuffer buffer = parseAvccForMarlin(data);
      if (buffer == null) {
        return false;
      }
      mCurrentMediaFormat.setByteBuffer("csd-0", buffer);

      parseSPS(buffer.array());
    } else {
      AvccData avccData = parseAvccData(data);
      if (avccData == null) {
        return false;
      }
      ByteBuffer csd0 = ByteBuffer.wrap(avccData.spsBuffer.array());
      ByteBuffer csd1 = ByteBuffer.wrap(avccData.ppsBuffer.array());
      mCurrentMediaFormat.setByteBuffer("csd-0", csd0);
      mCurrentMediaFormat.setByteBuffer("csd-1", csd1);

      parseSPS(avccData.spsBuffer.array());
    }

    return true;
  }
Ejemplo n.º 29
0
  /**
   * Decodes a dictionary from the bencoded byte array.
   *
   * @param bencoded_bytes the bencoded form of the dictionary.
   * @param offset the offset into {@code bencoded_bytes} where the dictionary begins.
   * @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
   *     dictionary (as a {@code Map}, in positions 0 and 1, respectively
   * @throws BencodingException if the bencoded object is incorrectly encoded.
   */
  @SuppressWarnings("unchecked")
  private static final Object[] decodeDictionary(byte[] bencoded_bytes, int offset)
      throws BencodingException {
    HashMap map = new HashMap();
    ++offset;
    ByteBuffer info_hash_bytes = null;
    while (bencoded_bytes[offset] != (byte) 'e') {

      // Decode the key, which must be a byte string
      Object[] vals = decodeString(bencoded_bytes, offset);
      ByteBuffer key = (ByteBuffer) vals[1];
      offset = ((Integer) vals[0]).intValue();
      boolean match = true;
      for (int i = 0; i < key.array().length && i < 4; i++) {
        if (!key.equals(ByteBuffer.wrap(new byte[] {'i', 'n', 'f', 'o'}))) {
          match = false;
          break;
        }
      }
      int info_offset = -1;
      if (match) info_offset = offset;
      vals = decode(bencoded_bytes, offset);
      offset = ((Integer) vals[0]).intValue();
      if (match) {
        info_hash_bytes = ByteBuffer.wrap(new byte[offset - info_offset]);
        info_hash_bytes.put(bencoded_bytes, info_offset, info_hash_bytes.array().length);
      } else if (vals[1] instanceof HashMap) {
        info_hash_bytes = (ByteBuffer) vals[2];
      }
      if (vals[1] != null) map.put(key, vals[1]);
    }

    return new Object[] {new Integer(++offset), map, info_hash_bytes};
  }
 public static void main(String[] args) throws IOException {
   Path pIn = FileSystems.getDefault().getPath(args[0]);
   Path pOut = FileSystems.getDefault().getPath(args[1]);
   ByteChannel in = Files.newByteChannel(pIn, StandardOpenOption.READ);
   ByteChannel out =
       Files.newByteChannel(pOut, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
   ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE);
   int nb = 0;
   while ((nb = in.read(bb)) != -1) {
     bb.flip();
     while (bb.hasRemaining()) {
       byte b = bb.get();
       ByteBuffer w;
       if (b == CONST) {
         byte[] arr = {b, b};
         w = ByteBuffer.wrap(arr);
       } else {
         byte[] arr = {b};
         w = ByteBuffer.wrap(arr);
       }
       out.write(w);
     }
     bb.clear();
   }
   in.close();
   out.close();
 }