org.eclipse.californium.core.coap.Response Java Examples
The following examples show how to use
org.eclipse.californium.core.coap.Response.
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: JsonCoapAdaptor.java From Groza with Apache License 2.0 | 6 votes |
@Override public Optional<Response> convertToAdaptorMsg(CoapSessionCtx ctx, SessionActorToAdaptorMsg source) throws AdaptorException { ToDeviceMsg msg = source.getMsg(); switch (msg.getSessionMsgType()) { case STATUS_CODE_RESPONSE: case TO_DEVICE_RPC_RESPONSE_ACK: return Optional.of(convertStatusCodeResponse((StatusCodeResponse) msg)); case GET_ATTRIBUTES_RESPONSE: return Optional.of(convertGetAttributesResponse((GetAttributesResponse) msg)); case ATTRIBUTES_UPDATE_NOTIFICATION: return Optional.of(convertNotificationResponse(ctx, (AttributesUpdateNotification) msg)); case TO_DEVICE_RPC_REQUEST: return Optional.of(convertToDeviceRpcRequest(ctx, (ToDeviceRpcRequestMsg) msg)); case TO_SERVER_RPC_RESPONSE: return Optional.of(convertToServerRpcResponse(ctx, (ToServerRpcResponseMsg) msg)); case RULE_ENGINE_ERROR: return Optional.of(convertToRuleEngineErrorResponse(ctx, (RuleEngineErrorMsg) msg)); default: log.warn("[{}] Unsupported msg type: {}!", source.getSessionId(), msg.getSessionMsgType()); throw new AdaptorException(new IllegalArgumentException("Unsupported msg type: " + msg.getSessionMsgType() + "!")); } }
Example #2
Source File: CoapResource.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * Remove all observe relations to CoAP clients and notify them that the * observe relation has been canceled. * * @param code * the error code why the relation was terminated * (e.g., 4.04 after deletion) */ public void clearAndNotifyObserveRelations(ResponseCode code) { /* * draft-ietf-core-observe-08, chapter 3.2 Notification states: * In the event that the resource changes in a way that would cause * a normal GET request at that time to return a non-2.xx response * (for example, when the resource is deleted), the server sends a * notification with a matching response code and removes the client * from the list of observers. * This method is called, when the resource is deleted. */ for (ObserveRelation relation:observeRelations) { relation.cancel(); relation.getExchange().sendResponse(new Response(code)); } }
Example #3
Source File: Utils.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * 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: CoapEndpoint.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@Override public void sendResponse(Exchange exchange, Response response) { if (response.getDestination() == null) throw new NullPointerException("Response has no destination address"); if (response.getDestinationPort() == 0) throw new NullPointerException("Response has no destination port"); matcher.sendResponse(exchange, response); /* * Logging here causes significant performance loss. * If necessary, add an interceptor that logs the messages, * e.g., the MessageTracer. */ for (MessageInterceptor interceptor:interceptors) interceptor.sendResponse(response); // MessageInterceptor might have canceled if (!response.isCanceled()) connector.send(serializer.serialize(response)); }
Example #5
Source File: CoapResource.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * This method is used to apply resource-specific knowledge on the exchange. * If the request was successful, it sets the Observe option for the * response. It is important to use the notificationOrderer of the resource * here. Further down the layer, race conditions could cause local * reordering of notifications. If the response has an error code, no * observe relation can be established and if there was one previously it is * canceled. When this resource allows to be observed by clients and the * request is a GET request with an observe option, the * {@link ServerMessageDeliverer} already created the relation, as it * manages the observing endpoints globally. * * @param exchange the exchange * @param response the response */ public void checkObserveRelation(Exchange exchange, Response response) { /* * If the request for the specified exchange tries to establish an observer * relation, then the ServerMessageDeliverer must have created such a relation * and added to the exchange. Otherwise, there is no such relation. * Remember that different paths might lead to this resource. */ ObserveRelation relation = exchange.getRelation(); if (relation == null) return; // because request did not try to establish a relation if (CoAP.ResponseCode.isSuccess(response.getCode())) { response.getOptions().setObserve(notificationOrderer.getCurrent()); if (!relation.isEstablished()) { relation.setEstablished(true); addObserveRelation(relation); } else if (observeType != null) { // The resource can control the message type of the notification response.setType(observeType); } } // ObserveLayer takes care of the else case }
Example #6
Source File: CoapExchange.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * Respond with the specified response. * @param response the response */ public void respond(Response response) { if (response == null) throw new NullPointerException(); // set the response options configured through the CoapExchange API if (locationPath != null) response.getOptions().setLocationPath(locationPath); if (locationQuery != null) response.getOptions().setLocationQuery(locationQuery); if (maxAge != 60) response.getOptions().setMaxAge(maxAge); if (eTag != null) { response.getOptions().clearETags(); response.getOptions().addETag(eTag); } resource.checkObserveRelation(exchange, response); exchange.sendResponse(response); }
Example #7
Source File: ReliabilityLayer.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * When we receive a Confirmable response, we acknowledge it and it also * counts as acknowledgment for the request. If the response is a duplicate, * we stop it here and do not forward it to the upper layer. */ @Override public void receiveResponse(Exchange exchange, Response response) { exchange.setFailedTransmissionCount(0); exchange.getCurrentRequest().setAcknowledged(true); LOGGER.finest("Cancel any retransmission"); exchange.setRetransmissionHandle(null); if (response.getType() == Type.CON && !exchange.getRequest().isCanceled()) { LOGGER.finer("Response is confirmable, send ACK"); EmptyMessage ack = EmptyMessage.newACK(response); sendEmptyMessage(exchange, ack); } if (response.isDuplicate()) { LOGGER.fine("Response is duplicate, ignore it"); } else { super.receiveResponse(exchange, response); } }
Example #8
Source File: ObserveLayer.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@Override public void onAcknowledgement() { synchronized (exchange) { ObserveRelation relation = exchange.getRelation(); final Response next = relation.getNextControlNotification(); relation.setCurrentControlNotification(next); // next may be null relation.setNextControlNotification(null); if (next != null) { LOGGER.fine("Notification has been acknowledged, send the next one"); // this is not a self replacement, hence a new MID next.setMID(Message.NONE); // Create a new task for sending next response so that we can leave the sync-block executor.execute(new Runnable() { public void run() { ObserveLayer.super.sendResponse(exchange, next); } }); } } }
Example #9
Source File: ReliabilityLayer.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * When we receive a Confirmable response, we acknowledge it and it also * counts as acknowledgment for the request. If the response is a duplicate, * we stop it here and do not forward it to the upper layer. */ @Override public void receiveResponse(Exchange exchange, Response response) { exchange.setFailedTransmissionCount(0); exchange.getCurrentRequest().setAcknowledged(true); LOGGER.finest("Cancel any retransmission"); exchange.setRetransmissionHandle(null); if (response.getType() == Type.CON && !exchange.getRequest().isCanceled()) { LOGGER.finer("Response is confirmable, send ACK"); EmptyMessage ack = EmptyMessage.newACK(response); sendEmptyMessage(exchange, ack); } if (response.isDuplicate()) { LOGGER.fine("Response is duplicate, ignore it"); } else { super.receiveResponse(exchange, response); } }
Example #10
Source File: CoapEndpoint.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
@Override public void sendResponse(Exchange exchange, Response response) { if (response.getDestination() == null) throw new NullPointerException("Response has no destination address"); if (response.getDestinationPort() == 0) throw new NullPointerException("Response has no destination port"); matcher.sendResponse(exchange, response); /* * Logging here causes significant performance loss. * If necessary, add an interceptor that logs the messages, * e.g., the MessageTracer. */ for (MessageInterceptor interceptor:interceptors) interceptor.sendResponse(response); // MessageInterceptor might have canceled if (!response.isCanceled()) connector.send(serializer.serialize(response)); }
Example #11
Source File: CoapResource.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
/** * Remove all observe relations to CoAP clients and notify them that the * observe relation has been canceled. * * @param code * the error code why the relation was terminated * (e.g., 4.04 after deletion) */ public void clearAndNotifyObserveRelations(ResponseCode code) { /* * draft-ietf-core-observe-08, chapter 3.2 Notification states: * In the event that the resource changes in a way that would cause * a normal GET request at that time to return a non-2.xx response * (for example, when the resource is deleted), the server sends a * notification with a matching response code and removes the client * from the list of observers. * This method is called, when the resource is deleted. */ for (ObserveRelation relation:observeRelations) { relation.cancel(); relation.getExchange().sendResponse(new Response(code)); } }
Example #12
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.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 #13
Source File: CongestionControlLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
/** * Forward the response to the lower layer. * @param exchange the exchange * @param response the current response */ @Override public void sendResponse(Exchange exchange, Response response) { // Check if exchange is already running into a retransmission; if so, don't call processMessage, since this is a retransmission if (exchange.getFailedTransmissionCount() > 0) { super.sendResponse(exchange, response); } else if (processMessage(exchange, response)) { checkAging(exchange); super.sendResponse(exchange, response); } }
Example #14
Source File: CongestionControlLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void receiveResponse(Exchange exchange, Response response) { //August: change the state of the remote endpoint (STRONG/WEAK/NOESTIMATOR) if failedTransmissionCount = 0; if (exchange.getFailedTransmissionCount() != 0) { getRemoteEndpoint(exchange).setEstimatorState(exchange); } super.receiveResponse(exchange, response); calculateRTT(exchange); checkRemoteEndpointQueue(exchange); }
Example #15
Source File: JsonCoapAdaptor.java From Groza with Apache License 2.0 | 5 votes |
private Response convertToServerRpcResponse(SessionContext ctx, ToServerRpcResponseMsg msg) { if (msg.isSuccess()) { Response response = new Response(CoAP.ResponseCode.CONTENT); JsonElement result = JsonConverter.toJson(msg); response.setPayload(result.toString()); return response; } else { return convertError(Optional.of(new RuntimeException("Server RPC response is empty!"))); } }
Example #16
Source File: JsonCoapAdaptor.java From Groza with Apache License 2.0 | 5 votes |
private Response convertError(Optional<Exception> exception) { if (exception.isPresent()) { log.warn("Converting exception: {}", exception.get().getMessage(), exception.get()); if (exception.get() instanceof ProcessingTimeoutException) { return new Response(CoAP.ResponseCode.SERVICE_UNAVAILABLE); } else { return new Response(CoAP.ResponseCode.INTERNAL_SERVER_ERROR); } } else { return new Response(CoAP.ResponseCode.INTERNAL_SERVER_ERROR); } }
Example #17
Source File: CongestionControlLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
/** * Forward the response to the lower layer. * @param exchange the exchange * @param response the current response */ @Override public void sendResponse(Exchange exchange, Response response) { // Check if exchange is already running into a retransmission; if so, don't call processMessage, since this is a retransmission if (exchange.getFailedTransmissionCount() > 0) { super.sendResponse(exchange, response); } else if (processMessage(exchange, response)) { checkAging(exchange); super.sendResponse(exchange, response); } }
Example #18
Source File: Exchange.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
/** * Sends the specified response over the same endpoint as the request has * arrived. * * @param response the response */ public void sendResponse(Response response) { response.setDestination(request.getSource()); response.setDestinationPort(request.getSourcePort()); setResponse(response); endpoint.sendResponse(this, response); }
Example #19
Source File: AbstractVertxBasedCoapAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * 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 #20
Source File: ServerMessageDeliverer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void deliverResponse(Exchange exchange, Response response) { if (response == null) throw new NullPointerException(); if (exchange == null) throw new NullPointerException(); if (exchange.getRequest() == null) throw new NullPointerException(); exchange.getRequest().setResponse(response); }
Example #21
Source File: Matcher.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private void removeNotificatoinsOf(ObserveRelation relation) { LOGGER.fine("Remove all remaining NON-notifications of observe relation"); for (Iterator<Response> iterator = relation.getNotificationIterator(); iterator.hasNext();) { Response previous = iterator.next(); // notifications are local MID namespace KeyMID idByMID = new KeyMID(previous.getMID(), null, 0); exchangesByMID.remove(idByMID); iterator.remove(); } }
Example #22
Source File: BlockwiseLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void sendResponse(Exchange exchange, Response response) { BlockOption block1 = exchange.getBlock1ToAck(); if (block1 != null) exchange.setBlock1ToAck(null); if (requireBlockwise(exchange, response)) { LOGGER.fine("Response payload "+response.getPayloadSize()+"/"+max_message_size+" requires Blockwise"); BlockwiseStatus status = findResponseBlockStatus(exchange, response); Response block = getNextResponseBlock(response, status); if (block1 != null) // in case we still have to ack the last block1 block.getOptions().setBlock1(block1); if (status.isComplete()) { // clean up blockwise status LOGGER.fine("Ongoing finished on first block "+status); exchange.setResponseBlockStatus(null); exchange.setBlockCleanupHandle(null); } else { LOGGER.fine("Ongoing started "+status); } exchange.setCurrentResponse(block); super.sendResponse(exchange, block); } else { if (block1 != null) response.getOptions().setBlock1(block1); exchange.setCurrentResponse(response); // Block1 transfer completed exchange.setBlockCleanupHandle(null); super.sendResponse(exchange, response); } }
Example #23
Source File: CoapEndpoint.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void sendResponse(final Exchange exchange, final Response response) { if (exchange.hasCustomExecutor()) { // handle sending by protocol stage instead of business logic stage runInProtocolStage(new Runnable() { public void run() { coapstack.sendResponse(exchange, response); } }); } else { // use same thread to save switching overhead coapstack.sendResponse(exchange, response); } }
Example #24
Source File: Matcher.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private void removeNotificatoinsOf(ObserveRelation relation) { LOGGER.fine("Remove all remaining NON-notifications of observe relation"); for (Iterator<Response> iterator = relation.getNotificationIterator(); iterator.hasNext();) { Response previous = iterator.next(); // notifications are local MID namespace KeyMID idByMID = new KeyMID(previous.getMID(), null, 0); exchangesByMID.remove(idByMID); iterator.remove(); } }
Example #25
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 #26
Source File: EndpointManager.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void deliverResponse(Exchange exchange, Response response) { if (exchange == null) throw new NullPointerException(); if (exchange.getRequest() == null) throw new NullPointerException(); if (response == null) throw new NullPointerException(); exchange.getRequest().setResponse(response); }
Example #27
Source File: CongestionControlLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void receiveResponse(Exchange exchange, Response response) { //August: change the state of the remote endpoint (STRONG/WEAK/NOESTIMATOR) if failedTransmissionCount = 0; if (exchange.getFailedTransmissionCount() != 0) { getRemoteEndpoint(exchange).setEstimatorState(exchange); } super.receiveResponse(exchange, response); calculateRTT(exchange); checkRemoteEndpointQueue(exchange); }
Example #28
Source File: BlockwiseLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private BlockwiseStatus findResponseBlockStatus(Exchange exchange, Response response) { BlockwiseStatus status = exchange.getResponseBlockStatus(); if (status == null) { status = new BlockwiseStatus(response.getOptions().getContentFormat()); status.setCurrentSzx( computeSZX(preferred_block_size) ); exchange.setResponseBlockStatus(status); LOGGER.finer("There is no blockwise status yet. Create and set new Block2 status: "+status); } else { LOGGER.finer("Current Block2 status: "+status); } // sets a timeout to complete exchange prepareBlockCleanup(exchange); return status; }
Example #29
Source File: CoapClient.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
private CoapResponse synchronous(Request request, Endpoint outEndpoint) { try { Response response = send(request, outEndpoint).waitForResponse(getTimeout()); if (response == null) return null; else return new CoapResponse(response); } catch (InterruptedException e) { throw new RuntimeException(e); } }
Example #30
Source File: ObserveLayer.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void receiveResponse(Exchange exchange, Response response) { if (response.getOptions().hasObserve() && exchange.getRequest().isCanceled()) { // The request was canceled and we no longer want notifications LOGGER.finer("Rejecting notification for canceled Exchange"); EmptyMessage rst = EmptyMessage.newRST(response); sendEmptyMessage(exchange, rst); // Matcher sets exchange as complete when RST is sent } else { // No observe option in response => always deliver super.receiveResponse(exchange, response); } }