Search in sources :

Example 16 with Code

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

the class CoapTestBase method testUploadMessageFailsForDisabledDevice.

/**
 * Verifies that the CoAP adapter rejects messages from a disabled device.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledDevice(final VertxTestContext ctx) {
    // GIVEN a disabled device
    final Tenant tenant = new Tenant();
    final Device deviceData = new Device();
    deviceData.setEnabled(false);
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, deviceData, SECRET).compose(ok -> {
        // WHEN the device tries to upload a message
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        // THEN a NOT_FOUND response code is returned
        client.advanced(getHandler(result, ResponseCode.NOT_FOUND), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    }).onComplete(ctx.succeedingThenComplete());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) KeyPair(java.security.KeyPair) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) AdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) CertificateType(org.eclipse.californium.scandium.dtls.CertificateType) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) CoapResponse(org.eclipse.californium.core.CoapResponse) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) GeneralSecurityException(java.security.GeneralSecurityException) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Utils(org.eclipse.californium.core.Utils) JsonObject(io.vertx.core.json.JsonObject) URI(java.net.URI) Tenants(org.eclipse.hono.tests.Tenants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Device(org.eclipse.hono.service.management.device.Device) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) MessageContext(org.eclipse.hono.application.client.MessageContext) SubscriberRole(org.eclipse.hono.tests.CommandEndpointConfiguration.SubscriberRole) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) InetSocketAddress(java.net.InetSocketAddress) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) Request(org.eclipse.californium.core.coap.Request) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) QoS(org.eclipse.hono.util.QoS) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapClient(org.eclipse.californium.core.CoapClient) X500Principal(javax.security.auth.x500.X500Principal) KeyLoader(org.eclipse.hono.config.KeyLoader) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Constants(org.eclipse.hono.util.Constants) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) MediaTypeRegistry(org.eclipse.californium.core.coap.MediaTypeRegistry) StaticNewAdvancedCertificateVerifier(org.eclipse.californium.scandium.dtls.x509.StaticNewAdvancedCertificateVerifier) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Type(org.eclipse.californium.core.coap.CoAP.Type) Logger(org.slf4j.Logger) AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Truth.assertThat(com.google.common.truth.Truth.assertThat) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Code(org.eclipse.californium.core.coap.CoAP.Code) Adapter(org.eclipse.hono.util.Adapter) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) CoapHandler(org.eclipse.californium.core.CoapHandler) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Promise(io.vertx.core.Promise) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Device(org.eclipse.hono.service.management.device.Device) CoapClient(org.eclipse.californium.core.CoapClient) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Timeout(io.vertx.junit5.Timeout)

Example 17 with Code

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

the class HonoClient method main.

/**
 * Main entry point.
 *
 * @param args the arguments
 * @throws IOException
 * @throws ConnectorException
 */
