org.eclipse.californium.core.server.resources.CoapExchange Java Examples
The following examples show how to use
org.eclipse.californium.core.server.resources.CoapExchange.
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: CaptureImageV2Driver.java From SoftwarePilot with MIT License | 6 votes |
private void deleteFiles(final CoapExchange ce) { drvSetLock("DEL"); mMediaManager.deleteFiles(mediaFileList, new CommonCallbacks.CompletionCallbackWithTwoParam<List<MediaFile>, DJICameraError>() { @Override public void onSuccess(List<MediaFile> x, DJICameraError y) { ce.respond("Delete file success"); drvUnsetLock(); } @Override public void onFailure(DJIError error) { ce.respond(error.getDescription()); drvUnsetLock(); } }); drvSpin(); }
Example #2
Source File: CoapReceiverResource.java From datacollector with Apache License 2.0 | 6 votes |
public void handle(CoapExchange exchange) { if (shuttingDown) { LOG.debug("Shutting down, discarding incoming request from '{}'", exchange.getSourceAddress()); exchange.respond(CoAP.ResponseCode.SERVICE_UNAVAILABLE); } else { long start = System.currentTimeMillis(); LOG.debug("Request accepted from '{}'", exchange.getSourceAddress()); try { if (receiver.process(exchange.getRequestPayload())) { exchange.respond(CoAP.ResponseCode.VALID); exchange.accept(); requestMeter.mark(); } else { exchange.respond(CoAP.ResponseCode.INTERNAL_SERVER_ERROR); exchange.accept(); errorRequestMeter.mark(); } } catch (IOException ex) { exchange.reject(); errorQueue.offer(ex); errorRequestMeter.mark(); } finally { requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS); } } }
Example #3
Source File: CoapTransportResource.java From Groza with Apache License 2.0 | 6 votes |
@Override public void handlePOST(CoapExchange exchange) { Optional<FeatureType> featureType = getFeatureType(exchange.advanced().getRequest()); if (!featureType.isPresent()) { log.trace("Missing feature type parameter"); exchange.respond(CoAP.ResponseCode.BAD_REQUEST); } else { switch (featureType.get()) { case ATTRIBUTES: processRequest(exchange, SessionMsgType.POST_ATTRIBUTES_REQUEST); break; case TELEMETRY: processRequest(exchange, SessionMsgType.POST_TELEMETRY_REQUEST); break; case RPC: Optional<Integer> requestId = getRequestId(exchange.advanced().getRequest()); if (requestId.isPresent()) { processRequest(exchange, SessionMsgType.TO_DEVICE_RPC_RESPONSE); } else { processRequest(exchange, SessionMsgType.TO_SERVER_RPC_REQUEST); } break; } } }
Example #4
Source File: CoapTransportResource.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public void handlePOST(CoapExchange exchange) { Optional<FeatureType> featureType = getFeatureType(exchange.advanced().getRequest()); if (!featureType.isPresent()) { log.trace("Missing feature type parameter"); exchange.respond(ResponseCode.BAD_REQUEST); } else { switch (featureType.get()) { case ATTRIBUTES: processRequest(exchange, MsgType.POST_ATTRIBUTES_REQUEST); break; case TELEMETRY: processRequest(exchange, MsgType.POST_TELEMETRY_REQUEST); break; case RPC: Optional<Integer> requestId = getRequestId(exchange.advanced().getRequest()); if (requestId.isPresent()) { processRequest(exchange, MsgType.TO_DEVICE_RPC_RESPONSE); } else { processRequest(exchange, MsgType.TO_SERVER_RPC_REQUEST); } break; } } }
Example #5
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 6 votes |
private static CoapExchange newCoapExchange(final Buffer payload, final Type requestType, final OptionSet options) { final Request request = mock(Request.class); when(request.getType()).thenReturn(requestType); when(request.isConfirmable()).thenReturn(requestType == Type.CON); when(request.getOptions()).thenReturn(options); final Exchange echange = new Exchange(request, Origin.REMOTE, mock(Executor.class)); final CoapExchange coapExchange = mock(CoapExchange.class); when(coapExchange.advanced()).thenReturn(echange); Optional.ofNullable(payload).ifPresent(b -> when(coapExchange.getRequestPayload()).thenReturn(b.getBytes())); when(coapExchange.getRequestOptions()).thenReturn(options); when(coapExchange.getQueryParameter(anyString())).thenAnswer(invocation -> { final String key = invocation.getArgument(0); return options.getUriQuery().stream() .map(param -> param.split("=", 2)) .filter(keyValue -> key.equals(keyValue[0])) .findFirst() .map(keyValue -> keyValue.length < 2 ? Boolean.TRUE.toString() : keyValue[1]) .orElse(null); }); return coapExchange; }
Example #6
Source File: VisionDriver.java From SoftwarePilot with MIT License | 5 votes |
FlightTimerTask(FlightControlData input, Timer t, int freq, CoapExchange ex, boolean sendMessage) { super(); fcd = input; ctrl=t; frequency = freq; ce = ex; send = sendMessage; }
Example #7
Source File: CoapContext.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Creates a new context for a CoAP request. * * @param request The CoAP exchange representing the request. * @param timer The object to use for measuring the time it takes to process the request. * @return The context. * @throws NullPointerException if any of the parameters are {@code null}. */ public static CoapContext fromRequest(final CoapExchange request, final Sample timer) { Objects.requireNonNull(request); Objects.requireNonNull(timer); final CoapContext result = new CoapContext(request); result.timer = timer; return result; }
Example #8
Source File: VertxBasedCoapAdapter.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Gets a device identity for a CoAP request. * * @param exchange The CoAP exchange with URI and/or peer's principal. * @return The device identity. */ public Future<ExtendedDevice> getExtendedDevice(final CoapExchange exchange) { final List<String> pathList = exchange.getRequestOptions().getUriPath(); if (pathList.isEmpty()) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "missing request URI")); } if (pathList.size() == 1) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "missing tenant and device ID in URI")); } else if (pathList.size() == 2) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "missing device ID in URI")); } try { final String[] path = pathList.toArray(new String[pathList.size()]); final ResourceIdentifier identifier = ResourceIdentifier.fromPath(path); final Device device = new Device(identifier.getTenantId(), identifier.getResourceId()); final Principal peer = exchange.advanced().getRequest().getSourceContext().getPeerIdentity(); if (peer == null) { return Future.succeededFuture(new ExtendedDevice(device, device)); } else { return getAuthenticatedExtendedDevice(device, exchange); } } catch (IllegalArgumentException cause) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "missing tenant and device ID in URI")); } }
Example #9
Source File: BatteryDriver.java From SoftwarePilot with MIT License | 5 votes |
@Override public void handlePUT(CoapExchange ce) { // Split on & and = then on ' ' String outLine = ""; byte[] payload = ce.getRequestPayload(); String inputLine = new String(payload); int AUAVsim = 0; if (inputLine.contains("dp=AUAVsim")) { AUAVsim = 1; } String[] args = inputLine.split("-");//??? switch (args[0]) { case "dc=help": ce.respond(getUsageInfo()); break; case "dc=qry": String qry = args[1].substring(3); ce.respond(queryH2(qry)); break; case "dc=dji": System.out.println("Battery Value is: " + djiLastReading); System.out.println("Battery MAH is: " + djiLastMAH); System.out.println("Battery Current is: "+djiCurrent); System.out.println("Battery Voltage is: "+djiVoltage); ce.respond("Percent=" + djiLastReading+", MAH="+djiLastMAH); case "dc=lcl": if (AUAVsim == 1) { lclLastReading--; addReadingH2(lclLastReading, "lcl"); ce.respond("Battery: " + Integer.toString(lclLastReading)); break; } try { Class<?> c = Class.forName("android.app.ActivityThread"); android.app.Application app = (android.app.Application) c.getDeclaredMethod("currentApplication").invoke(null); android.content.Context context = app.getApplicationContext(); BatteryManager bm = (BatteryManager)context.getSystemService("batterymanager"); int batLevel = bm.getIntProperty(4); lclLastReading = batLevel; addReadingH2(batLevel, "lcl"); ce.respond("Battery: " + Integer.toString(batLevel)); } catch (Exception e) { ce.respond("Battery: Error"); } break; case "dc=cfg": if(AUAVsim != 1){ initBatteryCallback(); } ce.respond("Battery: Configured"); default: ce.respond("Error: BatteryDriver unknown command\n"); } }
Example #10
Source File: MissionDriver.java From SoftwarePilot with MIT License | 5 votes |
FlightTimerTask(FlightControlData input, Timer t, int freq, CoapExchange ex, boolean sendMessage) { super(); fcd = input; ctrl=t; frequency = freq; ce = ex; send = sendMessage; }
Example #11
Source File: CoapSessionCtx.java From Groza with Apache License 2.0 | 5 votes |
public CoapSessionCtx(CoapExchange exchange, CoapTransportAdaptor adaptor, SessionMsgProcessor processor, DeviceAuthService authService, long timeout) { super(processor, authService); Request request = exchange.advanced().getRequest(); this.token = request.getTokenString(); this.sessionId = new CoapSessionId(request.getSource().getHostAddress(), request.getSourcePort(), this.token); this.exchange = exchange; this.adaptor = adaptor; this.timeout = timeout; }
Example #12
Source File: LocationDriver.java From SoftwarePilot with MIT License | 5 votes |
@Override public void handlePUT(CoapExchange ce) { // Split on & and = then on ' ' String outLine = ""; byte[] payload = ce.getRequestPayload(); String inputLine = new String(payload); int AUAVsim = 0; if (inputLine.contains("dp=AUAVsim")) { AUAVsim = 1; } String[] args = inputLine.split("-");//??? switch (args[0]) { case "dc=help": ce.respond(getUsageInfo()); break; case "dc=qry": String qry = args[1].substring(3); ce.respond("Location: "+queryH2(qry)); break; case "dc=tme": ce.respond("Location: time="+getStartTime()); break; case "dc=set": String Xpos = args[1].substring(3); String Ypos = args[2].substring(3); String Zpos = args[3].substring(3); addPositionH2(Xpos,Ypos,Zpos); Xcur = Xpos;Ycur=Ypos; Zcur=Zpos; ce.respond("Location: set"); break; case "dc=get": ce.respond("Location: x="+Xcur+"-y="+Ycur+"-z="+Zcur); break; default: ce.respond("Error: LocationDriver unknown command\n"); } }
Example #13
Source File: TracingSupportingHonoResourceTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Sets up the fixture. */ @BeforeEach public void setUp() { final Span span = mock(Span.class); spanBuilder = mock(SpanBuilder.class, RETURNS_SELF); when(spanBuilder.start()).thenReturn(span); tracer = mock(Tracer.class); when(tracer.buildSpan(anyString())).thenReturn(spanBuilder); resource = new TracingSupportingHonoResource(tracer, "test", "adapter") { @Override protected Future<ResponseCode> handlePost(final CoapExchange exchange, final Span currentSpan) { return Future.succeededFuture(ResponseCode.CHANGED); } }; }
Example #14
Source File: WritableResource.java From IOT-Technical-Guide with Apache License 2.0 | 5 votes |
@Override public void handlePUT(CoapExchange exchange) { byte[] payload = exchange.getRequestPayload(); try { value = new String(payload, "UTF-8"); exchange.respond(CHANGED, value); } catch (Exception e) { e.printStackTrace(); exchange.respond(BAD_REQUEST, "Invalid String"); } }
Example #15
Source File: CoapTransportResource.java From Groza with Apache License 2.0 | 5 votes |
private void processExchangeGetRequest(CoapExchange exchange, FeatureType featureType) { boolean unsubscribe = exchange.getRequestOptions().getObserve() == 1; SessionMsgType sessionMsgType; if (featureType == FeatureType.RPC) { sessionMsgType = unsubscribe ? SessionMsgType.UNSUBSCRIBE_RPC_COMMANDS_REQUEST : SessionMsgType.SUBSCRIBE_RPC_COMMANDS_REQUEST; } else { sessionMsgType = unsubscribe ? SessionMsgType.UNSUBSCRIBE_ATTRIBUTES_REQUEST : SessionMsgType.SUBSCRIBE_ATTRIBUTES_REQUEST; } Optional<SessionId> sessionId = processRequest(exchange, sessionMsgType); if (sessionId.isPresent()) { if (exchange.getRequestOptions().getObserve() == 1) { exchange.respond(CoAP.ResponseCode.VALID); } } }
Example #16
Source File: HelloWorld2.java From hands-on-coap with Eclipse Public License 1.0 | 5 votes |
@Override public void handlePUT(CoapExchange exchange) { byte[] payload = exchange.getRequestPayload(); try { value = new String(payload, "UTF-8"); exchange.respond(CHANGED, value); } catch (Exception e) { e.printStackTrace(); exchange.respond(BAD_REQUEST, "Invalid String"); } }
Example #17
Source File: CoapTransportResource.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public void handleGET(CoapExchange exchange) { Optional<FeatureType> featureType = getFeatureType(exchange.advanced().getRequest()); if (!featureType.isPresent()) { log.trace("Missing feature type parameter"); exchange.respond(ResponseCode.BAD_REQUEST); } else if (featureType.get() == FeatureType.TELEMETRY) { log.trace("Can't fetch/subscribe to timeseries updates"); exchange.respond(ResponseCode.BAD_REQUEST); } else if (exchange.getRequestOptions().hasObserve()) { boolean unsubscribe = exchange.getRequestOptions().getObserve() == 1; MsgType msgType; if (featureType.get() == FeatureType.RPC) { msgType = unsubscribe ? MsgType.UNSUBSCRIBE_RPC_COMMANDS_REQUEST : MsgType.SUBSCRIBE_RPC_COMMANDS_REQUEST; } else { msgType = unsubscribe ? MsgType.UNSUBSCRIBE_ATTRIBUTES_REQUEST : MsgType.SUBSCRIBE_ATTRIBUTES_REQUEST; } Optional<SessionId> sessionId = processRequest(exchange, msgType); if (sessionId.isPresent()) { if (exchange.getRequestOptions().getObserve() == 1) { exchange.respond(ResponseCode.VALID); } } } else if (featureType.get() == FeatureType.ATTRIBUTES) { processRequest(exchange, MsgType.GET_ATTRIBUTES_REQUEST); } else { log.trace("Invalid feature type parameter"); exchange.respond(ResponseCode.BAD_REQUEST); } }
Example #18
Source File: AbstractVertxBasedCoapAdapter.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Gets an authenticated device's identity for a CoAP request. * * @param device The device that the data in the request payload originates from. * If {@code null}, the origin of the data is assumed to be the authenticated device. * @param exchange The CoAP exchange with the authenticated device's principal. * @return A future indicating the outcome of the operation. * The future will be succeeded if the authenticated device can be determined from the CoAP exchange, * otherwise the future will be failed with a {@link ClientErrorException}. */ protected final Future<ExtendedDevice> getAuthenticatedExtendedDevice( final Device device, final CoapExchange exchange) { final Promise<ExtendedDevice> result = Promise.promise(); final Principal peerIdentity = exchange.advanced().getRequest().getSourceContext().getPeerIdentity(); if (peerIdentity instanceof ExtensiblePrincipal) { @SuppressWarnings("unchecked") final ExtensiblePrincipal<? extends Principal> extPrincipal = (ExtensiblePrincipal<? extends Principal>) peerIdentity; final Device authenticatedDevice = extPrincipal.getExtendedInfo().get("hono-device", Device.class); if (authenticatedDevice != null) { final Device originDevice = Optional.ofNullable(device).orElse(authenticatedDevice); result.complete(new ExtendedDevice(authenticatedDevice, originDevice)); } else { result.fail(new ClientErrorException( HttpURLConnection.HTTP_UNAUTHORIZED, "DTLS session does not contain authenticated Device")); } } else { result.fail(new ClientErrorException( HttpURLConnection.HTTP_UNAUTHORIZED, "DTLS session does not contain ExtensiblePrincipal")); } return result.future(); }
Example #19
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #20
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #21
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #22
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #23
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #24
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #25
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #27
Source File: InCse.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private boolean sendCoapResponse(OneM2mResponse resMessage, CoapExchange exchange) { if (exchange == null) { return false; } coapMap.remove(resMessage.getRequestIdentifier()); try { Response response = CoapResponseCodec.encode(resMessage, exchange); log.debug("<< SEND CoAP MESSAGE:"); log.debug(response.toString()); log.debug(response.getPayloadString()); exchange.respond(response); // added in 2017-10-31 to support CSE-relative Unstructured addressing //System.out.println("############### uripath-size=" + exchange.getRequestOptions().getUriPath().size()); //System.out.println("############### resMessage.getResponseStatusCode()=" + resMessage.getResponseStatusCode()); ///System.out.println("############### resourceId=" + ((Resource)resMessage.getContentObject()).getResourceID()); int len = exchange.getRequestOptions().getUriPath().size(); int resCode = resMessage.getResponseStatusCode(); if(resCode == 2001 && len == 1) { String resourceId = ((Resource)resMessage.getContentObject()).getResourceID(); coapServer.add(coapServer.new HCoapResource(resourceId)); } //coapServer.add(resources) return true; } catch (Exception e) { e.printStackTrace(); exchange.respond(ResponseCode.INTERNAL_SERVER_ERROR, "Respose encoding failed"); } return false; }
Example #28
Source File: HCoapServer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private void receiveRequest(CoapExchange exchange) { if(listener != null) { listener.receiveCoapRequest(exchange); } else { exchange.respond(ResponseCode.INTERNAL_SERVER_ERROR, "Not found listener"); } }
Example #29
Source File: HCoapServer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void handleGET(CoapExchange exchange) { // respond to the request //try { Thread.sleep(2000); } catch(Exception e) {} // System.out.println("RequestCode=" + exchange.getRequestCode()); // System.out.println("RequestPayload=" +exchange.getRequestPayload()); // System.out.println("Options=" + exchange.getRequestOptions()); // System.out.println("UriPath=" + exchange.getRequestOptions().getUriPathString()); // exchange.respond("Hello World!"); receiveRequest(exchange); }
Example #30
Source File: HCoapServer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void handleGET(CoapExchange exchange) { // respond to the request //try { Thread.sleep(2000); } catch(Exception e) {} // System.out.println("RequestCode=" + exchange.getRequestCode()); // System.out.println("RequestPayload=" +exchange.getRequestPayload()); // System.out.println("Options=" + exchange.getRequestOptions()); // System.out.println("UriPath=" + exchange.getRequestOptions().getUriPathString()); // exchange.respond("Hello World!"); receiveRequest(exchange); }