org.eclipse.californium.core.coap.MediaTypeRegistry Java Examples

The following examples show how to use org.eclipse.californium.core.coap.MediaTypeRegistry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void assertResponseContainsCommand(
        final CoapCommandEndpointConfiguration endpointConfiguration,
        final OptionSet responseOptions,
        final String expectedCommand,
        final String tenantId,
        final String commandTargetDeviceId) {

    assertThat(responseOptions.getLocationQuery())
        .as("location query must contain parameter [%s]", expectedCommand)
        .contains(expectedCommand);
    assertThat(responseOptions.getContentFormat()).isEqualTo(MediaTypeRegistry.APPLICATION_JSON);
    int idx = 0;
    assertThat(responseOptions.getLocationPath()).contains(CommandConstants.COMMAND_RESPONSE_ENDPOINT, Index.atIndex(idx++));
    if (endpointConfiguration.isSubscribeAsGateway()) {
        assertThat(responseOptions.getLocationPath()).contains(tenantId, Index.atIndex(idx++));
        assertThat(responseOptions.getLocationPath()).contains(commandTargetDeviceId, Index.atIndex(idx++));
    }
    // request ID
    assertThat(responseOptions.getLocationPath().get(idx))
        .as("location path must contain command request ID")
        .isNotNull();
}
 
Example #2
Source File: TradfriCoapClient.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void executeCommands() {
    while (true) {
        try {
            synchronized (commandsQueue) {
                PayloadCallbackPair payloadCallbackPair = commandsQueue.poll();
                if (payloadCallbackPair != null) {
                    logger.debug("CoAP PUT request\nuri: {}\npayload: {}", getURI(), payloadCallbackPair.payload);
                    put(new TradfriCoapHandler(payloadCallbackPair.callback), payloadCallbackPair.payload,
                            MediaTypeRegistry.TEXT_PLAIN);
                } else {
                    return;
                }
            }
            Thread.sleep(DEFAULT_DELAY_MILLIS);
        } catch (InterruptedException e) {
            logger.debug("commandExecutorThread was interrupted", e);
        }
    }
}
 
Example #3
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Formats a {@link Response} into a readable String representation. 
 * 
 * @param r the Response
 * @return the pretty print
 */
public static String prettyPrint(Response r) {

        StringBuilder sb = new StringBuilder();
        
        sb.append("##[ CoAP Response ]##############################################\n");
        sb.append(String.format("MID    : %d\n", r.getMID()));
        sb.append(String.format("Token  : %s\n", r.getTokenString()));
        sb.append(String.format("Type   : %s\n", r.getType().toString()));
        sb.append(String.format("Status : %s\n", r.getCode().toString()));
        sb.append(String.format("Options: %s\n", r.getOptions().toString()));
        sb.append(String.format("Payload: %d Bytes\n", r.getPayloadSize()));
        if (r.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(r.getOptions().getContentFormat())) {
        	sb.append("---------------------------------------------------------------\n");
        	sb.append(r.getPayloadString());
        	sb.append("\n");
        }
        sb.append("#################################################################");

        return sb.toString();
}
 
Example #4
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Formats a {@link Request} into a readable String representation. 
 * 
 * @param r the Request
 * @return the pretty print
 */
public static String prettyPrint(Request r) {

        StringBuilder sb = new StringBuilder();
        
        sb.append("##[ CoAP Request ]##############################################\n");
        sb.append(String.format("MID    : %d\n", r.getMID()));
        sb.append(String.format("Token  : %s\n", r.getTokenString()));
        sb.append(String.format("Type   : %s\n", r.getType().toString()));
        sb.append(String.format("Method : %s\n", r.getCode().toString()));
        sb.append(String.format("Options: %s\n", r.getOptions().toString()));
        sb.append(String.format("Payload: %d Bytes\n", r.getPayloadSize()));
        if (r.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(r.getOptions().getContentFormat())) {
        	sb.append("---------------------------------------------------------------");
        	sb.append(r.getPayloadString());
        }
        sb.append("############################################################");

        return sb.toString();
}
 
