Fixed SVACE detected Code in Stack, AccountServer and CI .
authorJung Seungho <shonest.jung@samsung.com>
Thu, 31 Mar 2016 09:44:16 +0000 (18:44 +0900)
committerJee Hyeok Kim <jihyeok13.kim@samsung.com>
Fri, 1 Apr 2016 00:31:38 +0000 (00:31 +0000)
CI remains 1 detect. and have to fix in RD

Change-Id: Ia23fbda13ef843181f5daaff97f2008b936510a8
Signed-off-by: Jung Seungho <shonest.jung@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/7489
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Jee Hyeok Kim <jihyeok13.kim@samsung.com>
15 files changed:
cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java
cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServerManager.java
cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/AccountDBManager.java
cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AccountResource.java
cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/AuthResource.java
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapAuthHandler.java
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/protocols/CoapRelayHandler.java
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java
cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java
cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTest.java
cloud/stack/src/main/java/org/iotivity/cloud/base/SessionManager.java
cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapMessage.java
cloud/stack/src/test/java/org/iotivity/cloud/base/protocols/coap/CoapRequestTest.java
cloud/stack/src/test/java/org/iotivity/cloud/util/UtilTest.java

index 2fefffe..11bec5d 100644 (file)
@@ -31,9 +31,9 @@ import org.iotivity.cloud.base.ResourceManager;
 import org.iotivity.cloud.util.Logger;
 
 /**
- * 
+ *
  * This class is in charge of running of account server.
- * 
+ *
  */
 public class AccountServer {
 
@@ -60,19 +60,19 @@ 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");
     }
 }
