Search in sources :

Example 6 with Code

use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.

the class Coap2HttpTranslator method getCoapResponse.

/**
 * Gets the CoAP response from an incoming HTTP response. No {@code null}
 * value is returned. The response is created from a the mapping of the HTTP
 * response code retrieved from the properties file. If the code is 204,
 * which has multiple meaning, the mapping is handled looking on the request
 * method that has originated the response. The options are set through the
 * HTTP headers and the option max-age, if not indicated, is set to the
 * default value (60 seconds). if the response has an enclosing entity, it
 * is mapped to a CoAP payload and the content-type of the CoAP message is
 * set properly.
 *
 * @param httpResponse the http-response
 * @param coapRequest related coap-request. Some response codes are
 *            translated according the requested code.
 * @return the coap response
 * @throws TranslationException the translation exception
 * @throws NullPointerException if one of the provided arguments is
 *             {@code null}.
 */
public Response getCoapResponse(Message<HttpResponse, ContentTypedEntity> httpResponse, Request coapRequest) throws TranslationException {
    if (httpResponse == null) {
        throw new NullPointerException("Http-response must not be null!");
    }
    if (coapRequest == null) {
        throw new NullPointerException("Coap-request must not be null!");
    }
    // get/set the response code
    int httpCode = httpResponse.getHead().getCode();
    Code coapMethod = coapRequest.getCode();
    // get the translation from the property file
    ResponseCode coapCode = httpTranslator.getCoapResponseCode(coapMethod, httpCode);
    // create the coap response
    Response coapResponse = new Response(coapCode);
    // translate the http headers in coap options
    List<Option> coapOptions = httpTranslator.getCoapOptions(httpResponse.getHead().getHeaders(), etagTranslator);
    coapResponse.getOptions().addOptions(coapOptions);
    // 10.1.1)
    if (!coapResponse.getOptions().hasMaxAge()) {
        // should always be set to 0 (draft-castellani-core-http-mapping).
        if (coapMethod == Code.GET) {
            coapResponse.getOptions().setMaxAge(OptionNumberRegistry.Defaults.MAX_AGE);
        } else {
            coapResponse.getOptions().setMaxAge(0);
        }
    }
    // translate the http body in coap payload
    ContentTypedEntity entity = httpResponse.getBody();
    httpTranslator.setCoapPayload(entity, coapResponse);
    LOGGER.debug("Incoming response translated correctly");
    return coapResponse;
}
Also used : Response(org.eclipse.californium.core.coap.Response) HttpResponse(org.apache.hc.core5.http.HttpResponse) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Option(org.eclipse.californium.core.coap.Option) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Code(org.eclipse.californium.core.coap.CoAP.Code)

Example 7 with Code

use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.

the class Http2CoapTranslator method getCoapRequest.

/**
 * Gets the coap request.
 *
 * Creates the CoAP request from the HTTP method and mapping it through the
 * properties file. The URI is translated by extracting the part after the
 * provided httpResource.
 * (http://proxyname.domain:80/proxy/coap://coapserver:5683/resource
 * converted in coap://coapserver:5683/resource.) It support proxy requests
 * or request mapped to a local coap-server. It also support http-request
 * send to this proxy using the http-proxy function itself. Though the
 * primary scheme maybe tested to be http/https, the destination scheme must
 * The method uses a decoder to translate the
 * application/x-www-form-urlencoded format of the uri. The CoAP options are
 * set translating the headers. If the HTTP message has an enclosing entity,
 * it is converted to create the payload of the CoAP message; finally the
 * content-type is set accordingly to the header and to the entity type.
 *
 * @param httpRequest the http request
 * @param httpResource the http resource, if present in the uri, indicates
 *            the need of forwarding for the current request
 * @param proxyingEnabled {@code true} to forward the request using the
 *            sub-path as URI, {@code false} to access a local coap
 *            resource.
 * @return the coap request
 * @throws TranslationException the translation exception
 * @throws NullPointerException if one of the provided arguments is
 *             {@code null}.
 */