public static void main(String[] args) throws IOException, ConnectorException {
    // hono sandbox
    TcpConfig.register();
    final Config clientConfig = new Config();
    clientConfig.setDefaultPskCredentials("sensor1@DEFAULT_TENANT", "hono-secret");
    clientConfig.defaultUri = "coaps://" + DEFAULT_HONO + "/telemetry";
    clientConfig.configurationHeader = CONFIG_HEADER;
    clientConfig.customConfigurationDefaultsProvider = DEFAULTS;
    clientConfig.configurationFile = CONFIG_FILE;
    ClientInitializer.init(args, clientConfig);
    if (clientConfig.helpRequested) {
        System.exit(0);
    }
    Random rand = new Random();
    CorrelationId id = new CorrelationId(rand);
    if (clientConfig.identity == null) {
        System.out.println("> " + clientConfig.uri);
    } else {
        System.out.println("> " + clientConfig.identity + ", " + clientConfig.uri);
    }
    CoapClient client = new CoapClient(clientConfig.uri);
    CoAP.Code code = clientConfig.method == null ? Code.POST : clientConfig.method;
    final Request request = new Request(code);
    if (clientConfig.messageType != null) {
        request.setConfirmable(clientConfig.messageType.con);
    }
    if (clientConfig.contentType == null) {
        clientConfig.contentType = new ContentType();
        clientConfig.contentType.contentType = MediaTypeRegistry.TEXT_PLAIN;
    }
    if (clientConfig.payload == null && request.isIntendedPayload()) {
        applyPayload(clientConfig.mode, request);
        clientConfig.payload = new Payload();
        clientConfig.payload.text = request.getPayloadString();
        clientConfig.payloadFormat = true;
        clientConfig.contentType.contentType = request.getOptions().getContentFormat();
    }
    request.getOptions().setAccept(clientConfig.contentType.contentType);
    request.getOptions().setContentFormat(clientConfig.contentType.contentType);
    request.setPayload(formatPayload(clientConfig, rand.nextInt(100), id));
    request.setURI(clientConfig.uri);
    request.addMessageObserver(new EndpointContextTracer() {

        @Override
        public void onReadyToSend() {
            System.out.println(Utils.prettyPrint(request));
            System.out.println();
        }

        @Override
        public void onAcknowledgement() {
            System.out.println(">>> ACK <<<");
        }

        @Override
        public void onDtlsRetransmission(int flight) {
            System.out.println(">>> DTLS retransmission, flight " + flight);
        }

        @Override
        protected void onContextChanged(EndpointContext endpointContext) {
            System.out.println(Utils.prettyPrint(endpointContext));
        }
    });
    long start = System.nanoTime();
    List<Long> rtt = new ArrayList<Long>(clientConfig.requests);
    CoapResponse coapResponse = exchange(clientConfig, client, request, true);
    if (coapResponse != null && getCommand(coapResponse) == null) {
        rtt.add(coapResponse.advanced().getApplicationRttNanos());
        Request followUpRequests = null;
        for (int index = 1; index < clientConfig.requests; ++index) {
            followUpRequests = new Request(code);
            followUpRequests.getOptions().setAccept(clientConfig.contentType.contentType);
            followUpRequests.getOptions().setContentFormat(clientConfig.contentType.contentType);
            id.next();
            followUpRequests.setPayload(formatPayload(clientConfig, rand.nextInt(100), id));
            followUpRequests.setURI(clientConfig.uri);
            coapResponse = exchange(clientConfig, client, followUpRequests, true);
            if (coapResponse == null) {
                System.out.format("Stale at %d.%n", index);
                break;
            } else if (!coapResponse.isSuccess()) {
                if (coapResponse.getCode() == ResponseCode.SERVICE_UNAVAILABLE) {
                    long age = coapResponse.advanced().getOptions().getMaxAge();
                    long delay = TimeUnit.SECONDS.toMillis(age < 2 ? 2 : age);
                    try {
                        Thread.sleep(delay);
                    } catch (InterruptedException e) {
                    }
                }
            }
            rtt.add(coapResponse.advanced().getApplicationRttNanos());
        }
        start = System.nanoTime() - start;
        if (followUpRequests != null && coapResponse != null) {
            System.out.println();
            System.out.println(Utils.prettyPrint(followUpRequests));
            System.out.println();
            System.out.println(Utils.prettyPrint(coapResponse));
        }
        int count = 0;
        int overtimeCount = 0;
        long average = 0;
        long overtime = 0;
        for (int index = 0; index < rtt.size(); ++index) {
            Long time = rtt.get(index);
            if (time != null) {
                ++count;
                long millis = TimeUnit.NANOSECONDS.toMillis(time);
                System.out.format("RTT[%d] : %d ms %n", index, millis);
                if (500 < millis) {
                    ++overtimeCount;
                    overtime += millis;
                }
                average += millis;
            }
        }
        System.out.format("Overall time: %d [ms] %n", TimeUnit.NANOSECONDS.toMillis(start));
        if (0 < count) {
            System.out.format("Average time: %d [ms] %n", average / count);
            if (0 < overtimeCount) {
                System.out.format("Overtime    : %d, %d [ms], avg %d [ms] %n", overtimeCount, overtime, overtime / overtimeCount);
            }
        }
    }
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) ContentType(org.eclipse.californium.cli.ClientConfig.ContentType) EndpointContext(org.eclipse.californium.elements.EndpointContext) TcpConfig(org.eclipse.californium.elements.config.TcpConfig) UdpConfig(org.eclipse.californium.elements.config.UdpConfig) ClientConfig(org.eclipse.californium.cli.ClientConfig) CoapConfig(org.eclipse.californium.core.config.CoapConfig) DtlsConfig(org.eclipse.californium.scandium.config.DtlsConfig) Request(org.eclipse.californium.core.coap.Request) EndpointContextTracer(org.eclipse.californium.core.coap.EndpointContextTracer) ArrayList(java.util.ArrayList) Code(org.eclipse.californium.core.coap.CoAP.Code) CoapClient(org.eclipse.californium.core.CoapClient) Random(java.util.Random) Payload(org.eclipse.californium.cli.ClientConfig.Payload) CoAP(org.eclipse.californium.core.coap.CoAP)

