Exemplo n.º 1
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();

    if (request.getContent().readableBytes() == 0) {
      BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected.");
      return;
    }

    transportMetrics.messagesReceived.mark();
    transportMetrics.messagesReceivedSize.update(request.getContent().readableBytes());

    // logger.debug("Received {}", request.getContent().toString(CharsetUtil.UTF_8));

    String contentTypeHeader = request.getHeader(CONTENT_TYPE);
    if (contentTypeHeader == null) {
      contentTypeHeader = BaseTransport.CONTENT_TYPE_PLAIN;
    }

    String decodedContent;
    if (BaseTransport.CONTENT_TYPE_FORM.equals(contentTypeHeader)) {
      QueryStringDecoder decoder =
          new QueryStringDecoder("?" + request.getContent().toString(CharsetUtil.UTF_8));
      List<String> d = decoder.getParameters().get("d");
      if (d == null) {
        BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected.");
        return;
      }
      decodedContent = d.get(0);
    } else {
      decodedContent = request.getContent().toString(CharsetUtil.UTF_8);
    }

    if (decodedContent.length() == 0) {
      BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected.");
      return;
    }

    String[] messages = MAPPER.readValue(decodedContent, String[].class);
    for (String message : messages) {
      SockJsMessage jsMessage = new SockJsMessage(message);
      ctx.sendUpstream(new UpstreamMessageEvent(e.getChannel(), jsMessage, e.getRemoteAddress()));
    }

    if (isJsonpEnabled) {
      BaseTransport.respond(e.getChannel(), OK, "ok");
    } else {
      BaseTransport.respond(e.getChannel(), NO_CONTENT, "");
    }
  }
  @Override
  protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg)
      throws Exception {

    HttpRequest request = (HttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

    DeviceSession deviceSession =
        getDeviceSession(channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
    if (deviceSession == null) {
      return null;
    }

    Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
    if (!parser.matches()) {
      return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    DateBuilder dateBuilder =
        new DateBuilder()
            .setDateReverse(parser.nextInt(), parser.nextInt(), parser.nextInt())
            .setTime(parser.nextInt(), parser.nextInt(), parser.nextInt());
    position.setTime(dateBuilder.getDate());

    position.setValid(true);
    position.setLatitude(parser.nextDouble());
    position.setLongitude(parser.nextDouble());
    position.setAltitude(parser.nextDouble());
    position.setSpeed(parser.nextDouble());
    position.setCourse(parser.nextDouble());

    if (channel != null) {
      HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
      channel.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    return position;
  }
Exemplo n.º 3
0
  private void processRequest(ResponseReceivedEvent event) {

    HttpRequest request = event.getRequest();

    URI uri = null;
    try {
      uri = new URI(request.getUri());
    } catch (URISyntaxException ex) {
      logger.error(
          "Can't create URI from request uri (" + request.getUri() + ")" + ex.getStackTrace());
    }

    events.addElement(request.getMethod() + " | " + request.getUri());
    executedEvents.ensureIndexIsVisible(events.getSize() - 1);

    int id = ++numberOfRequests;
    event.setId(id);

    /* URLs */
    if (urlBase == null) {
      protocol = uri.getScheme();
      host = uri.getHost();
      port = uri.getPort();
      urlBase = protocol + "://" + host;
      urlBaseString = "PROTOCOL + \"://\" + HOST";
      if (port != -1) {
        urlBase += ":" + port;
        urlBaseString += " + \":\" + PORT";
      }
    }

    String requestUrlBase = uri.getScheme() + "://" + uri.getHost();
    if (uri.getPort() != -1) requestUrlBase += ":" + uri.getPort();
    if (requestUrlBase.equals(urlBase)) event.setWithUrlBase(true);
    else urls.put("url_" + id, requestUrlBase + uri.getPath());

    String headerAuthorization = event.getRequest().getHeader("Authorization");
    request.removeHeader("Authorization");
    if (headerAuthorization != null) {
      if (basicAuth == null) {
        // Split on " " and take 2nd group (Basic credentialsInBase64==)
        String credentials =
            new String(Base64.decodeBase64(headerAuthorization.split(" ")[1].getBytes()));
        basicAuth =
            new BasicAuth(requestUrlBase, credentials.split(":")[0], credentials.split(":")[1]);
        event.setBasicAuth(basicAuth);
      } else {
        if (requestUrlBase.equals(basicAuth.getUrlBase())) event.setBasicAuth(basicAuth);
        else basicAuth = null;
      }
    }

    /* Headers */
    Map<String, String> requestHeaders = new TreeMap<String, String>();
    for (Entry<String, String> entry : request.getHeaders())
      requestHeaders.put(entry.getKey(), entry.getValue());
    requestHeaders.remove("Cookie");

    int bestChoice = 0;
    String headerKey = EMPTY;
    MapDifference<String, String> diff;
    Map<String, String> fullHeaders = new TreeMap<String, String>();
    boolean containsHeaders = false;

    if (headers.size() > 0) {
      for (Entry<String, Map<String, String>> header : headers.entrySet()) {

        fullHeaders = new TreeMap<String, String>(header.getValue());
        containsHeaders = false;

        if (header.getValue().containsKey("headers")) {
          fullHeaders.putAll(headers.get(header.getValue().get("headers")));
          fullHeaders.remove("headers");
          containsHeaders = true;
        }

        diff = Maps.difference(fullHeaders, requestHeaders);
        logger.debug(diff.toString());
        if (diff.areEqual()) {
          headerKey = header.getKey();
          bestChoice = 1;
          break;
        } else if (diff.entriesOnlyOnLeft().size() == 0
            && diff.entriesDiffering().size() == 0
            && !containsHeaders) {
          // header are included in requestHeaders
          headerKey = header.getKey();
          bestChoice = 2;
        } else if (bestChoice > 2
            && diff.entriesOnlyOnRight().size() == 0
            && diff.entriesDiffering().size() == 0
            && !containsHeaders) {
          // requestHeaders are included in header
          headerKey = header.getKey();
          bestChoice = 3;
        }
      }
    }

    switch (bestChoice) {
      case 1:
        event.setHeadersId(headerKey);
        break;
      case 2:
        diff = Maps.difference(headers.get(headerKey), requestHeaders);
        TreeMap<String, String> tm2 = new TreeMap<String, String>(diff.entriesOnlyOnRight());
        headers.put("headers_" + id, tm2);
        headers.get("headers_" + id).put("headers", headerKey);
        event.setHeadersId("headers_" + id);
        break;
      case 3:
        diff = Maps.difference(headers.get(headerKey), requestHeaders);
        TreeMap<String, String> tm3 = new TreeMap<String, String>(diff.entriesInCommon());
        headers.put("headers_" + id, tm3);
        event.setHeadersId("headers_" + id);
        headers.remove(headerKey);
        tm3 = new TreeMap<String, String>(diff.entriesOnlyOnLeft());
        headers.put(headerKey, tm3);
        headers.get(headerKey).put("headers", "headers_" + id);
        break;
      default:
        headers.put("headers_" + id, requestHeaders);
        event.setHeadersId("headers_" + id);
    }

    /* Add check if status is not in 20X */
    if ((event.getResponse().getStatus().getCode() < 200)
        || (event.getResponse().getStatus().getCode() > 210)) event.setWithCheck(true);

    /* Params */
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
    event.getRequestParams().putAll((decoder.getParameters()));

    /* Content */
    if (request.getContent().capacity() > 0) {
      String content = new String(request.getContent().array());
      // We check if it's a form validation and so we extract post params
      if ("application/x-www-form-urlencoded".equals(request.getHeader("Content-Type"))) {
        decoder = new QueryStringDecoder("http://localhost/?" + content);
        event.getRequestParams().putAll(decoder.getParameters());
      } else {
        event.setWithBody(true);
        dumpRequestBody(id, content);
      }
    }

    listEvents.add(event);
  }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (!(e.getMessage() instanceof HttpRequest)) {
      super.messageReceived(ctx, e);
    }

    HttpRequest request = (HttpRequest) e.getMessage();
    URI uri = entityManager.normalizeURI(getEntityManager().getURIBase() + request.getUri());
    String path = uri.getPath();

    System.out.println("# received request: " + uri);

    /*
     * TODO:
     * - if GET "$base/entities/create", return entity creation form
     * - if GET "$base/entities/" || GET "$base/.well-known/servers" return entity list
     * - if POST "$base/entities/", call createEntity($postdata)
     *
     * - if GET "$base/sources/", return sources list
     * - if GET "$base/sources/edit" return sources edit form
     * - if POST "$base/sources/", call setSources($postdata)
     */

    if (uri.equals(entityManager.normalizeURI(pathPrefix + "/list-entities"))) {
      if (request.getMethod() == HttpMethod.GET) {
        StringBuffer sb = new StringBuffer();
        sb.append("<html><head><title>SLSE List</title></head><body><h1>SLSE List</h1><ol>");

        for (ServiceLevelSemanticEntity slse : this.slseCache.getAll()) {
          sb.append("<li>");
          sb.append(slse.getURI() + "<pre>" + slse.getDescribes() + "</pre>");
          sb.append("</li>");
        }

        sb.append("</ol></body></html>");

        Channels.write(ctx.getChannel(), Answer.create(sb.toString()));
      }
    } else if (uri.equals(entityManager.normalizeURI(pathPrefix + "/create-entity"))) {
      if (request.getMethod() == HttpMethod.GET) {
        // copy into
        // HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(),
        // HttpResponseStatus.OK);
        // response.setContent(ChannelBuffers.wrappedBuffer(htmlContent));
        Channels.write(ctx.getChannel(), Answer.create(new String(htmlContent)));
        //				Channels.write(ctx.getChannel(),
        //						Answer.create(new File("data/slse/ui/create_entity_form.html")));
      } else if (request.getMethod() == HttpMethod.POST) {
        QueryStringDecoder qsd =
            new QueryStringDecoder(
                "http://blub.blah/?" + request.getContent().toString(Charset.defaultCharset()));

        String elementsQuery = "";
        String name = "";
        boolean dependsOnSensorValues = false;
        boolean multiNodeQuery = false;

        for (Map.Entry<String, List<String>> entry : qsd.getParameters().entrySet()) {
          String key = entry.getKey();
          for (String value : entry.getValue()) {
            if (entry.getKey().equals("elementsQuery")) {
              elementsQuery = value;
            } else if (entry.getKey().equals("name")) {
              name = value;
            } else if (key.equals("dependsOnSensorValues") && value.equals("yes")) {
              dependsOnSensorValues = true;
            } else if (key.equals("multiNodeQuery") && value.equals("yes")) {
              multiNodeQuery = true;
            }
          }
        }

        System.out.println(
            "# adding rule: name="
                + name
                + " dependsOnSensorValues="
                + dependsOnSensorValues
                + " multiNodeQuery="
                + multiNodeQuery);

        slseBuilder.addRule(name, elementsQuery, dependsOnSensorValues, multiNodeQuery);

        Channels.write(
            ctx.getChannel(),
            Answer.create(
                "<html><head><meta http-equiv=\"REFRESH\" content=\"0;url=/\"></head></html>"));
      }
    } else {
      uri = entityManager.toThing(uri);
      Model r = ModelFactory.createDefaultModel();

      if (waitForPolling) {
        //    System.out.println("# waiting for esecache: " + uri);
        synchronized (eseCache) {
          while (!eseCache.isPollComplete()) {
            try {
              eseCache.wait(1000);
            } catch (InterruptedException ex) {
              ex
                  .printStackTrace(); // To change body of catch statement use File | Settings |
                                      // File Templates.
            }
          }
        }
      }

      //  System.out.println("# waiting for slseCache: " + uri);
      synchronized (slseCache) {
        if (slseCache.get(uri.toString()) == null) {
          System.out.println(
              "! SLSE not found in cache: " + uri.toString() + " returning empty model");
        } else {
          r.add(slseCache.get(uri.toString()).getModel());
        }
      }
      ChannelFuture future = Channels.write(ctx.getChannel(), r);
      if (!HttpHeaders.isKeepAlive(request)) {
        future.addListener(ChannelFutureListener.CLOSE);
      }
      // System.out.println("# done: " + uri);

    }
  }