Package ch.ethz.inf.vs.californium.coap

Examples of ch.ethz.inf.vs.californium.coap.Request


  /*
   *  Sends a GET request to itself
   */
  public static void selfTest() {
    try {
      Request request = Request.newGet();
      request.setURI("localhost:5683/hello");
      request.send();
      Response response = request.waitForResponse(1000);
      System.out.println("received "+response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
View Full Code Here


  /**
   * This method uses the internal {@link Exchange} class for advanced handling.
   */
  @Override
  public void handleRequest(Exchange exchange) {
    Request request = exchange.getRequest();
    StringBuilder buffer = new StringBuilder();
    buffer.append("resource ").append(getURI()).append(" received request")
      .append("\n").append("Code: ").append(request.getCode())
      .append("\n").append("Source: ").append(request.getSource()).append(":").append(request.getSourcePort())
      .append("\n").append("Type: ").append(request.getType())
      .append("\n").append("MID: ").append(request.getMID())
      .append("\n").append("Token: ").append(request.getTokenString())
      .append("\n").append(request.getOptions());
    Response response = new Response(ResponseCode.CONTENT);
    response.setPayload(buffer.toString());
    response.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    exchange.sendResponse(response);
  }
View Full Code Here

//        if (Bench_Help.DO_LOG)
          LOGGER.finer("Incoming http request: " + httpRequest.getRequestLine());

        try {
          // translate the request in a valid coap request
          Request coapRequest = HttpTranslator.getCoapRequest(httpRequest, localResource, proxyingEnabled);
//          if (Bench_Help.DO_LOG)
            LOGGER.info("Received HTTP request and translate to "+coapRequest);

          // fill the maps
          exchangeMap.put(coapRequest, new Exchanger<Response>());
//          if (Bench_Help.DO_LOG)
            LOGGER.finer("Fill exchange with: " + coapRequest+" with hash="+coapRequest.hashCode());

          // the new thread will wait for the completion of
          // the coap request
          Thread worker = new CoapResponseWorker("HttpStack Worker", coapRequest, httpExchange, httpRequest);
View Full Code Here

    // get message type
    Type type = incomingRequest.getType();

    // create the request
    Request outgoingRequest = new Request(code);
    outgoingRequest.setConfirmable(type == Type.CON);

    // copy payload
    byte[] payload = incomingRequest.getPayload();
    outgoingRequest.setPayload(payload);

    // get the uri address from the proxy-uri option
    URI serverUri;
    try {
      /*
       * The new draft (14) only allows one proxy-uri option. Thus, this
       * code segment has changed.
       */
      String proxyUriString = URLDecoder.decode(
          incomingRequest.getOptions().getProxyURI(), "UTF-8");
      serverUri = new URI(proxyUriString);
    } catch (UnsupportedEncodingException e) {
      LOGGER.warning("UTF-8 do not support this encoding: " + e);
      throw new TranslationException("UTF-8 do not support this encoding", e);
    } catch (URISyntaxException e) {
      LOGGER.warning("Cannot translate the server uri" + e);
      throw new TranslationException("Cannot translate the server uri", e);
    }

    // copy every option from the original message
    // do not copy the proxy-uri option because it is not necessary in
    // the new message
    // do not copy the token option because it is a local option and
    // have to be assigned by the proper layer
    // do not copy the block* option because it is a local option and
    // have to be assigned by the proper layer
    // do not copy the uri-* options because they are already filled in
    // the new message
    OptionSet options = new OptionSet(incomingRequest.getOptions());
    options.removeProxyURI();
    options.removeBlock1();
    options.removeBlock2();
    options.clearURIPaths();
    options.clearURIQuery();
    outgoingRequest.setOptions(options);
   
    // set the proxy-uri as the outgoing uri
    if (serverUri != null) {
      outgoingRequest.setURI(serverUri);
    }

    LOGGER.finer("Incoming request translated correctly");
    return outgoingRequest;
  }
View Full Code Here

  }

  @Override
  public Response forwardRequest(Request request) {
    LOGGER.info("ProxyCoAP2CoAP forwards "+request);
    Request incomingRequest = request;

    // check the invariant: the request must have the proxy-uri set
    if (!incomingRequest.getOptions().hasProxyURI()) {
      LOGGER.warning("Proxy-uri option not set.");
      return new Response(ResponseCode.BAD_OPTION);
    }

    // remove the fake uri-path
    // FIXME: HACK // TODO: why? still necessary in new Cf?
    incomingRequest.getOptions().clearURIPaths();

    // create a new request to forward to the requested coap server
    Request outgoingRequest = null;
    try {
      // create the new request from the original
      outgoingRequest = CoapTranslator.getRequest(incomingRequest);

//      // enable response queue for blocking I/O
//      outgoingRequest.enableResponseQueue(true);

      // get the token from the manager // TODO: necessary?
//      outgoingRequest.setToken(TokenManager.getInstance().acquireToken());

      // execute the request
      LOGGER.finer("Sending coap request.");
//      outgoingRequest.execute();
      LOGGER.info("ProxyCoapClient received CoAP request and sends a copy to CoAP target");
      outgoingRequest.send();

      // accept the request sending a separate response to avoid the
      // timeout in the requesting client
      LOGGER.finer("Acknowledge message sent");
    } catch (TranslationException e) {
      LOGGER.warning("Proxy-uri option malformed: " + e.getMessage());
      return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    } catch (Exception e) {
      LOGGER.warning("Failed to execute request: " + e.getMessage());
      return new Response(ResponseCode.INTERNAL_SERVER_ERROR);
    }

    try {
      // receive the response // TODO: don't wait for ever
      Response receivedResponse = outgoingRequest.waitForResponse();

      if (receivedResponse != null) {
        LOGGER.finer("Coap response received.");

        // create the real response for the original request
View Full Code Here

    getAttributes().setTitle("Forward the requests to a HTTP client.");
  }

  @Override
  public Response forwardRequest(Request request) {
    final Request incomingCoapRequest = request;
   
    // check the invariant: the request must have the proxy-uri set
    if (!incomingCoapRequest.getOptions().hasProxyURI()) {
      LOGGER.warning("Proxy-uri option not set.");
      return new Response(ResponseCode.BAD_OPTION);
    }

    // remove the fake uri-path // TODO: why? still necessary in new Cf?
    incomingCoapRequest.getOptions().clearURIPaths();; // HACK

    // get the proxy-uri set in the incoming coap request
    URI proxyUri;
    try {
      String proxyUriString = URLDecoder.decode(
          incomingCoapRequest.getOptions().getProxyURI(), "UTF-8");
      proxyUri = new URI(proxyUriString);
    } catch (UnsupportedEncodingException e) {
      LOGGER.warning("Proxy-uri option malformed: " + e.getMessage());
      return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    } catch (URISyntaxException e) {
View Full Code Here

      throw new TranslationException("Cannot convert the http method in coap method", e);
    }

    // create the request
//    Request coapRequest = Request.getRequestForMethod(coapMethod);
    Request coapRequest = new Request(Code.valueOf(coapMethod));

    // get the uri
    String uriString = httpRequest.getRequestLine().getUri();
    // remove the initial "/"
    uriString = uriString.substring(1);

    // decode the uri to translate the application/x-www-form-urlencoded
    // format
    try {
      uriString = URLDecoder.decode(uriString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      LOGGER.warning("Failed to decode the uri: " + e.getMessage());
      throw new TranslationException("Failed decoding the uri: " + e.getMessage());
    } catch (Throwable e) {
      LOGGER.warning("Malformed uri: " + e.getMessage());
      throw new InvalidFieldException("Malformed uri: " + e.getMessage());
    }

    // if the uri contains the proxy resource name, the request should be
    // forwarded and it is needed to get the real requested coap server's
    // uri
    // e.g.:
    // /proxy/vslab-dhcp-17.inf.ethz.ch:5684/helloWorld
    // proxy resource: /proxy
    // coap server: vslab-dhcp-17.inf.ethz.ch:5684
    // coap resource: helloWorld
    if (uriString.matches(".?" + proxyResource + ".*")) {

      // find the first occurrence of the proxy resource
      int index = uriString.indexOf(proxyResource);
      // delete the slash
      index = uriString.indexOf('/', index);
      uriString = uriString.substring(index + 1);

      if (proxyingEnabled) {
        // if the uri hasn't the indication of the scheme, add it
        if (!uriString.matches("^coap://.*")) {
          uriString = "coap://" + uriString;
        }

        // the uri will be set as a proxy-uri option
        // set the proxy-uri option to allow the lower layers to underes
//        Option proxyUriOption = new Option(uriString, OptionRegistry.PROXY_URI);
//        coapRequest.addOption(proxyUriOption);
        coapRequest.getOptions().setProxyURI(uriString);
      } else {
        coapRequest.setURI(uriString);
      }

      // set the proxy as the sender to receive the response correctly
      try {
        // TODO check with multihomed hosts
        InetAddress localHostAddress = InetAddress.getLocalHost();
//        InetSocketAddress localHostEndpoint = new InetSocketAddress(localHostAddress);
//        coapRequest.setPeerAddress(localHostEndpoint);
        coapRequest.setDestination(localHostAddress);
        // TODO: setDestinationPort???
      } catch (UnknownHostException e) {
        LOGGER.warning("Cannot get the localhost address: " + e.getMessage());
        throw new TranslationException("Cannot get the localhost address: " + e.getMessage());
      }
    } else {
      // if the uri does not contains the proxy resource, it means the
      // request is local to the proxy and it shouldn't be forwarded

      // set the uri string as uri-path option
//      Option uriPathOption = new Option(uriString, OptionRegistry.URI_PATH);
//      coapRequest.setOption(uriPathOption);
      coapRequest.getOptions().setURIPath(uriString);
    }

    // translate the http headers in coap options
    List<Option> coapOptions = getCoapOptions(httpRequest.getAllHeaders());
//    coapRequest.setOptions(coapOptions);
    for (Option option:coapOptions)
      coapRequest.getOptions().addOption(option);

    // set the payload if the http entity is present
    if (httpRequest instanceof HttpEntityEnclosingRequest) {
      HttpEntity httpEntity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();

      // translate the http entity in coap payload
      byte[] payload = getCoapPayload(httpEntity);
      coapRequest.setPayload(payload);

      // set the content-type
      int coapContentType = getCoapMediaType(httpRequest);
      coapRequest.getOptions().setContentFormat(coapContentType);
    }

    return coapRequest;
  }
View Full Code Here

    client.setURI(uri + "/test");

    System.out.println("===============\nCC12");
    System.out.println("---------------\nGET /test w/o Token\n---------------");
    Request req12 = Request.newGet(); // never re-use a Request object
    req12.setToken(new byte[0]);
    response = client.advanced(req12);
    System.out.println(response.advanced().getType() + "-" + response.getCode());
    System.out.println(response.getResponseText());
   
    client.setURI(uri + "/seg1/seg2/seg3");
View Full Code Here

  public VeryEcoMessageProducer() { }
 
  public void setURI(URI uri) {
    Serializer serializer = new Serializer();
    Request request = new Request(Code.GET);
    request.setType(Type.CON);
    request.setToken(new byte[0]);
    request.setMID(0);
    request.setURI(uri);
    prototype = serializer.serialize(request).getBytes();
  }
View Full Code Here

    int count = 0;
    this.array = new ArrayList<RawData>(amount);
    for (int port = 1; port < (1 << 16) && count < amount; port++) {
      for (int mid = 0; mid < (1 << 16) && count < amount; mid++) {
        Request request = new Request(Code.GET);
        request.setType(Type.NON);
        request.setToken(new byte[0]);
        request.setMID(mid);
        request.setURI(targetURI);

        RawData raw = serializer.serialize(request);
        raw.setAddress(source);
        raw.setPort(port);
        array.add(raw);
View Full Code Here

TOP

Related Classes of ch.ethz.inf.vs.californium.coap.Request

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.