org.eclipse.californium.core.CoapServer Java Examples

The following examples show how to use org.eclipse.californium.core.CoapServer. 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: HelloWorld2.java    From hands-on-coap with Eclipse Public License 1.0 6 votes vote down vote up
public static void main(String[] args) {

        // binds on UDP port 5683
        CoapServer server = new CoapServer();

        // "hello"
        server.add(new HelloResource());

        // "subpath/Another"
        CoapResource path = new CoapResource("subpath");
        path.add(new AnotherResource());
        server.add(path);

        // "removeme!, "time", "writeme!"
        server.add(new RemovableResource(), new TimeResource(), new WritableResource());

        server.start();
    }
 
Example #2
Source File: TestCoapClientTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  int port =  TestHttpClientTarget.getFreePort();
  coapServer = new CoapServer(NetworkConfig.createStandardWithoutFile(), port);
  coapServer.add(new CoapResource("test") {
    @Override
    public void handlePOST(CoapExchange exchange) {
      serverRequested = true;
      if (returnErrorResponse) {
        exchange.respond(CoAP.ResponseCode.INTERNAL_SERVER_ERROR);
        return;
      }
      requestPayload = new String(exchange.getRequestPayload());
      exchange.respond(CoAP.ResponseCode.VALID);
    }
  });
  resourceURl = "coap://localhost:" + port + "/test";
  coapServer.start();
}
 
Example #3
Source File: CoapReceiverServer.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public List<Stage.ConfigIssue> init(Stage.Context context) {
  List<Stage.ConfigIssue> issues = new ArrayList<>();
  NetworkConfig networkConfig = NetworkConfig.createStandardWithoutFile();
  networkConfig.set(NetworkConfig.Keys.DEDUPLICATOR, NetworkConfig.Keys.NO_DEDUPLICATOR);
  networkConfig.set(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT, coAPServerConfigs.maxConcurrentRequests);
  networkConfig.set(NetworkConfig.Keys.NETWORK_STAGE_RECEIVER_THREAD_COUNT, coAPServerConfigs.maxConcurrentRequests);
  if (coAPServerConfigs.networkConfigs != null) {
    for (String key: coAPServerConfigs.networkConfigs.keySet()) {
      networkConfig.set(key, coAPServerConfigs.networkConfigs.get(key));
    }
  }
  coapServer = new CoapServer(networkConfig, coAPServerConfigs.port);
  coapReceiverResource = new CoapReceiverResource(context, receiver, errorQueue);
  coapServer.add(coapReceiverResource);
  coapServer.start();
  return issues;
}
 
Example #4
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>onStartupSuccess</em> method is not invoked if a client provided coap server fails to
 * start.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartDoesNotInvokeOnStartupSuccessIfStartupFails(final VertxTestContext ctx) {

    // GIVEN an adapter with a client provided http server that fails to bind to a socket when started
    final CoapServer server = getCoapServer(true);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true,
            s -> ctx.failNow(new AssertionError("should not have invoked onStartupSuccess")));

    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    adapter.start(startupTracker);
    // THEN the onStartupSuccess method has not been invoked, see ctx.fail
    startupTracker.future().onComplete(ctx.failing(s -> {
        ctx.completeNow();
    }));
}
 
Example #5
Source File: ExternalCommandsDriver.java    From SoftwarePilot with MIT License 6 votes vote down vote up
public ExternalCommandsDriver() {
		//ecdLogger.log(Level.FINEST, "In Constructor");
		try {
				NetworkConfig nc = new NetworkConfig();
				cs = new CoapServer(nc); //create a new coapserver
				InetSocketAddress bindToAddress = new InetSocketAddress( LISTEN_PORT);
				cs.addEndpoint(new CoapEndpoint(bindToAddress));//Adds an Endpoint to the server.
				driverPort = bindToAddress.getPort();

				cs.add(new ecdResource());//Add a resource to the server
		}
		catch(Exception e) {
		}



}
 
Example #6
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>onStartupSuccess</em> method is not invoked if no credentials authentication provider is
 * set.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartUpFailsIfCredentialsClientFactoryIsNotSet(final VertxTestContext ctx) {

    // GIVEN an adapter that has not all required service clients set
    final CoapServer server = getCoapServer(false);
    @SuppressWarnings("unchecked")
    final Handler<Void> successHandler = mock(Handler.class);
    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, false, successHandler);

    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    adapter.start(startupTracker);

    // THEN startup has failed
    startupTracker.future().onComplete(ctx.failing(t -> {
        // and the onStartupSuccess method has not been invoked
        ctx.verify(() -> verify(successHandler, never()).handle(any()));
        ctx.completeNow();
    }));

}
 
