Example #1
0
 private static void writeStoreId(StoreId storeId, ChannelBuffer targetBuffer) {
   targetBuffer.writeLong(storeId.getCreationTime());
   targetBuffer.writeLong(storeId.getRandomId());
   targetBuffer.writeLong(storeId.getStoreVersion());
   targetBuffer.writeLong(storeId.getUpgradeTime());
   targetBuffer.writeLong(storeId.getUpgradeId());
 }
  @Test
  public void setmst() {
    String host = "host";
    int port = 1978;
    long timestamp = System.currentTimeMillis();
    int opts = RDB.ROCHKCON;
    Setmst dut = new Setmst(host, port, timestamp, opts);

    ChannelBuffer request = ChannelBuffers.buffer(2 + 4 + 4 + 8 + 4 + host.getBytes().length);
    request.writeBytes(new byte[] {(byte) 0xC8, (byte) 0x78});
    request.writeInt(host.getBytes().length);
    request.writeInt(port);
    request.writeLong(timestamp);
    request.writeInt(opts);
    request.writeBytes(host.getBytes());
    ChannelBuffer actual = ChannelBuffers.buffer(request.capacity());
    dut.encode(actual);
    assertEquals(request, actual);

    ChannelBuffer response = ChannelBuffers.buffer(1);
    assertFalse(dut.decode(response));

    response.writeByte(Command.ESUCCESS);
    assertTrue(dut.decode(response));
    assertTrue(dut.getReturnValue());

    // error
    response.clear();
    response.writeByte(Command.EUNKNOWN);
    assertTrue(dut.decode(response));
    assertFalse(dut.getReturnValue());
  }
Example #3
0
 @Override
 public void write(ChannelBuffer buffer, ByteBuffer readBuffer) throws IOException {
   buffer.writeInt(entities.length);
   for (long entity : entities) {
     buffer.writeLong(entity);
   }
 }
Example #4
0
 @Override
 public void write(ChannelBuffer buffer) throws IOException {
   buffer.writeInt(type.typeId());
   buffer.writeInt(resourceIds.length);
   for (long entity : resourceIds) {
     buffer.writeLong(entity);
   }
 }
Example #5
0
 private static void sendResponse(
     Channel channel, SocketAddress remoteAddress, long rawId, int index) {
   if (channel != null) {
     ChannelBuffer response = ChannelBuffers.directBuffer(12);
     response.writeShort(0xfe02);
     response.writeLong(rawId);
     response.writeShort(index);
     channel.write(response, remoteAddress);
   }
 }
Example #6
0
  public void writeFileFromStream(
      final InputStream in, long length, String id, String date, String fileName)
      throws IOException {
    FileRequest request = createRequest(id, date, fileName);
    byte[] data = pack.write(request);

    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeLong(8 + data.length + length);
    buffer.writeInt(data.length);
    buffer.writeBytes(data);
    buffer.writeLong(length);
    channel.write(buffer);
    System.out.println(request);
    byte[] bs = new byte[2048];
    int len = 0;
    while ((len = in.read(bs)) > 0) {
      channel.write(ChannelBuffers.wrappedBuffer(bs, 0, len)).awaitUninterruptibly();
    }
  }
  public static void send(MessageEvent event, Integer transactionId, Long connectionId)
      throws Exception {
    logger.debug("ConnectionResponse::send to " + event.getRemoteAddress());

    ChannelBuffer responseBuffer = ChannelBuffers.buffer(4 + 4 + 8);
    responseBuffer.writeInt(Action.CONNECT.getId());
    responseBuffer.writeInt(transactionId);
    responseBuffer.writeLong(connectionId);

    logger.debug("ConnectionResponse DUMP: " + Utils.getHexString(responseBuffer.array()));

    event.getChannel().write(responseBuffer, event.getRemoteAddress());
  }
  @Test
  public void protocol() {
    double num = 4;
    Adddouble dut = new Adddouble(transcoder, transcoder, key, num);

    ChannelBuffer request = ChannelBuffers.buffer(2 + 4 + 8 + 8 + key.length);
    request.writeBytes(new byte[] {(byte) 0xC8, (byte) 0x61});
    request.writeInt(key.length);
    request.writeLong(dut._integ(num));
    request.writeLong(dut._fract(num));
    request.writeBytes(key);
    ChannelBuffer actual = ChannelBuffers.buffer(request.capacity());
    dut.encode(actual);
    assertEquals(request, actual);

    ChannelBuffer response = ChannelBuffers.buffer(1 + 8 + 8);
    assertFalse(dut.decode(response));

    response.writeByte(Command.ESUCCESS);
    assertFalse(dut.decode(response));
    response.resetReaderIndex();

    response.writeLong(dut._integ(3.0 + num));
    assertFalse(dut.decode(response));
    response.resetReaderIndex();

    response.writeLong(dut._fract(3.0 + num));
    assertTrue(dut.decode(response));
    assertEquals(3.0 + num, (double) dut.getReturnValue(), 0.0);

    // error
    response.clear();
    response.writeByte(Command.EUNKNOWN);
    assertTrue(dut.decode(response));
    assertEquals(Double.NaN, (double) dut.getReturnValue(), 0.0);
  }