Example #5
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Formats a {@link Response} into a readable String representation. 
 * 
 * @param r the Response
 * @return the pretty print
 */
public static String prettyPrint(Response r) {

        StringBuilder sb = new StringBuilder();
        
        sb.append("##[ CoAP Response ]##############################################\n");
        sb.append(String.format("MID    : %d\n", r.getMID()));
        sb.append(String.format("Token  : %s\n", r.getTokenString()));
        sb.append(String.format("Type   : %s\n", r.getType().toString()));
        sb.append(String.format("Status : %s\n", r.getCode().toString()));
        sb.append(String.format("Options: %s\n", r.getOptions().toString()));
        sb.append(String.format("Payload: %d Bytes\n", r.getPayloadSize()));
        if (r.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(r.getOptions().getContentFormat())) {
        	sb.append("---------------------------------------------------------------\n");
        	sb.append(r.getPayloadString());
        	sb.append("\n");
        }
        sb.append("#################################################################");

        return sb.toString();
}
 
Example #6
Source File: Utils.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Formats a {@link Request} into a readable String representation. 
 * 
 * @param r the Request
 * @return the pretty print
 */
public static String prettyPrint(Request r) {

        StringBuilder sb = new StringBuilder();
        
        sb.append("##[ CoAP Request ]##############################################\n");
        sb.append(String.format("MID    : %d\n", r.getMID()));
        sb.append(String.format("Token  : %s\n", r.getTokenString()));
        sb.append(String.format("Type   : %s\n", r.getType().toString()));
        sb.append(String.format("Method : %s\n", r.getCode().toString()));
        sb.append(String.format("Options: %s\n", r.getOptions().toString()));
        sb.append(String.format("Payload: %d Bytes\n", r.getPayloadSize()));
        if (r.getPayloadSize() > 0 && MediaTypeRegistry.isPrintable(r.getOptions().getContentFormat())) {
        	sb.append("---------------------------------------------------------------");
        	sb.append(r.getPayloadString());
        }
        sb.append("############################################################");

        return sb.toString();
}
 
Example #7
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
String requestPostCOAP(String topic, String payload) throws TradfriException {
    LOGGER.log(Level.FINE, "request POST COAP: {0}, {1}", new Object[]{topic, payload});
    try {
        URI uri = new URI("coaps://" + coapIP + "/" + topic);
        CoapClient client = new CoapClient(uri);
        client.setEndpoint(coapEndPoint);
        CoapResponse response = client.post(payload, MediaTypeRegistry.TEXT_PLAIN);
        if (response == null || !response.isSuccess()) {
            LOGGER.log(Level.WARNING, "COAP GET error: Response error.");
            throw new TradfriException("Connection to gateway failed. Check host and PSK.");
        }
        String result = response.getResponseText();
        client.shutdown();
        return result;
    } catch (URISyntaxException ex) {
        LOGGER.log(Level.WARNING, "COAP GET error: {0}", ex.getMessage());
        throw new TradfriException(ex);
    }
}
 
Example #8
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void assertResponseContainsOneWayCommand(
        final CoapCommandEndpointConfiguration endpointConfiguration,
        final OptionSet responseOptions,
        final String expectedCommand,
        final String tenantId,
        final String commandTargetDeviceId) {

    assertThat(responseOptions.getLocationQuery())
        .as("response doesn't contain command")
        .contains(expectedCommand);
    assertThat(responseOptions.getContentFormat()).isEqualTo(MediaTypeRegistry.APPLICATION_JSON);
    assertThat(responseOptions.getLocationPath()).contains(CommandConstants.COMMAND_ENDPOINT, Index.atIndex(0));
    if (endpointConfiguration.isSubscribeAsGateway()) {
        assertThat(responseOptions.getLocationPath()).contains(tenantId, Index.atIndex(1));
        assertThat(responseOptions.getLocationPath()).contains(commandTargetDeviceId, Index.atIndex(2));
    }
}
 