Example #7
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter registers resources as part of the start-up process.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartRegistersResources(final VertxTestContext ctx) {

    // GIVEN an adapter
    final CoapServer server = getCoapServer(false);
    // and a set of resources
    final Resource resource = mock(Resource.class);

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, s -> {});
    adapter.setResources(Collections.singleton(resource));

    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.succeeding(s -> {
        // THEN the resources have been registered with the server
        final ArgumentCaptor<VertxCoapResource> resourceCaptor = ArgumentCaptor.forClass(VertxCoapResource.class);
        ctx.verify(() -> {
            verify(server).add(resourceCaptor.capture());
            assertThat(resourceCaptor.getValue().getWrappedResource()).isEqualTo(resource);
        });
        ctx.completeNow();
    }));
    adapter.start(startupTracker);

}
 
Example #8
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>onStartupSuccess</em> method is invoked if the coap server has been started successfully.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartInvokesOnStartupSuccess(final VertxTestContext ctx) {

    // GIVEN an adapter
    final CoapServer server = getCoapServer(false);
    final Checkpoint onStartupSuccess = ctx.checkpoint();

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true,
            s -> onStartupSuccess.flag());

    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.completing());
    adapter.start(startupTracker);

    // THEN the onStartupSuccess method has been invoked
}
 
Example #9
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 #10
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter forwards an empty notification downstream.
 */
@Test
public void testUploadEmptyNotificationSucceeds() {

    // 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 is marked as an empty notification
    final OptionSet options = new OptionSet();
    options.addUriQuery(CoapContext.PARAM_EMPTY_CONTENT);
    final CoapExchange coapExchange = newCoapExchange(null, Type.NON, options);
    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 indicating success
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
    // and the message has been forwarded downstream
    verify(sender).send(argThat(msg -> EventConstants.isEmptyNotificationType(msg.getContentType())), any(SpanContext.class));
    verify(metrics).reportTelemetry(
            eq(MetricsTags.EndpointType.TELEMETRY),
            eq("my-tenant"),
            any(),
            eq(MetricsTags.ProcessingOutcome.FORWARDED),
            eq(MetricsTags.QoS.AT_MOST_ONCE),
            eq(0),
            eq(TtdStatus.NONE),
            any());
}
 
Example #11
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 #12
Source File: CoapTransportService.java    From Groza with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() throws UnknownHostException {
    log.info("Starting CoAP transport...");
    log.info("Lookup CoAP transport adaptor {}", adaptorName);
    this.adaptor = (CoapTransportAdaptor) appContext.getBean(adaptorName);
    log.info("Starting CoAP transport server");
    this.server = new CoapServer();
    createResources();
    InetAddress addr = InetAddress.getByName(host);
    InetSocketAddress sockAddr = new InetSocketAddress(addr, port);
    server.addEndpoint(new CoapEndpoint(sockAddr));
    server.start();
    log.info("CoAP transport started!");
}
 
Example #13
Source File: CoapTransportService.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() throws UnknownHostException {
  log.info("Starting CoAP transport...");
  log.info("Lookup CoAP transport adaptor {}", adaptorName);
  // this.adaptor = (CoapTransportAdaptor) appContext.getBean(adaptorName);
  log.info("Starting CoAP transport server");
  this.server = new CoapServer();
  createResources();
  InetAddress addr = InetAddress.getByName(host);
  InetSocketAddress sockAddr = new InetSocketAddress(addr, port);
  server.addEndpoint(new CoapEndpoint(sockAddr));
  server.start();
  log.info("CoAP transport started!");
}
 
Example #14
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 #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: AbstractVertxBasedCoapAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void addResources(final CoapServer startingServer) {
    resourcesToAdd.forEach(resource -> {
        log.info("adding resource to CoAP server [name: {}]", resource.getName());
        startingServer.add(new VertxCoapResource(resource, context));
    });
    resourcesToAdd.clear();
}
 
Example #17
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the resources registered with the adapter are always
 * executed on the adapter's vert.x context.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testResourcesAreRunOnVertxContext(final VertxTestContext ctx) {

    // GIVEN an adapter
    final Context context = vertx.getOrCreateContext();
    final CoapServer server = getCoapServer(false);
    // with a resource
    final Promise<Void> resourceInvocation = Promise.promise();
    final Resource resource = new CoapResource("test") {

        @Override
        public void handleGET(final CoapExchange exchange) {
            ctx.verify(() -> assertThat(Vertx.currentContext()).isEqualTo(context));
            resourceInvocation.complete();
        }
    };

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = getAdapter(server, true, s -> {});
    adapter.setResources(Collections.singleton(resource));

    final Promise<Void> startupTracker = Promise.promise();
    adapter.init(vertx, context);
    adapter.start(startupTracker);

    startupTracker.future()
        .compose(ok -> {
            // WHEN the resource receives a GET request
            final Request request = new Request(Code.GET);
            final Exchange getExchange = new Exchange(request, Origin.REMOTE, mock(Executor.class));
            final ArgumentCaptor<VertxCoapResource> resourceCaptor = ArgumentCaptor.forClass(VertxCoapResource.class);
            verify(server).add(resourceCaptor.capture());
            resourceCaptor.getValue().handleRequest(getExchange);
            // THEN the resource's handler has been run on the adapter's vert.x event loop
            return resourceInvocation.future();
        })
        .onComplete(ctx.completing());
}
 
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.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 #19
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 not empty but doesn't contain a content-format option.
 */
