/**
   * Create a {@link ChannelBuffer} which is terminated with a CRLF.CRLF sequence
   *
   * @param data
   * @return buffer
   */
  private static ChannelBuffer createDataTerminatingChannelBuffer(byte[] data) {
    int length = data.length;
    if (length < 1) {
      return ChannelBuffers.wrappedBuffer(CRLF_DOT_CRLF);
    } else {
      byte[] terminating;

      byte last = data[length - 1];

      if (length == 1) {
        if (last == CR) {
          terminating = LF_DOT_CRLF;
        } else {
          terminating = CRLF_DOT_CRLF;
        }
      } else {
        byte prevLast = data[length - 2];

        if (last == LF) {
          if (prevLast == CR) {
            terminating = DOT_CRLF;
          } else {
            terminating = CRLF_DOT_CRLF;
          }
        } else if (last == CR) {
          terminating = LF_DOT_CRLF;
        } else {
          terminating = CRLF_DOT_CRLF;
        }
      }
      return ChannelBuffers.wrappedBuffer(data, terminating);
    }
  }
  @Override
  public ChannelBuffer toChannelBuffer() {
    ChannelBuffer[] buffers;
    ChannelBuffer currentBuffer = null;
    BytesRef ref = new BytesRef();
    int pos = 0;

    // are we a slice?
    if (offset != 0) {
      // remaining size of page fragment at offset
      int fragmentSize = Math.min(length, PAGE_SIZE - (offset % PAGE_SIZE));
      bytearray.get(offset, fragmentSize, ref);
      currentBuffer = ChannelBuffers.wrappedBuffer(ref.bytes, ref.offset, fragmentSize);
      pos += fragmentSize;
    }

    // no need to create a composite buffer for a single page
    if (pos == length && currentBuffer != null) {
      return currentBuffer;
    }

    // a slice > pagesize will likely require extra buffers for initial/trailing fragments
    int numBuffers = countRequiredBuffers((currentBuffer != null ? 1 : 0), length - pos);

    buffers = new ChannelBuffer[numBuffers];
    int bufferSlot = 0;

    if (currentBuffer != null) {
      buffers[bufferSlot] = currentBuffer;
      bufferSlot++;
    }

    // handle remainder of pages + trailing fragment
    while (pos < length) {
      int remaining = length - pos;
      int bulkSize = (remaining > PAGE_SIZE) ? PAGE_SIZE : remaining;
      bytearray.get(offset + pos, bulkSize, ref);
      currentBuffer = ChannelBuffers.wrappedBuffer(ref.bytes, ref.offset, bulkSize);
      buffers[bufferSlot] = currentBuffer;
      bufferSlot++;
      pos += bulkSize;
    }

    // this would indicate that our numBuffer calculation is off by one.
    assert (numBuffers == bufferSlot);

    // we can use gathering writes from the ChannelBuffers, but only if they are
    // moderately small to prevent OOMs due to DirectBuffer allocations.
    return ChannelBuffers.wrappedBuffer(length <= NIO_GATHERING_LIMIT, buffers);
  }
Пример #3
0
 @Override
 public void createMiddle(LocalChannelReference lcr) throws OpenR66ProtocolPacketException {
   if (key == null) {
     throw new OpenR66ProtocolPacketException("Not enough data");
   }
   middle = ChannelBuffers.wrappedBuffer(key);
 }
Пример #4
0
 @Override
 protected ChannelBuffer newBuffer(int length) {
   buffer =
       ChannelBuffers.wrappedBuffer(new byte[length * 2], random.nextInt(length - 1) + 1, length);
   assertEquals(length, buffer.writerIndex());
   return buffer;
 }
