Search in sources :

Example 1 with CodecException

use of org.eclipse.leshan.core.node.codec.CodecException in project leshan by eclipse.

the class ObjectResource method handlePUT.

@Override
public void handlePUT(CoapExchange coapExchange) {
    ServerIdentity identity = extractServerIdentity(coapExchange, bootstrapHandler);
    String URI = coapExchange.getRequestOptions().getUriPathString();
    // get Observe Spec
    ObserveSpec spec = null;
    if (coapExchange.advanced().getRequest().getOptions().getURIQueryCount() != 0) {
        List<String> uriQueries = coapExchange.advanced().getRequest().getOptions().getUriQuery();
        spec = ObserveSpec.parse(uriQueries);
    }
    // Manage Write Attributes Request
    if (spec != null) {
        WriteAttributesResponse response = nodeEnabler.writeAttributes(identity, new WriteAttributesRequest(URI, spec));
        if (response.getCode().isError()) {
            coapExchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
        } else {
            coapExchange.respond(toCoapResponseCode(response.getCode()));
        }
        return;
    } else // Manage Write and Bootstrap Write Request (replace)
    {
        LwM2mPath path = new LwM2mPath(URI);
        if (!coapExchange.getRequestOptions().hasContentFormat()) {
            coapExchange.respond(ResponseCode.BAD_REQUEST, "Content Format is mandatory");
            return;
        }
        ContentFormat contentFormat = ContentFormat.fromCode(coapExchange.getRequestOptions().getContentFormat());
        if (!decoder.isSupported(contentFormat)) {
            coapExchange.respond(ResponseCode.UNSUPPORTED_CONTENT_FORMAT);
            return;
        }
        LwM2mNode lwM2mNode;
        try {
            LwM2mModel model = new LwM2mModel(nodeEnabler.getObjectModel());
            lwM2mNode = decoder.decode(coapExchange.getRequestPayload(), contentFormat, path, model);
            if (identity.isLwm2mBootstrapServer()) {
                BootstrapWriteResponse response = nodeEnabler.write(identity, new BootstrapWriteRequest(path, lwM2mNode, contentFormat));
                if (response.getCode().isError()) {
                    coapExchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
                } else {
                    coapExchange.respond(toCoapResponseCode(response.getCode()));
                }
            } else {
                WriteResponse response = nodeEnabler.write(identity, new WriteRequest(Mode.REPLACE, contentFormat, URI, lwM2mNode));
                if (response.getCode().isError()) {
                    coapExchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
                } else {
                    coapExchange.respond(toCoapResponseCode(response.getCode()));
                }
            }
            return;
        } catch (CodecException e) {
            LOG.warn("Unable to decode payload to write", e);
            coapExchange.respond(ResponseCode.BAD_REQUEST);
            return;
        }
    }
}
Also used : BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) ContentFormat(org.eclipse.leshan.core.request.ContentFormat) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest) WriteResponse(org.eclipse.leshan.core.response.WriteResponse) BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) WriteAttributesResponse(org.eclipse.leshan.core.response.WriteAttributesResponse) ObserveSpec(org.eclipse.leshan.ObserveSpec) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) WriteAttributesRequest(org.eclipse.leshan.core.request.WriteAttributesRequest) ResourceUtil.extractServerIdentity(org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity) ServerIdentity(org.eclipse.leshan.client.request.ServerIdentity) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) CodecException(org.eclipse.leshan.core.node.codec.CodecException) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest)

Example 2 with CodecException

use of org.eclipse.leshan.core.node.codec.CodecException 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;
    }
}
Also used : ContentFormat(org.eclipse.leshan.core.request.ContentFormat) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest) CreateRequest(org.eclipse.leshan.core.request.CreateRequest) CreateResponse(org.eclipse.leshan.core.response.CreateResponse) WriteResponse(org.eclipse.leshan.core.response.WriteResponse) BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) ExecuteResponse(org.eclipse.leshan.core.response.ExecuteResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) ResourceUtil.extractServerIdentity(org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity) ServerIdentity(org.eclipse.leshan.client.request.ServerIdentity) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) CodecException(org.eclipse.leshan.core.node.codec.CodecException)

Example 3 with CodecException