Example 18 with Code

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

the class OptionJuggleTest method testRealCodeRequest.

@Test
public void testRealCodeRequest() {
    Request request = new Request(Code.POST);
    request.setToken(token);
    request.setMID(mid);
    request.setType(type);
    request.setPayload(payload);
    request.setSourceContext(sourceContext);
    request.setDestinationContext(destinationContext);
    OptionSet options = new OptionSet();
    options.setAccept(accept);
    request.setOptions(options);
    Code realCode = Code.PUT;
    Request realed = OptionJuggle.setRealCodeRequest(request, realCode);
    OptionSet realOptions = realed.getOptions();
    assertEquals(realCode, realed.getCode());
    assertEquals(token, realed.getToken());
    assertEquals(mid, realed.getMID());
    assertEquals(type, realed.getType());
    assertEquals(payload, realed.getPayload());
    assertEquals(sourceContext, realed.getSourceContext());
    assertEquals(destinationContext, realed.getDestinationContext());
    assertEquals(accept, realOptions.getAccept());
}
Also used : 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) Test(org.junit.Test)

Example 19 with Code

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

the class Utils method prettyPrint.

/**
 * Formats a {@link Request} into a readable String representation.
 *
 * @param request the Request
 * @return the pretty print
 */
public static String prettyPrint(Request request) {
    String nl = StringUtil.lineSeparator();
    StringBuilder sb = new StringBuilder();
    sb.append("==[ CoAP Request ]=============================================").append(nl);
    sb.append(String.format("MID    : %d%n", request.getMID()));
    sb.append(String.format("Token  : %s%n", request.getTokenString()));
    sb.append(String.format("Type   : %s%n", request.getType()));
    Code code = request.getCode();
    if (code == null) {
        sb.append("Method : 0.00 - PING").append(nl);
    } else {
        sb.append(String.format("Method : %s - %s%n", code.text, code.name()));
    }
    if (request.getOffloadMode() != null) {
        sb.append("(offloaded)").append(nl);
    } else {
        sb.append(String.format("Options: %s%n", request.getOptions()));
        sb.append(String.format("Payload: %d Bytes%n", request.getPayloadSize()));
        if (request.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(request.getOptions().getContentFormat())) {
            sb.append("---------------------------------------------------------------").append(nl);
            sb.append(request.getPayloadString());
            sb.append(nl);
        }
    }
    sb.append("===============================================================");
    return sb.toString();
}
Also used : ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) Code(org.eclipse.californium.core.coap.CoAP.Code)

Example 20 with Code

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

the class CoapTest method testCode.

@Test
public void testCode() {
    for (Code code : Code.values()) {
        assertEquals(code, Code.valueOf(code.value));
        assertTrue(MessageFormat.REQUEST_CODE_LOWER_BOUND <= code.value);
        assertTrue(code.value <= MessageFormat.REQUEST_CODE_UPPER_BOUND);
    }
}
Also used : ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) 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