Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ncsdk 25967 create a new api endpoint for leshan bad server #1609

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -59,7 +59,7 @@ public class JSONFileBootstrapStore extends InMemoryBootstrapConfigStore {
private final Lock writeLock = readWriteLock.writeLock();

// default location for persistence
public static final String DEFAULT_FILE = "data/bootstrapStore.json";
public static final String DEFAULT_FILE = "data/bootstrapStore_bad.json";

private final String filename;
private final ObjectMapper mapper;
Expand Down
Expand Up @@ -89,7 +89,7 @@ public static void main(String[] args) {
try {
// Create Stores
EditableBootstrapConfigStore bsConfigStore = new JSONFileBootstrapStore(cli.main.configFilename);
EditableSecurityStore securityStore = new FileSecurityStore("data/bssecurity.data");
EditableSecurityStore securityStore = new FileSecurityStore("data/bssecurity_bad.data");

// Create LWM2M Server
LeshanBootstrapServer lwm2mBsServer = createBsLeshanServer(cli, bsConfigStore, securityStore);
Expand Down
@@ -0,0 +1,47 @@
/*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
* Public License v2.0 and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html and the Eclipse Distribution
* License is available at http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors: Sierra Wireless - initial API and implementation Achim Kraus (Bosch Software Innovations GmbH) - use
* Identity as destination Rokwoon Kim (contracted with NTELS) - use registrationIdProvider
*******************************************************************************/
package org.eclipse.leshan.core;

import java.util.HashMap;
import java.util.Map;

public class CustomTaskContainer {
public static Map<String, Map<String, Boolean>> taskInfo = null;
public boolean requestUpdateAnswer = true;
public boolean doubleRead = false;

private static CustomTaskContainer instance = null;

private void Container() {
}

public static CustomTaskContainer getInstance() {
if (instance == null) {
instance = new CustomTaskContainer();
}
return instance;
}

public static Map<String, Map<String, Boolean>> createInstance(String imei) {
if (taskInfo == null) {
Map<String, Boolean> insideInfo = new HashMap<>();
insideInfo.put("requestUpdateAnswer", true);
insideInfo.put("waitForSend", false);
insideInfo.put("sendReceived", false);
insideInfo.put("doubleRead", false);
taskInfo = new HashMap<>();
taskInfo.put(imei, insideInfo);
}
return taskInfo;
}
}
Expand Up @@ -36,6 +36,9 @@ public enum BindingMode {
/** Non-Ip */
N,

/** FAKE ONE */
F,

/** Queue Mode : removed since LWM2M 1.1 */
Q;

Expand Down Expand Up @@ -71,6 +74,8 @@ private static BindingMode valueOf(char c) {
return S;
case 'N':
return N;
case 'F':
return F;
case 'Q':
return Q;
default:
Expand Down
@@ -0,0 +1,75 @@
/*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.core.request;

import org.eclipse.leshan.core.CustomTaskContainer;
import org.eclipse.leshan.core.request.exception.InvalidRequestException;

/**
* A Lightweight M2M request for retrieving the values of resources from a LWM2M Client.
*
* The request can be used to retrieve the value(s) of one or all attributes of one particular or all instances of a
* particular object type.
*/
public class CustomTaskRequest {
public static void handleCustomTask(String taskName, String imei) {
checkRequest(taskName, imei);
}

static void checkRequest(String taskName, String imei) {
if (taskName.equals("NoAnswerRequest")) {
requestUpdateNoAnswer(imei);
}
if (taskName.equals("WaitForSend")) {
waitForSend(imei);
}
if (taskName.equals("CheckForSend")) {
checkForSend(imei);
}
if (taskName.equals("DoubleRead")) {
doubleRead(imei);
}
}

static void requestUpdateNoAnswer(String imei) {
CustomTaskContainer.createInstance(imei).get(imei).put("requestUpdateAnswer", false);
}

static void waitForSend(String imei) {
CustomTaskContainer.createInstance(imei).get(imei).put("waitForSend", true);
}

static void checkForSend(String imei) {
CustomTaskContainer.createInstance(imei);
if (!CustomTaskContainer.createInstance(imei).get(imei).get("waitForSend")
&& !CustomTaskContainer.createInstance(imei).get(imei).get("sendReceived")) {
throw new InvalidRequestException("Nothing is happening");
} else if (CustomTaskContainer.createInstance(imei).get(imei).get("waitForSend")
&& !CustomTaskContainer.createInstance(imei).get(imei).get("sendReceived")) {
throw new InvalidRequestException("Send has not been received");
} else if (!CustomTaskContainer.createInstance(imei).get(imei).get("waitForSend")
&& CustomTaskContainer.createInstance(imei).get(imei).get("sendReceived")) {
CustomTaskContainer.createInstance(imei).get(imei).put("sendReceived", false);
} else {
CustomTaskContainer.createInstance(imei).get(imei).put("sendReceived", false);
CustomTaskContainer.createInstance(imei).get(imei).put("waitForSend", false);
}
}

static void doubleRead(String imei) {
CustomTaskContainer.createInstance(imei).get(imei).put("doubleRead", true);
}
}
Expand Up @@ -93,9 +93,10 @@ public void verify(BootstrapConfig config) throws InvalidConfigurationException
}

protected void checkNoSec(ServerSecurity sec) throws InvalidConfigurationException {
assertIf(!isEmpty(sec.secretKey), "NO-SEC mode, secret key must be empty");
assertIf(!isEmpty(sec.publicKeyOrId), "NO-SEC mode, public key or ID must be empty");
assertIf(!isEmpty(sec.serverPublicKey), "NO-SEC mode, server public key must be empty");
;
// assertIf(!isEmpty(sec.secretKey), "NO-SEC mode, secret key must be empty");
// woops assertIf(!isEmpty(sec.publicKeyOrId), "NO-SEC mode, public key or ID must be empty");
// assertIf(!isEmpty(sec.serverPublicKey), "NO-SEC mode, server public key must be empty");
}

protected void checkPSK(ServerSecurity sec) throws InvalidConfigurationException {
Expand Down Expand Up @@ -190,7 +191,8 @@ protected void validateOneSecurityByServer(BootstrapConfig config) throws Invali
BootstrapConfig.ServerSecurity security = getSecurityEntry(config, srvCfg.shortId);

if (security == null) {
throw new InvalidConfigurationException("no security entry for server instance: " + e.getKey());
return;
// throw new InvalidConfigurationException("no security entry for server instance: " + e.getKey());
}

if (security.bootstrapServer) {
Expand Down
Expand Up @@ -19,7 +19,9 @@

import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.eclipse.leshan.core.CustomTaskContainer;
import org.eclipse.leshan.core.LwM2m.LwM2mVersion;
import org.eclipse.leshan.core.peer.LwM2mPeer;
import org.eclipse.leshan.core.request.DeregisterRequest;
Expand Down Expand Up @@ -137,6 +139,15 @@ public SendableResponse<UpdateResponse> update(LwM2mPeer sender, UpdateRequest u

// Validate request
LwM2mVersion lwM2mVersion = currentRegistration.getLwM2mVersion();
if (!CustomTaskContainer.getInstance().requestUpdateAnswer) {
CustomTaskContainer.getInstance().requestUpdateAnswer = true;
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
updateRequest.validate(lwM2mVersion);

// Extract data from object link
Expand Down
Expand Up @@ -41,7 +41,7 @@ public class FileSecurityStore extends InMemorySecurityStore {
private final String filename;

// default location for persistence
private static final String DEFAULT_FILE = "data/security.data";
private static final String DEFAULT_FILE = "data/security_bad.data";

public FileSecurityStore() {
this(DEFAULT_FILE);
Expand Down
Expand Up @@ -19,6 +19,7 @@
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import org.eclipse.leshan.core.CustomTaskContainer;
import org.eclipse.leshan.core.node.LwM2mNode;
import org.eclipse.leshan.core.node.LwM2mPath;
import org.eclipse.leshan.core.node.TimestampedLwM2mNodes;
Expand Down Expand Up @@ -153,6 +154,14 @@ protected SendResponse validateSendRequest(Registration registration, SendReques
}
}
}
CustomTaskContainer.createInstance(registration.getEndpoint());
if (CustomTaskContainer.createInstance(registration.getEndpoint()).get(registration.getEndpoint())
.get("waitForSend")) {
CustomTaskContainer.createInstance(registration.getEndpoint()).get(registration.getEndpoint())
.put("sendReceived", true);
CustomTaskContainer.createInstance(registration.getEndpoint()).get(registration.getEndpoint())
.put("waitForSend", false);
}
return SendResponse.success();
}
}
4 changes: 0 additions & 4 deletions leshan-server-demo/pom.xml
Expand Up @@ -49,10 +49,6 @@ Contributors:
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-server-redis</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.leshan</groupId>
<artifactId>leshan-tl-javacoap-server</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.californium</groupId>
<artifactId>californium-core</artifactId>
Expand Down
Expand Up @@ -62,7 +62,6 @@
import org.eclipse.leshan.server.redis.RedisSecurityStore;
import org.eclipse.leshan.server.security.EditableSecurityStore;
import org.eclipse.leshan.server.security.FileSecurityStore;
import org.eclipse.leshan.transport.javacoap.server.endpoint.JavaCoapServerEndpointsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -251,14 +250,8 @@ public static LeshanServer createLeshanServer(LeshanServerDemoCLI cli) throws Ex
: new InetSocketAddress(cli.main.secureLocalAddress, coapsPort);
endpointsBuilder.addEndpoint(coapsAddr, Protocol.COAPS);

// Create CoAP endpoint based on java-coap
int jcoapPort = cli.main.jlocalPort;
InetSocketAddress jcoapAddr = cli.main.jlocalAddress == null ? new InetSocketAddress(jcoapPort)
: new InetSocketAddress(cli.main.jlocalAddress, jcoapPort);
JavaCoapServerEndpointsProvider javacoapEndpointsProvider = new JavaCoapServerEndpointsProvider(jcoapAddr);

// Create LWM2M server
builder.setEndpointsProviders(endpointsBuilder.build(), javacoapEndpointsProvider);
builder.setEndpointsProviders(endpointsBuilder.build());
return builder.build();
}

Expand Down
Expand Up @@ -19,7 +19,6 @@

import org.eclipse.leshan.core.demo.cli.StandardHelpOptions;
import org.eclipse.leshan.core.demo.cli.VersionProvider;
import org.eclipse.leshan.core.demo.cli.converters.PortConverter;
import org.eclipse.leshan.server.core.demo.cli.DtlsSection;
import org.eclipse.leshan.server.core.demo.cli.GeneralSection;
import org.eclipse.leshan.server.core.demo.cli.IdentitySection;
Expand Down Expand Up @@ -56,18 +55,6 @@ public class LeshanServerDemoCLI implements Runnable {
public ServerGeneralSection main = new ServerGeneralSection();

public static class ServerGeneralSection extends GeneralSection {
@Option(names = { "-jh", "--java-coap-host" },
description = { //
"Set the local CoAP address of endpoint based on java-coap library.", //
"Default: any local address." })
public String jlocalAddress;

@Option(names = { "-jp", "--java-coap-port" },
description = { //
"Set the local CoAP port of endpoint based on java-coap library.", //
"Default: ${DEFAULT-VALUE}" },
converter = PortConverter.class)
public Integer jlocalPort = 5685;

@Option(names = { "-r", "--redis" },
description = { //
Expand Down
Expand Up @@ -53,6 +53,7 @@
import org.eclipse.leshan.core.request.CancelObservationRequest;
import org.eclipse.leshan.core.request.ContentFormat;
import org.eclipse.leshan.core.request.CreateRequest;
import org.eclipse.leshan.core.request.CustomTaskRequest;
import org.eclipse.leshan.core.request.DeleteRequest;
import org.eclipse.leshan.core.request.DiscoverRequest;
import org.eclipse.leshan.core.request.ExecuteRequest;
Expand Down Expand Up @@ -178,7 +179,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se
resp.setStatus(HttpServletResponse.SC_OK);
} else {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
resp.getWriter().format("No registered client with id '%s'", clientEndpoint).flush();
}
return;
}
Expand Down Expand Up @@ -236,6 +237,39 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se
return;
}

// /clients/endPoint/doubleRead/LWRequest : do custom LightWeight M2M read request on a given client.
if (path.length >= 2 && "doubleRead".equals(path[path.length - 4])) {
try {
Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
if (registration != null) {
String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint + "/doubleRead/");
CustomTaskRequest.handleCustomTask("DoubleRead", clientEndpoint);
// get content format
String contentFormatParam = req.getParameter(FORMAT_PARAM);
ContentFormat contentFormat = contentFormatParam != null
? ContentFormat.fromName(contentFormatParam.toUpperCase())
: null;

// create & process request
ReadRequest request = new ReadRequest(contentFormat, target);
for (int i = 0; i < 10; i++) {
server.send(registration, request, extractTimeout(req));
}
ReadResponse cResponse = server.send(registration, request, extractTimeout(req));
processDeviceResponse(req, resp, cResponse);
resp.setStatus(HttpServletResponse.SC_OK);
// resp.getWriter().format("I SEEEE '%s'", clientEndpoint).flush();
} else {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().format("Uh oh spaghetti, No registered client with id '%s'", clientEndpoint)
.flush();
}
} catch (RuntimeException | InterruptedException e) {
handleException(e, resp);
}
return;
}

// /clients/endPoint/LWRequest : do LightWeight M2M read request on a given client.
try {
String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
Expand Down Expand Up @@ -417,6 +451,25 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws S
return;
}

// /clients/endPoint/customTask : do LightWeight M2M discover request on a given client.
if (path.length >= 3 && "customTask".equals(path[path.length - 2])) {
try {
Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
if (registration != null) {
String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint + "/customTask/");
CustomTaskRequest.handleCustomTask(target, clientEndpoint);
resp.setStatus(HttpServletResponse.SC_OK);
resp.getWriter().format("I SEEEE '%s'", clientEndpoint).flush();
} else {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().format("No registered client with id '%s'", clientEndpoint).flush();
}
} catch (RuntimeException e) {
handleException(e, resp);
}
return;
}

// /clients/endPoint/LWRequest/observe : do LightWeight M2M observe request on a given client.
if (path.length >= 3 && "observe".equals(path[path.length - 1])) {
try {
Expand Down