use of org.eclipse.leshan.core.response.ObserveResponse in project leshan by eclipse.
the class ObserveTest method can_observe_timestamped_object.
@Test
public void can_observe_timestamped_object() throws InterruptedException {
TestObservationListener listener = new TestObservationListener();
helper.server.getObservationService().addListener(listener);
// observe device timezone
ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(), new ObserveRequest(3));
assertEquals(ResponseCode.CONTENT, observeResponse.getCode());
assertNotNull(observeResponse.getCoapResponse());
assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class)));
// an observation response should have been sent
Observation observation = observeResponse.getObservation();
assertEquals("/3", observation.getPath().toString());
assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId());
Set<Observation> observations = helper.server.getObservationService().getObservations(helper.getCurrentRegistration());
assertTrue("We should have only on observation", observations.size() == 1);
assertTrue("New observation is not there", observations.contains(observation));
// *** HACK send time-stamped notification as Leshan client does not support it *** //
// create time-stamped nodes
TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(), new LwM2mObject(3, new LwM2mObjectInstance(0, LwM2mSingleResource.newStringResource(15, "Paris"))));
List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
timestampedNodes.add(mostRecentNode);
timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2, new LwM2mObject(3, new LwM2mObjectInstance(0, LwM2mSingleResource.newStringResource(15, "Londres")))));
byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3"), new LwM2mModel(helper.createObjectModels()), new DefaultLwM2mValueConverter());
Response firstCoapResponse = (Response) observeResponse.getCoapResponse();
sendNotification(getConnector(helper.client), payload, firstCoapResponse, ContentFormat.JSON_CODE);
// *** Hack End *** //
// verify result
listener.waitForNotification(2000);
assertTrue(listener.receivedNotify().get());
assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent());
assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode());
assertNotNull(listener.getResponse().getCoapResponse());
assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class)));
}
use of org.eclipse.leshan.core.response.ObserveResponse in project leshan by eclipse.
the class RedisRequestResponseHandler method sendResponse.
private void sendResponse(String ticket, LwM2mResponse response) {
if (response instanceof ObserveResponse) {
Observation observation = ((ObserveResponse) response).getObservation();
observatioIdToTicket.put(new KeyId(observation.getId()), ticket);
}
try (Jedis j = pool.getResource()) {
JsonObject m = Json.object();
m.add("ticket", ticket);
m.add("rep", ResponseSerDes.jSerialize(response));
j.publish(RESPONSE_CHANNEL, m.toString());
}
}
use of org.eclipse.leshan.core.response.ObserveResponse in project leshan by eclipse.
the class ClientServlet method doPost.
/**
* {@inheritDoc}
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String[] path = StringUtils.split(req.getPathInfo(), '/');
String clientEndpoint = path[0];
// /clients/endPoint/LWRequest/observe : do LightWeight M2M observe request on a given client.
if (path.length >= 3 && "observe".equals(path[path.length - 1])) {
try {
String target = StringUtils.substringBetween(req.getPathInfo(), clientEndpoint, "/observe");
Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
if (registration != null) {
// get content format
String contentFormatParam = req.getParameter(FORMAT_PARAM);
ContentFormat contentFormat = contentFormatParam != null ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null;
// create & process request
ObserveRequest request = new ObserveRequest(contentFormat, target);
ObserveResponse cResponse = server.send(registration, request, TIMEOUT);
processDeviceResponse(req, resp, cResponse);
} else {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
}
} catch (RuntimeException | InterruptedException e) {
handleException(e, resp);
}
return;
}
String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
// /clients/endPoint/LWRequest : do LightWeight M2M execute request on a given client.
if (path.length == 4) {
try {
Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
if (registration != null) {
ExecuteRequest request = new ExecuteRequest(target, IOUtils.toString(req.getInputStream()));
ExecuteResponse cResponse = server.send(registration, request, TIMEOUT);
processDeviceResponse(req, resp, cResponse);
} else {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
}
} catch (RuntimeException | InterruptedException e) {
handleException(e, resp);
}
return;
}
// /clients/endPoint/LWRequest : do LightWeight M2M create request on a given client.
if (2 <= path.length && path.length <= 3) {
try {
Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
if (registration != null) {
// get content format
String contentFormatParam = req.getParameter(FORMAT_PARAM);
ContentFormat contentFormat = contentFormatParam != null ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null;
// create & process request
LwM2mNode node = extractLwM2mNode(target, req);
if (node instanceof LwM2mObjectInstance) {
CreateRequest request = new CreateRequest(contentFormat, target, (LwM2mObjectInstance) node);
CreateResponse cResponse = server.send(registration, request, TIMEOUT);
processDeviceResponse(req, resp, cResponse);
} else {
throw new IllegalArgumentException("payload must contain an object instance");
}
} else {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
}
} catch (RuntimeException | InterruptedException e) {
handleException(e, resp);
}
return;
}
}
use of org.eclipse.leshan.core.response.ObserveResponse in project leshan by eclipse.
the class ResponseSerDes method deserialize.
public static LwM2mResponse deserialize(JsonObject o) {
String sCode = o.getString("code", null);
if (sCode == null)
throw new IllegalStateException("Invalid response missing code attribute");
ResponseCode code = ResponseCode.fromName(sCode);
String errorMessage = o.getString("errorMessage", null);
String kind = o.getString("kind", null);
switch(kind) {
case "observe":
{
// TODO ser Observation
LwM2mNode content = LwM2mNodeSerDes.deserialize((JsonObject) o.get("content"));
return new ObserveResponse(code, content, null, null, errorMessage);
}
case "delete":
return new DeleteResponse(code, errorMessage);
case "discover":
String objectLinks = o.getString("objectLinks", "");
return new DiscoverResponse(code, Link.parse(objectLinks.getBytes()), errorMessage);
case "create":
{
String location = o.getString("location", null);
return new CreateResponse(code, location, errorMessage);
}
case "execute":
return new ExecuteResponse(code, errorMessage);
case "writeAttributes":
{
return new WriteAttributesResponse(code, errorMessage);
}
case "write":
{
return new WriteResponse(code, errorMessage);
}
case "read":
{
LwM2mNode content = LwM2mNodeSerDes.deserialize((JsonObject) o.get("content"));
return new ReadResponse(code, content, errorMessage);
}
default:
throw new IllegalStateException("Invalid response missing kind attribute");
}
}
Aggregations