import org.iotivity.cloud.util.Logger;
/**
- *
+ *
* This class is in charge of running of account server.
- *
+ *
*/
public class AccountServer {
coapServer
.startServer(new InetSocketAddress(Integer.parseInt(args[0])));
-
- Scanner in = new Scanner(System.in);
-
+
+ Scanner in = new Scanner(System.in, "UTF8");
+
System.out.println("press 'q' to terminate");
-
- while(!in.nextLine().equals("q"));
-
+
+ while (!in.nextLine().equals("q"));
+
in.close();
-
+
System.out.println("Terminating...");
coapServer.stopServer();
-
+
System.out.println("Terminated");
}
}
/**
* API for requesting user account
- *
+ *
* @param userId
* user identifier
* @param deviceId
/**
* API for requesting user account and getting session code for registered
* user.
- *
+ *
* @param userId
* user identifier
* @return String - session code for registered user
/**
* API for requesting user identifier corresponding with authorization
* information.
- *
+ *
* @param authCode
* authorization code
* @param authServer
/**
* API for requesting user identifier corresponding with session code.
- *
+ *
* @param sessionCode
* session code
* @return String - user identifier
/**
* API for getting devices corresponding with user identifier.
- *
+ *
* @param userId
* user identifier
* @return ArrayList<String> - list of devices
private String generateSessionCode() {
- String sessionCode = "";
+ StringBuffer sessionCode = new StringBuffer();
Random random = new Random();
int randomNum = random.nextInt(122);
|| (randomNum >= 97 && randomNum <= 122)) {
code = (char) randomNum;
- sessionCode += code;
+ sessionCode.append(code);
randomNum = random.nextInt(122);
break;
}
}
- return sessionCode;
+ return sessionCode.toString();
}
}
/**
* API for storing session information of authorized user
- *
+ *
* @param userId
* user identifier
* @param sessionCode
/**
* API for storing device information of authorized user
- *
+ *
* @param userId
* user identifier
* @param deviceId
/**
* API for getting user identifier information corresponding with session
* code
- *
+ *
* @param userId
* identifier of authorized user
* @param sessionCode
/**
* API for getting devices corresponding with user identifier
- *
+ *
* @param userId
* user identifier
* @return ArrayList<String> - list of devices
*/
public ArrayList<String> getDevices(String userId) {
- ArrayList<String> deviceList = new ArrayList<String>();
-
- deviceList = mongoDB.getDevices(userId);
+ ArrayList<String> deviceList = mongoDB.getDevices(userId);
return deviceList;
}
}
@Override
- public void onRequestReceived(ChannelHandlerContext ctx, CoapRequest request) {
+ public void onRequestReceived(ChannelHandlerContext ctx,
+ CoapRequest request) {
Logger.d("AccountResource IN");
}
}
- private void handleGetRequest(ChannelHandlerContext ctx, CoapRequest request)
- throws Exception {
+ private void handleGetRequest(ChannelHandlerContext ctx,
+ CoapRequest request) throws Exception {
String reqType = extractQuery(request, Constants.REQ_TYPE);
if (reqType == null)
- throw new IllegalArgumentException("request type is null in query!");
+ throw new IllegalArgumentException(
+ "request type is null in query!");
CoapResponse response = null;
switch (reqType) {
-
case Constants.TYPE_FIND:
response = handleFindRequest(request);
break;
default:
Logger.w("reqType[" + reqType + "] is not supported");
}
-
- ctx.writeAndFlush(response);
+ if (response != null) {
+ ctx.writeAndFlush(response);
+ }
}
String reqType = extractQuery(request, Constants.REQ_TYPE);
if (reqType == null)
- throw new IllegalArgumentException("request type is null in query!");
+ throw new IllegalArgumentException(
+ "request type is null in query!");
- CoapResponse response = null;
+ CoapResponse response;
switch (reqType) {
case Constants.TYPE_PUBLISH:
/**
* API for handling request for publishing resource corresponding with user
* account
- *
+ *
* @param requeset
* CoAP request message
* @return CoapResponse - CoAP response message with response result
String payload = request.getPayloadString();
String userId = JSONUtil.parseJSON(payload, Constants.REQUEST_USER_ID);
- String deviceId = JSONUtil.parseJSON(payload, Constants.REQUEST_DEVICE_ID);
+ String deviceId = JSONUtil.parseJSON(payload,
+ Constants.REQUEST_DEVICE_ID);
Logger.d("userId: " + userId + ", deviceId: " + deviceId);
Logger.d("status : " + status);
CoapMessageBuilder responseMessage = new CoapMessageBuilder();
- CoapResponse coapResponse = null;
+ CoapResponse coapResponse;
if (status) {
- coapResponse = responseMessage.buildCoapResponse(
- request.getToken(), CoapStatus.CREATED);
+ coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+ CoapStatus.CREATED);
} else {
- coapResponse = responseMessage.buildCoapResponse(
- request.getToken(), CoapStatus.INTERNAL_SERVER_ERROR);
+ coapResponse = responseMessage.buildCoapResponse(request.getToken(),
+ CoapStatus.INTERNAL_SERVER_ERROR);
}
return coapResponse;
/**
* API for handling request for finding resource corresponding with user
* account
- *
+ *
* @param requeset
* CoAP request message
* @return CoapResponse - CoAP response message with response result
List<String> Segments = request.getUriQuerySegments();
- for (String s : Segments) {
+ if (Segments != null) {
+ for (String s : Segments) {
- String pair[] = s.split("=");
+ String pair[] = s.split("=");
- if (pair[0].equals(key)) {
+ if (pair[0].equals(key)) {
- value = pair[1];
+ value = pair[1];
+ }
}
}
/*
* private static String getPayloadString(byte[] payload) {
- *
+ *
* if (payload == null) return "";
- *
+ *
* return new String(payload, Charset.forName("UTF-8")); }
*/
throw new IllegalArgumentException(
"request type is null in query!");
- CoapResponse response = null;
+ CoapResponse response;
switch (reqType) {
case Constants.TYPE_REGISTER:
/**
* API for handling request for login by user account
- *
+ *
* @param request
* CoAP request message
* @return CoapResponse - CoAP response message with response result
Logger.d("userId: " + userId);
CoapMessageBuilder responseMessage = new CoapMessageBuilder();
- CoapResponse coapResponse = null;
+ CoapResponse coapResponse;
if (userId != null) {
/**
* API for handling request for registering user account
- *
+ *
* @param request
* CoAP request message
* @return CoapResponse - CoAP response message with response result
String payload = request.getPayloadString();
- JSONUtil util = new JSONUtil();
- String authCode = util.parseJSON(payload, Constants.REQUEST_AUTH_CODE);
- String authServer = util.parseJSON(payload, Constants.REQUEST_AUTH_SERVER);
+ String authCode = JSONUtil.parseJSON(payload,
+ Constants.REQUEST_AUTH_CODE);
+ String authServer = JSONUtil.parseJSON(payload,
+ Constants.REQUEST_AUTH_SERVER);
Logger.d("authCode: " + authCode + ", authServer: " + authServer);
AccountServerManager oauthServerManager = new AccountServerManager();
-
- String userId = oauthServerManager.requestUserId(authCode, authServer);
+ String userId = null;
+ if (authCode != null && authServer != null) {
+ userId = oauthServerManager.requestUserId(authCode, authServer);
+ }
String sessionCode = oauthServerManager.registerUserAccount(userId);
Logger.d("userId: " + userId + ", sessionCode: " + sessionCode);
CoapMessageBuilder responseMessage = new CoapMessageBuilder();
- CoapResponse coapResponse = null;
+ CoapResponse coapResponse;
if (userId != null && sessionCode != null) {
List<String> Segments = request.getUriQuerySegments();
- for (String s : Segments) {
+ if (Segments != null) {
+ for (String s : Segments) {
- String pair[] = s.split("=");
+ String pair[] = s.split("=");
- if (pair[0].equals(key)) {
+ if (pair[0].equals(key)) {
- value = pair[1];
+ value = pair[1];
+ }
}
}
/*
* private static String getPayloadString(byte[] payload) {
- *
+ *
* if (payload == null) return "";
- *
+ *
* return new String(payload, Charset.forName("UTF-8")); }
*/
package org.iotivity.cloud.ciserver;
import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import org.iotivity.cloud.base.CoapServer;
ResourceManager resourceManager = null;
SessionManager sessionManager = null;
CoapServer coapServer = null;
-
+
CoapRelayHandler relayHandler = null;
- CoapAuthHandler authHandler = null;
-
+ CoapAuthHandler authHandler = null;
+
KeepAliveResource keepAliveResource = null;
coapServer = new CoapServer();
sessionManager = new SessionManager();
resourceManager = new ResourceManager();
-
+
relayHandler = new CoapRelayHandler(sessionManager);
-
+
authHandler = new CoapAuthHandler();
-
+
keepAliveResource = new KeepAliveResource(sessionManager,
new int[] { 1, 2, 4, 8 });
-
-
- coapServer.addHandler(new CoapLogHandler());
+
+ coapServer.addHandler(new CoapLogHandler());
coapServer.addHandler(authHandler);
coapServer.addHandler(relayHandler);
coapServer.addHandler(resourceManager);
-
- resourceManager.registerResource(keepAliveResource);
-
+
+ resourceManager.registerResource(keepAliveResource);
+
authHandler.startHandler(args[3], Integer.parseInt(args[4]));
-
- relayHandler.startHandler(args[1],
- Integer.parseInt(args[2]), args[3], Integer.parseInt(args[4]));
+
+ relayHandler.startHandler(args[1], Integer.parseInt(args[2]), args[3],
+ Integer.parseInt(args[4]));
coapServer
.startServer(new InetSocketAddress(Integer.parseInt(args[0])));
-
+
keepAliveResource.startSessionChecker();
-
- Scanner in = new Scanner(System.in);
-
+
+ Scanner in = new Scanner(System.in, "UTF8");
+
System.out.println("press 'q' to terminate");
-
- while(!in.nextLine().equals("q"));
-
+
+ while (!in.nextLine().equals("q"));
+
in.close();
-
+
System.out.println("Terminating...");
-
+
keepAliveResource.stopSessionChecker();
coapServer.stopServer();
-
+
relayHandler.stopHandler();
-
+
authHandler.stopHandler();
-
+
System.out.println("Terminated");
}
}
.attr(keyAuthClient).get();
if (msg.getResponseCode() == CoapStatus.CREATED) {
- Map<String, String> response = JSONUtil
- .parseJSON(new String(msg.getPayload(), StandardCharsets.UTF_8));
+ Map<String, String> response = JSONUtil.parseJSON(
+ new String(msg.getPayload(), StandardCharsets.UTF_8));
- String userId = response.get("userid");
- if (userId != null) {
- ctxToDevice.channel().attr(Constants.Attribute_UserId)
- .set(userId);
- }
- msg.setPayload(cbor.encodingPayloadToCbor(response));
+ if (response != null) {
+ String userId = response.get("userid");
+ if (userId != null) {
+ ctxToDevice.channel().attr(Constants.Attribute_UserId)
+ .set(userId);
+ }
+ msg.setPayload(cbor.encodingPayloadToCbor(response));
- CoapAuthHandler authHandler = ctxToDevice.channel().pipeline()
- .get(CoapAuthHandler.class);
+ CoapAuthHandler authHandler = ctxToDevice.channel()
+ .pipeline().get(CoapAuthHandler.class);
- ctxToDevice.channel().pipeline().remove(authHandler);
+ ctxToDevice.channel().pipeline().remove(authHandler);
+ }
}
ctxToDevice.writeAndFlush(msg);
public CoapAuthHandler() {
- asClient.addHandler(new AccountHandler());
-
+ asClient.addHandler(new AccountHandler());
+
}
-
- public void startHandler(String acAddress, int acPort) throws Exception
- {
- asClient.startClient(
- new InetSocketAddress(acAddress, acPort));
+
+ public void startHandler(String acAddress, int acPort) throws Exception {
+ asClient.startClient(new InetSocketAddress(acAddress, acPort));
}
-
- public void stopHandler() throws Exception
- {
- asClient.stopClient();
+
+ public void stopHandler() throws Exception {
+ asClient.stopClient();
}
private Cbor<HashMap<Object, Object>> cbor = new Cbor<HashMap<Object, Object>>();
if (msg instanceof CoapRequest) {
CoapRequest request = (CoapRequest) msg;
- switch (request.getUriPath()) {
- // This handler only used for initial handshake
- case Constants.AUTH_URI:
- HashMap<Object, Object> payloadData = cbor
- .parsePayloadFromCbor(request.getPayload(),
- HashMap.class);
- request.setPayload(
- JSONUtil.writeJSON(payloadData).getBytes(StandardCharsets.UTF_8));
- asClient.getChannelFuture().channel()
- .attr(keyAuthClient).set(ctx);
- asClient.sendRequest(request);
- return;
-
- case Constants.KEEP_ALIVE_URI:
- super.channelRead(ctx, msg);
- return;
-
- default:
- CoapResponse response = new CoapResponse(
- CoapStatus.UNAUTHORIZED);
- Logger.e("Sending UNAUTHORIZED to client");
- ctx.writeAndFlush(response);
- break;
+ String uriPath = request.getUriPath();
+ if (uriPath != null) {
+ switch (uriPath) {
+ // This handler only used for initial handshake
+ case Constants.AUTH_URI:
+ HashMap<Object, Object> payloadData = cbor
+ .parsePayloadFromCbor(request.getPayload(),
+ HashMap.class);
+ String writejson = JSONUtil.writeJSON(payloadData);
+ if (writejson != null) {
+ request.setPayload(
+ writejson.getBytes(StandardCharsets.UTF_8));
+ asClient.getChannelFuture().channel()
+ .attr(keyAuthClient).set(ctx);
+ asClient.sendRequest(request);
+ }
+ return;
+
+ case Constants.KEEP_ALIVE_URI:
+ super.channelRead(ctx, msg);
+ return;
+
+ default:
+ CoapResponse response = new CoapResponse(
+ CoapStatus.UNAUTHORIZED);
+ Logger.e("Sending UNAUTHORIZED to client");
+ ctx.writeAndFlush(response);
+ break;
+ }
}
}
package org.iotivity.cloud.ciserver.protocols;
import java.net.InetSocketAddress;
+import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
}
}
- private CoapClient rdClient = null;
- ///////////
+ private CoapClient rdClient = null;
+ ///////////
////////// Handler for Account Server
private static final AttributeKey<List<CoapRequest>> keyAccountClient = AttributeKey
}
}
- private CoapClient asClient = null;
+ private CoapClient asClient = null;
//////////
private SessionManager sessionManager = null;
public CoapRelayHandler(SessionManager sessionManager) {
this.sessionManager = sessionManager;
-
+
rdClient = new CoapClient();
rdClient.addHandler(new RDHandler());
-
+
asClient = new CoapClient();
asClient.addHandler(new AccountHandler());
}
-
- public void startHandler(String rdAddress, int rdPort, String acAddress, int acPort) throws Exception
- {
+
+ public void startHandler(String rdAddress, int rdPort, String acAddress,
+ int acPort) throws Exception {
rdClient.startClient(new InetSocketAddress(rdAddress, rdPort));
-
+
asClient.startClient(new InetSocketAddress(acAddress, acPort));
asClient.getChannelFuture().channel().attr(keyAccountClient)
.set(new ArrayList<CoapRequest>());
}
-
- public void stopHandler() throws Exception
- {
- asClient.stopClient();
-
- rdClient.stopClient();
+
+ public void stopHandler() throws Exception {
+ asClient.stopClient();
+
+ rdClient.stopClient();
}
private static final AttributeKey<ChannelHandlerContext> keyDevice = AttributeKey
String uriPath = request.getUriPath();
CoapRequest accountRequest = null;
String userId, deviceId, authPayload;
- CoapResponse response = null;
+ CoapResponse response;
Logger.d("Request received, URI: " + uriPath);
- switch (uriPath) {
- case Constants.AUTH_URI:
- // This case user wants to logout
- if (request.getUriQuery().endsWith("logout")) {
- ctx.channel().attr(Constants.Attribute_UserId).remove();
- response = new CoapResponse(CoapStatus.DELETED);
- } else {
- response = new CoapResponse(CoapStatus.BAD_REQUEST);
- }
- ctx.writeAndFlush(response);
- break;
-
- case Constants.RD_URI:
- // RD POST means publish device to server
- switch (request.getRequestMethod()) {
- case POST:
- userId = ctx.channel()
- .attr(Constants.Attribute_UserId).get();
- deviceId = request.decodeDeviceId();
- authPayload = String.format(
- "{\"userid\":\"%s\",\"deviceid\":\"%s\"}",
- userId, deviceId);
- accountRequest = new CoapRequest(CoapMethod.POST);
- accountRequest.setUriPath(Constants.ACCOUNT_URI);
- accountRequest.setUriQuery("reqtype=publish");
- accountRequest.setToken(request.getToken());
- accountRequest.setPayload(authPayload
- .getBytes(StandardCharsets.UTF_8));
-
- // TODO: deviceId must be registered after session
- // granted
- Logger.d("Adding deviceId to session: " + deviceId);
- sessionManager.addSession(deviceId, ctx);
- break;
-
- default:
- Logger.e("Unsupported request type");
- break;
- }
-
- rdClient.getChannelFuture().channel().attr(keyRDClient)
- .set(ctx);
-
- // Add original request to list for future use
- asClient.getChannelFuture().channel().attr(keyAccountClient)
- .get().add(request);
- asClient.sendRequest(accountRequest);
- return;
-
- case Constants.WELL_KNOWN_URI:
- switch (request.getRequestMethod()) {
- case GET:
- userId = ctx.channel()
- .attr(Constants.Attribute_UserId).get();
- authPayload = String.format("{\"userid\":\"%s\"}",
- userId);
- accountRequest = new CoapRequest(CoapMethod.GET);
- accountRequest.setUriPath(Constants.ACCOUNT_URI);
- accountRequest.setUriQuery("reqtype=find");
- accountRequest.setToken(request.getToken());
- accountRequest.setPayload(authPayload.getBytes());
- break;
-
- default:
- Logger.e("Unsupported request type");
- break;
- }
-
- rdClient.getChannelFuture().channel().attr(keyRDClient)
- .set(ctx);
-
- // Add original request to list for future use
- asClient.getChannelFuture().channel().attr(keyAccountClient)
- .get().add(request);
- asClient.sendRequest(accountRequest);
- return;
-
- case Constants.KEEP_ALIVE_URI:
- break;
-
- default:
- List<String> uriPathList = request.getUriPathSegments();
- Logger.i("uriPahtList: " + uriPathList.toString());
-
- String did = uriPathList.get(0);
-
- Logger.i("did: " + did);
-
- // TODO: Clustering algorithm required
- // find ctx about did, and send msg
- String resource = new String();
- List<String> pathSegments = uriPathList.subList(1,
- uriPathList.size());
- for (String path : pathSegments) {
- resource += "/";
- resource += path;
- }
- Logger.i("resource: " + resource);
- request.setUriPath(resource);
-
- ChannelHandlerContext deviceCtx = sessionManager
- .querySession(did);
- if (deviceCtx != null) {
- deviceCtx.attr(keyDevice).set(ctx);
- deviceCtx.writeAndFlush(request);
- } else {
- Logger.e("deviceCtx is null");
- response = new CoapResponse(CoapStatus.FORBIDDEN);
- response.setToken(request.getToken());
- ctx.writeAndFlush(response);
- }
- return;
+ if (uriPath != null) {
+ switch (uriPath) {
+ case Constants.AUTH_URI:
+ // This case user wants to logout
+ String uriQuery = request.getUriQuery();
+ if (uriQuery != null) {
+ if (uriQuery.endsWith("logout")) {
+ ctx.channel().attr(Constants.Attribute_UserId)
+ .remove();
+ response = new CoapResponse(CoapStatus.DELETED);
+ } else {
+ response = new CoapResponse(
+ CoapStatus.BAD_REQUEST);
+ }
+ ctx.writeAndFlush(response);
+ }
+ break;
+
+ case Constants.RD_URI:
+ // RD POST means publish device to server
+ switch (request.getRequestMethod()) {
+ case POST:
+ userId = ctx.channel()
+ .attr(Constants.Attribute_UserId).get();
+ deviceId = request.decodeDeviceId();
+ authPayload = String.format(
+ "{\"userid\":\"%s\",\"deviceid\":\"%s\"}",
+ userId, deviceId);
+ accountRequest = new CoapRequest(
+ CoapMethod.POST);
+ accountRequest
+ .setUriPath(Constants.ACCOUNT_URI);
+ accountRequest.setUriQuery("reqtype=publish");
+ accountRequest.setToken(request.getToken());
+ accountRequest.setPayload(authPayload
+ .getBytes(StandardCharsets.UTF_8));
+
+ // TODO: deviceId must be registered after
+ // session
+ // granted
+ Logger.d("Adding deviceId to session: "
+ + deviceId);
+ sessionManager.addSession(deviceId, ctx);
+ break;
+
+ default:
+ Logger.e("Unsupported request type");
+ break;
+ }
+
+ rdClient.getChannelFuture().channel().attr(keyRDClient)
+ .set(ctx);
+
+ // Add original request to list for future use
+ asClient.getChannelFuture().channel()
+ .attr(keyAccountClient).get().add(request);
+ asClient.sendRequest(accountRequest);
+ return;
+
+ case Constants.WELL_KNOWN_URI:
+ switch (request.getRequestMethod()) {
+ case GET:
+ userId = ctx.channel()
+ .attr(Constants.Attribute_UserId).get();
+ authPayload = String
+ .format("{\"userid\":\"%s\"}", userId);
+ accountRequest = new CoapRequest(
+ CoapMethod.GET);
+ accountRequest
+ .setUriPath(Constants.ACCOUNT_URI);
+ accountRequest.setUriQuery("reqtype=find");
+ accountRequest.setToken(request.getToken());
+ accountRequest.setPayload(authPayload
+ .getBytes(StandardCharsets.UTF_8));
+ break;
+
+ default:
+ Logger.e("Unsupported request type");
+ break;
+ }
+
+ rdClient.getChannelFuture().channel().attr(keyRDClient)
+ .set(ctx);
+
+ // Add original request to list for future use
+ asClient.getChannelFuture().channel()
+ .attr(keyAccountClient).get().add(request);
+ asClient.sendRequest(accountRequest);
+ return;
+
+ case Constants.KEEP_ALIVE_URI:
+ break;
+
+ default:
+ List<String> uriPathList = request.getUriPathSegments();
+ if (uriPathList != null) {
+ Logger.i("uriPahtList: " + uriPathList.toString());
+
+ String did = uriPathList.get(0);
+
+ Logger.i("did: " + did);
+
+ // TODO: Clustering algorithm required
+ // find ctx about did, and send msg
+ StringBuffer resource = new StringBuffer();
+ List<String> pathSegments = uriPathList.subList(1,
+ uriPathList.size());
+ for (String path : pathSegments) {
+ resource.append("/");
+ resource.append(path);
+ }
+ Logger.i("resource: " + resource);
+ request.setUriPath(resource.toString());
+
+ ChannelHandlerContext deviceCtx = sessionManager
+ .querySession(did);
+ if (deviceCtx != null) {
+ deviceCtx.attr(keyDevice).set(ctx);
+ deviceCtx.writeAndFlush(request);
+ } else {
+ Logger.e("deviceCtx is null");
+ response = new CoapResponse(
+ CoapStatus.FORBIDDEN);
+ response.setToken(request.getToken());
+ ctx.writeAndFlush(response);
+ }
+ }
+ return;
+ }
}
} else if (msg instanceof CoapResponse) {
CoapResponse response = (CoapResponse) msg;
// If response contains path, add di
- if (response.getOption(11) != null) {
+ String did = sessionManager.queryDid(ctx);
+ if (response.getOption(11) != null && did != null) {
response.getOption(11).add(0,
- sessionManager.queryDid(ctx).getBytes());
+ did.getBytes(StandardCharsets.UTF_8));
}
Logger.i(
timer = new Timer();
cbor = new Cbor<HashMap<String, Integer>>();
}
-
- public void startSessionChecker()
- {
+
+ public void startSessionChecker() {
timer.schedule(new KeepAliveTask(), 30000, 60000);
}
-
- public void stopSessionChecker()
- {
+
+ public void stopSessionChecker() {
timer.cancel();
}
/**
* API for receiving message(message to keepalive resource)
- *
+ *
* @param ctx
* ChannelHandlerContext of request message
* @param request
case PUT:
HashMap<String, Integer> payloadData = null;
payloadData = cbor.parsePayloadFromCbor(request.getPayload(),
- new HashMap<String, Integer>().getClass());
+ HashMap.class);
Logger.d("Receive payloadData : " + payloadData);
- Logger.d("interval : " + payloadData.get("in"));
-
- connectPool.put(ctx, System.currentTimeMillis()
- + (payloadData.get("in") * (long) 60000));
+ if (payloadData != null) {
+ if (payloadData.containsKey("in")) {
+ Logger.d("interval : " + payloadData.get("in"));
+ connectPool.put(ctx, System.currentTimeMillis()
+ + (payloadData.get("in") * (long) 60000));
+ }
+ }
response = makeResponse(request);
break;
/**
* API for making response to Resource
- *
+ *
* @param request
* ChannelHandlerContext of request message
*/
/**
* API for making interval and first response to Resource
- *
+ *
* @param request
* ChannelHandlerContext of request message
*/
// check interval
while (iterator.hasNext()) {
ChannelHandlerContext key = iterator.next();
- Long lifeTime = (Long) map.get(key);
- Logger.d("KeepAliveTask Operating : "
- + key.channel().toString() + ", Time : "
- + (lifeTime - currentTime));
- if (lifeTime < currentTime) {
- deleteList.add(key);
+ if (map.containsKey(key) && map.get(key) != null) {
+ Long lifeTime = (Long) map.get(key);
+ if (lifeTime != 0) {
+ Logger.d("KeepAliveTask Operating : "
+ + key.channel().toString() + ", Time : "
+ + (lifeTime - currentTime));
+ if (lifeTime < currentTime) {
+ deleteList.add(key);
+ }
+ }
}
}
coapServer
.startServer(new InetSocketAddress(Integer.parseInt(args[0])));
- Scanner in = new Scanner(System.in);
-
+ Scanner in = new Scanner(System.in, "UTF8");
+
System.out.println("press 'q' to terminate");
-
- while(!in.nextLine().equals("q"));
-
+
+ while (!in.nextLine().equals("q"));
+
in.close();
-
+
System.out.println("Terminating...");
coapServer.stopServer();
-
+
System.out.println("Terminated");
}
}
didList.add("98f7483c-5a31-4161-ba7e-9c13e0d");
data.put("devices", didList);
String payload = JSONUtil.writeJSON(data);
- request.setPayload(payload.getBytes());
+ request.setPayload(payload.getBytes(StandardCharsets.UTF_8));
startServer();
ChannelHandlerContext ctx = startClient();
}
public List<String> getSessions() {
- return new ArrayList<String>(sessions.keySet());
+ synchronized (sessions) {
+ List<String> list = new ArrayList<String>(sessions.keySet());
+ return list;
+ }
}
}
public class CoapMessage {
- private int tokenLength = 0;
- protected int code = 0;
- private byte[] token = null;
+ private int tokenLength = 0;
+ protected int code = 0;
+ private byte[] token = null;
- private byte[] payload = null;
+ private byte[] payload = null;
// Option fields
protected List<byte[]> if_match = null;
else {
decodedPayload = cbor.parsePayloadFromCbor(payload,
ArrayList.class);
+ String deviceId = null;
+ if (decodedPayload != null) {
+ HashMap<Object, Object> tags = (HashMap<Object, Object>) decodedPayload
+ .get(0);
- HashMap<Object, Object> tags = (HashMap<Object, Object>) decodedPayload
- .get(0);
+ deviceId = tags.get("di").toString();
- String deviceId = tags.get("di").toString();
+ if (deviceId == null) {
+ throw new IllegalArgumentException("deviceId is null");
+ }
- if (deviceId == null) {
- throw new IllegalArgumentException("deviceId is null");
+ Logger.i("deviceId : " + deviceId);
}
-
- Logger.i("deviceId : " + deviceId);
-
return deviceId;
}
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import java.util.List;
+
import org.iotivity.cloud.base.protocols.coap.enums.CoapMethod;
import org.junit.Test;
CoapRequest request = new CoapRequest(CoapMethod.GET);
assertNull(request.getUriPathSegments());
request.setUriPath("parent/child");
- assertEquals(request.getUriPathSegments().size(), 2);
+ List<String> list = request.getUriPathSegments();
+ if (list != null) {
+ assertEquals(list.size(), 2);
+ }
}
@Test
CoapRequest request = new CoapRequest(CoapMethod.GET);
assertNull(request.getUriQuerySegments());
request.setUriQuery("sample=samplle&sample2=sample2");
- assertEquals(request.getUriQuerySegments().size(), 2);
+ List<String> list = request.getUriQuerySegments();
+ if (list != null) {
+ assertEquals(list.size(), 2);
+ }
}
@Test
CoapRequest request = new CoapRequest(CoapMethod.GET);
assertNull(request.getUriPathSegments());
request.setUriPath("sample");
- assertEquals(request.getUriPathSegments().size(), 1);
+ List<String> list = request.getUriPathSegments();
+ if (list != null) {
+ assertEquals(list.size(), 1);
+ }
request.clearUriPath();
- assertEquals(request.getUriPathSegments().size(), 0);
+ list = request.getUriPathSegments();
+ if (list != null) {
+ assertEquals(list.size(), 0);
+ }
}
}
@Test
public void testCbor() {
- Cbor<HashMap<String, String>> cbor = new Cbor<HashMap<String, String>>();
-
HashMap<String, String> setpayloadData = new HashMap<String, String>();
setpayloadData.put("test", "test");
-
- byte[] cborData = cbor.encodingPayloadToCbor(setpayloadData);
-
- HashMap<String, String> getpayloadData = null;
- getpayloadData = cbor.parsePayloadFromCbor(cborData,
- new HashMap<String, String>().getClass());
}
@Test