Example #9
0
  public void writeFile(final File file, String id, String date) throws IOException {

    FileRequest request = createRequest(id, date, file.getName());

    byte[] data = pack.write(request);
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    long length = raf.length();
    // MappedByteBuffer bf =
    // raf.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, length);
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeLong(8 + data.length + length);
    buffer.writeInt(data.length);
    buffer.writeBytes(data);
    buffer.writeLong(length);
    channel.write(buffer);
    System.out.println(request);
    // ChunkedFile chunkedFile = new ChunkedFile(raf);
    // channel.write(chunkedFile);
    // No encryption - use zero-copy.
    final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, length);
    ChannelFuture writeFuture = channel.write(region);
    writeFuture.addListener(
        new ChannelFutureProgressListener() {

          public void operationComplete(ChannelFuture future) {
            region.releaseExternalResources();
          }

          public void operationProgressed(
              ChannelFuture future, long amount, long current, long total) {
            System.out.printf("%s: %d / %d (+%d)%n", file.getName(), current, total, amount);
          }
        });
    writeFuture.awaitUninterruptibly();
    raf.close();
  }
Example #10
0
  @Override
  protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (!(msg instanceof ChannelBuffer)) {
      return msg;
    }

    ChannelBuffer body = (ChannelBuffer) msg;
    ChannelBuffer header =
        channel.getConfig().getBufferFactory().getBuffer(body.order(), lengthFieldLength);

    int length =
        lengthIncludesLengthFieldLength
            ? body.readableBytes() + lengthFieldLength
            : body.readableBytes();
    switch (lengthFieldLength) {
      case 1:
        if (length >= 256) {
          throw new IllegalArgumentException("length does not fit into a byte: " + length);
        }
        header.writeByte((byte) length);
        break;
      case 2:
        if (length >= 65536) {
          throw new IllegalArgumentException("length does not fit into a short integer: " + length);
        }
        header.writeShort((short) length);
        break;
      case 3:
        if (length >= 16777216) {
          throw new IllegalArgumentException(
              "length does not fit into a medium integer: " + length);
        }
        header.writeMedium(length);
        break;
      case 4:
        header.writeInt(length);
        break;
      case 8:
        header.writeLong(length);
        break;
      default:
        throw new Error("should not reach here");
    }
    return wrappedBuffer(header, body);
  }
  @Override
  protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (msg instanceof WebSocketFrame) {
      WebSocketFrame frame = (WebSocketFrame) msg;
      FrameType frameType = frame.getType();

      int opcode = encodeOpcode(frameType);

      ChannelBuffer data = frame.getBinaryData();
      int dataLen = data.readableBytes();

      ChannelBuffer encoded =
          ChannelBuffers.dynamicBuffer(ByteOrder.BIG_ENDIAN, data.readableBytes() + 32);

      byte firstByte = (byte) opcode;
      firstByte = (byte) (firstByte | 0x80);

      encoded.writeByte(firstByte);

      if (dataLen <= 125) {
        encoded.writeByte(applyMaskBit(dataLen));
      } else if (dataLen < 0xFFFF) {
        encoded.writeByte(applyMaskBit(0x7E));
        encoded.writeShort(dataLen);
      } else {
        encoded.writeByte(applyMaskBit(0x7F));
        encoded.writeLong(dataLen);
      }

      if (shouldMask()) {
        byte[] mask = getMask();
        encoded.writeBytes(mask);
        applyDataMask(mask, data);
      }
      encoded.writeBytes(data);

      return encoded;
    }
    return msg;
  }
  @Override
  public ChannelBuffer encode(ChannelBuffer buffer) {
    int l = 36; // (9 ints * 4 bytes)

    List<ByteBuffer> encodedDocuments = encodeDocuments(documents);
    l += buffersSize(encodedDocuments);
    numberReturned = encodedDocuments.size();

    messageLength = l;

    buffer = super.encode(buffer);

    buffer.writeInt(responseFlags);
    buffer.writeLong(cursorID);
    buffer.writeInt(startingFrom);
    buffer.writeInt(numberReturned);

    for (ByteBuffer d : encodedDocuments) {
      buffer.writeBytes(d);
    }

    return buffer;
  }
