use of org.eclipse.leshan.core.node.LwM2mObjectInstance in project leshan by eclipse.
the class ObjectEnabler method doObserve.
@Override
protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) {
final LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) {
lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue(), identity, true));
}
return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ObserveResponse.notFound();
if (path.getResourceId() == null) {
return ObserveResponse.success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance, identity, true));
}
// Manage Resource case
return instance.observe(path.getResourceId());
}
use of org.eclipse.leshan.core.node.LwM2mObjectInstance in project leshan by eclipse.
the class ObjectEnabler method doWrite.
@Override
protected WriteResponse doWrite(ServerIdentity identity, WriteRequest request) {
LwM2mPath path = request.getPath();
// Manage Instance case
LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return WriteResponse.notFound();
if (path.isObjectInstance()) {
// instance write
Map<Integer, LwM2mResource> writeResources = ((LwM2mObjectInstance) request.getNode()).getResources();
if (request.isReplaceRequest()) {
// REPLACE
// make them modifiable
writeResources = new HashMap<>(writeResources);
for (ResourceModel resourceModel : getObjectModel().resources.values()) {
if (!identity.isLwm2mServer() || resourceModel.operations.isWritable()) {
LwM2mResource writeResource = writeResources.remove(resourceModel.id);
if (null != writeResource) {
instance.write(resourceModel.id, writeResource);
} else {
instance.reset(resourceModel.id);
}
}
}
}
// UPDATE and resources currently not in the model
for (LwM2mResource resource : writeResources.values()) {
instance.write(resource.getId(), resource);
}
return WriteResponse.success();
}
// Manage Resource case
return instance.write(path.getResourceId(), (LwM2mResource) request.getNode());
}
use of org.eclipse.leshan.core.node.LwM2mObjectInstance in project leshan by eclipse.
the class ServersInfoExtractor method getInfo.
public static ServersInfo getInfo(Map<Integer, LwM2mObjectEnabler> objectEnablers) {
LwM2mObjectEnabler securityEnabler = objectEnablers.get(SECURITY);
LwM2mObjectEnabler serverEnabler = objectEnablers.get(SERVER);
if (securityEnabler == null || serverEnabler == null)
return null;
ServersInfo infos = new ServersInfo();
LwM2mObject securities = (LwM2mObject) securityEnabler.read(SYSTEM, new ReadRequest(SECURITY)).getContent();
LwM2mObject servers = (LwM2mObject) serverEnabler.read(SYSTEM, new ReadRequest(SERVER)).getContent();
for (LwM2mObjectInstance security : securities.getInstances().values()) {
try {
if ((boolean) security.getResource(SEC_BOOTSTRAP).getValue()) {
if (infos.bootstrap != null) {
LOG.warn("There is more than one bootstrap configuration in security object.");
} else {
// create bootstrap info
ServerInfo info = new ServerInfo();
LwM2mResource serverIdResource = security.getResource(SEC_SERVER_ID);
if (serverIdResource != null && serverIdResource.getValue() != null)
info.serverId = (long) serverIdResource.getValue();
else
info.serverId = 0;
info.serverUri = new URI((String) security.getResource(SEC_SERVER_URI).getValue());
info.secureMode = SecurityMode.fromCode((long) security.getResource(SEC_SECURITY_MODE).getValue());
infos.bootstrap = info;
}
} else {
// create device management info
DmServerInfo info = new DmServerInfo();
info.serverUri = new URI((String) security.getResource(SEC_SERVER_URI).getValue());
info.serverId = (long) security.getResource(SEC_SERVER_ID).getValue();
info.secureMode = SecurityMode.fromCode((long) security.getResource(SEC_SECURITY_MODE).getValue());
// search corresponding device management server
for (LwM2mObjectInstance server : servers.getInstances().values()) {
if (info.serverId == (Long) server.getResource(SRV_SERVER_ID).getValue()) {
info.lifetime = (long) server.getResource(SRV_LIFETIME).getValue();
info.binding = BindingMode.valueOf((String) server.getResource(SRV_BINDING).getValue());
infos.deviceMangements.put(info.serverId, info);
break;
}
}
}
} catch (URISyntaxException e) {
LOG.error(String.format("Invalid URI %s", (String) security.getResource(SEC_SERVER_URI).getValue()), e);
}
}
return infos;
}
use of org.eclipse.leshan.core.node.LwM2mObjectInstance in project leshan by eclipse.
the class ObjectResource method handlePOST.
@Override
public void handlePOST(CoapExchange exchange) {
ServerIdentity identity = extractServerIdentity(exchange, bootstrapHandler);
String URI = exchange.getRequestOptions().getUriPathString();
LwM2mPath path = new LwM2mPath(URI);
// Manage Execute Request
if (path.isResource()) {
byte[] payload = exchange.getRequestPayload();
ExecuteResponse response = nodeEnabler.execute(identity, new ExecuteRequest(URI, payload != null ? new String(payload) : null));
if (response.getCode().isError()) {
exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
} else {
exchange.respond(toCoapResponseCode(response.getCode()));
}
return;
}
// handle content format for Write (Update) and Create request
if (!exchange.getRequestOptions().hasContentFormat()) {
exchange.respond(ResponseCode.BAD_REQUEST, "Content Format is mandatory");
return;
}
ContentFormat contentFormat = ContentFormat.fromCode(exchange.getRequestOptions().getContentFormat());
if (!decoder.isSupported(contentFormat)) {
exchange.respond(ResponseCode.UNSUPPORTED_CONTENT_FORMAT);
return;
}
LwM2mModel model = new LwM2mModel(nodeEnabler.getObjectModel());
// Manage Update Instance
if (path.isObjectInstance()) {
try {
LwM2mNode lwM2mNode = decoder.decode(exchange.getRequestPayload(), contentFormat, path, model);
WriteResponse response = nodeEnabler.write(identity, new WriteRequest(Mode.UPDATE, contentFormat, URI, lwM2mNode));
if (response.getCode().isError()) {
exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
} else {
exchange.respond(toCoapResponseCode(response.getCode()));
}
} catch (CodecException e) {
LOG.warn("Unable to decode payload to write", e);
exchange.respond(ResponseCode.BAD_REQUEST);
}
return;
}
// Manage Create Request
try {
// decode the payload as an instance
LwM2mObjectInstance newInstance = decoder.decode(exchange.getRequestPayload(), contentFormat, new LwM2mPath(path.getObjectId()), model, LwM2mObjectInstance.class);
CreateRequest createRequest;
if (newInstance.getId() != LwM2mObjectInstance.UNDEFINED) {
createRequest = new CreateRequest(contentFormat, path.getObjectId(), newInstance);
} else {
// the instance Id was not part of the create request payload.
// will be assigned by the client.
createRequest = new CreateRequest(contentFormat, path.getObjectId(), newInstance.getResources().values());
}
CreateResponse response = nodeEnabler.create(identity, createRequest);
if (response.getCode() == org.eclipse.leshan.ResponseCode.CREATED) {
exchange.setLocationPath(response.getLocation());
exchange.respond(toCoapResponseCode(response.getCode()));
return;
} else {
exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
return;
}
} catch (CodecException e) {
LOG.warn("Unable to decode payload to create", e);
exchange.respond(ResponseCode.BAD_REQUEST);
return;
}
}
use of org.eclipse.leshan.core.node.LwM2mObjectInstance in project leshan by eclipse.
the class LwM2mNodeJsonDecoder method parseJSON.
private static List<TimestampedLwM2mNode> parseJSON(JsonRootObject jsonObject, LwM2mPath path, LwM2mModel model, Class<? extends LwM2mNode> nodeClass) throws CodecException {
LOG.trace("Parsing JSON content for path {}: {}", path, jsonObject);
// Group JSON entry by time-stamp
Map<Long, Collection<JsonArrayEntry>> jsonEntryByTimestamp = groupJsonEntryByTimestamp(jsonObject);
// Extract baseName
LwM2mPath baseName = extractAndValidateBaseName(jsonObject, path);
if (baseName == null)
// if no base name, use request path as base name
baseName = path;
// fill time-stamped nodes collection
List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
for (Entry<Long, Collection<JsonArrayEntry>> entryByTimestamp : jsonEntryByTimestamp.entrySet()) {
// Group JSON entry by instance
Map<Integer, Collection<JsonArrayEntry>> jsonEntryByInstanceId = groupJsonEntryByInstanceId(entryByTimestamp.getValue(), baseName);
// Create lwm2m node
LwM2mNode node;
if (nodeClass == LwM2mObject.class) {
Collection<LwM2mObjectInstance> instances = new ArrayList<>();
for (Entry<Integer, Collection<JsonArrayEntry>> entryByInstanceId : jsonEntryByInstanceId.entrySet()) {
Map<Integer, LwM2mResource> resourcesMap = extractLwM2mResources(entryByInstanceId.getValue(), baseName, model);
instances.add(new LwM2mObjectInstance(entryByInstanceId.getKey(), resourcesMap.values()));
}
node = new LwM2mObject(baseName.getObjectId(), instances);
} else if (nodeClass == LwM2mObjectInstance.class) {
// validate we have resources for only 1 instance
if (jsonEntryByInstanceId.size() != 1)
throw new CodecException("One instance expected in the payload [path:%s]", path);
// Extract resources
Entry<Integer, Collection<JsonArrayEntry>> instanceEntry = jsonEntryByInstanceId.entrySet().iterator().next();
Map<Integer, LwM2mResource> resourcesMap = extractLwM2mResources(instanceEntry.getValue(), baseName, model);
// Create instance
node = new LwM2mObjectInstance(instanceEntry.getKey(), resourcesMap.values());
} else if (nodeClass == LwM2mResource.class) {
// validate we have resources for only 1 instance
if (jsonEntryByInstanceId.size() > 1)
throw new CodecException("Only one instance expected in the payload [path:%s]", path);
// Extract resources
Map<Integer, LwM2mResource> resourcesMap = extractLwM2mResources(jsonEntryByInstanceId.values().iterator().next(), baseName, model);
// validate there is only 1 resource
if (resourcesMap.size() != 1)
throw new CodecException("One resource should be present in the payload [path:%s]", path);
node = resourcesMap.values().iterator().next();
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
// compute time-stamp
Long timestamp = computeTimestamp(jsonObject.getBaseTime(), entryByTimestamp.getKey());
// add time-stamped node
timestampedNodes.add(new TimestampedLwM2mNode(timestamp, node));
}
return timestampedNodes;
}
Aggregations