Example #9
Source File: Main.java    From TRADFRI2MQTT with Apache License 2.0 6 votes vote down vote up
private void set(String uriString, String payload) {
	//System.out.println("payload\n" + payload);
	try {
		URI uri = new URI(uriString);
		CoapClient client = new CoapClient(uri);
		client.setEndpoint(endPoint);
		CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN);
		if (response != null && response.isSuccess()) {
			//System.out.println("Yay");
		} else {
			System.out.println("Sending payload to " + uriString + " failed!");
		}
		client.shutdown();
	} catch (URISyntaxException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #10
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
void requestPutCOAP(String topic, String payload) {
    LOGGER.log(Level.FINE, "requext PUT COAP: {0}, {1}", new Object[]{topic, payload});
    try {
        URI uri = new URI("coaps://" + coapIP + "/" + topic);
        CoapClient client = new CoapClient(uri);
        client.setEndpoint(coapEndPoint);
        CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN);
        if (response == null || !response.isSuccess()) {
            LOGGER.log(Level.WARNING, "COAP PUT error: {0}", response.getResponseText());
        }
        client.shutdown();
    } catch (URISyntaxException ex) {
        LOGGER.log(Level.WARNING, "COAP PUT error: {0}", ex.getMessage());
    }
}
 
Example #11
Source File: TestCoapServerPushSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testSource() throws Exception {
  CoapServerConfigs coapServerConfigs = new CoapServerConfigs();
  coapServerConfigs.resourceName = () -> "sdc";
  coapServerConfigs.port = NetworkUtils.getRandomPort();
  coapServerConfigs.maxConcurrentRequests = 1;
  CoapServerPushSource source =
      new CoapServerPushSource(coapServerConfigs, DataFormat.TEXT, new DataParserFormatConfig());
  final PushSourceRunner runner =
      new PushSourceRunner.Builder(CoapServerDPushSource.class, source).addOutputLane("a").build();
  runner.runInit();
  try {
    final List<Record> records = new ArrayList<>();
    runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
      @Override
      public void processBatch(StageRunner.Output output) {
        records.clear();
        records.addAll(output.getRecords().get("a"));
        runner.setStop();
      }
    });

    URI coapURI = new URI("coap://localhost:" + coapServerConfigs.port + "/" + coapServerConfigs.resourceName.get());
    CoapClient client = new CoapClient(coapURI);
    CoapResponse response = client.post("Hello", MediaTypeRegistry.TEXT_PLAIN);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getCode(), CoAP.ResponseCode.VALID);

    runner.waitOnProduce();
    Assert.assertEquals(1, records.size());
    Assert.assertEquals("Hello", records.get(0).get("/text").getValue());

  } finally {
    runner.runDestroy();
  }
}
 
Example #12
Source File: CoapClientTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private int getContentType() {
  switch (conf.dataFormat) {
    case TEXT:
      return MediaTypeRegistry.TEXT_PLAIN;
    case BINARY:
      return MediaTypeRegistry.APPLICATION_OCTET_STREAM;
    case JSON:
    case SDC_JSON:
    default:
      return MediaTypeRegistry.APPLICATION_JSON;
  }
}
 
Example #13
Source File: AbstractVertxBasedCoapAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Adds a command to a CoAP response.
 * <p>
 * This default implementation adds the command name, content format and response URI to the
 * CoAP response options and puts the command's input data (if any) to the response body.
 *
 * @param response The CoAP response.
 * @param commandContext The context containing the command to add.
 * @param currentSpan The Open Tracing span used for tracking the CoAP request.
 */