use of org.eclipse.leshan.core.node.codec.CodecException 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;
}
Also used : ArrayList(java.util.ArrayList) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) TimestampedLwM2mNode(org.eclipse.leshan.core.node.TimestampedLwM2mNode) LwM2mResource(org.eclipse.leshan.core.node.LwM2mResource) TimestampedLwM2mNode(org.eclipse.leshan.core.node.TimestampedLwM2mNode) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) JsonArrayEntry(org.eclipse.leshan.json.JsonArrayEntry) Entry(java.util.Map.Entry) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) Collection(java.util.Collection) LwM2mObject(org.eclipse.leshan.core.node.LwM2mObject) CodecException(org.eclipse.leshan.core.node.codec.CodecException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) JsonArrayEntry(org.eclipse.leshan.json.JsonArrayEntry)

Example 4 with CodecException

use of org.eclipse.leshan.core.node.codec.CodecException in project leshan by eclipse.

the class LwM2mNodeJsonDecoder method groupJsonEntryByInstanceId.

/**
 * Group all JsonArrayEntry by instanceId
 *
 * @param jsonEntries
 * @param baseName
 *
 * @return a map (instanceId => collection of JsonArrayEntry)
 */
private static Map<Integer, Collection<JsonArrayEntry>> groupJsonEntryByInstanceId(Collection<JsonArrayEntry> jsonEntries, LwM2mPath baseName) throws CodecException {
    Map<Integer, Collection<JsonArrayEntry>> result = new HashMap<>();
    for (JsonArrayEntry e : jsonEntries) {
        // Build resource path
        LwM2mPath nodePath = baseName.append(e.getName());
        // Validate path
        if (!nodePath.isResourceInstance() && !nodePath.isResource()) {
            throw new CodecException("Invalid path [%s] for resource, it should be a resource or a resource instance path", nodePath);
        }
        // Get jsonArray for this instance
        Collection<JsonArrayEntry> jsonArray = result.get(nodePath.getObjectInstanceId());
        if (jsonArray == null) {
            jsonArray = new ArrayList<>();
            result.put(nodePath.getObjectInstanceId(), jsonArray);
        }
        // Add it to the list
        jsonArray.add(e);
    }
    // Create an entry for an empty instance if possible
    if (result.isEmpty() && baseName.getObjectInstanceId() != null) {
        result.put(baseName.getObjectInstanceId(), new ArrayList<JsonArrayEntry>());
    }
    return result;
}
Also used : HashMap(java.util.HashMap) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) Collection(java.util.Collection) CodecException(org.eclipse.leshan.core.node.codec.CodecException) JsonArrayEntry(org.eclipse.leshan.json.JsonArrayEntry)

Example 5 with CodecException

use of org.eclipse.leshan.core.node.codec.CodecException in project leshan by eclipse.

the class LwM2mNodeTextDecoder method decode.

public static LwM2mNode decode(byte[] content, LwM2mPath path, LwM2mModel model) throws CodecException {
    if (!path.isResource())
        throw new CodecException("Invalid path %s : TextDecoder decodes resource only", path);
    ResourceModel rDesc = model.getResourceModel(path.getObjectId(), path.getResourceId());
    String strValue = content != null ? new String(content, StandardCharsets.UTF_8) : "";
    if (rDesc != null && rDesc.type != null) {
        return LwM2mSingleResource.newResource(path.getResourceId(), parseTextValue(strValue, rDesc.type, path), rDesc.type);
    } else {
        // unknown resource, returning a default string value
        return LwM2mSingleResource.newStringResource(path.getResourceId(), strValue);
    }
}
Also used : ResourceModel(org.eclipse.leshan.core.model.ResourceModel) CodecException(org.eclipse.leshan.core.node.codec.CodecException)

Aggregations

CodecException (org.eclipse.leshan.core.node.codec.CodecException)11 LwM2mPath (org.eclipse.leshan.core.node.LwM2mPath)6 HashMap (java.util.HashMap)4 LwM2mObject (org.eclipse.leshan.core.node.LwM2mObject)4 ResourceModel (org.eclipse.leshan.core.model.ResourceModel)3 Type (org.eclipse.leshan.core.model.ResourceModel.Type)3 LwM2mNode (org.eclipse.leshan.core.node.LwM2mNode)3 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)3 JsonArrayEntry (org.eclipse.leshan.json.JsonArrayEntry)3 JsonRootObject (org.eclipse.leshan.json.JsonRootObject)3 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 Map (java.util.Map)2 SortedMap (java.util.SortedMap)2 TreeMap (java.util.TreeMap)2 ResourceUtil.extractServerIdentity (org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity)2 ServerIdentity (org.eclipse.leshan.client.request.ServerIdentity)2 LwM2mModel (org.eclipse.leshan.core.model.LwM2mModel)2 LwM2mResource (org.eclipse.leshan.core.node.LwM2mResource)2 TimestampedLwM2mNode (org.eclipse.leshan.core.node.TimestampedLwM2mNode)2