Пример #5
0
  public void sendResponse(final MessageEvent e) {
    // Build the response object.
    final HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    final ByteArrayOutputStream bos = receivedData;
    try {
      bos.write(" successfully received by server".getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException e1) {
      e1.printStackTrace();
    } catch (final IOException e1) {
      e1.printStackTrace();
    }
    final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(bos.toByteArray());
    response.setContent(buffer);
    // response.setContent(arg0)
    // response.setContent(ChannelBuffers.copiedBuffer(buf.toString(),
    // CharsetUtil.UTF_8));
    response.setHeader(CONTENT_TYPE, "application/octet-stream");

    final ChannelFuture future = e.getChannel().write(response);

    // Close the non-keep-alive connection after the write operation is
    // done.
    // if (!keepAlive) {
    future.addListener(ChannelFutureListener.CLOSE);
    // }
  }
Пример #6
0
  @Override
  protected final Object encode(
      final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception {

    // 不是计费类型的消息,不进行解析, 直接返回
    if (!(msg instanceof BaseMessage)) {
      // Ignore what this encoder can't encode.
      return msg;
    }

    //
    // 开始解析
    //

    // 将REPLY消息封装
    JsonElement element = gson.toJsonElement(msg);
    Mcpack mcpack = new Mcpack();
    byte[] dataByte = mcpack.toMcpack(ConanCommonConstants.ENCODING, element);

    // 设置消息头
    NsHead nsHead = new NsHead();
    nsHead.setReserved(ConanCommonConstants.DEFAULT_RESERVED);
    nsHead.setType((short) ConanMessageType.CONAN_REPLY_TYPE_DATA.getValue());
    nsHead.setVersion(ConanCommonConstants.CURRENT_VERSION);
    nsHead.setBodyLength(dataByte.length);

    // 发送消息
    byte[] headerByte = nsHead.toBytes();
    ChannelBuffer cb =
        ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, headerByte, dataByte);

    LOGGER.debug("server encode: " + element.toString());

    return cb;
  }
Пример #7
0
 @Override
 public void createHeader(LocalChannelReference lcr) throws OpenR66ProtocolPacketException {
   if (hostId == null) {
     throw new OpenR66ProtocolPacketException("Not enough data");
   }
   header = ChannelBuffers.wrappedBuffer(hostId.getBytes());
 }
 @Override
 public void sendResponse(Throwable error) throws IOException {
   BytesStreamOutput stream;
   try {
     stream = BytesStreamOutput.Cached.cached();
     writeResponseExceptionHeader(stream);
     RemoteTransportException tx =
         new RemoteTransportException(
             transport.nodeName(),
             transport.wrapAddress(channel.getLocalAddress()),
             action,
             error);
     ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
     too.writeObject(tx);
     too.close();
   } catch (NotSerializableException e) {
     stream = BytesStreamOutput.Cached.cached();
     writeResponseExceptionHeader(stream);
     RemoteTransportException tx =
         new RemoteTransportException(
             transport.nodeName(),
             transport.wrapAddress(channel.getLocalAddress()),
             action,
             new NotSerializableTransportException(error));
     ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
     too.writeObject(tx);
     too.close();
   }
   ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(stream.copiedByteArray());
   buffer.setInt(0, buffer.writerIndex() - 4); // update real size.
   channel.write(buffer);
 }
Пример #9
0
  public static HttpResponse buildHttpServletResponse(HttpResponseExchange forwardResponse)
      throws IOException {

    if (null == forwardResponse) {
      return new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_TIMEOUT);
    }
    HttpResponse response =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(forwardResponse.getResponseCode()));

    List<String[]> headers = forwardResponse.getHeaders();
    for (String[] header : headers) {
      if (header[0].equalsIgnoreCase(HttpHeaders.Names.SET_COOKIE)
          || header[0].equalsIgnoreCase(HttpHeaders.Names.SET_COOKIE2)) {
        List<SetCookieHeaderValue> cookies = SetCookieHeaderValue.parse(header[1]);
        for (SetCookieHeaderValue cookie : cookies) {
          response.addHeader(header[0], cookie.toString());
        }
      } else {
        response.addHeader(header[0], header[1]);
      }
    }
    byte[] content = forwardResponse.getBody();
    if (null != content) {
      ChannelBuffer bufer = ChannelBuffers.wrappedBuffer(content);
      response.setContent(bufer);
    }

    return response;
  }
 /**
  * From the current context (currentBuffer and currentData), returns the next HttpChunk (if
  * possible) trying to get sizeleft bytes more into the currentBuffer. This is the Multipart
  * version.
  *
  * @param sizeleft the number of bytes to try to get from currentData
  * @return the next HttpChunk or null if not enough bytes were found
  * @throws ErrorDataEncoderException if the encoding is in error
  */
 private HttpChunk encodeNextChunkMultipart(int sizeleft) throws ErrorDataEncoderException {
   if (currentData == null) {
     return null;
   }
   ChannelBuffer buffer;
   if (currentData instanceof InternalAttribute) {
     String internal = ((InternalAttribute) currentData).toString();
     byte[] bytes;
     try {
       bytes = internal.getBytes("ASCII");
     } catch (UnsupportedEncodingException e) {
       throw new ErrorDataEncoderException(e);
     }
     buffer = ChannelBuffers.wrappedBuffer(bytes);
     currentData = null;
   } else {
     if (currentData instanceof Attribute) {
       try {
         buffer = ((Attribute) currentData).getChunk(sizeleft);
       } catch (IOException e) {
         throw new ErrorDataEncoderException(e);
       }
     } else {
       try {
         buffer = ((FileUpload) currentData).getChunk(sizeleft);
       } catch (IOException e) {
         throw new ErrorDataEncoderException(e);
       }
     }
     if (buffer.capacity() == 0) {
       // end for current InterfaceHttpData, need more data
       currentData = null;
       return null;
     }
   }
   if (currentBuffer == null) {
     currentBuffer = buffer;
   } else {
     currentBuffer = ChannelBuffers.wrappedBuffer(currentBuffer, buffer);
   }
   if (currentBuffer.readableBytes() < HttpPostBodyUtil.chunkSize) {
     currentData = null;
     return null;
   }
   buffer = fillChannelBuffer();
   return new DefaultHttpChunk(buffer);
 }
