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

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


        sendSimpleHttpResponse(httpExchange, HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      // get the response
      Response coapResponse = null;
      try {
        coapResponse = exchanger.exchange(Response_NULL, GATEWAY_TIMEOUT, TimeUnit.MILLISECONDS);
      } catch (TimeoutException e) {
        LOGGER.warning("Timeout occurred");
        // send the timeout error message
View Full Code Here


    responseCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).recordStats().expireAfterWrite(CACHE_RESPONSE_MAX_AGE, TimeUnit.SECONDS).build(new CacheLoader<CacheKey, Response>() {
      @Override
      public Response load(CacheKey request) throws NullPointerException {
        // retreive the response from the incoming request, no
        // exceptions are thrown
        Response cachedResponse = request.getResponse();

        // check for null and raise an exception that clients must
        // handle
        if (cachedResponse == null) {
          throw new NullPointerException();
View Full Code Here

        // increase the max-age value according to the new response
//        Option maxAgeOption = response.getFirstOption(OptionNumberRegistry.MAX_AGE);
        Long maxAgeOption = response.getOptions().getMaxAge();
        if (maxAgeOption != null) {
          // get the cached response
          Response cachedResponse = responseCache.getUnchecked(cacheKey);

          // calculate the new parameters
          long newCurrentTime = response.getTimestamp();
          int newMaxAge = maxAgeOption.intValue();

          // set the new parameters
//          cachedResponse.getFirstOption(OptionNumberRegistry.MAX_AGE).setIntValue(newMaxAge);
          cachedResponse.getOptions().setMaxAge(newMaxAge);
          cachedResponse.setTimestamp(newCurrentTime);

          LOGGER.finer("Updated cached response");
        } else {
          LOGGER.warning("No max-age option set in response: " + response);
        }
      } else if (code == ResponseCode.CONTENT) {
        // set max-age if not set
//        Option maxAgeOption = response.getFirstOption(OptionNumberRegistry.MAX_AGE);
        Long maxAgeOption = response.getOptions().getMaxAge();
        if (maxAgeOption == null) {
          response.getOptions().setMaxAge(OptionNumberRegistry.DEFAULT_MAX_AGE);
        }

        if (maxAgeOption > 0) {
          // cache the request
          try {
            // Caches loaded by a CacheLoader will call
            // CacheLoader.load(K) to load new values into the cache
            // when used the get method.
            Response responseInserted = responseCache.get(cacheKey);
            if (responseInserted != null) {
//              if (Bench_Help.DO_LOG)
                LOGGER.finer("Cached response");
            } else {
              LOGGER.warning("Failed to insert the response in the cache");
View Full Code Here

    // get the status
    ResponseCode status = incomingResponse.getCode();

    // create the response
    Response outgoingResponse = new Response(status);

    // copy payload
    byte[] payload = incomingResponse.getPayload();
    outgoingResponse.setPayload(payload);

    // copy the timestamp
    long timestamp = incomingResponse.getTimestamp();
    outgoingResponse.setTimestamp(timestamp);

    // copy every option
    outgoingResponse.setOptions(new OptionSet(
        incomingResponse.getOptions()));
   
    LOGGER.finer("Incoming response translated correctly");
    return outgoingResponse;
  }
View Full Code Here

    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
        Response outgoingResponse = CoapTranslator.getResponse(receivedResponse);

        return outgoingResponse;
      } else {
        LOGGER.warning("No response received.");
        return new Response(CoapTranslator.STATUS_TIMEOUT);
      }
    } catch (InterruptedException e) {
      LOGGER.warning("Receiving of response interrupted: " + e.getMessage());
      return new Response(ResponseCode.INTERNAL_SERVER_ERROR);
    }
  }
View Full Code Here

    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) {
      LOGGER.warning("Proxy-uri option malformed: " + e.getMessage());
      return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    }

    // get the requested host, if the port is not specified, the constructor
    // sets it to -1
    HttpHost httpHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());

    HttpRequest httpRequest = null;
    try {
      // get the mapping to http for the incoming coap request
      httpRequest = HttpTranslator.getHttpRequest(incomingCoapRequest);
      LOGGER.finer("Outgoing http request: " + httpRequest.getRequestLine());
    } catch (InvalidFieldException e) {
      LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
      return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
    } catch (TranslationException e) {
      LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
      return new Response(CoapTranslator.STATUS_TRANSLATION_ERROR);
    }

    ResponseHandler<Response> httpResponseHandler = new ResponseHandler<Response>() {
      @Override
      public Response handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
        long timestamp = System.nanoTime();
        LOGGER.finer("Incoming http response: " + httpResponse.getStatusLine());
        // the entity of the response, if non repeatable, could be
        // consumed only one time, so do not debug it!
        // System.out.println(EntityUtils.toString(httpResponse.getEntity()));

        // translate the received http response in a coap response
        try {
          Response coapResponse = HttpTranslator.getCoapResponse(httpResponse, incomingCoapRequest);
          coapResponse.setTimestamp(timestamp);
          return coapResponse;
        } catch (InvalidFieldException e) {
          LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
          return new Response(CoapTranslator.STATUS_FIELD_MALFORMED);
        } catch (TranslationException e) {
          LOGGER.warning("Problems during the http/coap translation: " + e.getMessage());
          return new Response(CoapTranslator.STATUS_TRANSLATION_ERROR);
        }
      }
    };

    // accept the request sending a separate response to avoid the timeout
    // in the requesting client
    LOGGER.finer("Acknowledge message sent");

    Response coapResponse = null;
    try {
      // execute the request
      coapResponse = HTTP_CLIENT.execute(httpHost, httpRequest, httpResponseHandler, null);
    } catch (IOException e) {
      LOGGER.warning("Failed to get the http response: " + e.getMessage());
      return new Response(ResponseCode.INTERNAL_SERVER_ERROR);
    }

    return coapResponse;
  }
View Full Code Here

        throw new TranslationException("Cannot convert the status code in number", e);
      }
    }

    // create the coap reaponse
    Response coapResponse = new Response(coapCode);

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

    // the response should indicate a max-age value (CoAP 10.1.1)
//    if (coapResponse.getFirstOption(OptionRegistry.MAX_AGE) == null) {
    if (!coapResponse.getOptions().hasMaxAge()) {
      // The Max-Age Option for responses to POST, PUT or DELETE requests
      // should always be set to 0 (draft-castellani-core-http-mapping).
      if (coapMethod == Code.GET) {
        coapResponse.getOptions().setMaxAge(OptionNumberRegistry.DEFAULT_MAX_AGE);
      } else {
        coapResponse.getOptions().setMaxAge(0);
      }
    }

    // get the entity
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
      // translate the http entity in coap payload
      byte[] payload = getCoapPayload(httpEntity);
      if (payload != null && payload.length > 0) {
        coapResponse.setPayload(payload);

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

    return coapResponse;
  }
View Full Code Here

  }

  @Override
  public void handleRequest(Exchange exchange) {
    exchange.sendAccept();
    Response response = forwardRequest(exchange.getRequest());
    exchange.sendResponse(response);
  }
View Full Code Here

TOP

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

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.