public Request getCoapRequest(Message<HttpRequest, ContentTypedEntity> httpRequest, String httpResource, boolean proxyingEnabled) throws TranslationException {
    if (httpRequest == null) {
        throw new NullPointerException("httpRequest must not be null!");
    }
    if (httpResource == null) {
        throw new NullPointerException("httpResource must not be null!");
    }
    // get the http method
    String httpMethod = httpRequest.getHead().getMethod();
    // get the coap method
    Code code = httpTranslator.getCoapCode(httpMethod);
    // create the request -- since HTTP is reliable use CON
    Request coapRequest = new Request(code, Type.CON);
    // get the uri
    URI uri;
    try {
        uri = httpRequest.getHead().getUri();
        LOGGER.debug("URI <= '{}'", uri);
    } catch (URISyntaxException ex) {
        throw new TranslationException("Malformed uri: " + ex.getMessage());
    }
    if (!httpResource.startsWith("/")) {
        httpResource = "/" + httpResource;
    }
    // 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/coap://vslab-dhcp-17.inf.ethz.ch:5684/helloWorld
    // proxy resource: /proxy
    // coap server: coap://vslab-dhcp-17.inf.ethz.ch:5684
    // coap resource: helloWorld
    String path = uri.getPath();
    LOGGER.debug("URI path => '{}'", path);
    if (path.startsWith(httpResource + "/")) {
        path = path.substring(httpResource.length() + 1);
        String target = path;
        if (uri.getQuery() != null) {
            target = path + "?" + uri.getQuery();
        }
        int index = target.indexOf(":/");
        if (index > 0) {
            // "coap://host" may have been normalized to "coap:/host"
            index += 2;
            if (target.charAt(index) != '/') {
                // add /
                target = target.substring(0, index) + "/" + target.substring(index);
            }
        }
        try {
            uri = new URI(target);
            if (proxyingEnabled) {
                // if the uri hasn't the indication of the scheme, add it
                if (uri.getScheme() == null) {
                    throw new InvalidFieldException("Malformed uri: destination scheme missing! Use http://<proxy-host>" + httpResource + "/coap://<destination-host>/<path>");
                }
                // the uri will be set as a proxy-uri option
                LOGGER.debug("URI destination => '{}'", target);
                coapRequest.getOptions().setProxyUri(target);
            } else {
                if (uri.getScheme() != null) {
                    throw new InvalidFieldException("Malformed uri: local destination doesn't support scheme! Use http://<proxy-host>" + httpResource + "/<path>");
                }
                // the uri will be set as a coap-uri
                target = "coap://localhost/" + target;
                LOGGER.debug("URI local => '{}'", target);
                coapRequest.setURI(target);
            }
        } catch (URISyntaxException e) {
            LOGGER.warn("Malformed destination uri", e);
            throw new InvalidFieldException("Malformed destination uri: " + target + "!");
        }
    } else if (proxyingEnabled && path.equals(httpResource)) {
        String target = null;
        if (uri.getQuery() != null) {
            List<NameValuePair> query = WWWFormCodec.parse(uri.getQuery(), StandardCharsets.UTF_8);
            for (NameValuePair arg : query) {
                if (arg.getName().equalsIgnoreCase("target_uri")) {
                    target = arg.getValue();
                    break;
                }
            }
        }
        if (target == null) {
            throw new InvalidFieldException("Malformed uri: target_uri is missing! Use http://<proxy-host>" + httpResource + "?target_uri=coap://<destination-host>/<path>");
        }
        try {
            uri = new URI(target);
            // if the uri hasn't the indication of the scheme, add it
            if (uri.getScheme() == null) {
                throw new InvalidFieldException("Malformed uri: destination scheme missing! Use http://<proxy-host>" + httpResource + "?target_uri=coap://<destination-host>/<path>");
            }
            // the uri will be set as a proxy-uri option
            LOGGER.debug("URI destination => '{}'", target);
            coapRequest.getOptions().setProxyUri(target);
        } catch (URISyntaxException e) {
            LOGGER.warn("Malformed destination uri", e);
            throw new InvalidFieldException("Malformed destination uri: " + target + "!");
        }
    } else if (proxyingEnabled && uri.getScheme() != null) {
        // http-server configured as http-proxy
        int index = path.lastIndexOf('/');
        if (0 < index) {
            String scheme = path.substring(index + 1);
            if (scheme.matches("\\w+:$")) {
                scheme = scheme.substring(0, scheme.length() - 1);
                path = path.substring(0, index);
                try {
                    URI destination = new URI(scheme, null, uri.getHost(), uri.getPort(), path, uri.getQuery(), null);
                    coapRequest.getOptions().setProxyUri(destination.toASCIIString());
                } catch (URISyntaxException e) {
                    LOGGER.debug("Malformed proxy uri", e);
                    throw new TranslationException("Malformed proxy uri: '" + uri + "' " + e.getMessage());
                }
            } else {
                throw new TranslationException("Malformed proxy uri: target scheme missing! Use http://<destination-host>/<path>/<target-scheme>:");
            }
        } else {
            throw new TranslationException("Malformed proxy uri: target scheme missing! Use http://<destination-host>/<path>/<target-scheme>:");
        }
    } else {
        throw new IllegalArgumentException("URI '" + uri + "' doesn't match handler '" + httpResource + "'!");
    }
    // translate the http headers in coap options
    List<Option> coapOptions = httpTranslator.getCoapOptions(httpRequest.getHead().getHeaders(), etagTranslator);
    coapRequest.getOptions().addOptions(coapOptions);
    // set the payload if the http entity is present
    ContentTypedEntity entity = httpRequest.getBody();
    httpTranslator.setCoapPayload(entity, coapRequest);
    return coapRequest;
}
Also used : NameValuePair(org.apache.hc.core5.http.NameValuePair) Request(org.eclipse.californium.core.coap.Request) HttpRequest(org.apache.hc.core5.http.HttpRequest) TranslationException(org.eclipse.californium.proxy2.TranslationException) URISyntaxException(java.net.URISyntaxException) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Code(org.eclipse.californium.core.coap.CoAP.Code) URI(java.net.URI) List(java.util.List) Option(org.eclipse.californium.core.coap.Option) InvalidFieldException(org.eclipse.californium.proxy2.InvalidFieldException)