protected void addCommandToResponse(
        final Response response,
        final CommandContext commandContext,
        final Span currentSpan) {

    final Command command = commandContext.getCommand();
    final OptionSet options = response.getOptions();
    options.addLocationQuery(Constants.HEADER_COMMAND + "=" + command.getName());
    if (command.isOneWay()) {
        options.setLocationPath(CommandConstants.COMMAND_ENDPOINT);
    } else {
        options.setLocationPath(CommandConstants.COMMAND_RESPONSE_ENDPOINT);
    }

    currentSpan.setTag(Constants.HEADER_COMMAND, command.getName());
    log.debug("adding command [name: {}, request-id: {}] to response for device [tenant-id: {}, device-id: {}]",
            command.getName(), command.getRequestId(), command.getTenant(), command.getDeviceId());
    commandContext.getCurrentSpan().log("forwarding command to device in CoAP response");

    if (command.isTargetedAtGateway()) {
        options.addLocationPath(command.getTenant());
        options.addLocationPath(command.getOriginalDeviceId());
        currentSpan.setTag(Constants.HEADER_COMMAND_TARGET_DEVICE, command.getOriginalDeviceId());
    }
    if (!command.isOneWay()) {
        options.addLocationPath(command.getRequestId());
        currentSpan.setTag(Constants.HEADER_COMMAND_REQUEST_ID, command.getRequestId());
    }
    final int formatCode = MediaTypeRegistry.parse(command.getContentType());
    if (formatCode != MediaTypeRegistry.UNDEFINED) {
        options.setContentFormat(formatCode);
    } else {
        currentSpan.log("ignoring unknown content type [" + command.getContentType() + "] of command");
    }
    Optional.ofNullable(command.getPayload()).ifPresent(b -> response.setPayload(b.getBytes()));
}
 
Example #14
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of an event with a 4.03 result if the device belongs to a tenant for
 * which the adapter is disabled.
 */
@Test
public void testUploadTelemetryFailsForDisabledTenant() {

    // GIVEN an adapter
    final DownstreamSender sender = givenATelemetrySender(Promise.promise());
    // which is disabled for tenant "my-tenant"
    final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
    myTenantConfig.addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("my-tenant"), any(SpanContext.class))).thenReturn(Future.succeededFuture(myTenantConfig));
    final CoapServer server = getCoapServer(false);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device that belongs to "my-tenant" publishes a telemetry message
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.NON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("my-tenant", "the-device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadTelemetryMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the device gets a response with code 4.03
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.FORBIDDEN.equals(res.getCode())));

    // and the message has not been forwarded downstream
    verify(sender, never()).send(any(Message.class), any(SpanContext.class));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.TELEMETRY),
            eq("my-tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.UNPROCESSABLE),
            eq(MetricsTags.QoS.AT_MOST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #15
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter immediately responds with a 2.04 status if a
 * device publishes telemetry data using a NON message.
 */
@Test
public void testUploadTelemetryWithQoS0() {

    // GIVEN an adapter with a downstream telemetry consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenATelemetrySender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an telemetry message
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.NON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadTelemetryMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the device gets a response indicating success
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
    // and the message has been forwarded downstream
    verify(sender).send(any(Message.class), any(SpanContext.class));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.TELEMETRY),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.FORWARDED),
            eq(MetricsTags.QoS.AT_MOST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #16
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a CoAP request using the <em>coaps</em> scheme.
 *
 * @param code The CoAP request code.
 * @param type The message type.
 * @param resource the resource path.
 * @param payload The payload to send in the request body.
 * @return The request to send.
 */
protected Request createCoapsRequest(
        final Code code,
        final Type type,
        final String resource,
        final byte[] payload) {
    final Request request = new Request(code, type);
    request.setURI(getCoapsRequestUri(resource));
    request.setPayload(payload);
    request.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    return request;
}
 
Example #17
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a CoAP request using the <em>coap</em> scheme.
 *
 * @param code The CoAP request code.
 * @param type The message type.
 * @param resource the resource path.
 * @param msgNo The message number.
 * @return The request to send.
 */
protected Request createCoapRequest(
        final Code code,
        final Type type,
        final String resource,
        final int msgNo) {
    final Request request = new Request(code, type);
    request.setURI(getCoapRequestUri(resource));
    request.setPayload("hello " + msgNo);
    request.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    return request;
}
 
Example #18
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of an event with a 4.00 result
 * if the request body is empty but is not marked as an empty notification.
 */
@Test
public void testUploadTelemetryFailsForEmptyBody() {

    // GIVEN an adapter
    final DownstreamSender sender = givenATelemetrySender(Promise.promise());
    final CoapServer server = getCoapServer(false);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an empty message that doesn't contain
    // a URI-query option
    final CoapExchange coapExchange = newCoapExchange(null, Type.NON, MediaTypeRegistry.UNDEFINED);
    final Device authenticatedDevice = new Device("my-tenant", "the-device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadTelemetryMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the device gets a response with code 4.00
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.BAD_REQUEST.equals(res.getCode())));

    // and the message has not been forwarded downstream
    verify(sender, never()).send(any(Message.class), any(SpanContext.class));
    verify(metrics, never()).reportTelemetry(
            any(MetricsTags.EndpointType.class),
            anyString(),
            any(),
            any(MetricsTags.ProcessingOutcome.class),
            any(MetricsTags.QoS.class),
            anyInt(),
            any(TtdStatus.class),
            any());
}
 
Example #19
Source File: TradfriGateway.java    From ThingML-Tradfri with Apache License 2.0 5 votes vote down vote up
protected void set(String path, String payload) {
           Logger.getLogger(TradfriGateway.class.getName()).log(Level.INFO, "SET: " + "coaps://" + gateway_ip + "/" + path + " = " + payload);
           CoapClient client = new CoapClient("coaps://" + gateway_ip + "/" + path);
           client.setEndpoint(coap);
           CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN);
           if (response != null && response.isSuccess()) {
                   //System.out.println("Yay");
           } else {
                   logger.log(Level.SEVERE, "Sending payload to " + "coaps://" + gateway_ip + "/" + path + " failed!");
           }
           client.shutdown();
}
 