Пример #11
0
  /** 向server端发送消息 */
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
    System.out.println("client start..");

    String message = "[" + name + "]baicai AAA";
    ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(message.getBytes());
    event.getChannel().write(channelBuffer);
  }
Пример #12
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
    if (!(me.getMessage() instanceof HttpRequest)) {
      ctx.sendUpstream(me);
      return;
    }

    HttpRequest request = (HttpRequest) me.getMessage();
    Object response;

    // Look up resource
    String path = request.getUri();
    String host = request.getHeader("host");
    log.debug("Received request for path:" + path);

    boolean showHtml = false;
    if (path.endsWith("?html")) {
      showHtml = true;
      path = path.replace("?html", "");
    }

    for (String service : resources.keySet()) {
      log.debug("Available Service: " + service);
    }

    Model model = resources.get(path);

    if (model != null) {
      if (request.getMethod() == HttpMethod.GET) {
        if (showHtml) {
          String html = HtmlCreator.createModelPage(model, new URI(path), host);
          response = ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8")));

          log.debug("Returned html page for resource: " + path);
        } else {
          response = new SelfDescription(model, new URI(request.getUri()));

          log.debug("Resource found: " + path);
        }
      } else {
        response =
            new DefaultHttpResponse(
                request.getProtocolVersion(), HttpResponseStatus.METHOD_NOT_ALLOWED);

        log.debug("Method not allowed: " + request.getMethod());
      }
    } else {
      response =
          HttpResponseFactory.createHttpResponse(
              request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND);

      log.debug("Resource not found: " + path);
    }

    // Send response
    ChannelFuture future = Channels.write(ctx.getChannel(), response);
    future.addListener(ChannelFutureListener.CLOSE);
  }
  @org.junit.Test
  public void testBinaryWithByteBufferAsync() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<Throwable>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();

    class TestEndPoint extends Endpoint {
      @Override
      public void onOpen(final Session session, EndpointConfig config) {
        connected.set(true);
        session.addMessageHandler(
            new MessageHandler.Partial<ByteBuffer>() {
              @Override
              public void onMessage(ByteBuffer message, boolean last) {
                Assert.assertTrue(last);
                ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                buf.put(message);
                buf.flip();
                try {
                  session.getBasicRemote().sendBinary(buf);
                } catch (IOException e) {
                  e.printStackTrace();
                  cause.set(e);
                  latch.setException(e);
                }
              }
            });
      }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE);
    builder.start(
        HttpClient.create(DefaultServer.getWorker(), OptionMap.EMPTY),
        new ByteBufferSlicePool(100, 100));

    builder.addEndpoint(
        ServerEndpointConfig.Builder.create(TestEndPoint.class, "/")
            .configurator(new InstanceConfigurator(new TestEndPoint()))
            .build());
    deployServlet(builder);

    WebSocketTestClient client =
        new WebSocketTestClient(
            getVersion(),
            new URI(
                "ws://"
                    + DefaultServer.getHostAddress("default")
                    + ":"
                    + DefaultServer.getHostPort("default")
                    + "/"));
    client.connect();
    client.send(
        new BinaryWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)),
        new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    Assert.assertNull(cause.get());
    client.destroy();
  }
