コード例 #1
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);
  }
コード例 #2
0
ファイル: NettyCommunicator.java プロジェクト: jhorey/Paja
    @Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) {
      PaxosMessage msg;
      ChannelBuffer sendBuf;
      byte[] data;

      msg = (PaxosMessage) e.getMessage(); // The original message.

      // Serialize the message.
      data = msg.serialize();
      sendBuf = ChannelBuffers.buffer(data.length);
      sendBuf.writeBytes(data); // Write the actual msg.

      // Send the message upstream.
      Channels.write(ctx, e.getFuture(), sendBuf);
    }
コード例 #3
0
  private void writeReset(final InetSocketAddress remoteEndpoint, final int messageID) {
    try {
      CoapMessage resetMessage = CoapMessage.createEmptyReset(messageID);
      ChannelFuture future = Channels.future(ctx.getChannel());

      Channels.write(this.getChannelHandlerContext(), future, resetMessage, remoteEndpoint);

      future.addListener(
          new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
              log.info("RST for message ID {} succesfully sent to {}.", messageID, remoteEndpoint);
            }
          });
    } catch (IllegalArgumentException e) {
      log.error("This should never happen.", e);
    }
  }
コード例 #4
0
  private void writeEmptyAcknowledgement(
      final InetSocketAddress remoteAddress, final int messageID) {
    try {
      CoapMessage emptyAcknowledgement = CoapMessage.createEmptyAcknowledgement(messageID);

      ChannelFuture future = Channels.future(ctx.getChannel());
      Channels.write(ctx, future, emptyAcknowledgement, remoteAddress);

      future.addListener(
          new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
              log.info(
                  "Empty ACK for message ID {} succesfully sent to {}.", messageID, remoteAddress);
            }
          });
    } catch (IllegalArgumentException e) {
      log.error("This should never happen.", e);
    }
  }
コード例 #5
0
  @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);

    }
  }