Example #20
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that an event message is rejected due to the limit exceeded.
 *
 */
@Test
public void testMessageLimitExceededForAnEventMessage() {

    // GIVEN an adapter with a downstream event consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenAnEventSender(outcome);

    final CoapServer server = getCoapServer(false);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN the message limit exceeds
    when(resourceLimitChecks.isMessageLimitReached(any(TenantObject.class), anyLong(), any(SpanContext.class)))
            .thenReturn(Future.succeededFuture(Boolean.TRUE));

    // WHEN a device publishes an event message
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext ctx = CoapContext.fromRequest(coapExchange);
    adapter.uploadEventMessage(ctx, authenticatedDevice, authenticatedDevice);

    // THEN the message is not being forwarded downstream
    verify(sender, never()).sendAndWaitForOutcome(any(Message.class), any(SpanContext.class));
    // and the device gets a 4.29
    final ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
    verify(coapExchange).respond(captor.capture());
    assertThat(captor.getValue().getCode()).isEqualTo(ResponseCode.TOO_MANY_REQUESTS);
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.EVENT),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.UNPROCESSABLE),
            eq(MetricsTags.QoS.AT_LEAST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #21
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a telemetry message is rejected due to the limit exceeded.
 *
 */
@Test
public void testMessageLimitExceededForATelemetryMessage() {

    // GIVEN an adapter with a downstream telemetry consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenATelemetrySender(outcome);

    final CoapServer server = getCoapServer(false);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device that belongs to a tenant for which the message limit is exceeded
    // publishes a telemetry message
    when(resourceLimitChecks.isMessageLimitReached(any(TenantObject.class), anyLong(), any(SpanContext.class)))
        .thenReturn(Future.succeededFuture(Boolean.TRUE));
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.NON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext ctx = CoapContext.fromRequest(coapExchange);
    adapter.uploadTelemetryMessage(ctx, authenticatedDevice, authenticatedDevice);

    // THEN the message is not being forwarded downstream
    verify(sender, never()).send(any(Message.class), any(SpanContext.class));
    // and the device gets a 4.29
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.TOO_MANY_REQUESTS.equals(res.getCode())));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.TELEMETRY),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.UNPROCESSABLE),
            eq(MetricsTags.QoS.AT_MOST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #22
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of a command response with a 4.03
 * if the adapter is disabled for the device's tenant.
 */
@Test
public void testUploadCommandResponseFailsForDisabledTenant() {

    // GIVEN an adapter that is not enabled for a device's tenant
    final TenantObject to = TenantObject.from("tenant", true);
    to.addAdapter(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_COAP).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(to));

    final Promise<ProtonDelivery> outcome = Promise.promise();
    final CommandResponseSender sender = givenACommandResponseSender(outcome);
    final CoapServer server = getCoapServer(false);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an command response
    final String reqId = Command.getRequestId("correlation", "replyToId", "device");
    final Buffer payload = Buffer.buffer("some payload");
    final OptionSet options = new OptionSet();
    options.addUriPath(CommandConstants.COMMAND_RESPONSE_ENDPOINT).addUriPath(reqId);
    options.addUriQuery(String.format("%s=%d", Constants.HEADER_COMMAND_RESPONSE_STATUS, 200));
    options.setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, options);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadCommandResponseMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the command response not been forwarded downstream
    verify(sender, never()).sendCommandResponse(any(CommandResponse.class), any(SpanContext.class));
    // and the device gets a 4.03 response
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.FORBIDDEN.equals(res.getCode())));
    // and the response has not been reported as forwarded
    verify(metrics, never()).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            any(),
            eq(ProcessingOutcome.FORWARDED),
            anyInt(),
            any());
}
 