Пример #14
0
  public Object nextChunk() throws Exception {
    ByteBuffer buffer = peekNextChunk();
    if (buffer == null || buffer == EOF) {
      return null;
    }
    nextChunk = null;

    return ChannelBuffers.wrappedBuffer(buffer);
  }
  @Override
  public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object msg = e.getMessage();

    if (msg instanceof ISenseOtapPacketEncoderSetAESKeyRequest) {

      iSenseAes128BitKey key = ((ISenseOtapPacketEncoderSetAESKeyRequest) msg).getKey();

      if (key != null) {
        log.info("Encrypting payload of otap packets");
        this.aes = new iSenseAes(key);
      } else {
        log.info("Disabled otap payload encryption");
        this.aes = null;
      }

      return;
    }

    byte[] bytes = null;

    if (msg instanceof OtapInitReply) {
      bytes = MacroFabricSerializer.serialize((OtapInitReply) msg);
    } else if (msg instanceof OtapInitRequest) {
      bytes = MacroFabricSerializer.serialize((OtapInitRequest) msg);
    } else if (msg instanceof OtapProgramReply) {
      bytes = MacroFabricSerializer.serialize((OtapProgramReply) msg);
    } else if (msg instanceof OtapProgramRequest) {
      bytes = MacroFabricSerializer.serialize((OtapProgramRequest) msg);
    } else if (msg instanceof PresenceDetectRequest) {
      bytes = MacroFabricSerializer.serialize((PresenceDetectRequest) msg);
    } else if (msg instanceof PresenceDetectReply) {
      bytes = MacroFabricSerializer.serialize((PresenceDetectReply) msg);
    }

    if (bytes != null) {

      if (aes != null) {
        log.trace(("Encrypted otap payload wit AES"));
        bytes = aes.encodeWithRandomNonce(bytes);
      }

      ISerAerialOutgoingPacket iSerAerialPacket =
          new ISerAerialOutgoingPacket(
              ISerAerialOutgoingPacket.BROADCAST_ADDRESS_16_BIT,
              (byte) 0x0,
              ChannelBuffers.wrappedBuffer(bytes, computeCrc(bytes)));

      log.trace(
          "Encoded {} otap packet with crc: {}", msg.getClass().getSimpleName(), iSerAerialPacket);

      HandlerTools.sendDownstream(iSerAerialPacket, ctx);
    } else {
      super.writeRequested(ctx, e);
    }
  }
  public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
    if (!nioBuffer.isReadOnly() && nioBuffer.isDirect()) {
      return ChannelBuffers.wrappedBuffer(nioBuffer);
    }

    ChannelBuffer buf = getBuffer(nioBuffer.order(), nioBuffer.remaining());
    int pos = nioBuffer.position();
    buf.writeBytes(nioBuffer);
    nioBuffer.position(pos);
    return buf;
  }
Пример #17
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    RpcInfo info = (RpcInfo) e.getMessage();
    RpcCall call = (RpcCall) info.header();
    if (LOG.isTraceEnabled()) {
      LOG.trace(program + " procedure #" + call.getProcedure());
    }

    if (this.progNumber != call.getProgram()) {
      LOG.warn("Invalid RPC call program " + call.getProgram());
      RpcAcceptedReply reply =
          RpcAcceptedReply.getInstance(
              call.getXid(), AcceptState.PROG_UNAVAIL, Verifier.VERIFIER_NONE);

      XDR out = new XDR();
      reply.write(out);
      ChannelBuffer b = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap().buffer());
      RpcResponse rsp = new RpcResponse(b, info.remoteAddress());
      RpcUtil.sendRpcResponse(ctx, rsp);
      return;
    }

    int ver = call.getVersion();
    if (ver < lowProgVersion || ver > highProgVersion) {
      LOG.warn("Invalid RPC call version " + ver);
      RpcAcceptedReply reply =
          RpcAcceptedReply.getInstance(
              call.getXid(), AcceptState.PROG_MISMATCH, Verifier.VERIFIER_NONE);

      XDR out = new XDR();
      reply.write(out);
      out.writeInt(lowProgVersion);
      out.writeInt(highProgVersion);
      ChannelBuffer b = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap().buffer());
      RpcResponse rsp = new RpcResponse(b, info.remoteAddress());
      RpcUtil.sendRpcResponse(ctx, rsp);
      return;
    }

    handleInternal(ctx, info);
  }
  /**
   * Constructs and returns a new ChannelBuffer with the correct header for the given cluster and
   * API-key.
   *
   * @return The ChannelBuffer containing the header.
   * @throws java.io.IOException if error
   */
  public ChannelBuffer getHeaderBuffer() throws IOException {
    byte[] clusterNameBytes = clusterName.getBytes(StandardCharsets.UTF_8);
    int clusterNameLength = clusterNameBytes.length;

    byte[] apiKeyBytes = apiKey.getBytes(StandardCharsets.UTF_8);
    int apiKeyLength = apiKeyBytes.length;

    ChannelBuffer headerPayload =
        ChannelBuffers.wrappedBuffer(
            getIntBytes(revisionLength),
            getIntBytes(revision),
            getIntBytes(versionLength + moduleVersionLength),
            getIntBytes(Version.CURRENT.id),
            getIntBytes(FoundModuleVersion.CURRENT.id),
            getIntBytes(clusterNameLength),
            clusterNameBytes,
            getIntBytes(apiKeyLength),
            apiKeyBytes);

    return ChannelBuffers.wrappedBuffer(
        ChannelBuffers.wrappedBuffer(getIntBytes(headerPayload.readableBytes())), headerPayload);
  }