@Test
public void testUploadTelemetryFailsForMissingContentFormat() {

    // 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 a non-empty message that lacks a content-format option
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.NON, (Integer) null);
    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 #20
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 #21
Source File: BatteryDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public BatteryDriver() throws Exception {
	bdLogger.log(Level.FINEST, "In Constructor");
	cs = new CoapServer(); //initilize the server
	InetSocketAddress bindToAddress =
			new InetSocketAddress("localhost", LISTEN_PORT);//get the address
	CoapEndpoint tmp = new CoapEndpoint(bindToAddress); //create endpoint
	cs.addEndpoint(tmp);//add endpoint to server
	startTime = System.currentTimeMillis();
	tmp.start();//Start this endpoint and all its components.
	driverPort = tmp.getAddress().getPort();
	cs.add(new bdResource());

	try {
			Class.forName("org.h2.Driver");
			Connection conn = DriverManager.getConnection("jdbc:h2:mem:BatteryDriver;DB_CLOSE_DELAY=-1",
																						 "user", "password");
			conn.createStatement().executeUpdate("CREATE TABLE data ("
																					 +" key  INTEGER AUTO_INCREMENT,"
																					 +" time BIGINT, "
																					 +" type VARCHAR(16), "
																					 +" value VARCHAR(1023) )");
			conn.close();
	}
	catch(Exception e) {
									e.printStackTrace();
	}

}
 
Example #22
Source File: TemplateDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public TemplateDriver() throws Exception {
		logger.log(Level.FINEST, "In Constructor");
		cs = new CoapServer(); //initilize the server
		InetSocketAddress bindToAddress =
				new InetSocketAddress("localhost", LISTEN_PORT);//get the address
		CoapEndpoint tmp = new CoapEndpoint(bindToAddress); //create endpoint
		cs.addEndpoint(tmp);//add endpoint to server
		tmp.start();//Start this endpoint and all its components.
		driverPort = tmp.getAddress().getPort();
		cs.add(new Resource());
}
 
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: VisionDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public VisionDriver() throws Exception {
		fddLogger.log(Level.FINEST, "In Constructor");
		cs = new CoapServer(); //initilize the server
		InetSocketAddress bindToAddress = new InetSocketAddress( LISTEN_PORT);//get the address
		CoapEndpoint tmp = new CoapEndpoint(bindToAddress); //create endpoint
		cs.addEndpoint(tmp);//add endpoint to server
		tmp.start();//Start this endpoint and all its components.
		driverPort = tmp.getAddress().getPort();

		cs.add(new fddResource());
}
 
Example #25
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 #26
Source File: DroneGimbalDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public DroneGimbalDriver() throws Exception {
		dgdLogger.log(Level.FINEST, "In Constructor");
		cs = new CoapServer(); //initilize the server
		InetSocketAddress bindToAddress = new InetSocketAddress( LISTEN_PORT);//get the address
		CoapEndpoint tmp = new CoapEndpoint(bindToAddress); //create endpoint
		cs.addEndpoint(tmp);//add endpoint to server
		tmp.start();//Start this endpoint and all its components.
		driverPort = tmp.getAddress().getPort();

		cs.add(new dgdResource());

}
 
Example #27
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 #28
Source File: PicTraceDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public PicTraceDriver() throws Exception {
		bdLogger.log(Level.FINEST, "In Constructor");
		cs = new CoapServer(); //initilize the server
		InetSocketAddress bindToAddress =
				new InetSocketAddress( LISTEN_PORT);//get the address
		CoapEndpoint tmp = new CoapEndpoint(bindToAddress); //create endpoint
		cs.addEndpoint(tmp);//add endpoint to server
		startTime = System.currentTimeMillis();
		tmp.start();//Start this endpoint and all its components.
		driverPort = tmp.getAddress().getPort();
		cs.add(new bdResource());
		makeH2();
}
 
Example #29
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 #30
Source File: LocationDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public LocationDriver() throws Exception {
		bdLogger.log(Level.FINEST, "In Constructor");
		cs = new CoapServer(); //initilize the server
		InetSocketAddress bindToAddress =
				new InetSocketAddress( LISTEN_PORT);//get the address
		CoapEndpoint tmp = new CoapEndpoint(bindToAddress); //create endpoint
		cs.addEndpoint(tmp);//add endpoint to server
		startTime = System.currentTimeMillis();
		tmp.start();//Start this endpoint and all its components.
		driverPort = tmp.getAddress().getPort();
		cs.add(new bdResource());
		makeH2();
}