index 85ec5ed..b2b29a8 100644 (file)
@@ -38,7 +38,7 @@ public class AccountServerManager {
 
     /**
      * API for requesting user account
-     * 
+     *
      * @param userId
      *            user identifier
      * @param deviceId
@@ -59,7 +59,7 @@ public class AccountServerManager {
     /**
      * API for requesting user account and getting session code for registered
      * user.
-     * 
+     *
      * @param userId
      *            user identifier
      * @return String - session code for registered user
@@ -79,7 +79,7 @@ public class AccountServerManager {
     /**
      * API for requesting user identifier corresponding with authorization
      * information.
-     * 
+     *
      * @param authCode
      *            authorization code
      * @param authServer
@@ -98,7 +98,7 @@ public class AccountServerManager {
 
     /**
      * API for requesting user identifier corresponding with session code.
-     * 
+     *
      * @param sessionCode
      *            session code
      * @return String - user identifier
@@ -115,7 +115,7 @@ public class AccountServerManager {
 
     /**
      * API for getting devices corresponding with user identifier.
-     * 
+     *
      * @param userId
      *            user identifier
      * @return ArrayList<String> - list of devices
@@ -166,7 +166,7 @@ public class AccountServerManager {
 
     private String generateSessionCode() {
 
-        String sessionCode = "";
+        StringBuffer sessionCode = new StringBuffer();
 
         Random random = new Random();
         int randomNum = random.nextInt(122);
@@ -180,7 +180,7 @@ public class AccountServerManager {
                         || (randomNum >= 97 && randomNum <= 122)) {
 
                     code = (char) randomNum;
-                    sessionCode += code;
+                    sessionCode.append(code);
 
                     randomNum = random.nextInt(122);
                     break;
@@ -192,6 +192,6 @@ public class AccountServerManager {
             }
         }
 
-        return sessionCode;
+        return sessionCode.toString();
     }
 }
index b012a9a..8569753 100644 (file)
@@ -60,7 +60,7 @@ public class AccountDBManager {
 
     /**
      * API for storing session information of authorized user
-     * 
+     *
      * @param userId
      *            user identifier
      * @param sessionCode
@@ -82,7 +82,7 @@ public class AccountDBManager {
 
     /**
      * API for storing device information of authorized user
-     * 
+     *
      * @param userId
      *            user identifier
      * @param deviceId
@@ -105,7 +105,7 @@ public class AccountDBManager {
     /**
      * API for getting user identifier information corresponding with session
      * code
-     * 
+     *
      * @param userId
      *            identifier of authorized user
      * @param sessionCode
@@ -123,16 +123,14 @@ public class AccountDBManager {
 
     /**
      * 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;
     }
index 4618df9..23d48a6 100644 (file)
@@ -51,7 +51,8 @@ public class AccountResource extends Resource {
     }
 
     @Override
-    public void onRequestReceived(ChannelHandlerContext ctx, CoapRequest request) {
+    public void onRequestReceived(ChannelHandlerContext ctx,
+            CoapRequest request) {
 
         Logger.d("AccountResource IN");
 
@@ -86,26 +87,27 @@ public class AccountResource extends Resource {
         }
     }
 
-    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);
+        }
 
     }
 
@@ -115,9 +117,10 @@ public class AccountResource extends Resource {
         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:
@@ -134,7 +137,7 @@ public class AccountResource extends Resource {
     /**
      * API for handling request for publishing resource corresponding with user
      * account
-     * 
+     *
      * @param requeset
      *            CoAP request message
      * @return CoapResponse - CoAP response message with response result
@@ -145,7 +148,8 @@ public class AccountResource extends Resource {
         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);
 
@@ -156,14 +160,14 @@ public class AccountResource extends Resource {
         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;
@@ -172,7 +176,7 @@ public class AccountResource extends Resource {
     /**
      * API for handling request for finding resource corresponding with user
      * account
-     * 
+     *
      * @param requeset
      *            CoAP request message
      * @return CoapResponse - CoAP response message with response result
@@ -224,13 +228,15 @@ public class AccountResource extends Resource {
 
         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];
+                }
             }
         }
 
@@ -239,9 +245,9 @@ public class AccountResource extends Resource {
 
     /*
      * private static String getPayloadString(byte[] payload) {
-     * 
+     *
      * if (payload == null) return "";
-     * 
+     *
      * return new String(payload, Charset.forName("UTF-8")); }
      */
 
index 50d2793..734acb9 100644 (file)
@@ -87,7 +87,7 @@ public class AuthResource extends Resource {
             throw new IllegalArgumentException(
                     "request type is null in query!");
 
-        CoapResponse response = null;
+        CoapResponse response;
 
         switch (reqType) {
             case Constants.TYPE_REGISTER:
@@ -106,7 +106,7 @@ public class AuthResource extends Resource {
 
     /**
      * API for handling request for login by user account
-     * 
+     *
      * @param request
      *            CoAP request message
      * @return CoapResponse - CoAP response message with response result
@@ -126,7 +126,7 @@ public class AuthResource extends Resource {
         Logger.d("userId: " + userId);
 
         CoapMessageBuilder responseMessage = new CoapMessageBuilder();
-        CoapResponse coapResponse = null;
+        CoapResponse coapResponse;
 
         if (userId != null) {
 
@@ -151,7 +151,7 @@ public class AuthResource extends Resource {
 
     /**
      * API for handling request for registering user account
-     * 
+     *
      * @param request
      *            CoAP request message
      * @return CoapResponse - CoAP response message with response result
@@ -161,21 +161,24 @@ public class AuthResource extends Resource {
 
         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) {
 
@@ -239,13 +242,15 @@ public class AuthResource extends Resource {
 
         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];
+                }
             }
         }
 
@@ -254,9 +259,9 @@ public class AuthResource extends Resource {
 
     /*
      * private static String getPayloadString(byte[] payload) {
-     * 
+     *
      * if (payload == null) return "";
-     * 
+     *
      * return new String(payload, Charset.forName("UTF-8")); }
      */
 
index 7188ff5..75953de 100644 (file)
@@ -22,6 +22,7 @@
 package org.iotivity.cloud.ciserver;
 
 import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
 import java.util.Scanner;
 
 import org.iotivity.cloud.base.CoapServer;
@@ -49,10 +50,10 @@ public class CloudInterfaceServer {
         ResourceManager resourceManager = null;
         SessionManager sessionManager = null;
         CoapServer coapServer = null;
-        
+
         CoapRelayHandler relayHandler = null;
-        CoapAuthHandler  authHandler = null;
-        
+        CoapAuthHandler authHandler = null;
+
         KeepAliveResource keepAliveResource = null;
 
         coapServer = new CoapServer();
@@ -60,53 +61,52 @@ public class CloudInterfaceServer {
         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");
     }
 }
index d2f2186..3e626e3 100644 (file)
@@ -59,20 +59,22 @@ public class CoapAuthHandler extends ChannelDuplexHandler {
                     .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);
@@ -93,19 +95,16 @@ public class CoapAuthHandler extends ChannelDuplexHandler {
 
     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>>();
@@ -116,29 +115,35 @@ public class CoapAuthHandler extends ChannelDuplexHandler {
 
         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;
+                }
             }
         }
 
index e2eab57..be472e3 100644 (file)
@@ -22,6 +22,7 @@
 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;
@@ -73,8 +74,8 @@ public class CoapRelayHandler extends ChannelDuplexHandler {
         }
     }
 
-    private CoapClient rdClient = null;
-    ///////////
+    private CoapClient                                   rdClient         = null;
+                                                                          ///////////
 
     ////////// Handler for Account Server
     private static final AttributeKey<List<CoapRequest>> keyAccountClient = AttributeKey
@@ -121,38 +122,37 @@ public class CoapRelayHandler extends ChannelDuplexHandler {
         }
     }
 
-    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
@@ -168,121 +168,138 @@ public class CoapRelayHandler extends ChannelDuplexHandler {
             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) {
@@ -293,9 +310,10 @@ public class CoapRelayHandler extends ChannelDuplexHandler {
                 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(
index 98d63ed..d6c62ed 100644 (file)
@@ -71,20 +71,18 @@ public class KeepAliveResource extends Resource {
         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
@@ -109,14 +107,17 @@ public class KeepAliveResource extends Resource {
             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;
 
@@ -132,7 +133,7 @@ public class KeepAliveResource extends Resource {
 
     /**
      * API for making response to Resource
-     * 
+     *
      * @param request
      *            ChannelHandlerContext of request message
      */
@@ -145,7 +146,7 @@ public class KeepAliveResource extends Resource {
 
     /**
      * API for making interval and first response to Resource
-     * 
+     *
      * @param request
      *            ChannelHandlerContext of request message
      */
@@ -183,12 +184,16 @@ public class KeepAliveResource extends Resource {
                 // 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);
+                            }
+                        }
                     }
                 }
 
index e7eff9d..9b0903e 100644 (file)
@@ -55,18 +55,18 @@ public class ResourceDirectoryServer {
         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");
     }
 }
index 7608f24..2770326 100644 (file)
@@ -186,7 +186,7 @@ public class RDServerTest {
         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();
index 3a376a6..ca371f7 100644 (file)
@@ -78,6 +78,9 @@ public class SessionManager {
     }
 
     public List<String> getSessions() {
-        return new ArrayList<String>(sessions.keySet());
+        synchronized (sessions) {
+            List<String> list = new ArrayList<String>(sessions.keySet());
+            return list;
+        }
     }
 }
index d22bd80..fb77b06 100644 (file)
@@ -33,11 +33,11 @@ import org.iotivity.cloud.util.Logger;
 
 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;
@@ -302,18 +302,19 @@ public class CoapMessage {
         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;
         }
     }
index 7cea05c..0dbe337 100644 (file)
@@ -4,6 +4,8 @@ import static org.junit.Assert.assertEquals;
 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;
 
@@ -40,7 +42,10 @@ public class CoapRequestTest {
         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
@@ -62,7 +67,10 @@ public class CoapRequestTest {
         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
@@ -70,8 +78,14 @@ public class CoapRequestTest {
         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);
+        }
     }
 }
index 9727a4a..a2f44b1 100644 (file)
@@ -13,16 +13,8 @@ public class UtilTest {
 
     @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