Пример #19
0
 /**
  * Initialized the internals from a new chunk
  *
  * @param chunk the new received chunk
  * @throws ErrorDataDecoderException if there is a problem with the charset decoding or other
  *     errors
  */
 public void offer(HttpChunk chunk) throws ErrorDataDecoderException {
   ChannelBuffer chunked = chunk.getContent();
   if (undecodedChunk == null) {
     undecodedChunk = chunked;
   } else {
     // undecodedChunk = ChannelBuffers.wrappedBuffer(undecodedChunk, chunk.getContent());
     // less memory usage
     undecodedChunk = ChannelBuffers.wrappedBuffer(undecodedChunk, chunked);
   }
   if (chunk.isLast()) {
     isLastChunk = true;
   }
   parseBody();
 }
 @Override
 public void sendResponse(Streamable message) throws IOException {
   HandlesStreamOutput stream = BytesStreamOutput.Cached.cachedHandles();
   stream.writeBytes(LENGTH_PLACEHOLDER); // fake size
   stream.writeLong(requestId);
   byte status = 0;
   status = setResponse(status);
   stream.writeByte(status); // 0 for request, 1 for response.
   message.writeTo(stream);
   byte[] data = ((BytesStreamOutput) stream.wrappedOut()).copiedByteArray();
   ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(data);
   buffer.setInt(0, buffer.writerIndex() - 4); // update real size.
   channel.write(buffer);
 }
  @org.junit.Test
  public void testTextByFuture() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Future<Void>> sendResult = new AtomicReference<Future<Void>>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();

    class TestEndPoint extends Endpoint {
      @Override
      public void onOpen(final Session session, EndpointConfig config) {
        connected.set(true);
        session.addMessageHandler(
            new MessageHandler.Whole<String>() {
              @Override
              public void onMessage(String message) {
                sendResult.set(session.getAsyncRemote().sendText(message));
              }
            });
      }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE);
    builder.start(
        HttpClient.create(DefaultServer.getWorker(), OptionMap.EMPTY),
        new ByteBufferSlicePool(100, 100));
    builder.addEndpoint(
        ServerEndpointConfig.Builder.create(TestEndPoint.class, "/")
            .configurator(new InstanceConfigurator(new TestEndPoint()))
            .build());
    deployServlet(builder);

    WebSocketTestClient client =
        new WebSocketTestClient(
            getVersion(),
            new URI(
                "ws://"
                    + DefaultServer.getHostAddress("default")
                    + ":"
                    + DefaultServer.getHostPort("default")
                    + "/"));
    client.connect();
    client.send(
        new TextWebSocketFrame(ChannelBuffers.wrappedBuffer(payload)),
        new FrameChecker(TextWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();

    sendResult.get();

    client.destroy();
  }
Пример #22
0
 public void fire(Object something) {
   try {
     String result = (String) something;
     if (result.equals(RedisServer.TIME_OUT_STRING)) {
       logger.error("fire message timeout error, message id:" + getIdentify());
       response.setContent(
           ChannelBuffers.wrappedBuffer(
               JResultUtil.getFailureJsonString(CoreProxyHandler.RESULT_TIMEOUT).getBytes()));
       response.setStatus(HttpResponseStatus.OK);
     } else {
       logger.info("fire message success, message id:" + getIdentify());
       response.setContent(
           ChannelBuffers.wrappedBuffer(JResultUtil.getOkJsonString(result).getBytes()));
       response.setStatus(HttpResponseStatus.OK);
     }
   } catch (Exception e) {
     logger.error("fire message error, e:" + e.getMessage() + " result:" + something);
     response.setContent(
         ChannelBuffers.wrappedBuffer(
             JResultUtil.getFailureJsonString(CoreProxyHandler.RESULT_ERROR).getBytes()));
     response.setStatus(HttpResponseStatus.OK);
   }
   NettyHttpOutput.output(response, event.getChannel());
 }
Пример #23
0
 static void sendRedirect(
     final ChannelHandlerContext ctx,
     final ChannelEvent e,
     final Class<? extends ComponentId> compClass,
     final MappingHttpRequest request) {
   e.getFuture().cancel();
   String redirectUri = null;
   if (Topology.isEnabled(compClass)) { // have an enabled service, lets use that
     final URI serviceUri = ServiceUris.remote(Topology.lookup(compClass));
     redirectUri =
         serviceUri.toASCIIString() + request.getServicePath().replace(serviceUri.getPath(), "");
   } else if (Topology.isEnabled(
       Eucalyptus.class)) { // can't find service info, redirect via clc master
     final URI serviceUri = ServiceUris.remote(Topology.lookup(Eucalyptus.class));
     redirectUri =
         serviceUri.toASCIIString().replace(Eucalyptus.INSTANCE.getServicePath(), "")
             + request.getServicePath().replace(serviceUri.getPath(), "");
   }
   HttpResponse response = null;
   if (redirectUri == null || isRedirectLoop(request, redirectUri)) {
     response =
         new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE);
     if (Logs.isDebug()) {
       String errorMessage =
           "Failed to lookup service for "
               + Components.lookup(compClass).getName()
               + " for path "
               + request.getServicePath()
               + ".\nCurrent state: \n\t"
               + Joiner.on("\n\t").join(Topology.enabledServices());
       byte[] errorBytes = Exceptions.string(new ServiceStateException(errorMessage)).getBytes();
       response.setContent(ChannelBuffers.wrappedBuffer(errorBytes));
     }
   } else {
     response =
         new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
     if (request.getQuery() != null) {
       redirectUri += "?" + request.getQuery();
     }
     response.setHeader(HttpHeaders.Names.LOCATION, redirectUri);
   }
   response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
   if (ctx.getChannel().isConnected()) {
     ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
   }
 }
