Search in sources :

Example 6 with LwM2mNode

use of org.eclipse.leshan.core.node.LwM2mNode in project leshan by eclipse.

the class LwM2mNodeDeserializer method deserialize.

@Override
public LwM2mNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json == null) {
        return null;
    }
    LwM2mNode node;
    if (json.isJsonObject()) {
        JsonObject object = (JsonObject) json;
        if (!object.has("id")) {
            throw new JsonParseException("Missing id");
        }
        int id = object.get("id").getAsInt();
        if (object.has("instances")) {
            JsonArray array = object.get("instances").getAsJsonArray();
            LwM2mObjectInstance[] instances = new LwM2mObjectInstance[array.size()];
            for (int i = 0; i < array.size(); i++) {
                instances[i] = context.deserialize(array.get(i), LwM2mNode.class);
            }
            node = new LwM2mObject(id, instances);
        } else if (object.has("resources")) {
            JsonArray array = object.get("resources").getAsJsonArray();
            LwM2mResource[] resources = new LwM2mResource[array.size()];
            for (int i = 0; i < array.size(); i++) {
                resources[i] = context.deserialize(array.get(i), LwM2mNode.class);
            }
            node = new LwM2mObjectInstance(id, resources);
        } else if (object.has("value")) {
            // single value resource
            JsonPrimitive val = object.get("value").getAsJsonPrimitive();
            org.eclipse.leshan.core.model.ResourceModel.Type expectedType = getTypeFor(val);
            node = LwM2mSingleResource.newResource(id, deserializeValue(val, expectedType), expectedType);
        } else if (object.has("values")) {
            // multi-instances resource
            Map<Integer, Object> values = new HashMap<>();
            org.eclipse.leshan.core.model.ResourceModel.Type expectedType = null;
            for (Entry<String, JsonElement> entry : object.get("values").getAsJsonObject().entrySet()) {
                JsonPrimitive pval = entry.getValue().getAsJsonPrimitive();
                expectedType = getTypeFor(pval);
                values.put(Integer.valueOf(entry.getKey()), deserializeValue(pval, expectedType));
            }
            // use string by default;
            if (expectedType == null)
                expectedType = org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
            node = LwM2mMultipleResource.newResource(id, values, expectedType);
        } else {
            throw new JsonParseException("Invalid node element");
        }
    } else {
        throw new JsonParseException("Invalid node element");
    }
    return node;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) JsonParseException(com.google.gson.JsonParseException) JsonArray(com.google.gson.JsonArray) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) Type(java.lang.reflect.Type) Entry(java.util.Map.Entry) LwM2mObject(org.eclipse.leshan.core.node.LwM2mObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with LwM2mNode

use of org.eclipse.leshan.core.node.LwM2mNode in project leshan by eclipse.

the class DownlinkRequestSerDes method deserialize.

public static DownlinkRequest<?> deserialize(JsonObject o) {
    String kind = o.getString("kind", null);
    String path = o.getString("path", null);
    switch(kind) {
        case "observe":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                return new ObserveRequest(ContentFormat.fromCode(format), path);
            }
        case "delete":
            return new DeleteRequest(path);
        case "discover":
            return new DiscoverRequest(path);
        case "create":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                int instanceId = o.getInt("instanceId", LwM2mObjectInstance.UNDEFINED);
                Collection<LwM2mResource> resources = new ArrayList<>();
                JsonArray jResources = (JsonArray) o.get("resources");
                for (JsonValue jResource : jResources) {
                    LwM2mResource resource = (LwM2mResource) LwM2mNodeSerDes.deserialize((JsonObject) jResource);
                    resources.add(resource);
                }
                return new CreateRequest(ContentFormat.fromCode(format), path, new LwM2mObjectInstance(instanceId, resources));
            }
        case "execute":
            String parameters = o.getString("parameters", null);
            return new ExecuteRequest(path, parameters);
        case "writeAttributes":
            {
                String observeSpec = o.getString("observeSpec", null);
                return new WriteAttributesRequest(path, ObserveSpec.parse(observeSpec));
            }
        case "write":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                Mode mode = o.getString("mode", "REPLACE").equals("REPLACE") ? Mode.REPLACE : Mode.UPDATE;
                LwM2mNode node = LwM2mNodeSerDes.deserialize((JsonObject) o.get("node"));
                return new WriteRequest(mode, ContentFormat.fromCode(format), path, node);
            }
        case "read":
            {
                int format = o.getInt("contentFormat", ContentFormat.TLV.getCode());
                return new ReadRequest(ContentFormat.fromCode(format), path);
            }
        default:
            throw new IllegalStateException("Invalid request missing kind attribute");
    }
}
Also used : CreateRequest(org.eclipse.leshan.core.request.CreateRequest) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) Mode(org.eclipse.leshan.core.request.WriteRequest.Mode) JsonValue(com.eclipsesource.json.JsonValue) JsonObject(com.eclipsesource.json.JsonObject) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) LwM2mResource(org.eclipse.leshan.core.node.LwM2mResource) WriteAttributesRequest(org.eclipse.leshan.core.request.WriteAttributesRequest) JsonArray(com.eclipsesource.json.JsonArray) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) DiscoverRequest(org.eclipse.leshan.core.request.DiscoverRequest) Collection(java.util.Collection) DeleteRequest(org.eclipse.leshan.core.request.DeleteRequest) ReadRequest(org.eclipse.leshan.core.request.ReadRequest)

