//Create settable future to wait for response
final SettableFuture<CoapResponse> responseFuture = SettableFuture.create();
//Look up web service instance to handle the request
final Webservice webservice = registeredServices.get(coapRequest.getUriPath());
if(coapRequest.getObserve() == 1 && webservice instanceof ObservableWebservice){
Token token = coapRequest.getToken();
if(((ObservableWebservice) webservice).removeObservation(remoteEndpoint, token)){
log.info("Stopped observation due to GET request with observe = 1 (remote endpoint: {}, token: {})",
remoteEndpoint, token);
}
else{
log.warn("No observation found to be stopped due to GET request with observe = 1 (remote endpoint:" +
"{}, token: {}", remoteEndpoint, token);
}
}
responseFuture.addListener(new Runnable() {
@Override
public void run() {
try{
CoapResponse coapResponse = responseFuture.get();
coapResponse.setMessageID(coapRequest.getMessageID());
coapResponse.setToken(coapRequest.getToken());
if(coapResponse.isUpdateNotification()){
if(webservice instanceof ObservableWebservice && coapRequest.getObserve() == 0){
ObservableWebservice observableWebservice = (ObservableWebservice) webservice;
observableWebservice.addObservation(remoteEndpoint, coapResponse.getToken(),
coapResponse.getContentFormat());
sendUpdateNotification(ctx, remoteEndpoint, coapResponse, observableWebservice);
}
else{
coapResponse.removeOptions(OptionValue.Name.OBSERVE);
log.warn("Removed observe option from response!");
sendCoapResponse(ctx, remoteEndpoint, coapResponse);
}
}
else{
sendCoapResponse(ctx, remoteEndpoint, coapResponse);
}
}
catch (Exception e) {
log.error("Exception while processing inbound request", e);
CoapResponse errorResponse = CoapResponse.createErrorResponse(coapRequest.getMessageTypeName(),
MessageCode.Name.INTERNAL_SERVER_ERROR_500, e.getMessage());
errorResponse.setMessageID(coapRequest.getMessageID());
errorResponse.setToken(coapRequest.getToken());
sendCoapResponse(ctx, remoteEndpoint, errorResponse);
}
}
}, executor);
try{
//The requested Webservice does not exist
if(webservice == null)
webServiceNotFoundHandler.processCoapRequest(responseFuture, coapRequest, remoteEndpoint);
//The IF-NON-MATCH option indicates that the request is only to be processed if the webservice does not
//(yet) exist. But it does. So send an error response
else if(coapRequest.isIfNonMatchSet())
sendPreconditionFailed(coapRequest.getMessageTypeName(), coapRequest.getUriPath(), responseFuture);
//The inbound request is to be handled by the addressed service
else
webservice.processCoapRequest(responseFuture, coapRequest, remoteEndpoint);
}
catch (Exception e) {
log.error("This should never happen.", e);
responseFuture.setException(e);