Пример #24
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();
    }
  }
  @Test
  public void testWithContent() throws Exception {

    byte[] expectedBytes = UUID.randomUUID().toString().getBytes();

    Response nettyResponse =
        new Response() {
          private HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_0, OK);

          @Override
          public HttpResponse httpResponse() {
            return httpResponse;
          }
        };

    nettyResponse.setContent(ChannelBuffers.wrappedBuffer(expectedBytes));

    ClientResponse resteasyResponse = translate(nettyResponse);
    assertStatus(resteasyResponse, Status.OK);
    assertContent(resteasyResponse, expectedBytes);
  }
Пример #26
0
  @SuppressWarnings("unchecked")
  @Override
  protected Object encode(ChannelHandlerContext ctx, Channel c, Object msg) throws Exception {
    if (msg instanceof Message) {
      Message message = (Message) msg;

      Class<? extends Message> clazz = message.getClass();
      MessageCodec<Message> codec = (MessageCodec<Message>) CodecLookupService.find(clazz);
      if (codec == null) {
        throw new IOException("Unknown message type: " + clazz + ".");
      }

      ChannelBuffer opcodeBuf = ChannelBuffers.buffer(3);
      opcodeBuf.writeByte(codec.getOpcode());

      ChannelBuffer codecBuf = codec.encode(message);
      opcodeBuf.writeInt(codecBuf.capacity());

      return ChannelBuffers.wrappedBuffer(opcodeBuf, codecBuf);
    }
    return msg;
  }
  @Override
  protected void service(IndexedFileSystem fs, Channel channel, OnDemandRequest request)
      throws IOException {
    FileDescriptor desc = request.getFileDescriptor();

    ByteBuffer buf = fs.getFile(desc);
    int length = buf.remaining();

    for (int chunk = 0; buf.remaining() > 0; chunk++) {
      int chunkSize = buf.remaining();
      if (chunkSize > CHUNK_LENGTH) {
        chunkSize = CHUNK_LENGTH;
      }

      byte[] tmp = new byte[chunkSize];
      buf.get(tmp, 0, tmp.length);
      ChannelBuffer chunkData = ChannelBuffers.wrappedBuffer(tmp, 0, chunkSize);

      OnDemandResponse response = new OnDemandResponse(desc, length, chunk, chunkData);
      channel.write(response);
    }
  }