Example 8 with Code

use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.

the class Coap2CoapTranslator method getRequest.

/**
 * Starting from an external CoAP request, the method fills a new request
 * for the internal CoAP nodes. Prepares the new request using the provided
 * destination URI and simply copies the options and the payload from the
 * original request to the new one.
 *
 * @param destination destination for outgoing request
 * @param incomingRequest the original incoming request
 * @return Request the created outgoing request
 * @throws TranslationException the translation exception
 */
public Request getRequest(URI destination, Request incomingRequest) throws TranslationException {
    // check parameters
    if (destination == null) {
        throw new NullPointerException("destination == null");
    }
    if (incomingRequest == null) {
        throw new NullPointerException("incomingRequest == null");
    }
    // get the code
    Code code = incomingRequest.getCode();
    // 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);
    // 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.removeProxyScheme();
    options.removeProxyUri();
    options.removeBlock1();
    options.removeBlock2();
    options.removeUriHost();
    options.removeUriPort();
    options.clearUriPath();
    options.clearUriQuery();
    outgoingRequest.setOptions(options);
    // set the proxy-uri as the outgoing uri
    outgoingRequest.setURI(destination);
    LOGGER.debug("Incoming request translated correctly");
    return outgoingRequest;
}
Also used : Type(org.eclipse.californium.core.coap.CoAP.Type) Request(org.eclipse.californium.core.coap.Request) OptionSet(org.eclipse.californium.core.coap.OptionSet) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Code(org.eclipse.californium.core.coap.CoAP.Code)

Example 9 with Code

use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.

the class CoapTest method testGetCodeClass.

@Test
public void testGetCodeClass() {
    for (Code code : Code.values()) {
        assertThat(CoAP.getCodeClass(code.value), is(CodeClass.REQUEST.value));
    }
    // success
    assertThat(CoAP.getCodeClass(ResponseCode.CREATED.value), is(CodeClass.SUCCESS_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.CHANGED.value), is(CodeClass.SUCCESS_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.CONTINUE.value), is(CodeClass.SUCCESS_RESPONSE.value));
    // errors
    assertThat(CoAP.getCodeClass(ResponseCode.BAD_REQUEST.value), is(CodeClass.ERROR_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.CONFLICT.value), is(CodeClass.ERROR_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.UNSUPPORTED_CONTENT_FORMAT.value), is(CodeClass.ERROR_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.UNPROCESSABLE_ENTITY.value), is(CodeClass.ERROR_RESPONSE.value));
    // server errors
    assertThat(CoAP.getCodeClass(ResponseCode.INTERNAL_SERVER_ERROR.value), is(CodeClass.SERVER_ERROR_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.NOT_IMPLEMENTED.value), is(CodeClass.SERVER_ERROR_RESPONSE.value));
    assertThat(CoAP.getCodeClass(ResponseCode.SERVICE_UNAVAILABLE.value), is(CodeClass.SERVER_ERROR_RESPONSE.value));
}
Also used : ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Code(org.eclipse.californium.core.coap.CoAP.Code) Test(org.junit.Test)

Example 10 with Code

use of org.eclipse.californium.core.coap.CoAP.Code in project californium by eclipse.

the class RequestTest method setObserveFailsForNonGetRequest.

/**
 * Verifies that only GET requests can be marked for establishing an observe relation.
 */
@Test
public void setObserveFailsForNonGetRequest() {
    Code[] illegalCodes = new Code[] { Code.PATCH, Code.DELETE, Code.POST, Code.PUT };
    for (Code code : illegalCodes) {
        try {
            Request req = new Request(code);
            req.setObserve();
            fail("should not be able to set observe option on " + code + " request");
        } catch (IllegalStateException e) {
        // as expected
        }
    }
}
Also used : Code(org.eclipse.californium.core.coap.CoAP.Code) Test(org.junit.Test)

Aggregations

Code (org.eclipse.californium.core.coap.CoAP.Code)26 Request (org.eclipse.californium.core.coap.Request)18 ResponseCode (org.eclipse.californium.core.coap.CoAP.ResponseCode)14 CoapResponse (org.eclipse.californium.core.CoapResponse)12 CoapClient (org.eclipse.californium.core.CoapClient)11 Test (org.junit.Test)11 Future (io.vertx.core.Future)8 OptionSet (org.eclipse.californium.core.coap.OptionSet)8 Test (org.junit.jupiter.api.Test)8 URI (java.net.URI)7 Truth.assertThat (com.google.common.truth.Truth.assertThat)6 Handler (io.vertx.core.Handler)6 Promise (io.vertx.core.Promise)6 Timeout (io.vertx.junit5.Timeout)6 VertxTestContext (io.vertx.junit5.VertxTestContext)6 URISyntaxException (java.net.URISyntaxException)6 StandardCharsets (java.nio.charset.StandardCharsets)6 X509Certificate (java.security.cert.X509Certificate)6 List (java.util.List)6 TimeUnit (java.util.concurrent.TimeUnit)6