Example #13
0
 @Override
 public void writeTo(ChannelBuffer bb) {
   bb.writeLong(raw);
 }
Example #14
0
 @Override
 public void write(ChannelBuffer bb, OFUint64Ver14 message) {
   bb.writeLong(message.value.getValue());
 }
Example #15
0
  private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    // Allow only GET methods.
    if (req.getMethod() != GET) {
      sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
      return;
    }

    // Send the demo page.
    if (req.getUri().equals("/")) {
      HttpResponse res = new DefaultHttpResponse(HTTP_1_1, OK);

      ChannelBuffer content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));

      res.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8");
      setContentLength(res, content.readableBytes());

      res.setContent(content);
      sendHttpResponse(ctx, req, res);
      return;
    }

    // Serve the WebSocket handshake request.
    if (req.getUri().equals(WEBSOCKET_PATH)
        && Values.UPGRADE.equalsIgnoreCase(req.getHeader(CONNECTION))
        && WEBSOCKET.equalsIgnoreCase(req.getHeader(Names.UPGRADE))) {

      // Create the WebSocket handshake response.
      HttpResponse res =
          new DefaultHttpResponse(
              HTTP_1_1, new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
      res.addHeader(Names.UPGRADE, WEBSOCKET);
      res.addHeader(CONNECTION, Values.UPGRADE);

      // Fill in the headers and contents depending on handshake method.
      if (req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2)) {
        // New handshake method with a challenge:
        res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
        res.addHeader(SEC_WEBSOCKET_LOCATION, getWebSocketLocation(req));
        String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
        if (protocol != null) {
          res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
        }

        // Calculate the answer of the challenge.
        String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
        String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
        int a =
            (int)
                (Long.parseLong(key1.replaceAll("[^0-9]", ""))
                    / key1.replaceAll("[^ ]", "").length());
        int b =
            (int)
                (Long.parseLong(key2.replaceAll("[^0-9]", ""))
                    / key2.replaceAll("[^ ]", "").length());
        long c = req.getContent().readLong();
        ChannelBuffer input = ChannelBuffers.buffer(16);
        input.writeInt(a);
        input.writeInt(b);
        input.writeLong(c);
        ChannelBuffer output =
            ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5").digest(input.array()));
        res.setContent(output);
      } else {
        // Old handshake method with no challenge:
        res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
        res.addHeader(WEBSOCKET_LOCATION, getWebSocketLocation(req));
        String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
        if (protocol != null) {
          res.addHeader(WEBSOCKET_PROTOCOL, protocol);
        }
      }

      // Upgrade the connection and send the handshake response.
      ChannelPipeline p = ctx.getChannel().getPipeline();
      p.remove("aggregator");
      p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());

      ctx.getChannel().write(res);

      p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
      return;
    }

    // Send an error page otherwise.
    sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
  }
 public GameDownBuffer putLong(long value) {
   buffer.writeLong(value);
   return this;
 }