Example #23
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of a command response with a 4.00
 * response code if it is rejected by the downstream peer.
 */
@Test
public void testUploadCommandResponseFailsForRejectedOutcome() {

    // GIVEN an adapter with a downstream application attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final CommandResponseSender sender = givenACommandResponseSender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an command response
    final String reqId = Command.getRequestId("correlation", "replyToId", "device");
    final Buffer payload = Buffer.buffer("some payload");
    final OptionSet options = new OptionSet();
    options.addUriPath(CommandConstants.COMMAND_RESPONSE_ENDPOINT).addUriPath(reqId);
    options.addUriQuery(String.format("%s=%d", Constants.HEADER_COMMAND_RESPONSE_STATUS, 200));
    options.setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, options);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadCommandResponseMessage(context, authenticatedDevice, authenticatedDevice);
    outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed message"));

    // THEN the command response is being forwarded downstream
    verify(sender).sendCommandResponse(any(CommandResponse.class), any(SpanContext.class));
    // and the device gets a 4.00 response
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.BAD_REQUEST.equals(res.getCode())));
    // and the response has not been reported as forwarded
    verify(metrics, never()).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            any(),
            eq(ProcessingOutcome.FORWARDED),
            anyInt(),
            any());
}
 
Example #24
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of an event with a 4.00 result if it is rejected by the downstream
 * peer.
 */
@Test
public void testUploadEventFailsForRejectedOutcome() {

    // GIVEN an adapter with a downstream event consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenAnEventSender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an event that is not accepted by the peer
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext ctx = CoapContext.fromRequest(coapExchange);

    adapter.uploadEventMessage(ctx, authenticatedDevice, authenticatedDevice);
    verify(sender).sendAndWaitForOutcome(any(Message.class), any(SpanContext.class));
    outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed message"));

    // THEN the device gets a 4.00
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.BAD_REQUEST.equals(res.getCode())));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.EVENT),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.UNPROCESSABLE),
            eq(MetricsTags.QoS.AT_LEAST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #25
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter waits for an event being send with wait for outcome before responding with a 2.04
 * status to the device.
 */
@Test
public void testUploadEventWaitsForAcceptedOutcome() {

    // GIVEN an adapter with a downstream event consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenAnEventSender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an event
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadEventMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the message is being forwarded downstream
    verify(sender).sendAndWaitForOutcome(any(Message.class), any(SpanContext.class));
    // but the device does not get a response
    verify(coapExchange, never()).respond(any(Response.class));

    // until the event has been accepted
    outcome.complete(mock(ProtonDelivery.class));

    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.EVENT),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.FORWARDED),
            eq(MetricsTags.QoS.AT_LEAST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #26
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter waits for a the AMQP Messaging Network to accept a
 * forwarded telemetry message that has been published using a CON message,
 * before responding with a 2.04 status to the device.
 */
@Test
public void testUploadTelemetryWithQoS1() {

    // GIVEN an adapter with a downstream telemetry consumer attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender sender = givenATelemetrySender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an telemetry message with QoS 1
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
    final CoapContext context = CoapContext.fromRequest(coapExchange);
    final Device authenticatedDevice = new Device("tenant", "device");

    adapter.uploadTelemetryMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the message is being forwarded downstream
    verify(sender).sendAndWaitForOutcome(any(Message.class), any(SpanContext.class));
    // and the device does not get a response
    verify(coapExchange, never()).respond(any(Response.class));
    // until the telemetry message has been accepted
    outcome.complete(mock(ProtonDelivery.class));

    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.TELEMETRY),
            eq("tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.FORWARDED),
            eq(MetricsTags.QoS.AT_LEAST_ONCE),
            eq(payload.length()),
            eq(TtdStatus.NONE),
            any());
}
 