Пример #28
0
  private ChannelBuffer getHtmlListOfServices() {
    String html = HtmlCreator.createMainPage(uiElements, entities);

    return ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8")));
  }
Пример #29
0
  /** Expected Message types: - HTTP Requests */
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    if (!(e.getMessage() instanceof HttpRequest)) {
      super.messageReceived(ctx, e);
      return;
    }

    HttpRequest httpRequest = (HttpRequest) e.getMessage();
    URI targetUri =
        toThing(URI.create("http://" + httpRequest.getHeader("HOST") + httpRequest.getUri()));

    log.debug("Received HTTP request for " + targetUri);

    if (httpRequest.getHeader("HOST").contains(DNS_WILDCARD_POSTFIX)) {
      String targetUriHost = InetAddress.getByName(targetUri.getHost()).getHostAddress();
      // remove leading zeros per block
      targetUriHost = targetUriHost.replaceAll(":0000", ":0");
      targetUriHost = targetUriHost.replaceAll(":000", ":0");
      targetUriHost = targetUriHost.replaceAll(":00", ":0");
      targetUriHost = targetUriHost.replaceAll("(:0)([ABCDEFabcdef123456789])", ":$2");

      // return shortened IP
      targetUriHost =
          targetUriHost.replaceAll("((?:(?:^|:)0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2");
      log.debug("Target host: " + targetUriHost);

      String targetUriPath = targetUri.getRawPath();
      log.debug("Target path: " + targetUriPath);

      if (IPAddressUtil.isIPv6LiteralAddress(targetUriHost)) {
        targetUriHost = "[" + targetUriHost + "]";
      }

      targetUri = toThing(URI.create("http://" + targetUriHost + httpRequest.getUri()));
      log.debug("Shortened target URI: " + targetUri);
    }

    URI uriToCheck = targetUri;
    if ((uriToCheck.getQuery() != null) && (uriToCheck.getQuery().equals("html"))) {
      uriToCheck = toThing(URI.create("http://" + targetUri.getHost() + targetUri.getPath()));
    }

    if (entities.containsKey(uriToCheck)) {
      Backend backend = entities.get(uriToCheck);
      try {
        ctx.getPipeline().remove("Backend to handle request");
      } catch (NoSuchElementException ex) {
        // Fine. There was no handler to be removed.
      }
      ctx.getPipeline().addLast("Backend to handle request", backend);
      log.debug("Forward request to " + backend);
    } else if (virtualEntities.containsKey(uriToCheck)) {
      Backend backend = virtualEntities.get(uriToCheck);
      try {
        ctx.getPipeline().remove("Backend to handle request");
      } catch (NoSuchElementException ex) {
        // Fine. There was no handler to be removed.
      }
      ctx.getPipeline().addLast("Backend to handle request", backend);
      log.debug("Forward request to " + backend);
    }

    //        else if (targetUriPath.equals(PATH_TO_SERVER_LIST)) {
    //            // Handle request for resource at path ".well-known/core"
    //            StringBuilder buf = new StringBuilder();
    //            for(URI entity: getServices()) {
    //                buf.append(toThing(entity).toString() + "\n");
    //            }
    //            Channels.write(ctx.getChannel(),
    // Answer.create(buf.toString()).setMime("text/plain"));
    //            return;
    //        }

    //        else if("/visualizer".equals(targetUriPath)){
    //            try {
    //                ctx.getPipeline().remove("Backend to handle request");
    //            }
    //            catch(NoSuchElementException ex) {
    //                //Fine. There was no handler to be removed.
    //            }
    //            ctx.getPipeline().addLast("VisualizerService", VisualizerService.getInstance());
    //            log.debug("Forward request to visualizer.");
    //        }

    /*else if(targetUriPath.startsWith(SERVER_PATH_TO_SLSE_UI)) {
    	String f = LOCAL_PATH_TO_SLSE_UI + targetUriPath.substring(SERVER_PATH_TO_SLSE_UI.length());
    	Channels.write(ctx.getChannel(), Answer.create(new File(f)).setMime("text/n3"));
    }*/

    else if ("/".equals(targetUri.getRawPath())) {
      HttpResponse httpResponse =
          new DefaultHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK);

      httpResponse.setContent(getHtmlListOfServices());
      ChannelFuture future = Channels.write(ctx.getChannel(), httpResponse);
      future.addListener(ChannelFutureListener.CLOSE);
      return;
    } else if (httpRequest.getUri().endsWith("spitfire-logo.png")
        || (httpRequest.getUri().endsWith("favicon.ico"))) {
      File img;
      if (httpRequest.getUri().endsWith("spitfire-logo.png")) {
        img = new File("spitfire-logo.png");
      } else {
        img = new File("favicon.ico");
      }

      int imgLength = (int) img.length();

      FileInputStream in = new FileInputStream(img);
      byte[] imgMemory = new byte[imgLength];
      in.read(imgMemory);
      in.close();

      HttpResponse httpResponse =
          new DefaultHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK);
      httpResponse.setContent(ChannelBuffers.wrappedBuffer(imgMemory));
      ChannelFuture future = Channels.write(ctx.getChannel(), httpResponse);
      future.addListener(ChannelFutureListener.CLOSE);

      if (httpRequest.getUri().endsWith("spitfire-logo.png")) {
        log.debug("Served request for Spitfire image.");
      } else {
        log.debug("Served favicon.");
      }

      return;
    }

    ctx.sendUpstream(e);
  }
  @Override
  protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg)
      throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;
    int type = buf.readUnsignedShort();
    buf.readUnsignedShort(); // length

    if (type == MSG_IDENT || type == MSG_IDENT_FULL) {

      buf.readUnsignedInt(); // id
      int length = buf.readUnsignedShort();
      buf.skipBytes(length);
      length = buf.readUnsignedShort();
      buf.skipBytes(length);
      length = buf.readUnsignedShort();
      String imei = buf.readBytes(length).toString(Charset.defaultCharset());
      identify(imei, channel, remoteAddress);

    } else if (hasDeviceId() && (type == MSG_POINT || type == MSG_ALARM || type == MSG_LOGMSG)) {

      List<Position> positions = new LinkedList<>();

      int recordCount = 1;
      if (type == MSG_LOGMSG) {
        recordCount = buf.readUnsignedShort();
      }

      for (int j = 0; j < recordCount; j++) {
        Position position = new Position();
        position.setProtocol(getProtocolName());
        position.setDeviceId(getDeviceId());

        if (type == MSG_LOGMSG) {
          position.set(Event.KEY_ARCHIVE, true);
          int subtype = buf.readUnsignedShort();
          if (subtype == MSG_ALARM) {
            position.set(Event.KEY_ALARM, true);
          }
          if (buf.readUnsignedShort() > buf.readableBytes()) {
            lastIndex += 1;
            break; // workaround for device bug
          }
          lastIndex = buf.readUnsignedInt();
          position.set(Event.KEY_INDEX, lastIndex);
        } else {
          newIndex = buf.readUnsignedInt();
        }

        position.setTime(new Date(buf.readUnsignedInt() * 1000));
        position.setLatitude(buf.readInt() * 180.0 / 0x7FFFFFFF);
        position.setLongitude(buf.readInt() * 180.0 / 0x7FFFFFFF);
        position.setSpeed(buf.readUnsignedInt() * 0.01);
        position.setCourse(buf.readUnsignedShort() * 0.01);
        position.setAltitude(buf.readUnsignedShort() * 0.01);

        int satellites = buf.readUnsignedByte();
        position.setValid(satellites >= 3);
        position.set(Event.KEY_SATELLITES, satellites);

        position.set(Event.KEY_GSM, buf.readUnsignedByte());
        position.set(Event.KEY_ODOMETER, buf.readUnsignedInt());

        long extraFlags = buf.readLong();

        if (BitUtil.check(extraFlags, 0)) {
          int count = buf.readUnsignedShort();
          for (int i = 1; i <= count; i++) {
            position.set(Event.PREFIX_ADC + i, buf.readUnsignedShort());
          }
        }

        if (BitUtil.check(extraFlags, 1)) {
          int size = buf.readUnsignedShort();
          position.set("can", buf.toString(buf.readerIndex(), size, Charset.defaultCharset()));
          buf.skipBytes(size);
        }

        if (BitUtil.check(extraFlags, 2)) {
          position.set("passenger", ChannelBuffers.hexDump(buf.readBytes(buf.readUnsignedShort())));
        }

        if (type == MSG_ALARM) {
          position.set(Event.KEY_ALARM, true);
          byte[] response = {(byte) 0xC9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
          channel.write(ChannelBuffers.wrappedBuffer(response));
        }

        buf.readUnsignedInt(); // crc

        positions.add(position);
      }

      requestArchive(channel);

      return positions;
    }

    return null;
  }