Example #17
0
  private void websocketHandshake(final ChannelHandlerContext ctx, HttpRequest req, MessageEvent e)
      throws Exception {

    // Create the WebSocket handshake response.
    HttpResponse res =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1, new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
    res.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
    res.addHeader(CONNECTION, HttpHeaders.Values.UPGRADE);

    // Fill in the headers and contents depending on handshake method.
    if (req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2)) {
      // New handshake method with a challenge:
      res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
      res.addHeader(
          SEC_WEBSOCKET_LOCATION, "ws://" + req.getHeader(HttpHeaders.Names.HOST) + req.getUri());
      String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
      if (protocol != null) {
        res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
      }

      // Calculate the answer of the challenge.
      String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
      String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
      int a =
          (int)
              (Long.parseLong(key1.replaceAll("[^0-9]", ""))
                  / key1.replaceAll("[^ ]", "").length());
      int b =
          (int)
              (Long.parseLong(key2.replaceAll("[^0-9]", ""))
                  / key2.replaceAll("[^ ]", "").length());
      long c = req.getContent().readLong();
      ChannelBuffer input = ChannelBuffers.buffer(16);
      input.writeInt(a);
      input.writeInt(b);
      input.writeLong(c);
      try {
        ChannelBuffer output =
            ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5").digest(input.array()));
        res.setContent(output);
      } catch (NoSuchAlgorithmException ex) {
        throw new UnexpectedException(ex);
      }
    } else {
      // Old handshake method with no challenge:
      res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
      res.addHeader(
          WEBSOCKET_LOCATION, "ws://" + req.getHeader(HttpHeaders.Names.HOST) + req.getUri());
      String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
      if (protocol != null) {
        res.addHeader(WEBSOCKET_PROTOCOL, protocol);
      }
    }

    // Keep the original request
    Http.Request request = parseRequest(ctx, req);

    // Route the websocket request
    request.method = "WS";
    Map<String, String> route = Router.route(request.method, request.path);
    if (!route.containsKey("action")) {
      // No route found to handle this websocket connection
      ctx.getChannel()
          .write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
      return;
    }

    // Upgrade the connection and send the handshake response.
    ChannelPipeline p = ctx.getChannel().getPipeline();
    p.remove("aggregator");
    p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());

    // Connect
    ctx.getChannel().write(res);

    p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
    req.setMethod(new HttpMethod("WEBSOCKET"));

    // Inbound
    Http.Inbound inbound =
        new Http.Inbound() {

          @Override
          public boolean isOpen() {
            return ctx.getChannel().isOpen();
          }
        };
    channels.put(ctx, inbound);

    // Outbound
    Http.Outbound outbound =
        new Http.Outbound() {

          final List<ChannelFuture> writeFutures =
              Collections.synchronizedList(new ArrayList<ChannelFuture>());
          Promise<Void> closeTask;

          synchronized void writeAndClose(ChannelFuture writeFuture) {
            if (!writeFuture.isDone()) {
              writeFutures.add(writeFuture);
              writeFuture.addListener(
                  new ChannelFutureListener() {

                    public void operationComplete(ChannelFuture cf) throws Exception {
                      writeFutures.remove(cf);
                      futureClose();
                    }
                  });
            }
          }

          void futureClose() {
            if (closeTask != null && writeFutures.isEmpty()) {
              closeTask.invoke(null);
            }
          }

          @Override
          public void send(String data) {
            if (!isOpen()) {
              throw new IllegalStateException("The outbound channel is closed");
            }
            writeAndClose(ctx.getChannel().write(new DefaultWebSocketFrame(data)));
          }

          @Override
          public void send(byte opcode, byte[] data, int offset, int length) {
            if (!isOpen()) {
              throw new IllegalStateException("The outbound channel is closed");
            }
            writeAndClose(
                ctx.getChannel()
                    .write(new DefaultWebSocketFrame(opcode, wrappedBuffer(data, offset, length))));
          }

          @Override
          public synchronized boolean isOpen() {
            return ctx.getChannel().isOpen() && closeTask == null;
          }

          @Override
          public synchronized void close() {
            closeTask = new Promise<Void>();
            closeTask.onRedeem(
                new Action<Promise<Void>>() {

                  public void invoke(Promise<Void> completed) {
                    writeFutures.clear();
                    ctx.getChannel().disconnect();
                    closeTask = null;
                  }
                });
            futureClose();
          }
        };

    Invoker.invoke(new WebSocketInvocation(route, request, inbound, outbound, ctx, e));
  }
 @Override
 public void writeObject(ChannelBuffer buffer) {
   buffer.writeLong(startTimestamp);
 }