Example #27
Source File: DiscoveryResource.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Responds with a list of all resources of the server, i.e. links.
 * 
 * @param exchange the exchange
 */
@Override
public void handleGET(CoapExchange exchange) {
	String tree = discoverTree(root, exchange.getRequestOptions().getUriQuery());
	exchange.respond(ResponseCode.CONTENT, tree, MediaTypeRegistry.APPLICATION_LINK_FORMAT);
}
 
Example #28
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter waits for a command response being settled and accepted
 * by a downstream peer before responding with a 2.04 status to the device.
 */
@Test
public void testUploadCommandResponseWaitsForAcceptedOutcome() {

    // GIVEN an adapter with a downstream application attached
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final CommandResponseSender sender = givenACommandResponseSender(outcome);
    final CoapServer server = getCoapServer(false);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, null);

    // WHEN a device publishes an command response
    final String reqId = Command.getRequestId("correlation", "replyToId", "device");
    final Buffer payload = Buffer.buffer("some payload");
    final OptionSet options = new OptionSet();
    options.addUriPath(CommandConstants.COMMAND_RESPONSE_ENDPOINT).addUriPath(reqId);
    options.addUriQuery(String.format("%s=%d", Constants.HEADER_COMMAND_RESPONSE_STATUS, 200));
    options.setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, options);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange);

    adapter.uploadCommandResponseMessage(context, authenticatedDevice, authenticatedDevice);

    // THEN the command response is being forwarded downstream
    verify(sender).sendCommandResponse(any(CommandResponse.class), any(SpanContext.class));
    // but the device does not get a response
    verify(coapExchange, never()).respond(any(Response.class));
    // and the response has not been reported as forwarded
    verify(metrics, never()).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            any(),
            eq(ProcessingOutcome.FORWARDED),
            anyInt(),
            any());

    // until the message has been accepted
    outcome.complete(mock(ProtonDelivery.class));

    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
    verify(metrics).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            any(),
            eq(ProcessingOutcome.FORWARDED),
            eq(payload.length()),
            any());
}
 
Example #29
Source File: DiscoveryResource.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Responds with a list of all resources of the server, i.e. links.
 * 
 * @param exchange the exchange
 */
@Override
public void handleGET(CoapExchange exchange) {
	String tree = discoverTree(root, exchange.getRequestOptions().getUriQuery());
	exchange.respond(ResponseCode.CONTENT, tree, MediaTypeRegistry.APPLICATION_LINK_FORMAT);
}
 
Example #30
Source File: CoapExchange.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * Respond with the specified response code and the specified payload.
 * <ul>
 *   <li>GET: Content (2.05), Valid (2.03)</li>
 *   <li>POST: Created (2.01), Changed (2.04), Deleted (2.02) </li>
 *   <li>PUT: Created (2.01), Changed (2.04)</li>
 *   <li>DELETE: Deleted (2.02)</li>
 * </ul>
 *
 * @param code the response code
 * @param payload the payload
 */
public void respond(ResponseCode code, String payload) {
	Response response = new Response(code);
	response.setPayload(payload);
	response.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
	respond(response);
}