Example 8 with LwM2mNode

use of org.eclipse.leshan.core.node.LwM2mNode in project leshan by eclipse.

the class ClientServlet method doPut.

/**
 * {@inheritDoc}
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];
    // at least /endpoint/objectId/instanceId
    if (path.length < 3) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid path");
        return;
    }
    try {
        String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
        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);
            WriteRequest request = new WriteRequest(Mode.REPLACE, contentFormat, target, node);
            WriteResponse 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);
    }
}
Also used : Registration(org.eclipse.leshan.server.registration.Registration) ContentFormat(org.eclipse.leshan.core.request.ContentFormat) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) WriteResponse(org.eclipse.leshan.core.response.WriteResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode)

Example 9 with LwM2mNode

use of org.eclipse.leshan.core.node.LwM2mNode 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;
    }
}
Also used : ContentFormat(org.eclipse.leshan.core.request.ContentFormat) CreateRequest(org.eclipse.leshan.core.request.CreateRequest) CreateResponse(org.eclipse.leshan.core.response.CreateResponse) ExecuteResponse(org.eclipse.leshan.core.response.ExecuteResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) Registration(org.eclipse.leshan.server.registration.Registration)

Example 10 with LwM2mNode

use of org.eclipse.leshan.core.node.LwM2mNode in project leshan by eclipse.

the class BootstrapHandler method sendServers.

private void sendServers(final BootstrapSession session, final BootstrapConfig cfg, final List<Integer> toSend) {
    if (!toSend.isEmpty()) {
        // get next config
        Integer key = toSend.remove(0);
        ServerConfig serverConfig = cfg.servers.get(key);
        // extract write request parameters
        LwM2mPath path = new LwM2mPath(1, key);
        final LwM2mNode serverInstance = convertToServerInstance(key, serverConfig);
        final BootstrapWriteRequest writeServerRequest = new BootstrapWriteRequest(path, serverInstance, session.getContentFormat());
        send(session, writeServerRequest, new ResponseCallback<BootstrapWriteResponse>() {

            @Override
            public void onResponse(BootstrapWriteResponse response) {
                LOG.trace("Bootstrap write {} return code {}", session.getEndpoint(), response.getCode());
                // recursive call until toSend is empty
                sendServers(session, cfg, toSend);
            }
        }, new ErrorCallback() {

            @Override
            public void onError(Exception e) {
                LOG.warn(String.format("Error during bootstrap write of server instance %s on %s", serverInstance, session.getEndpoint()), e);
                sessionManager.failed(session, WRITE_SERVER_FAILED, writeServerRequest);
            }
        });
    } else {
        final BootstrapFinishRequest finishBootstrapRequest = new BootstrapFinishRequest();
        send(session, finishBootstrapRequest, new ResponseCallback<BootstrapFinishResponse>() {

            @Override
            public void onResponse(BootstrapFinishResponse response) {
                LOG.trace("Bootstrap Finished {} return code {}", session.getEndpoint(), response.getCode());
                if (response.isSuccess()) {
                    sessionManager.end(session);
                } else {
                    sessionManager.failed(session, FINISHED_WITH_ERROR, finishBootstrapRequest);
                }
            }
        }, new ErrorCallback() {

            @Override
            public void onError(Exception e) {
                LOG.debug(String.format("Error during bootstrap finished on %s", session.getEndpoint()), e);
                sessionManager.failed(session, SEND_FINISH_FAILED, finishBootstrapRequest);
            }
        });
    }
}
Also used : BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) ErrorCallback(org.eclipse.leshan.core.response.ErrorCallback) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) BootstrapFinishRequest(org.eclipse.leshan.core.request.BootstrapFinishRequest) ServerConfig(org.eclipse.leshan.server.bootstrap.BootstrapConfig.ServerConfig) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) BootstrapFinishResponse(org.eclipse.leshan.core.response.BootstrapFinishResponse) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest)

Aggregations

LwM2mNode (org.eclipse.leshan.core.node.LwM2mNode)12 LwM2mPath (org.eclipse.leshan.core.node.LwM2mPath)6 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)5 ContentFormat (org.eclipse.leshan.core.request.ContentFormat)5 BootstrapWriteRequest (org.eclipse.leshan.core.request.BootstrapWriteRequest)4 WriteRequest (org.eclipse.leshan.core.request.WriteRequest)4 BootstrapWriteResponse (org.eclipse.leshan.core.response.BootstrapWriteResponse)4 WriteResponse (org.eclipse.leshan.core.response.WriteResponse)4 ResourceUtil.extractServerIdentity (org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity)3 ServerIdentity (org.eclipse.leshan.client.request.ServerIdentity)3 LwM2mModel (org.eclipse.leshan.core.model.LwM2mModel)3 CodecException (org.eclipse.leshan.core.node.codec.CodecException)3 CreateRequest (org.eclipse.leshan.core.request.CreateRequest)3 ExecuteRequest (org.eclipse.leshan.core.request.ExecuteRequest)3 ObserveRequest (org.eclipse.leshan.core.request.ObserveRequest)3 JsonObject (com.eclipsesource.json.JsonObject)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2