aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorOndrej <ondrej.tomcik@kistler.com>2018-11-27 07:36:10 +0100
committerOndrej Tomcik <ondrej.tomcik@kistler.com>2018-11-27 07:55:17 +0000
commita2b078f28950d92888e05363df5e4d5423c5f03a (patch)
treee97cdf6442da9baab138339b3123a7d7a877c640
parent34ed55ce4f2ae794a09dfc2b3f3eaa56ab90c77a (diff)
parent08ef99e6839afccd63a464f2165ef4ce9fd572b7 (diff)
Merge branch 'iotivity-cloud' reverifyzigbee-bridgingfeat-bridging-zigbee
Change-Id: Iacf81170fac09e4f7e9b7f6f4f51eb0182db1ce3 Signed-off-by: Ondrej Tomcik <ondrej.tomcik@kistler.com>
-rw-r--r--cloud/account/Dockerfile22
-rw-r--r--cloud/account/pom.xml23
-rw-r--r--cloud/account/properties/config.properties10
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java52
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java62
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Github.java10
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Google.java18
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthProviderFactory.java2
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountManager.java37
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountResource.java11
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/SecAccountResource.java39
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SecSessionResource.java40
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SessionResource.java5
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/SecTokenRefreshResource.java40
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/TokenRefreshResource.java5
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManager.java3
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupBrokerManager.java12
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupManager.java11
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/Acl.java24
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/AclManager.java12
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/verify/AclVerifyResource.java2
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateConstants.java12
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateResource.java14
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateStorage.java8
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlManager.java10
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlResource.java12
-rw-r--r--cloud/account/src/main/java/org/iotivity/cloud/accountserver/x509/cert/CSRParser.java8
-rw-r--r--cloud/account/src/main/resources/logback.xml12
-rw-r--r--cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/account/AccountResourceTest.java7
-rw-r--r--cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManagerTest.java37
-rw-r--r--cloud/interface/Dockerfile20
-rw-r--r--cloud/interface/pom.xml24
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java97
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java8
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/DeviceServerSystem.java90
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DevicePresenter.java12
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java72
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/UpdateDeviceStateListener.java57
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/Account.java5
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSession.java11
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccount.java40
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccountSession.java50
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresence.java9
-rw-r--r--cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectory.java11
-rw-r--r--cloud/interface/src/main/resources/logback.xml12
-rw-r--r--cloud/interface/src/test/java/org/iotivity/cloud/ciserver/DeviceServerSystemTest.java2
-rw-r--r--cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSessionTest.java10
-rw-r--r--cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java3
-rw-r--r--cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectoryTest.java4
-rw-r--r--cloud/messagequeue/Dockerfile15
-rw-r--r--cloud/messagequeue/pom.xml22
-rw-r--r--cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueServer.java27
-rw-r--r--cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueUtils.java8
-rw-r--r--cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaCommonWrapper.java13
-rw-r--r--cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaConsumerWrapper.java41
-rw-r--r--cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaProducerWrapper.java7
-rw-r--r--cloud/messagequeue/src/main/resources/logback.xml12
-rw-r--r--cloud/messagequeue/src/test/java/org/iotivity/cloud/mqserver/resources/MQBrokerResourceTest.java6
-rw-r--r--cloud/pom.xml25
-rw-r--r--cloud/resourcedirectory/Dockerfile21
-rw-r--r--cloud/resourcedirectory/pom.xml24
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java40
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java36
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java71
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java148
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java9
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java179
-rw-r--r--cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java46
-rw-r--r--cloud/resourcedirectory/src/main/resources/logback.xml12
-rw-r--r--cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java3
-rw-r--r--cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java3
-rw-r--r--cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java8
-rw-r--r--cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java3
-rw-r--r--cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java3
-rw-r--r--cloud/stack/pom.xml10
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/OICConstants.java14
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/ServerSystem.java32
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapClient.java10
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapConnector.java41
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectionEstablishedListener.java9
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectorPool.java20
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/device/CoapDevice.java12
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/device/Device.java19
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/exception/ServerException.java12
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/HealthHolder.java9
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/SimpleHealthHolder.java26
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java10
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapLogHandler.java63
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java5
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/websocket/WebSocketFrameHandler.java19
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/enums/ResponseStatus.java11
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyHandler.java17
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyProcessor.java11
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HttpLogHandler.java33
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/SimpleHttpHandler.java53
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/resource/CloudPingResource.java13
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/resource/Resource.java2
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/server/HttpServer.java11
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/server/Server.java6
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/base/server/SimpleHttpServer.java52
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/util/Log.java213
-rw-r--r--cloud/stack/src/main/java/org/iotivity/cloud/util/WebsocketLog.java107
102 files changed, 1701 insertions, 1018 deletions
diff --git a/cloud/account/Dockerfile b/cloud/account/Dockerfile
index a4d5177..e20c9bd 100644
--- a/cloud/account/Dockerfile
+++ b/cloud/account/Dockerfile
@@ -1,5 +1,9 @@
FROM openjdk:8-jre-alpine
+RUN apk add --update \
+ curl \
+ && rm -rf /var/cache/apk/*
+
ADD ./target/CloudAccount-0.0.1-SNAPSHOT.jar iotivity/AccountServer.jar
ADD ./target/lib/* iotivity/lib/
ADD ./properties/* iotivity/properties/
@@ -7,8 +11,24 @@ ADD ./properties/* iotivity/properties/
WORKDIR iotivity/
ENV COAP_PORT 5685
+ENV HEALTH_CHECK_ENABLED 1
ENV TLS_MODE 0
ENV MONGODB_ADDRESS mongodb
ENV MONGODB_PORT 27017
-ENTRYPOINT ["java", "-jar", "AccountServer.jar"] \ No newline at end of file
+
+ENV JMX_PORT 9002
+ENV JAVA_JMX_OPTS "-Dcom.sun.management.jmxremote \
+ -Dcom.sun.management.jmxremote.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.local.only=false \
+ -Dcom.sun.management.jmxremote.authenticate=false \
+ -Dcom.sun.management.jmxremote.ssl=false \
+ -Djava.rmi.server.hostname= \
+ -XX:MetaspaceSize=30m -XX:MaxMetaspaceSize=40m \
+ -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -server "
+
+EXPOSE 9002
+
+ENTRYPOINT exec java $JAVA_JMX_OPTS $JAVA_MEMORY_OPTS -jar AccountServer.jar
+HEALTHCHECK --interval=30s --timeout=2s --retries=3 CMD curl -f http://localhost/api/healthcheck || exit 1
diff --git a/cloud/account/pom.xml b/cloud/account/pom.xml
index d5ddcd9..d9800b6 100644
--- a/cloud/account/pom.xml
+++ b/cloud/account/pom.xml
@@ -10,6 +10,10 @@
<groupId>org.iotivity.cloud</groupId>
<artifactId>CloudAccount</artifactId>
+ <properties>
+ <docker.image.name>iotivity/accountserver</docker.image.name>
+ </properties>
+
<dependencies>
<!-- Local -->
<dependency>
@@ -111,7 +115,24 @@
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</plugin>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>docker-maven-plugin</artifactId>
+ <version>0.26.0</version>
+ <configuration>
+ <images>
+ <image>
+ <name>${docker.image.name}</name>
+ <build>
+ <dockerFileDir>${project.basedir}</dockerFileDir>
+ <tags>
+ <tag>${docker.image.version}</tag>
+ </tags>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ </plugin>
</plugins>
</build>
-
</project> \ No newline at end of file
diff --git a/cloud/account/properties/config.properties b/cloud/account/properties/config.properties
index 283a666..899f034 100644
--- a/cloud/account/properties/config.properties
+++ b/cloud/account/properties/config.properties
@@ -1,18 +1,18 @@
#New Serial number
-#Fri Dec 22 15:54:31 CET 2017
+#Wed Oct 31 14:15:38 CET 2018
keyGeneratorAlgorithm=ECDSA
notAfterInterval=20
securityProvider=BC
ellipticCurve=secp256r1
keystoreDir=keystore
keyStoreLocation=keystore{0}certificateStorage.jks
-keystoreType=BKS
-nextUpdateInterval=1
signatureAlgorithm=SHA256withECDSA
+nextUpdateInterval=1
+keystoreType=BKS
rootOU=OCF Sub CA
-serialNumber=20
+serialNumber=75
rootO=Samsung
-subjectName=uuid\:31313131-3131-3131-3131-313131313131
caAlias=uuid\:31313131-3131-3131-3131-313131313131
+subjectName=uuid\:31313131-3131-3131-3131-313131313131
password=PASSWORD
rootC=KR
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java
index 8e14660..6beea9c 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java
@@ -23,7 +23,16 @@ package org.iotivity.cloud.accountserver;
import java.net.InetSocketAddress;
import java.util.Scanner;
-
+import java.util.concurrent.TimeUnit;
+
+import org.iotivity.cloud.accountserver.resources.account.SecAccountResource;
+import org.iotivity.cloud.accountserver.resources.account.session.SecSessionResource;
+import org.iotivity.cloud.accountserver.resources.account.tokenrefresh.SecTokenRefreshResource;
+import org.iotivity.cloud.base.healthcheck.HealthHolder;
+import org.iotivity.cloud.base.healthcheck.SimpleHealthHolder;
+import org.iotivity.cloud.base.server.SimpleHttpServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.resources.account.AccountResource;
import org.iotivity.cloud.accountserver.resources.account.session.SessionResource;
@@ -37,7 +46,6 @@ import org.iotivity.cloud.accountserver.resources.credprov.crl.CrlResource;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.resource.CloudPingResource;
import org.iotivity.cloud.base.server.CoapServer;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -45,31 +53,27 @@ import org.iotivity.cloud.util.Log;
*
*/
public class AccountServer {
-
- private static int coapServerPort;
- private static boolean tlsMode;
- private static String databaseHost;
- private static String webLogHost;
+ private final static Logger Log = LoggerFactory.getLogger(AccountServer.class);
+ private static int coapServerPort;
+ private static boolean tlsMode;
+ private static String databaseHost;
+ private static String webLogHost;
+ private static boolean healthCheckEnabled;
public static void main(String[] args) throws Exception {
- System.out.println("-----Account SERVER-----");
- Log.Init();
+ Log.info("Starting Account Server");
if (!parseConfiguration(args)) {
- Log.e("\nCoAP-server <Port> Database <Address> <Port> TLS-mode <0|1> are required. WebSocketLog-Server <Addres> <Port> is optional.\n"
+ Log.error("\nCoAP-server <Port> Database <Address> <Port> TLS-mode <0|1> are required.\n"
+ "ex) " + Constants.DEFAULT_COAP_PORT
+ " 127.0.0.1 27017 0\n");
return;
}
- if (webLogHost != null)
- Log.InitWebLog(webLogHost,
- AccountServer.class.getSimpleName().toString());
AccountDBManager.createInstance(databaseHost);
-
+ HealthHolder healthHolder = new SimpleHealthHolder(TimeUnit.SECONDS,100);
ServerSystem serverSystem = new ServerSystem();
-
- serverSystem.addResource(new CloudPingResource());
+ serverSystem.addResource(new CloudPingResource(healthHolder));
serverSystem.addResource(new AccountResource());
serverSystem.addResource(new SessionResource());
serverSystem.addResource(new TokenRefreshResource());
@@ -81,9 +85,18 @@ public class AccountServer {
serverSystem.addResource(new AclResource());
serverSystem.addResource(new InviteResource());
+ //change in version 2.0.0
+ serverSystem.addResource(new SecAccountResource());
+ serverSystem.addResource(new SecTokenRefreshResource());
+ serverSystem.addResource(new SecSessionResource());
+
serverSystem.addServer(
new CoapServer(new InetSocketAddress(coapServerPort)));
+ if(healthCheckEnabled){
+ serverSystem.addServer(new SimpleHttpServer(new InetSocketAddress(80),healthHolder));
+ }
+
serverSystem.startSystem(tlsMode);
Scanner in = new Scanner(System.in, "UTF-8");
@@ -103,22 +116,21 @@ public class AccountServer {
private static boolean parseConfiguration(String[] args) {
// configuration provided by arguments
- if (args.length == 4 || args.length == 6) {
+ if (args.length == 4) {
coapServerPort = Integer.parseInt(args[0]);
databaseHost = args[1] + ":" + args[2];
tlsMode = Integer.parseInt(args[3]) == 1;
- if (args.length == 6)
- webLogHost = args[4] + ":" + args[5];
+ healthCheckEnabled = false;
return true;
}
// configuration provided by docker env
String tlsModeEnv = System.getenv("TLS_MODE");
if (tlsModeEnv != null) {
-
coapServerPort = Integer.parseInt(System.getenv("COAP_PORT"));
databaseHost = System.getenv("MONGODB_ADDRESS") + ":"
+ System.getenv("MONGODB_PORT");
tlsMode = Integer.parseInt(tlsModeEnv) == 1;
+ healthCheckEnabled = Integer.parseInt(System.getenv("HEALTH_CHECK_ENABLED")) == 1;
return true;
}
return false;
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java
index 83dfb78..7df3546 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/MongoDB.java
@@ -29,8 +29,9 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bson.Document;
-import org.iotivity.cloud.util.Log;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
@@ -45,9 +46,9 @@ import com.mongodb.client.result.DeleteResult;
*
*/
public class MongoDB {
-
- private MongoClient mongoClient = null;
- private MongoDatabase db = null;
+ private final static Logger Log = LoggerFactory.getLogger(MongoDB.class);
+ private MongoClient mongoClient = null;
+ private MongoDatabase db = null;
/**
* API creating MongoClient and initializing MongoDatabase
@@ -60,7 +61,6 @@ public class MongoDB {
*/
public MongoDB(String host, String dbname) throws Exception {
mongoClient = new MongoClient(host);
- mongoClient.dropDatabase(dbname);
db = mongoClient.getDatabase(dbname);
}
@@ -71,8 +71,23 @@ public class MongoDB {
* collection name
*/
public void createTable(String tableName) {
+ if (!collectionExists(tableName))
+ db.createCollection(tableName);
+ }
+
+ private boolean collectionExists(String tableName ) {
+ return db.listCollectionNames().into(new ArrayList<>()).contains(tableName);
+ }
- db.createCollection(tableName);
+ /**
+ * API for dropping collection
+ *
+ * @param tableName
+ * collection name
+ */
+ public void dropTable(String tableName) {
+ if (collectionExists(tableName))
+ db.getCollection(tableName).drop();
}
/**
@@ -142,7 +157,7 @@ public class MongoDB {
} else {
- Log.w("DB insert failed due to duplecated one.");
+ Log.warn("DB insert failed due to duplecated one.");
return false;
}
@@ -152,8 +167,6 @@ public class MongoDB {
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -191,8 +204,6 @@ public class MongoDB {
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -218,12 +229,10 @@ public class MongoDB {
if (collection.findOneAndReplace(filter, record) == null) {
- Log.w("DB updateX509CRL failed due to no matched record!");
+ Log.warn("DB updateX509CRL failed due to no matched record!");
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -249,7 +258,7 @@ public class MongoDB {
DeleteResult result = collection.deleteMany(record);
if (result.getDeletedCount() == 0) {
- Log.w("DB delete failed due to no mached record!");
+ Log.warn("DB delete failed due to no mached record!");
return false;
}
@@ -259,8 +268,6 @@ public class MongoDB {
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -336,25 +343,4 @@ public class MongoDB {
return resourceMap;
}
-
- private void showRecord(String tableName) {
-
- MongoCollection<Document> collection = db.getCollection(tableName);
- MongoCursor<Document> cursor = collection.find().iterator();
-
- Log.i("<" + tableName + ">");
-
- HashMap<String, Object> records = null;
- int index = 0;
- while (cursor.hasNext()) {
-
- Document doc = cursor.next();
- records = convertDocumentToHashMap(doc);
-
- Log.i("[" + index + "] " + records.toString());
- index++;
- }
-
- cursor.close();
- }
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Github.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Github.java
index 73abb96..e74be22 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Github.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Github.java
@@ -23,6 +23,8 @@ package org.iotivity.cloud.accountserver.oauth;
import java.util.HashMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
@@ -38,7 +40,6 @@ import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.util.JSONUtil;
-import org.iotivity.cloud.util.Log;;
/**
*
@@ -48,6 +49,7 @@ import org.iotivity.cloud.util.Log;;
*/
public class Github implements OAuthProvider {
+ private final static Logger Log = LoggerFactory.getLogger(Github.class);
// do not use 'client_id' and 'secret' variables.
// should use values that are obtained from github.
final static private String client_id = "ea9c18f540323b0213d0";
@@ -102,7 +104,7 @@ public class Github implements OAuthProvider {
UserTable userInfo = new UserTable();
if (accessToken == null) {
- Log.w("accessToken is null!");
+ Log.warn("accessToken is null!");
return null;
}
@@ -118,7 +120,7 @@ public class Github implements OAuthProvider {
request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
response = resourceResponse.getBody();
- Log.d("response: " + response);
+ Log.debug("response: " + response);
} catch (OAuthSystemException | OAuthProblemException e) {
e.printStackTrace();
@@ -132,7 +134,7 @@ public class Github implements OAuthProvider {
HashMap.class);
if (parsedData == null) {
- Log.d("parsedData is null!");
+ Log.debug("parsedData is null!");
return null;
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Google.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Google.java
index 72577c7..d2e1de6 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Google.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/Google.java
@@ -23,6 +23,8 @@ package org.iotivity.cloud.accountserver.oauth;
import java.util.HashMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
@@ -39,7 +41,6 @@ import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.util.JSONUtil;
-import org.iotivity.cloud.util.Log;;
/**
*
@@ -49,6 +50,7 @@ import org.iotivity.cloud.util.Log;;
*/
public class Google implements OAuthProvider {
+ private final static Logger Log = LoggerFactory.getLogger(Google.class);
// do not use 'client_id' and 'secret' variables.
// should use values that are obtained from github.
final static private String client_id = "447649044559-f9r5sl6op3kkk0312u384o4g6hhucje1.apps.googleusercontent.com";
@@ -63,7 +65,7 @@ public class Google implements OAuthProvider {
if (authCode == null) {
- Log.w("authCode is null!");
+ Log.warn("authCode is null!");
return tokenInfo;
}
@@ -84,7 +86,7 @@ public class Google implements OAuthProvider {
oauthResponse = oauthClient.accessToken(request, cl);
- Log.d("OAuth response: " + oauthResponse.getBody());
+ Log.debug("OAuth response: " + oauthResponse.getBody());
tokenInfo.setAccesstoken(oauthResponse.getAccessToken());
tokenInfo.setRefreshtoken(oauthResponse.getRefreshToken());
@@ -107,7 +109,7 @@ public class Google implements OAuthProvider {
if (refreshToken == null) {
- Log.w("refreshToken is null!");
+ Log.warn("refreshToken is null!");
return tokenInfo;
}
@@ -127,7 +129,7 @@ public class Google implements OAuthProvider {
oauthResponse = oauthClient.accessToken(request, cl);
- Log.d("OAuth response: " + oauthResponse.getBody());
+ Log.debug("OAuth response: " + oauthResponse.getBody());
tokenInfo.setAccesstoken(oauthResponse.getAccessToken());
// Google provides refreshToken in one time.
@@ -150,7 +152,7 @@ public class Google implements OAuthProvider {
UserTable userInfo = new UserTable();
if (accessToken == null) {
- Log.w("accessToken is null!");
+ Log.warn("accessToken is null!");
return userInfo;
}
@@ -168,7 +170,7 @@ public class Google implements OAuthProvider {
request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
response = resourceResponse.getBody();
- Log.d("response: " + response);
+ Log.debug("response: " + response);
} catch (OAuthSystemException | OAuthProblemException e) {
e.printStackTrace();
@@ -183,7 +185,7 @@ public class Google implements OAuthProvider {
HashMap.class);
if (parsedData == null) {
- Log.d("parsedData is null!");
+ Log.debug("parsedData is null!");
return userInfo;
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthProviderFactory.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthProviderFactory.java
index 52f3148..d5d390c 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthProviderFactory.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/oauth/OAuthProviderFactory.java
@@ -26,13 +26,11 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
-import java.util.Set;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
-import org.iotivity.cloud.util.Log;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountManager.java
index fd2da9d..dcd71a1 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountManager.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountManager.java
@@ -38,6 +38,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.UUID;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.TokenTable;
@@ -51,7 +53,6 @@ import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.base.exception.ServerException.NotFoundException;
import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -60,7 +61,7 @@ import org.iotivity.cloud.util.Log;
*
*/
public class AccountManager {
-
+ private final static Logger Log = LoggerFactory.getLogger(AccountManager.class);
private OAuthProviderFactory mFactory = null;
private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
@@ -241,7 +242,7 @@ public class AccountManager {
private String checkAuthProviderName(String authProviderName) {
String libraryFileName = getValidFileName(Constants.OAUTH_LIBRARIES_PATH, authProviderName + ".jar");
if (libraryFileName == null) {
- Log.w("OAuth 3rd party library " + authProviderName + " does not exist.");
+ Log.warn("OAuth 3rd party library " + authProviderName + " does not exist.");
return authProviderName;
}
return libraryFileName.substring(0, libraryFileName.length() - 4);
@@ -349,16 +350,16 @@ public class AccountManager {
private TokenTable requestAccessToken(String authCode, Object options) {
TokenTable tokenInfo = mFactory.requestAccessTokenInfo(authCode,
options);
- Log.d("access token : " + tokenInfo.getAccesstoken());
- Log.d("refresh token : " + tokenInfo.getRefreshtoken());
- Log.d("expired time : " + tokenInfo.getExpiredtime());
+ Log.debug("access token : " + tokenInfo.getAccesstoken());
+ Log.debug("refresh token : " + tokenInfo.getRefreshtoken());
+ Log.debug("expired time : " + tokenInfo.getExpiredtime());
return tokenInfo;
}
private UserTable requestUserInfo(String accessToken, Object options) {
UserTable userInfo = mFactory.requestGetUserInfo(accessToken, options);
- Log.d("user id : " + userInfo.getUserid());
+ Log.debug("user id : " + userInfo.getUserid());
return userInfo;
}
@@ -366,7 +367,7 @@ public class AccountManager {
private String generateUuid() {
UUID uuid = UUID.randomUUID();
String userUuid = uuid.toString();
- Log.d("generated uuid : " + userUuid);
+ Log.debug("generated uuid : " + userUuid);
return userUuid;
}
@@ -415,10 +416,10 @@ public class AccountManager {
private boolean checkRefreshTokenInDB(TokenTable tokenInfo, String token) {
if (tokenInfo.getRefreshtoken() == null) {
- Log.w("Refreshtoken doesn't exist");
+ Log.warn("Refreshtoken doesn't exist");
return false;
} else if (!tokenInfo.getRefreshtoken().equals(token)) {
- Log.w("Refreshtoken is not correct");
+ Log.warn("Refreshtoken is not correct");
return false;
}
return true;
@@ -426,10 +427,10 @@ public class AccountManager {
private boolean checkAccessTokenInDB(TokenTable tokenInfo, String token) {
if (tokenInfo.getAccesstoken() == null) {
- Log.w("AccessToken doesn't exist");
+ Log.warn("AccessToken doesn't exist");
return false;
} else if (!tokenInfo.getAccesstoken().equals(token)) {
- Log.w("AccessToken is not correct");
+ Log.warn("AccessToken is not correct");
return false;
}
return true;
@@ -443,7 +444,7 @@ public class AccountManager {
long remainTime = getElaspedSeconds(issuedTime);
if (remainTime > expiredTime) {
- Log.w("access token is expired");
+ Log.warn("access token is expired");
return false;
}
return true;
@@ -463,7 +464,7 @@ public class AccountManager {
long difference = currentTime.getTime() - issuedTimeDate.getTime();
long elaspedSeconds = difference / 1000;
- Log.d("accessToken elasped time: " + elaspedSeconds + "s");
+ Log.debug("accessToken elasped time: " + elaspedSeconds + "s");
return elaspedSeconds;
}
@@ -494,9 +495,9 @@ public class AccountManager {
TokenTable tokenInfo = mFactory.requestRefreshTokenInfo(refreshToken);
- Log.d("access token : " + tokenInfo.getAccesstoken());
- Log.d("refresh token : " + tokenInfo.getRefreshtoken());
- Log.d("expired time : " + tokenInfo.getExpiredtime());
+ Log.debug("access token : " + tokenInfo.getAccesstoken());
+ Log.debug("refresh token : " + tokenInfo.getRefreshtoken());
+ Log.debug("expired time : " + tokenInfo.getExpiredtime());
return tokenInfo;
}
@@ -516,7 +517,7 @@ public class AccountManager {
}
response.put(Constants.RESP_USER_LIST, ulist);
- Log.d("User List " + response.toString());
+ Log.debug("User List " + response.toString());
return response;
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountResource.java
index 5f67c93..7ee11d4 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountResource.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/AccountResource.java
@@ -25,6 +25,8 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.resources.account.AccountManager.SearchOperation;
import org.iotivity.cloud.base.device.Device;
@@ -38,7 +40,6 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -47,6 +48,7 @@ import org.iotivity.cloud.util.Log;
*
*/
public class AccountResource extends Resource {
+ private final static Logger Log = LoggerFactory.getLogger(AccountResource.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
@@ -54,7 +56,10 @@ public class AccountResource extends Resource {
public AccountResource() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.ACCOUNT_URI));
+ }
+ public AccountResource(final List<String> pathSegments) {
+ super(pathSegments);
}
@Override
@@ -110,7 +115,7 @@ public class AccountResource extends Resource {
String authProvider = payloadData.get(Constants.REQ_AUTH_PROVIDER)
.toString();
- Log.d("authCode: " + authCode);
+ Log.debug("authCode: " + authCode);
Object options = payloadData.get(Constants.REQ_AUTH_OPTIONS);
@@ -145,7 +150,7 @@ public class AccountResource extends Resource {
SearchOperation.OR));
}
- Log.d("Search criteria query : " + queryData);
+ Log.debug("Search criteria query : " + queryData);
return MessageBuilder.createResponse(request, ResponseStatus.CONTENT,
ContentFormat.APPLICATION_CBOR,
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/SecAccountResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/SecAccountResource.java
new file mode 100644
index 0000000..3883836
--- /dev/null
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/SecAccountResource.java
@@ -0,0 +1,39 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.cloud.accountserver.resources.account;
+
+import org.iotivity.cloud.accountserver.Constants;
+
+import java.util.Arrays;
+
+/**
+ *
+ * This class provides a set of APIs to manage resources corresponding with user
+ * account. Version. 2.0.0
+ *
+ */
+public class SecAccountResource extends AccountResource {
+
+ public SecAccountResource() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.SEC_URI ,Constants.ACCOUNT_URI));
+ }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SecSessionResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SecSessionResource.java
new file mode 100644
index 0000000..8ba8f9b
--- /dev/null
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SecSessionResource.java
@@ -0,0 +1,40 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.cloud.accountserver.resources.account.session;
+
+import org.iotivity.cloud.accountserver.Constants;
+
+import java.util.Arrays;
+
+/**
+ *
+ * This class provides a set of APIs to handle sign-in/sign-out requests for. Version 2.0.0
+ *
+ */
+
+public class SecSessionResource extends SessionResource {
+
+ public SecSessionResource() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.SEC_URI,
+ Constants.SESSION_URI));
+ }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SessionResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SessionResource.java
index f2d6763..163a359 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SessionResource.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/session/SessionResource.java
@@ -23,6 +23,7 @@ package org.iotivity.cloud.accountserver.resources.account.session;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.resources.account.AccountManager;
@@ -54,6 +55,10 @@ public class SessionResource extends Resource {
Constants.SESSION_URI));
}
+ public SessionResource(List<String> pathSegments) {
+ super(pathSegments);
+ }
+
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/SecTokenRefreshResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/SecTokenRefreshResource.java
new file mode 100644
index 0000000..1743e2b
--- /dev/null
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/SecTokenRefreshResource.java
@@ -0,0 +1,40 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.cloud.accountserver.resources.account.tokenrefresh;
+
+import org.iotivity.cloud.accountserver.Constants;
+
+import java.util.Arrays;
+
+/**
+ *
+ * This class provides a set of APIs to handle token refresh requests. Version 2.0.0
+ *
+ */
+
+public class SecTokenRefreshResource extends TokenRefreshResource {
+
+ public SecTokenRefreshResource() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.SEC_URI,
+ Constants.TOKEN_REFRESH_URI));
+ }
+}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/TokenRefreshResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/TokenRefreshResource.java
index d189ccf..fac1e76 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/TokenRefreshResource.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/account/tokenrefresh/TokenRefreshResource.java
@@ -23,6 +23,7 @@ package org.iotivity.cloud.accountserver.resources.account.tokenrefresh;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.resources.account.AccountManager;
@@ -54,6 +55,10 @@ public class TokenRefreshResource extends Resource {
Constants.TOKEN_REFRESH_URI));
}
+ public TokenRefreshResource(List<String> pathSegments) {
+ super(pathSegments);
+ }
+
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManager.java
index c302c83..9fff8e0 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManager.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManager.java
@@ -6,6 +6,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.AceTable;
@@ -25,6 +27,7 @@ import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorExce
*/
public class GroupAclManager {
+ private final static Logger Log = LoggerFactory.getLogger(GroupAclManager.class);
private static GroupAclManager mGrAclManager = new GroupAclManager();
private TypeCastingManager<AceTable> mTypeAceTable = new TypeCastingManager<AceTable>();
private TypeCastingManager<AceResource> mTypeAceResource = new TypeCastingManager<AceResource>();
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupBrokerManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupBrokerManager.java
index f675585..8ca3302 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupBrokerManager.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupBrokerManager.java
@@ -6,6 +6,8 @@ import java.util.HashMap;
import java.util.ListIterator;
import java.util.UUID;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.GroupTable;
@@ -18,13 +20,13 @@ import org.iotivity.cloud.base.protocols.coap.CoapRequest;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
/**
* This class provides a set of APIs manage a group broker
*/
public class GroupBrokerManager {
+ private final static Logger Log = LoggerFactory.getLogger(GroupBrokerManager.class);
private static GroupBrokerManager mGroupBrokerMgr = new GroupBrokerManager();
private TypeCastingManager<GroupTable> mTypeGroup = new TypeCastingManager<>();
private HashMap<String, Object> mGroupResourceInfo = new HashMap<>();
@@ -108,7 +110,7 @@ public class GroupBrokerManager {
response.put(Constants.RESP_GROUPS, records);
}
- Log.d("Group get response : " + response.toString());
+ Log.debug("Group get response : " + response.toString());
return response;
}
@@ -182,7 +184,7 @@ public class GroupBrokerManager {
response.put(Constants.KEYFIELD_GROUP_PARENT, parent);
}
- Log.d("Group post response : " + response.toString());
+ Log.debug("Group post response : " + response.toString());
return response;
}
@@ -258,7 +260,7 @@ public class GroupBrokerManager {
&& coapRequest.getTokenString().equals(
((CoapRequest) request).getTokenString())) {
iterator.remove();
- Log.d("subscriber removed, "
+ Log.debug("subscriber removed, "
+ ((CoapRequest) request).getTokenString());
}
}
@@ -291,7 +293,7 @@ public class GroupBrokerManager {
mCbor.encodingPayloadToCbor(
makeGetResponse(uid))));
}
- Log.d("subscriber : " + uid
+ Log.debug("subscriber : " + uid
+ " , subscriber internal Token list : "
+ subscriberTokenList);
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupManager.java
index 79aa494..16d8795 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupManager.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupManager.java
@@ -26,13 +26,14 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.GroupTable;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -41,6 +42,8 @@ import org.iotivity.cloud.util.Log;
*/
public class GroupManager {
+
+ private final static Logger Log = LoggerFactory.getLogger(GroupManager.class);
private static GroupManager mGrManager = new GroupManager();
private TypeCastingManager<GroupTable> mTypeGroup = new TypeCastingManager<GroupTable>();
private GroupPolicyManager mGroupPolicyManager = new GroupPolicyManager();
@@ -420,7 +423,7 @@ public class GroupManager {
*/
private <T> void addProperties(String gid, String property,
ArrayList<T> values) {
- Log.d("added property name: " + property + ", values : " + values
+ Log.debug("added property name: " + property + ", values : " + values
+ " , to group : " + gid);
if (values == null || values.isEmpty()) {
return;
@@ -450,7 +453,7 @@ public class GroupManager {
*/
private <T> void deleteProperties(String gid, String property,
ArrayList<T> values) {
- Log.d("deleted property name: " + property + ", values : " + values
+ Log.debug("deleted property name: " + property + ", values : " + values
+ " , from group : " + gid);
GroupTable groupTable = getGroupTable(gid);
if (groupTable == null || values == null || values.isEmpty()) {
@@ -486,7 +489,7 @@ public class GroupManager {
* value string
*/
private void replaceProperties(String gid, String property, String value) {
- Log.d("replaced property name: " + property + ", value : " + value
+ Log.debug("replaced property name: " + property + ", value : " + value
+ ", to group : " + gid);
if (value == null || value.isEmpty()) {
return;
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/Acl.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/Acl.java
index 3f06327..4732d2a 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/Acl.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/Acl.java
@@ -28,6 +28,8 @@ import java.util.List;
import java.util.ListIterator;
import java.util.UUID;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.AclTable;
@@ -41,10 +43,9 @@ import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
public class Acl {
-
+ private final static Logger Log = LoggerFactory.getLogger(Acl.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
private String mAclid = null;
private String mOid = null;
@@ -77,8 +78,15 @@ public class Acl {
return (object == null) ? "" : object.toString();
}
+ public static Acl convertMaptoAcl(HashMap<String, Object> aclMap) {
+ return new Acl(
+ valueOf(aclMap.get(Constants.KEYFIELD_ACLID)),
+ valueOf(aclMap.get(Constants.REQ_OWNER_ID)),
+ valueOf(aclMap.get(Constants.KEYFIELD_DI)));
+ }
+
@SuppressWarnings("unchecked")
- public static AclTable convertMaptoAclObject(
+ public static AclTable convertMaptoAclTable(
HashMap<String, Object> aclMap) {
AclTable aclTable = new AclTable();
try {
@@ -149,7 +157,7 @@ public class Acl {
public List<HashMap<String, Object>> addACE(
List<HashMap<String, Object>> aclist) {
- Log.v("IN addACE");
+ Log.trace("IN addACE");
HashMap<String, Object> hashmap = AccountDBManager.getInstance()
.selectRecord(Constants.ACL_TABLE, getCondition()).get(0);
if (hashmap == null) {
@@ -180,7 +188,7 @@ public class Acl {
AccountDBManager.getInstance().updateRecord(Constants.ACL_TABLE,
hashmap);
notifyToSubscriber(getResponsePayload(true));
- Log.v("OUT addACE");
+ Log.trace("OUT addACE");
return aclist;
}
@@ -226,7 +234,7 @@ public class Acl {
}
public void updateACE(String aceid, HashMap<String, Object> ace) {
- Log.v("IN updateACE");
+ Log.trace("IN updateACE");
HashMap<String, Object> hashmap = AccountDBManager.getInstance()
.selectRecord(Constants.ACL_TABLE, getCondition()).get(0);
@@ -251,7 +259,7 @@ public class Acl {
AccountDBManager.getInstance().updateRecord(Constants.ACL_TABLE,
hashmap);
notifyToSubscriber(getResponsePayload(true));
- Log.v("OUT updateACE");
+ Log.trace("OUT updateACE");
}
@@ -342,7 +350,7 @@ public class Acl {
private AclTable getAclTable() {
AclTable getAclTable = new AclTable();
- getAclTable = convertMaptoAclObject(AccountDBManager.getInstance()
+ getAclTable = convertMaptoAclTable(AccountDBManager.getInstance()
.selectRecord(Constants.ACL_TABLE, getCondition()).get(0));
return getAclTable;
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/AclManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/AclManager.java
index 081315f..62accb5 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/AclManager.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/id/AclManager.java
@@ -35,10 +35,7 @@ import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.protocols.IRequest;
-import org.iotivity.cloud.util.Log;
-
public class AclManager {
- public HashMap<String, Acl> mAcls = new HashMap<>();
private TypeCastingManager<AclTable> mTypeAcl = new TypeCastingManager<AclTable>();
public HashMap<String, Object> createAcl(String oid, String di) {
@@ -50,13 +47,15 @@ public class AclManager {
AccountDBManager.getInstance().insertRecord(Constants.ACL_TABLE,
mTypeAcl.convertObjectToMap(newAclTable));
- mAcls.put(aclid, new Acl(aclid));
responsePayload.put(Constants.REQ_ACL_ID, aclid);
return responsePayload;
}
public Acl getAcl(String aclid) {
- return mAcls.get(aclid);
+ HashMap<String, Object> condition = new HashMap<>();
+ condition.put(Constants.REQ_ACL_ID, aclid);
+ HashMap<String, Object> result = AccountDBManager.getInstance().selectOneRecord(Constants.ACL_TABLE, condition);
+ return Acl.convertMaptoAcl(result);
}
public HashMap<String, Object> getAclid(String di) {
@@ -70,7 +69,7 @@ public class AclManager {
{
for (HashMap<String, Object> element : result) {
AclTable getAclTable = new AclTable();
- getAclTable = Acl.convertMaptoAclObject(element);
+ getAclTable = Acl.convertMaptoAclTable(element);
aclid = getAclTable.getAclid();
responsePayload.put(Constants.KEYFIELD_ACLID, aclid);
return responsePayload;
@@ -84,7 +83,6 @@ public class AclManager {
condition.put(Constants.REQ_ACL_ID, aclid);
AccountDBManager.getInstance().deleteRecord(Constants.ACL_TABLE,
condition);
- mAcls.remove(aclid);
}
public List<HashMap<String, Object>> addAclACE(String aclid, List<HashMap<String, Object>> aclist) {
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/verify/AclVerifyResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/verify/AclVerifyResource.java
index bc83ef3..5a7a72f 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/verify/AclVerifyResource.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/acl/verify/AclVerifyResource.java
@@ -116,7 +116,7 @@ public class AclVerifyResource extends Resource {
for (HashMap<String, Object> eachAclMap : aclResult) {
- AclTable aclTable = Acl.convertMaptoAclObject(eachAclMap);
+ AclTable aclTable = Acl.convertMaptoAclTable(eachAclMap);
if (aclTable.getOid().equals(sid)) {
return true;
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateConstants.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateConstants.java
index 4ba157a..c204970 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateConstants.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateConstants.java
@@ -21,11 +21,12 @@
*/
package org.iotivity.cloud.accountserver.resources.credprov.cert;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bouncycastle.asn1.x500.X500Name;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.x509.cert.Utility;
-import org.iotivity.cloud.util.Log;
import java.io.File;
import java.io.FileInputStream;
@@ -44,11 +45,12 @@ import static java.security.cert.CertificateFactory.getInstance;
* This utility class is used for getting all properties from properties file.
*/
public final class CertificateConstants {
+ private final static Logger Log = LoggerFactory.getLogger(CertificateConstants.class);
/**
* Properties object is used for loading pre-defined configurations: algorithm names and so on.
*/
- public static final Properties PROPERTIES = new Properties();
+ public static final Properties PROPERTIES = new Properties();
/**
* Load properties from specified properties file.
@@ -57,7 +59,7 @@ public final class CertificateConstants {
try (FileInputStream inputStream = new FileInputStream(Constants.PROPERTIES_FILE_NAME)) {
PROPERTIES.load(inputStream);
} catch (IOException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
@@ -141,7 +143,7 @@ public final class CertificateConstants {
try {
CERTIFICATE_FACTORY = getInstance("X509");
} catch (CertificateException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
@@ -162,7 +164,7 @@ public final class CertificateConstants {
try (FileOutputStream outputStream = new FileOutputStream(Constants.PROPERTIES_FILE_NAME)) {
PROPERTIES.store(outputStream, "New Serial number");
} catch (IOException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateResource.java
index 13bf1d5..9db800f 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateResource.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateResource.java
@@ -21,6 +21,8 @@
*/
package org.iotivity.cloud.accountserver.resources.credprov.cert;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.Extension;
@@ -45,7 +47,6 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import java.io.IOException;
import java.security.GeneralSecurityException;
@@ -70,12 +71,13 @@ import static org.iotivity.cloud.accountserver.resources.credprov.cert.Certifica
* personal certificate, issued by CA certificate and certificate chain.
*/
public class CertificateResource extends Resource {
+ private final static Logger Log = LoggerFactory.getLogger(CertificateResource.class);
/**
* This constant object is used for parsing cbor payload to Map object and to
* encoding map object to cbor format.
*/
- private static final Cbor<Map<String, Object>> MAP_CBOR = new Cbor<>();
+ private static final Cbor<Map<String, Object>> MAP_CBOR = new Cbor<>();
/**
* Inserts BouncyCastleProvider into 0 position in security provider list,
@@ -90,7 +92,7 @@ public class CertificateResource extends Resource {
CertificateStorage.load();
}
} catch (GeneralSecurityException | IOException | OperatorCreationException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
@@ -179,7 +181,7 @@ public class CertificateResource extends Resource {
try {
CrlManager.CRL_MANAGER.revoke(certificateTable.getSerialNumber());
} catch (CRLException | OperatorCreationException e) {
- Log.e(e.getMessage() + e.getClass());
+ Log.error(e.getMessage() + e.getClass());
}
certificateManager.update(certificateTable, true);
}
@@ -208,12 +210,12 @@ public class CertificateResource extends Resource {
ContentFormat.APPLICATION_CBOR,
MAP_CBOR.encodingPayloadToCbor(certificateManager.getPayLoad()));
} catch (GeneralSecurityException | OperatorCreationException | CertIOException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
}
} catch (IOException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateStorage.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateStorage.java
index 9363549..3de3f7c 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateStorage.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/cert/CertificateStorage.java
@@ -21,13 +21,14 @@
*/
package org.iotivity.cloud.accountserver.resources.credprov.cert;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.operator.OperatorCreationException;
import org.iotivity.cloud.accountserver.x509.cert.CertificateBuilder;
import org.iotivity.cloud.accountserver.x509.cert.CertificateExtension;
-import org.iotivity.cloud.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -46,6 +47,7 @@ import static org.iotivity.cloud.accountserver.resources.credprov.cert.Certifica
* Also it generates CA certificate and puts it to keystore.
*/
public final class CertificateStorage {
+ private final static Logger Log = LoggerFactory.getLogger(CertificateStorage.class);
/**
* This attribute is used to get password to kestore, that stores CA certificate info.
@@ -97,7 +99,7 @@ public final class CertificateStorage {
try (InputStream inputStream = new FileInputStream(KEYSTORE_FILE)) {
keyStore.load(inputStream, PASSWORD.toCharArray());
} catch (IOException ioException) {
- Log.e(ioException.getMessage());
+ Log.error(ioException.getMessage());
}
ROOT_PRIVATE_KEY = (PrivateKey) keyStore.getKey(CA_ALIAS, PASSWORD.toCharArray());
ROOT_CERTIFICATE = (X509Certificate) keyStore.getCertificate(CA_ALIAS);
@@ -132,7 +134,7 @@ public final class CertificateStorage {
try (FileOutputStream out = new FileOutputStream(KEYSTORE_FILE)) {
keyStore.store(out, PASSWORD.toCharArray());
} catch (IOException ioException) {
- Log.e(ioException.getMessage());
+ Log.error(ioException.getMessage());
}
}
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlManager.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlManager.java
index 32b6ce9..27a9fcb 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlManager.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlManager.java
@@ -40,24 +40,26 @@ import java.util.Date;
import java.util.HashMap;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bouncycastle.operator.OperatorCreationException;
import org.bson.types.Binary;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.CRLTable;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
import org.iotivity.cloud.base.exception.ServerException;
-import org.iotivity.cloud.util.Log;
/**
* Class is used to manage CRLs. It helps to create, update CRLS, revoke
* certificates.
*/
public final class CrlManager {
+ private final static Logger Log = LoggerFactory.getLogger(CrlManager.class);
/**
* Casting manager for working with CRLTable in mongo db
*/
- private static TypeCastingManager<CRLTable> castingManager = new TypeCastingManager<>();
+ private static TypeCastingManager<CRLTable> castingManager = new TypeCastingManager<>();
/**
* X509 CRL presentation.
@@ -85,7 +87,7 @@ public final class CrlManager {
new CRLTable(thisUpdate, new Binary(data))));
setX509CRL(data);
} catch (CRLException | IOException | OperatorCreationException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
@@ -141,7 +143,7 @@ public final class CrlManager {
.parse(lastUpdate).before(x509CRL.getThisUpdate());
}
} catch (ParseException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
return checkCondition;
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlResource.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlResource.java
index fa75701..652c7af 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlResource.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/resources/credprov/crl/CrlResource.java
@@ -34,6 +34,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.DecoderException;
@@ -47,17 +49,17 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
/**
* Class is used working with POST and GET requests and handles CRL requests.
*/
public class CrlResource extends Resource {
+ private final static Logger Log = LoggerFactory.getLogger(CrlResource.class);
/**
* CBOR container with help of map presentation.
*/
- private static final Cbor<Map<String, Object>> MAP_CBOR = new Cbor<>();
+ private static final Cbor<Map<String, Object>> MAP_CBOR = new Cbor<>();
/**
* Creates resource for handling CRL requests(GET and POST)
@@ -113,7 +115,7 @@ public class CrlResource extends Resource {
MAP_CBOR.encodingPayloadToCbor(payload));
}
} catch (CRLException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
}
}
@@ -172,13 +174,13 @@ public class CrlResource extends Resource {
response = MessageBuilder.createResponse(
request, ResponseStatus.CHANGED);
} catch (DecoderException e) {
- Log.e(e.getMessage() + e.getClass());
+ Log.error(e.getMessage() + e.getClass());
}
}
}
} catch (CRLException | IOException
| OperatorCreationException | ParseException e) {
- Log.e(e.getMessage() + e.getClass());
+ Log.error(e.getMessage() + e.getClass());
}
}
}
diff --git a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/x509/cert/CSRParser.java b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/x509/cert/CSRParser.java
index 71fb1a0..6ac2003 100644
--- a/cloud/account/src/main/java/org/iotivity/cloud/accountserver/x509/cert/CSRParser.java
+++ b/cloud/account/src/main/java/org/iotivity/cloud/accountserver/x509/cert/CSRParser.java
@@ -21,6 +21,8 @@
*/
package org.iotivity.cloud.accountserver.x509.cert;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bouncycastle.asn1.x500.AttributeTypeAndValue;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.openssl.PEMException;
@@ -29,7 +31,6 @@ import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCSException;
-import org.iotivity.cloud.util.Log;
import java.io.IOException;
import java.security.PublicKey;
@@ -41,6 +42,7 @@ import static org.iotivity.cloud.accountserver.resources.credprov.cert.Certifica
* Class is used for parsing CSR requests.
*/
public class CSRParser {
+ private final static Logger Log = LoggerFactory.getLogger(CSRParser.class);
/**
* PKCS10CertificationRequest attribute.
@@ -71,7 +73,7 @@ public class CSRParser {
publicKey = new JcaPEMKeyConverter().setProvider(SECURITY_PROVIDER).
getPublicKey(mCsr.getSubjectPublicKeyInfo());
} catch (PEMException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
return publicKey;
}
@@ -87,7 +89,7 @@ public class CSRParser {
condition = mCsr.isSignatureValid(new JcaContentVerifierProviderBuilder()
.setProvider(SECURITY_PROVIDER).build(mCsr.getSubjectPublicKeyInfo()));
} catch (OperatorCreationException | PKCSException e) {
- Log.e(e.getMessage());
+ Log.error(e.getMessage());
}
return condition;
}
diff --git a/cloud/account/src/main/resources/logback.xml b/cloud/account/src/main/resources/logback.xml
new file mode 100644
index 0000000..1ff4a85
--- /dev/null
+++ b/cloud/account/src/main/resources/logback.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <!-- To log coap message payload, include variable %X{coappayload} into pattern -->
+ <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5level | %class{0}.%method:%L | %msg%n</pattern>
+ </encoder>
+ </appender>
+ <root level="trace">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration> \ No newline at end of file
diff --git a/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/account/AccountResourceTest.java b/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/account/AccountResourceTest.java
index 6fbc4f8..1e41894 100644
--- a/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/account/AccountResourceTest.java
+++ b/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/account/AccountResourceTest.java
@@ -56,6 +56,7 @@ import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
@@ -110,15 +111,19 @@ public class AccountResourceTest {
}).when(mMockDevice).sendResponse(Mockito.anyObject());
}
- @After
public void resetAccountDatabase() throws Exception {
MongoDB mongoDB = new MongoDB("127.0.0.1", Constants.DB_NAME);
+ mongoDB.dropTable(Constants.USER_TABLE);
+ mongoDB.dropTable(Constants.TOKEN_TABLE);
+ mongoDB.dropTable(Constants.GROUP_TABLE);
+
mongoDB.createTable(Constants.USER_TABLE);
mongoDB.createTable(Constants.TOKEN_TABLE);
mongoDB.createTable(Constants.GROUP_TABLE);
}
@Test
+ @Ignore("This test require valid oauth token to oauth provider. In case test this scenario. Please provider valid oAuth token")
public void testSignUpOnDefaultRequestReceived() throws Exception {
getTestMethodName();
signUp(DEVICE_ID, mAuthProvider, mAuthCode);
diff --git a/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManagerTest.java b/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManagerTest.java
index bf66e30..71d5bf9 100644
--- a/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManagerTest.java
+++ b/cloud/account/src/test/java/org/iotivity/cloud/accountserver/resources/acl/group/GroupAclManagerTest.java
@@ -14,7 +14,6 @@ import org.iotivity.cloud.accountserver.db.GroupTable;
import org.iotivity.cloud.accountserver.db.MongoDB;
import org.iotivity.cloud.accountserver.resources.acl.id.AclResource;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
-import org.iotivity.cloud.util.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -94,7 +93,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByResourcesOnlyOwner() {
- Log.v("--------------testAddAceByResourcesOnlyOwner------------");
+ System.out.println("--------------testAddAceByResourcesOnlyOwner------------");
// initialize group info --
ArrayList<String> members = new ArrayList<>();
@@ -120,7 +119,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByResources() {
- Log.v("--------------testAddAceByResoruces------------");
+ System.out.println("--------------testAddAceByResoruces------------");
// initialize group info --
ArrayList<String> members = new ArrayList<>();
@@ -172,7 +171,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByResourcesNoMembers() {
- Log.v("--------------testAddAceByResorucesNoMembers------------");
+ System.out.println("--------------testAddAceByResorucesNoMembers------------");
setGroupInfo(mGid1, new HashMap<>());
ArrayList<HashMap<String, Object>> resources = new ArrayList<>();
@@ -190,7 +189,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByDevices() {
- Log.v("--------------testAddAceByDevices------------");
+ System.out.println("--------------testAddAceByDevices------------");
// initialize group info --
ArrayList<String> members = new ArrayList<>();
@@ -227,7 +226,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByDevicesOnlyOwner() {
- Log.v("--------------testAddAceByDevicesOnlyOwner------------");
+ System.out.println("--------------testAddAceByDevicesOnlyOwner------------");
// initialize group info --
ArrayList<String> members = new ArrayList<>();
@@ -253,7 +252,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByDevicesNoMembers() {
- Log.v("--------------testAddAceByDevicesNoMembers------------");
+ System.out.println("--------------testAddAceByDevicesNoMembers------------");
setGroupInfo(mGid1, new HashMap<>());
ArrayList<String> devices = new ArrayList<>();
@@ -270,7 +269,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByMembersWithDevice() {
- Log.v("--------------testAddAceByMembersWithDevice------------");
+ System.out.println("--------------testAddAceByMembersWithDevice------------");
// initialize group info --
ArrayList<String> devices = new ArrayList<>();
@@ -314,7 +313,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByMembersWithDeviceAndResource() {
- Log.v("--------------testAddAceByMembersWithDeviceAndResource------------");
+ System.out.println("--------------testAddAceByMembersWithDeviceAndResource------------");
// initialize group info --
ArrayList<String> devices = new ArrayList<>();
@@ -401,7 +400,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByMembersNoDevice() {
- Log.v("--------------testAddAceByMembersNoDevice------------");
+ System.out.println("--------------testAddAceByMembersNoDevice------------");
setGroupInfo(mGid1, new HashMap<>());
ArrayList<String> members = new ArrayList<>();
@@ -418,7 +417,7 @@ public class GroupAclManagerTest {
@Test
public void testAddAceByMembersOwnerDevice() {
- Log.v("--------------testAddAceByMembersOwnerDevice------------");
+ System.out.println("--------------testAddAceByMembersOwnerDevice------------");
// initialize group info --
ArrayList<String> devices = new ArrayList<>();
@@ -444,7 +443,7 @@ public class GroupAclManagerTest {
@Test
public void testRemoveAceByGroup() {
- Log.v("--------------testRemoveAceByGroup------------");
+ System.out.println("--------------testRemoveAceByGroup------------");
// initialize group info --
ArrayList<String> members = new ArrayList<>();
@@ -513,7 +512,7 @@ public class GroupAclManagerTest {
@Test
public void testRemoveAceByMembers() {
- Log.v("--------------testRemoveAceByMembers------------");
+ System.out.println("--------------testRemoveAceByMembers------------");
// initialize group info --
ArrayList<String> devices = new ArrayList<>();
@@ -573,7 +572,7 @@ public class GroupAclManagerTest {
@Test
public void testRemoveAceByDevices() {
- Log.v("--------------testRemoveAceByDevices------------");
+ System.out.println("--------------testRemoveAceByDevices------------");
// initialize group info --
ArrayList<String> devices = new ArrayList<>();
@@ -653,7 +652,7 @@ public class GroupAclManagerTest {
@Test
public void testRemoveAceByResourcesDeleteAce() {
- Log.v("--------------testRemoveAceByResourcesDeleteAce------------");
+ System.out.println("--------------testRemoveAceByResourcesDeleteAce------------");
// initialize group info --
ArrayList<String> devices = new ArrayList<>();
@@ -774,11 +773,11 @@ public class GroupAclManagerTest {
private boolean checkAclTable(String di, String aceid, String subjectUuid,
List<HashMap<String, Object>> resource) {
- Log.v("--------------checkAclTable : " + di + " ------------");
+ System.out.println("--------------checkAclTable : " + di + " ------------");
HashMap<String, Object> getAclist = AclResource.getInstance()
.getAclACE((String) AclResource.getInstance().getAclid(di)
.get(Constants.KEYFIELD_ACLID), aceid);
- Log.v("check result : " + getAclist);
+ System.out.println("check result : " + getAclist);
if (getAclist.isEmpty()) {
return false;
}
@@ -812,10 +811,10 @@ public class GroupAclManagerTest {
private boolean checkAceTable(HashMap<String, Object> condition,
HashMap<String, Object> key) {
- Log.v("--------------checkAceTable : " + condition.toString()
+ System.out.println("--------------checkAceTable : " + condition.toString()
+ " ------------");
HashMap<String, Object> getAce = getAceTable(condition).get(0);
- Log.v("check result : " + getAce);
+ System.out.println("check result : " + getAce);
if (getAce.isEmpty()) {
return false;
}
diff --git a/cloud/interface/Dockerfile b/cloud/interface/Dockerfile
index 5f06b91..4f012cd 100644
--- a/cloud/interface/Dockerfile
+++ b/cloud/interface/Dockerfile
@@ -8,13 +8,25 @@ WORKDIR iotivity/
ENV COAP_PORT 5683
ENV TLS_MODE 0
ENV KEEPALIVE_CLOUD 1
-ENV HC_PROXY_MODE 0
+ENV HTTP_PROXY_MODE 0
+ENV HTTP_PROXY_PORT 80
ENV WEBSOCKET_MODE 0
ENV RESOURCE_DIRECTORY_ADDRESS iotivity-resourcedirectory
ENV RESOURCE_DIRECTORY_PORT 5684
ENV ACCOUNT_SERVER_ADDRESS iotivity-accountserver
ENV ACCOUNT_SERVER_PORT 5685
-ENV MESSAGE_QUEUE_ADDRESS iotivity-messagequeue
-ENV MESSAGE_QUEUE_PORT 5686
-ENTRYPOINT ["java", "-jar", "CloudInterface.jar"] \ No newline at end of file
+ENV JMX_PORT 9001
+ENV JAVA_JMX_OPTS "-Dcom.sun.management.jmxremote \
+ -Dcom.sun.management.jmxremote.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.local.only=false \
+ -Dcom.sun.management.jmxremote.authenticate=false \
+ -Dcom.sun.management.jmxremote.ssl=false \
+ -Djava.rmi.server.hostname= \
+ -XX:MetaspaceSize=20m -XX:MaxMetaspaceSize=25m \
+ -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -server "
+
+EXPOSE 9001
+
+ENTRYPOINT exec java $JAVA_JMX_OPTS $JAVA_MEMORY_OPTS -jar CloudInterface.jar
diff --git a/cloud/interface/pom.xml b/cloud/interface/pom.xml
index f7d0688..1220d7e 100644
--- a/cloud/interface/pom.xml
+++ b/cloud/interface/pom.xml
@@ -11,6 +11,11 @@
<groupId>org.iotivity.cloud</groupId>
<artifactId>CloudInterface</artifactId>
+ <properties>
+ <docker.image.name>iotivity/interface</docker.image.name>
+ </properties>
+
+
<dependencies>
<!-- Local -->
<dependency>
@@ -78,7 +83,24 @@
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</plugin>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>docker-maven-plugin</artifactId>
+ <version>0.26.0</version>
+ <configuration>
+ <images>
+ <image>
+ <name>${docker.image.name}</name>
+ <build>
+ <dockerFileDir>${project.basedir}</dockerFileDir>
+ <tags>
+ <tag>${docker.image.version}</tag>
+ </tags>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ </plugin>
</plugins>
</build>
-
</project> \ No newline at end of file
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java
index 158b637..4ec1fa4 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/CloudInterfaceServer.java
@@ -24,6 +24,10 @@ package org.iotivity.cloud.ciserver;
import java.net.InetSocketAddress;
import java.util.Scanner;
+import org.iotivity.cloud.ciserver.resources.UpdateDeviceStateListener;
+import org.iotivity.cloud.ciserver.resources.proxy.account.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.connector.ConnectorPool;
import org.iotivity.cloud.base.server.CoapServer;
import org.iotivity.cloud.base.server.HttpServer;
@@ -31,46 +35,36 @@ import org.iotivity.cloud.base.server.WebSocketServer;
import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
import org.iotivity.cloud.ciserver.resources.KeepAliveResource;
import org.iotivity.cloud.ciserver.resources.RouteResource;
-import org.iotivity.cloud.ciserver.resources.proxy.account.Account;
-import org.iotivity.cloud.ciserver.resources.proxy.account.AccountSession;
-import org.iotivity.cloud.ciserver.resources.proxy.account.Acl;
-import org.iotivity.cloud.ciserver.resources.proxy.account.AclGroup;
-import org.iotivity.cloud.ciserver.resources.proxy.account.AclInvite;
-import org.iotivity.cloud.ciserver.resources.proxy.account.Certificate;
-import org.iotivity.cloud.ciserver.resources.proxy.account.Crl;
import org.iotivity.cloud.ciserver.resources.proxy.mq.MessageQueue;
import org.iotivity.cloud.ciserver.resources.proxy.rd.DevicePresence;
import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceDirectory;
import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceFind;
import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourcePresence;
-import org.iotivity.cloud.util.Log;
public class CloudInterfaceServer {
-
- private static int[] deviceKeepAliveMinutes = new int[] { 1, 2, 4, 8 };
- private static int coapServerPort;
- private static boolean tlsMode;
- private static boolean keepAlive = false;
- private static boolean hcProxyMode;
- private static int hcProxyPort;
- private static boolean websocketMode;
- private static int websocketPort;
- private static String resourceDirectoryAddress;
- private static int resourceDirectoryPort;
- private static String accountServerAddress;
- private static int accountServerPort;
- private static String messageQueueAddress;
- private static int messageQueuePort;
- private static String webLogHost;
+ private final static Logger Log = LoggerFactory.getLogger(CloudInterfaceServer.class);
+ private static int[] deviceKeepAliveMinutes = new int[] { 1, 2, 4, 8 };
+ private static int coapServerPort;
+ private static boolean tlsMode;
+ private static boolean keepAlive = false;
+ private static boolean hcProxyMode;
+ private static int hcProxyPort;
+ private static boolean websocketMode;
+ private static int websocketPort;
+ private static String resourceDirectoryAddress;
+ private static int resourceDirectoryPort;
+ private static String accountServerAddress;
+ private static int accountServerPort;
+ private static boolean messageQueueEnabled;
+ private static String messageQueueAddress;
+ private static int messageQueuePort;
public static void main(String[] args) throws Exception {
- System.out.println("-----CI SERVER-------");
- Log.Init();
+ Log.info("Starting Cloud Interface Server");
if (!parseConfiguration(args)) {
- Log.e("\nCoAP-server <Port> RD-server <Address> <Port> Account-server <Address> <Port> MQ-broker <Address> <Port> HC-proxy [HTTP-port] "
- + "Websocket-server <Port> and TLS-mode <0|1> are required. WebSocketLog-Server <Addres> <Port> "
- + "and KeepAlive for cloud components <0|1> are optional.\n"
+ Log.error("\nCoAP-server <Port> RD-server <Address> <Port> Account-server <Address> <Port> MQ-broker <Address> <Port> HC-proxy [HTTP-port] "
+ + "Websocket-server <Port> and TLS-mode <0|1> are required.\n"
+ "ex) " + Constants.DEFAULT_COAP_PORT
+ " 127.0.0.1 " + Constants.DEFAULT_RESOURCE_DIRECTORY_PORT
+ " 127.0.0.1 " + Constants.DEFAULT_ACCOUNT_SERVER_PORT
@@ -79,19 +73,21 @@ public class CloudInterfaceServer {
+ " " + Constants.DEFAULT_WEBSOCKET_PORT + " 0\n");
return;
}
- if (webLogHost != null)
- Log.InitWebLog(webLogHost,
- CloudInterfaceServer.class.getSimpleName().toString());
+ final KeepAliveResource resKeepAlive = new KeepAliveResource(deviceKeepAliveMinutes);
+ final UpdateDeviceStateListener updatePresenceState = new UpdateDeviceStateListener(resKeepAlive);
ConnectorPool.requestConnection("rd",
new InetSocketAddress(resourceDirectoryAddress, resourceDirectoryPort),
- tlsMode, keepAlive);
+ tlsMode, keepAlive, updatePresenceState);
ConnectorPool.requestConnection("account",
new InetSocketAddress(accountServerAddress, accountServerPort),
tlsMode, keepAlive);
- ConnectorPool.requestConnection("mq",
- new InetSocketAddress(messageQueueAddress, messageQueuePort),
- tlsMode, keepAlive);
+
+ if(messageQueueEnabled) {
+ ConnectorPool.requestConnection("mq",
+ new InetSocketAddress(messageQueueAddress, messageQueuePort),
+ tlsMode, keepAlive);
+ }
DeviceServerSystem deviceServer = new DeviceServerSystem();
@@ -109,6 +105,13 @@ public class CloudInterfaceServer {
Crl crlHandler = new Crl();
CoapDevicePool devicePool = deviceServer.getDevicePool();
+ //version 2.0.0
+ SecAccount secAcHandler = new SecAccount();
+ SecAccountSession secAcSessionHandler = new SecAccountSession();
+ deviceServer.addResource(secAcHandler);
+ deviceServer.addResource(secAcSessionHandler);
+
+
deviceServer.addResource(acHandler);
deviceServer.addResource(acSessionHandler);
@@ -133,8 +136,6 @@ public class CloudInterfaceServer {
deviceServer.addResource(crlHandler);
- KeepAliveResource resKeepAlive = new KeepAliveResource(deviceKeepAliveMinutes);
-
deviceServer.addResource(resKeepAlive);
deviceServer.addResource(new RouteResource(devicePool));
@@ -173,7 +174,7 @@ public class CloudInterfaceServer {
private static boolean parseConfiguration(String[] args) {
// configuration provided by arguments
- if (args.length == 10 || args.length == 13) {
+ if (args.length == 10) {
coapServerPort = Integer.parseInt(args[0]);
resourceDirectoryAddress = args[1];
resourceDirectoryPort = Integer.parseInt(args[2]);
@@ -186,10 +187,6 @@ public class CloudInterfaceServer {
websocketPort = Integer.parseInt(args[8]);
websocketMode = websocketPort != 0;
tlsMode = Integer.parseInt(args[9]) == 1;
- if (args.length == 13) {
- webLogHost = args[10] + ":" + args[11];
- keepAlive = Integer.parseInt(args[12]) == 1;
- }
return true;
}
@@ -202,10 +199,8 @@ public class CloudInterfaceServer {
resourceDirectoryPort = Integer.parseInt(System.getenv("RESOURCE_DIRECTORY_PORT"));
accountServerAddress = System.getenv("ACCOUNT_SERVER_ADDRESS");
accountServerPort = Integer.parseInt(System.getenv("ACCOUNT_SERVER_PORT"));
- messageQueueAddress = System.getenv("MESSAGE_QUEUE_ADDRESS");
- messageQueuePort = Integer.parseInt(System.getenv("MESSAGE_QUEUE_PORT"));
- hcProxyMode = Integer.parseInt(System.getenv("HC_PROXY_MODE")) == 1;
- hcProxyPort = Constants.DEFAULT_HC_PROXY_PORT;
+ hcProxyMode = Integer.parseInt(System.getenv("HTTP_PROXY_MODE")) == 1;
+ hcProxyPort = Integer.parseInt(System.getenv("HTTP_PROXY_PORT"));
websocketMode = Integer.parseInt(System.getenv("WEBSOCKET_MODE")) == 1;
websocketPort = Constants.DEFAULT_WEBSOCKET_PORT;
keepAlive = Integer.parseInt(System.getenv("KEEPALIVE_CLOUD")) == 1;
@@ -213,6 +208,14 @@ public class CloudInterfaceServer {
String keepAliveEnv = System.getenv("DEVICE_KEEPALIVE_MINUTES");
if (keepAliveEnv != null && !keepAliveEnv.isEmpty())
deviceKeepAliveMinutes = new int[] { Integer.parseInt(keepAliveEnv) };
+
+ String messageQueueEnv = System.getenv("MESSAGE_QUEUE_ADDRESS");
+ if(messageQueueEnv != null)
+ {
+ messageQueueAddress = System.getenv("MESSAGE_QUEUE_ADDRESS");
+ messageQueuePort = Integer.parseInt(System.getenv("MESSAGE_QUEUE_PORT"));
+ messageQueueEnabled = true;
+ }
return true;
}
return false;
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java
index 59164a4..97a8092 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/Constants.java
@@ -35,7 +35,6 @@ public class Constants extends OICConstants {
public static final String USER_ID = "uid";
public static final String DEVICE_ID = "di";
- public static final String PRESENCE_STATE = "state";
public static final String REQ_LOGIN = "login";
@@ -67,4 +66,11 @@ public class Constants extends OICConstants {
public static final String REQ_LINKS = "links";
public static final String REQ_HREF = "href";
public static final String REQ_CRL = "crl";
+
+
+ /** '/oic/prs' resource property */
+ public static final String PRESENCE_STATE = "state";
+ public static final String PRESENCE_ON = "on";
+ public static final String PRESENCE_LIST = "prslist";
+
}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/DeviceServerSystem.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/DeviceServerSystem.java
index 4bbde23..aaa278d 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/DeviceServerSystem.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/DeviceServerSystem.java
@@ -24,7 +24,10 @@ package org.iotivity.cloud.ciserver;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.OICConstants;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.connector.ConnectorPool;
@@ -51,7 +54,6 @@ import org.iotivity.cloud.base.server.Server;
import org.iotivity.cloud.base.server.WebSocketServer;
import org.iotivity.cloud.util.Bytes;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
@@ -66,10 +68,12 @@ import io.netty.channel.ChannelPromise;
*/
public class DeviceServerSystem extends ServerSystem {
-
+ private final static Logger Log = LoggerFactory.getLogger(DeviceServerSystem.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<HashMap<String, Object>>();
private HashMap<ChannelHandlerContext, CoapSignaling> mCsmMap = new HashMap<>();
+ public static final String LOGOUT_DEVICE = "LOGOUT_DEVICE";
+ public static final String EMPTY_CHANNEL = "EMPTY_CHANNEL";
/**
*
* This class provides a set of APIs to manage device pool.
@@ -194,7 +198,7 @@ public class DeviceServerSystem extends ServerSystem {
}
}
} catch (Throwable t) {
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
ResponseStatus responseStatus = t instanceof ServerException
? ((ServerException) t).getErrorResponse()
: ResponseStatus.INTERNAL_SERVER_ERROR;
@@ -216,9 +220,12 @@ public class DeviceServerSystem extends ServerSystem {
// This is CoapResponse
// Once the response is valid, add this to deviceList
CoapResponse response = (CoapResponse) msg;
+ if (!response.getStatus().isSuccess()) {
+ ctx.writeAndFlush(msg);
+ return;
+ }
String urlPath = response.getUriPath();
-
if (urlPath == null) {
throw new InternalServerErrorException(
"request uriPath is null");
@@ -226,11 +233,16 @@ public class DeviceServerSystem extends ServerSystem {
switch (urlPath) {
case OICConstants.ACCOUNT_SESSION_FULL_URI:
- if (response.getStatus() != ResponseStatus.CHANGED) {
+ case OICConstants.SEC_ACCOUNT_SESSION_FULL_URI:
+ final Device device = ctx.channel()
+ .attr(keyDevice).get();
+ if(device.existParameter(LOGOUT_DEVICE)){
+ Log.debug("Device: {} was logout. ", device.getDeviceId());
bCloseConnection = true;
}
break;
case OICConstants.ACCOUNT_FULL_URI:
+ case OICConstants.SEC_ACCOUNT_FULL_URI:
if (response.getStatus() == ResponseStatus.DELETED) {
bCloseConnection = true;
}
@@ -239,9 +251,8 @@ public class DeviceServerSystem extends ServerSystem {
}
ctx.writeAndFlush(msg);
-
- if (bCloseConnection == true) {
- ctx.close();
+ if (bCloseConnection ) {
+ closeTcpConnection(ctx);
}
}
@@ -249,10 +260,14 @@ public class DeviceServerSystem extends ServerSystem {
public void channelActive(ChannelHandlerContext ctx) {
Device device = ctx.channel().attr(keyDevice).get();
// Authenticated device connected
-
- sendDevicePresence(device.getDeviceId(), "on");
+ Log.debug("Device: {} online", device.getDeviceId());
+ try {
+ sendDevicePresence(device.getDeviceId(), "on");
+ } catch (ServerException.ServiceUnavailableException e) {
+ Log.warn(e.getMessage());
+ ctx.close();
+ }
mDevicePool.addDevice(device);
-
device.onConnected();
}
@@ -265,16 +280,36 @@ public class DeviceServerSystem extends ServerSystem {
// same di.
// So compare actual value, and remove if same.
if (device != null) {
- sendDevicePresence(device.getDeviceId(), "off");
-
- device.onDisconnected();
-
- mDevicePool.removeDevice(device);
- ctx.channel().attr(keyDevice).remove();
-
+ Log.debug("Device: {} offline ", device.getDeviceId());
+ try {
+ if(!device.existParameter(DeviceServerSystem.EMPTY_CHANNEL)){
+ sendDevicePresence(device.getDeviceId(), "off");
+ }
+ } catch (ServerException.ServiceUnavailableException e) {
+ Log.warn(e.getMessage());
+ ctx.close();
+ } finally {
+ device.onDisconnected();
+ mDevicePool.removeDevice(device);
+ ctx.channel().attr(keyDevice).remove();
+ }
}
}
+ private void closeTcpConnection(final ChannelHandlerContext ctx){
+ CompletableFuture.runAsync(()->{
+ try {
+ Thread.sleep(500);
+ final Device device = ctx.channel()
+ .attr(keyDevice).get();
+ Log.info("After sign-out, close channel for device: {}",device.getDeviceId());
+ ctx.close().awaitUninterruptibly();
+ } catch (InterruptedException e) {
+ Log.error("Unable to sleep: ",e);
+ }
+ });
+ }
+
/**
* API for sending state to resource directory
*
@@ -327,14 +362,16 @@ public class DeviceServerSystem extends ServerSystem {
// Once the response is valid, add this to deviceList
CoapResponse response = (CoapResponse) msg;
+ if (!response.getStatus().isSuccess()) {
+ ctx.writeAndFlush(msg);
+ return;
+ }
String urlPath = response.getUriPath();
-
if (urlPath == null) {
throw new InternalServerErrorException(
"request uriPath is null");
}
-
switch (urlPath) {
/*
* case OICConstants.ACCOUNT_FULL_URI:
@@ -342,6 +379,7 @@ public class DeviceServerSystem extends ServerSystem {
*/
case OICConstants.ACCOUNT_SESSION_FULL_URI:
+ case OICConstants.SEC_ACCOUNT_SESSION_FULL_URI:
HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(),
HashMap.class);
@@ -373,7 +411,7 @@ public class DeviceServerSystem extends ServerSystem {
ctx.writeAndFlush(msg);
} catch (Throwable t) {
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
ctx.writeAndFlush(msg);
ctx.close();
}
@@ -400,8 +438,10 @@ public class DeviceServerSystem extends ServerSystem {
switch (urlPath) {
// Check whether request is about account
case OICConstants.ACCOUNT_FULL_URI:
- case OICConstants.ACCOUNT_TOKENREFRESH_FULL_URI:
+ case OICConstants.SEC_ACCOUNT_FULL_URI:
+ case OICConstants.ACCOUNT_TOKENREFRESH_FULL_URI:
+ case OICConstants.SEC_ACCOUNT_TOKENREFRESH_FULL_URI:
if (ctx.channel().attr(keyDevice).get() == null) {
// Create device first and pass to upperlayer
Device device = new CoapDevice(ctx);
@@ -411,7 +451,7 @@ public class DeviceServerSystem extends ServerSystem {
break;
case OICConstants.ACCOUNT_SESSION_FULL_URI:
-
+ case OICConstants.SEC_ACCOUNT_SESSION_FULL_URI:
HashMap<String, Object> authPayload = mCbor
.parsePayloadFromCbor(request.getPayload(),
HashMap.class);
@@ -452,7 +492,7 @@ public class DeviceServerSystem extends ServerSystem {
: ResponseStatus.UNAUTHORIZED;
ctx.writeAndFlush(MessageBuilder
.createResponse((CoapRequest) msg, responseStatus));
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
}
}
}
@@ -552,7 +592,7 @@ public class DeviceServerSystem extends ServerSystem {
ctx.writeAndFlush(MessageBuilder.createSignalingResponse(
(CoapSignaling) msg, responseStatus));
}
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
}
}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DevicePresenter.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DevicePresenter.java
new file mode 100644
index 0000000..2de38af
--- /dev/null
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DevicePresenter.java
@@ -0,0 +1,12 @@
+package org.iotivity.cloud.ciserver.resources;
+
+import java.util.Set;
+
+/**
+ * Component for selecting actively connected devices to cloud
+ */
+public interface DevicePresenter {
+
+ Set<String> getDeviceIds();
+
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java
index 9503358..087a301 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/KeepAliveResource.java
@@ -21,14 +21,8 @@
*/
package org.iotivity.cloud.ciserver.resources;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
+import java.util.*;
+import java.util.stream.Collectors;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
@@ -39,8 +33,12 @@ import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
+import org.iotivity.cloud.ciserver.CloudInterfaceServer;
import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.ciserver.DeviceServerSystem;
import org.iotivity.cloud.util.Cbor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
@@ -48,7 +46,8 @@ import org.iotivity.cloud.util.Cbor;
* connection.
*
*/
-public class KeepAliveResource extends Resource {
+public class KeepAliveResource extends Resource implements DevicePresenter {
+ private final static Logger Log = LoggerFactory.getLogger(KeepAliveResource.class);
private int[] mIntervals = null;
private Timer mTimer = new Timer();
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
@@ -123,6 +122,16 @@ public class KeepAliveResource extends Resource {
return MessageBuilder.createResponse(request, ResponseStatus.VALID);
}
+
+ @Override
+ public Set<String> getDeviceIds() {
+ Map<Device, Long> map = Collections
+ .synchronizedMap(mConnectionPool);
+ synchronized (map){
+ return new HashSet<>(map.keySet().stream().map(device -> device.getDeviceId()).collect(Collectors.toSet()));
+ }
+ }
+
/**
* API for managing session
*/
@@ -134,22 +143,43 @@ public class KeepAliveResource extends Resource {
.synchronizedMap(mConnectionPool);
List<Device> deleteList = new ArrayList<>();
-
- synchronized (map) {
- Long currentTime = System.currentTimeMillis();
- for (Device device : map.keySet()) {
- Long lifeTime = (Long) map.get(device);
- if (lifeTime != null && lifeTime < currentTime) {
- deleteList.add(device);
+ try {
+ synchronized (map) {
+ Long currentTime = System.currentTimeMillis();
+ for (Device device : map.keySet()) {
+ Long lifeTime = (Long) map.get(device);
+ if (lifeTime != null && lifeTime < currentTime) {
+ deleteList.add(device);
+ }
+ }
+ for(final Device device : deleteList){
+ final List<Device> samedevice = map.keySet().stream().filter(d -> filter(d,device)).collect(Collectors.toList());
+ if(device != null && samedevice != null && samedevice.size() > 0){
+ Log.info("Channel for device: {} is empty", device.getDeviceId());
+ device.setParameter(DeviceServerSystem.EMPTY_CHANNEL,true);
+ }
}
}
- }
- for (Device device : deleteList) {
- mConnectionPool.remove(device);
- device.getCtx().fireChannelInactive();
- device.getCtx().close();
+ for (Device device : deleteList) {
+ mConnectionPool.remove(device);
+ device.getCtx().fireChannelInactive();
+ device.getCtx().close();
+ }
+ } catch (final Exception e){
+ Log.error("Unable to remove not responding device", e);
+ }
+ }
+
+ private boolean filter(final Device listDevice, final Device device){
+ if(listDevice == null || listDevice.getDeviceId() == null || device == null || device.getDeviceId() == null){
+ return false;
+ }
+ if(listDevice.getCtx() == null && listDevice.getCtx().channel() == null && device.getCtx() == null && device.getCtx().channel() == null){
+ return false;
}
+ return listDevice.getDeviceId().compareTo(device.getDeviceId()) == 0
+ && listDevice.getCtx().channel().id().asLongText().compareTo(device.getCtx().channel().id().asLongText()) != 0;
}
}
}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/UpdateDeviceStateListener.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/UpdateDeviceStateListener.java
new file mode 100644
index 0000000..ca78c4d
--- /dev/null
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/UpdateDeviceStateListener.java
@@ -0,0 +1,57 @@
+package org.iotivity.cloud.ciserver.resources;
+
+import org.iotivity.cloud.base.connector.ConnectionEstablishedListener;
+import org.iotivity.cloud.base.connector.ConnectorPool;
+import org.iotivity.cloud.base.device.IRequestChannel;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.protocols.enums.RequestMethod;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.util.Cbor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class UpdateDeviceStateListener implements ConnectionEstablishedListener {
+
+ private final static Logger Log = LoggerFactory.getLogger(UpdateDeviceStateListener.class);
+
+ private final DevicePresenter devicePresenter;
+
+ public UpdateDeviceStateListener(DevicePresenter devicePresenter) {
+ this.devicePresenter = devicePresenter;
+ }
+
+ @Override
+ public void onConnectionEstablished(IRequestChannel requestChannel) {
+
+ final Set<String> deviceIds = devicePresenter.getDeviceIds().stream()
+ .filter(Objects::nonNull).collect(Collectors.toSet());
+ if(deviceIds == null || deviceIds.size() == 0){
+ return;
+ }
+ Log.debug("RD is connected. Update presence table of actually connected device");
+ Cbor<HashMap<String, Object>> cbor = new Cbor<>();
+ HashMap<String, Object> payload = new HashMap<String, Object>();
+ List<Map<String,Object>> devicePresenceList = new LinkedList<>();
+ payload.put(Constants.PRESENCE_LIST, devicePresenceList);
+ deviceIds.stream().forEach(deviceId -> {
+ final HashMap<String, Object> deviceStatusRecord = new HashMap<>();
+ deviceStatusRecord.put(Constants.DEVICE_ID, deviceId);
+ deviceStatusRecord.put(Constants.PRESENCE_STATE, Constants.PRESENCE_ON);
+ devicePresenceList.add(deviceStatusRecord);
+ });
+
+ Log.debug("Payload for presence update: {} ", payload);
+ StringBuffer uriPath = new StringBuffer();
+ uriPath.append("/" + Constants.PREFIX_OIC);
+ uriPath.append("/" + Constants.DEVICE_PRESENCE_URI);
+ requestChannel.sendRequest(MessageBuilder.createRequest(
+ RequestMethod.PUT, uriPath.toString(), null,
+ ContentFormat.APPLICATION_CBOR,
+ cbor.encodingPayloadToCbor(payload)), null);
+ Log.debug("Presence table of RD successfully updated");
+ }
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/Account.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/Account.java
index 1d40572..c1ba728 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/Account.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/Account.java
@@ -22,6 +22,7 @@
package org.iotivity.cloud.ciserver.resources.proxy.account;
import java.util.Arrays;
+import java.util.List;
import org.iotivity.cloud.base.connector.ConnectorPool;
import org.iotivity.cloud.base.device.Device;
@@ -49,6 +50,10 @@ public class Account extends Resource {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.ACCOUNT_URI));
}
+ public Account(List<String> pathSegments) {
+ super(pathSegments);
+ }
+
class RDReceiveHandler implements IResponseEventHandler {
private Device mSrcDevice;
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSession.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSession.java
index f3d36bb..8165c57 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSession.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSession.java
@@ -23,6 +23,7 @@ package org.iotivity.cloud.ciserver.resources.proxy.account;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import org.iotivity.cloud.base.connector.ConnectorPool;
import org.iotivity.cloud.base.device.Device;
@@ -33,6 +34,7 @@ import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.ciserver.DeviceServerSystem;
import org.iotivity.cloud.util.Cbor;
/**
@@ -49,6 +51,10 @@ public class AccountSession extends Resource {
Constants.SESSION_URI));
}
+ public AccountSession(List<String> pathSegments) {
+ super(pathSegments);
+ }
+
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
@@ -67,6 +73,11 @@ public class AccountSession extends Resource {
request = MessageBuilder.modifyRequest(request, null, uriQuery,
ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(payloadData));
+ srcDevice.setParameter(DeviceServerSystem.LOGOUT_DEVICE,true);
+ }
+ if (!ConnectorPool.containConnection("rd")) {
+ // connection is required for proper presence state configuration
+ throw new ServerException.ServiceUnavailableException("Required connection to resource directory is not available");
}
ConnectorPool.getConnection("account").sendRequest(request, srcDevice);
}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccount.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccount.java
new file mode 100644
index 0000000..0ab9f44
--- /dev/null
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccount.java
@@ -0,0 +1,40 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.cloud.ciserver.resources.proxy.account;
+
+import org.iotivity.cloud.ciserver.Constants;
+
+import java.util.Arrays;
+
+/**
+ *
+ * This class provides a set of APIs to send requests about account to account. Version 2.0.0
+ *
+ */
+
+public class SecAccount extends Account {
+
+ public SecAccount() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.SEC_URI, Constants.ACCOUNT_URI));
+ }
+
+}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccountSession.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccountSession.java
new file mode 100644
index 0000000..800ad00
--- /dev/null
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/account/SecAccountSession.java
@@ -0,0 +1,50 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.cloud.ciserver.resources.proxy.account;
+
+import org.iotivity.cloud.base.connector.ConnectorPool;
+import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.resource.Resource;
+import org.iotivity.cloud.ciserver.Constants;
+import org.iotivity.cloud.ciserver.DeviceServerSystem;
+import org.iotivity.cloud.util.Cbor;
+
+import java.util.Arrays;
+import java.util.HashMap;
+
+/**
+ *
+ * This class provides a set of APIs to send requests about session to account. Version 2.0.0
+ *
+ */
+
+public class SecAccountSession extends AccountSession {
+
+ public SecAccountSession() {
+ super(Arrays.asList(Constants.PREFIX_OIC, Constants.SEC_URI,
+ Constants.SESSION_URI));
+ }
+} \ No newline at end of file
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresence.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresence.java
index ab74400..4209878 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresence.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresence.java
@@ -95,8 +95,13 @@ public class DevicePresence extends Resource {
+ (mRequest.getUriQuery() != null
? (";" + mRequest.getUriQuery())
: "");
- mRequest = MessageBuilder.modifyRequest(mRequest,
- null, uriQuery, null, null);
+ if(mRequest.getUriQueryMap() != null && mRequest.getUriQueryMap().containsKey(Constants.DEVICE_ID)){
+ mRequest = MessageBuilder.modifyRequest(mRequest,
+ null, uriQuery, null, null);
+ }else {
+ mRequest = MessageBuilder.modifyRequest(mRequest,
+ null, null, null, null);
+ }
}
}
diff --git a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectory.java b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectory.java
index 2f066c7..9cdd239 100644
--- a/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectory.java
+++ b/cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectory.java
@@ -40,6 +40,7 @@ import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
import org.iotivity.cloud.util.Cbor;
+import org.slf4j.LoggerFactory;
/**
*
@@ -50,6 +51,7 @@ import org.iotivity.cloud.util.Cbor;
public class ResourceDirectory extends Resource {
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private final static org.slf4j.Logger Log = LoggerFactory.getLogger(ResourceDirectory.class);
public ResourceDirectory() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.RD_URI));
@@ -83,8 +85,9 @@ public class ResourceDirectory extends Resource {
query.toString(), ContentFormat.APPLICATION_CBOR,
mCbor.encodingPayloadToCbor(requestPayload));
+ IRequestChannel resourceDirectoryConnection = ConnectorPool.getConnection("rd");
ConnectorPool.getConnection("account").sendRequest(requestToAS,
- new AccountReceiveHandler(request, srcDevice));
+ new AccountReceiveHandler(resourceDirectoryConnection, request, srcDevice));
break;
case DELETE:
@@ -98,10 +101,12 @@ public class ResourceDirectory extends Resource {
}
class AccountReceiveHandler implements IResponseEventHandler {
+ private IRequestChannel resourceDirectoryConnection;
private Device mSrcDevice;
private IRequest mRequest;
- public AccountReceiveHandler(IRequest request, Device srcDevice) {
+ public AccountReceiveHandler(IRequestChannel resourceDirectoryConnection, IRequest request, Device srcDevice) {
+ this.resourceDirectoryConnection = resourceDirectoryConnection;
mSrcDevice = srcDevice;
mRequest = request;
}
@@ -119,7 +124,7 @@ public class ResourceDirectory extends Resource {
null, ContentFormat.APPLICATION_CBOR,
convertedPayload);
- ConnectorPool.getConnection("rd").sendRequest(mRequest,
+ resourceDirectoryConnection.sendRequest(mRequest,
new PublishResponseHandler(mSrcDevice));
break;
diff --git a/cloud/interface/src/main/resources/logback.xml b/cloud/interface/src/main/resources/logback.xml
new file mode 100644
index 0000000..9f4a48c
--- /dev/null
+++ b/cloud/interface/src/main/resources/logback.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <!-- To log coap message payload, include variable %X{coappayload} into pattern -->
+ <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5level | %class{0}.%method:%L | %msg%n</pattern>
+ </encoder>
+ </appender>
+ <root level="trace">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/DeviceServerSystemTest.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/DeviceServerSystemTest.java
index 05523da..12857b1 100644
--- a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/DeviceServerSystemTest.java
+++ b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/DeviceServerSystemTest.java
@@ -56,7 +56,6 @@ import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceDirectory;
import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceFind;
import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourcePresence;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -108,7 +107,6 @@ public class DeviceServerSystemTest {
@Before
public void setUp() throws Exception {
- Log.createfile();
MockitoAnnotations.initMocks(this);
mRes = null;
mReq = null;
diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSessionTest.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSessionTest.java
index ebc1d37..c91c2c5 100644
--- a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSessionTest.java
+++ b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/account/AccountSessionTest.java
@@ -66,8 +66,9 @@ public class AccountSessionTest {
private ConnectorPool mConnectorPool = null;
private DeviceServerSystem mDeviceServerSystem = new DeviceServerSystem();
private final CountDownLatch mLatch = new CountDownLatch(1);
- @Mock
- private IRequestChannel mRequestChannel;
+
+ @Mock(name = "mASServer")
+ IRequestChannel mRequestChannelASServer;
@InjectMocks
private AccountSession mAcSessionHandler = new AccountSession();
@@ -98,11 +99,12 @@ public class AccountSessionTest {
"\t---------uriquery : " + request.getUriQuery());
return null;
}
- }).when(mRequestChannel).sendRequest(Mockito.any(IRequest.class),
+ }).when(mRequestChannelASServer).sendRequest(Mockito.any(IRequest.class),
Mockito.any(CoapDevice.class));
PowerMockito.mockStatic(ConnectorPool.class);
- PowerMockito.when(ConnectorPool.getConnection(Mockito.anyString())).thenReturn(mRequestChannel);
+ PowerMockito.when(ConnectorPool.getConnection("account")).thenReturn(mRequestChannelASServer);
+ PowerMockito.when(ConnectorPool.containConnection(Mockito.anyString())).thenReturn(true);
}
@Test
diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java
index d68c536..40fc6b1 100644
--- a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java
+++ b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/DevicePresenceTest.java
@@ -136,9 +136,6 @@ public class DevicePresenceTest {
EntireDeviceHandler.onResponseReceived(response);
HashMap<String, List<String>> queryMap = mReq.getUriQueryMap();
assertTrue(mReq.getMethod() == RequestMethod.GET);
- assertTrue(queryMap.get("di").contains("device1"));
- assertTrue(queryMap.get("di").contains("device2"));
- assertTrue(queryMap.get("di").contains("device3"));
assertTrue(mReq.getObserve() == Observe.SUBSCRIBE);
}
diff --git a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectoryTest.java b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectoryTest.java
index 08a5ac4..62bb487 100644
--- a/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectoryTest.java
+++ b/cloud/interface/src/test/java/org/iotivity/cloud/ciserver/resources/proxy/rd/ResourceDirectoryTest.java
@@ -157,7 +157,7 @@ public class ResourceDirectoryTest {
@Test
public void testRDResourcePublishOnResponseReceived() throws Exception {
- ResourceDirectory.AccountReceiveHandler accountReceiveHandler = mRdHandler.new AccountReceiveHandler(
+ ResourceDirectory.AccountReceiveHandler accountReceiveHandler = mRdHandler.new AccountReceiveHandler(ConnectorPool.getConnection("rd"),
rdPublishRequest, mMockDevice);
IRequest request = makeResourcePublishRequest();
@@ -171,7 +171,7 @@ public class ResourceDirectoryTest {
@Test
public void testRDResourcePublishPayloadConverted() throws Exception {
- ResourceDirectory.AccountReceiveHandler accountReceiveHandler = mRdHandler.new AccountReceiveHandler(
+ ResourceDirectory.AccountReceiveHandler accountReceiveHandler = mRdHandler.new AccountReceiveHandler(ConnectorPool.getConnection("rd"),
rdPublishRequest, mMockDevice);
IRequest request = makeResourcePublishRequest();
diff --git a/cloud/messagequeue/Dockerfile b/cloud/messagequeue/Dockerfile
index 61e4818..25823cd 100644
--- a/cloud/messagequeue/Dockerfile
+++ b/cloud/messagequeue/Dockerfile
@@ -12,4 +12,17 @@ ENV ZOOKEEPER_PORT 2181
ENV KAFKA_ADDRESS kafka-zookeeper
ENV KAFKA_PORT 9092
-ENTRYPOINT ["java", "-jar", "MessageQueue.jar"] \ No newline at end of file
+ENV JMX_PORT 9003
+ENV JAVA_JMX_OPTS "-Dcom.sun.management.jmxremote \
+ -Dcom.sun.management.jmxremote.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.local.only=false \
+ -Dcom.sun.management.jmxremote.authenticate=false \
+ -Dcom.sun.management.jmxremote.ssl=false \
+ -Djava.rmi.server.hostname= \
+ -XX:MetaspaceSize=20m -XX:MaxMetaspaceSize=25m \
+ -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -server "
+
+EXPOSE 9003
+
+ENTRYPOINT exec java $JAVA_JMX_OPTS $JAVA_MEMORY_OPTS -jar MessageQueue.jar
diff --git a/cloud/messagequeue/pom.xml b/cloud/messagequeue/pom.xml
index 3a63f1e..1d0434f 100644
--- a/cloud/messagequeue/pom.xml
+++ b/cloud/messagequeue/pom.xml
@@ -11,6 +11,9 @@
<groupId>org.iotivity.cloud</groupId>
<artifactId>CloudMessageQueue</artifactId>
+ <properties>
+ <docker.image.name>iotivity/messagequeue</docker.image.name>
+ </properties>
<dependencies>
<dependency>
@@ -65,7 +68,24 @@
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</plugin>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>docker-maven-plugin</artifactId>
+ <version>0.26.0</version>
+ <configuration>
+ <images>
+ <image>
+ <name>${docker.image.name}</name>
+ <build>
+ <dockerFileDir>${project.basedir}</dockerFileDir>
+ <tags>
+ <tag>${docker.image.version}</tag>
+ </tags>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ </plugin>
</plugins>
</build>
-
</project> \ No newline at end of file
diff --git a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueServer.java b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueServer.java
index 3b1fac1..b6e9d99 100644
--- a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueServer.java
+++ b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueServer.java
@@ -24,34 +24,29 @@ package org.iotivity.cloud.mqserver;
import java.net.InetSocketAddress;
import java.util.Scanner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.resource.CloudPingResource;
import org.iotivity.cloud.base.server.CoapServer;
import org.iotivity.cloud.mqserver.resources.MQBrokerResource;
-import org.iotivity.cloud.util.Log;
public class MessageQueueServer {
-
- private static int coapServerPort;
- private static boolean tlsMode;
- private static String zookeeperHost;
- private static String kafkaHost;
- private static String webLogHost;
+ private final static Logger Log = LoggerFactory.getLogger(MessageQueueServer.class);
+ private static int coapServerPort;
+ private static boolean tlsMode;
+ private static String zookeeperHost;
+ private static String kafkaHost;
public static void main(String[] args) throws Exception {
- System.out.println("-----MQ SERVER-----");
- Log.Init();
+ Log.info("Starting Message Queue Server");
if (!parseConfiguration(args)) {
- Log.e("\nCoAP-server <Port> Zookeeper <Address> <Port> Kafka <Address> <Port> TLS-mode <0|1> are required. "
- + "WebSocketLog-Server <Addres> <Port> is optional.\n"
+ Log.error("\nCoAP-server <Port> Zookeeper <Address> <Port> Kafka <Address> <Port> TLS-mode <0|1> are required.\n"
+ "ex) " + Constants.DEFAULT_COAP_PORT
+ " 127.0.0.1 2181 127.0.0.1 9092 0\n");
return;
}
- if (webLogHost != null)
- Log.InitWebLog(webLogHost,
- MessageQueueServer.class.getSimpleName().toString());
ServerSystem serverSystem = new ServerSystem();
@@ -83,13 +78,11 @@ public class MessageQueueServer {
private static boolean parseConfiguration(String[] args) {
// configuration provided by arguments
- if (args.length == 6 || args.length == 8) {
+ if (args.length == 6) {
coapServerPort = Integer.parseInt(args[0]);
zookeeperHost = args[1] + ":" + args[2];
kafkaHost = args[3] + ":" + args[4];
tlsMode = Integer.parseInt(args[5]) == 1;
- if (args.length == 8)
- webLogHost = args[6] + ":" + args[7];
return true;
}
// configuration provided by docker env
diff --git a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueUtils.java b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueUtils.java
index 052bc14..150ea1f 100644
--- a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueUtils.java
+++ b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/MessageQueueUtils.java
@@ -23,8 +23,9 @@ package org.iotivity.cloud.mqserver;
import java.util.HashMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -32,6 +33,7 @@ import org.iotivity.cloud.util.Log;
*
*/
public class MessageQueueUtils {
+ private final static Logger Log = LoggerFactory.getLogger(MessageQueueUtils.class);
/**
* API to get data in the payload with specific property key
@@ -46,7 +48,7 @@ public class MessageQueueUtils {
public static <T> T extractDataFromPayload(byte[] payload, String key) {
if (payload == null || key.isEmpty()) {
- Log.e("payload or key is empty");
+ Log.error("payload or key is empty");
return null;
}
@@ -56,7 +58,7 @@ public class MessageQueueUtils {
parsedData = cbor.parsePayloadFromCbor(payload, HashMap.class);
if (parsedData == null || parsedData.containsKey(key) == false) {
- Log.e("payload doesn't contain " + key + " information");
+ Log.error("payload doesn't contain " + key + " information");
return null;
}
diff --git a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaCommonWrapper.java b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaCommonWrapper.java
index dfc9458..f699a24 100644
--- a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaCommonWrapper.java
+++ b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaCommonWrapper.java
@@ -29,8 +29,9 @@ import kafka.utils.ZkUtils;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.mqserver.Constants;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -38,9 +39,9 @@ import org.iotivity.cloud.util.Log;
*
*/
public class KafkaCommonWrapper {
-
- private ZkClient mZkClient = null;
- private ZkUtils mZkUtils = null;
+ private final static Logger Log = LoggerFactory.getLogger(KafkaCommonWrapper.class);
+ private ZkClient mZkClient = null;
+ private ZkUtils mZkUtils = null;
public KafkaCommonWrapper(String zookeeperAddress, String brokerAddress) {
@@ -63,7 +64,7 @@ public class KafkaCommonWrapper {
*/
public boolean createTopic(String topic) {
- Log.d("kafka createTopic - " + topic);
+ Log.debug("kafka createTopic - " + topic);
topic = topic.replace('/', '.');
@@ -89,7 +90,7 @@ public class KafkaCommonWrapper {
*/
public boolean deleteTopic(String topic) {
- Log.d("kafka deleteTopic - " + topic);
+ Log.debug("kafka deleteTopic - " + topic);
topic = topic.replace('/', '.');
diff --git a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaConsumerWrapper.java b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaConsumerWrapper.java
index 1ff5224..f688300 100644
--- a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaConsumerWrapper.java
+++ b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaConsumerWrapper.java
@@ -32,9 +32,10 @@ import java.util.concurrent.Executors;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.mqserver.Constants;
import org.iotivity.cloud.mqserver.topic.Topic;
-import org.iotivity.cloud.util.Log;
import kafka.admin.AdminUtils;
import kafka.api.FetchRequest;
@@ -61,21 +62,21 @@ import kafka.utils.ZkUtils;
*
*/
public class KafkaConsumerWrapper {
+ private final static Logger Log = LoggerFactory.getLogger(KafkaConsumerWrapper.class);
+ private String mTopicName = null;
- private String mTopicName = null;
+ private String mZookeeper = null;
+ private String mBroker = null;
- private String mZookeeper = null;
- private String mBroker = null;
+ private ZkClient mZkClient = null;
+ private ZkUtils mZkUtils = null;
- private ZkClient mZkClient = null;
- private ZkUtils mZkUtils = null;
+ private ConsumerConnector mConsumerConnector = null;
+ private ExecutorService mConsumerExecutor = null;
- private ConsumerConnector mConsumerConnector = null;
- private ExecutorService mConsumerExecutor = null;
+ private Topic mInternalConsumer = null;
- private Topic mInternalConsumer = null;
-
- private boolean mConsumerStarted = false;
+ private boolean mConsumerStarted = false;
public KafkaConsumerWrapper(String zookeeperAddress, String brokerAddress,
Topic consumer) {
@@ -111,7 +112,7 @@ public class KafkaConsumerWrapper {
*/
public boolean subscribeTopic() {
- Log.d("kafka subscribeTopic - " + mTopicName);
+ Log.debug("kafka subscribeTopic - " + mTopicName);
if (mConsumerStarted == true) {
return true;
@@ -144,7 +145,7 @@ public class KafkaConsumerWrapper {
for (final KafkaStream<byte[], byte[]> stream : streams) {
- Log.d("kafka subscribe complete");
+ Log.debug("kafka subscribe complete");
mConsumerExecutor.execute(new Runnable() {
@@ -172,7 +173,7 @@ public class KafkaConsumerWrapper {
*/
public boolean unsubscribeTopic() {
- Log.d("kafka unsubscribeTopic - " + mTopicName);
+ Log.debug("kafka unsubscribeTopic - " + mTopicName);
// remove consumer group info in zookeeper
List<String> subscribers = mZkClient
@@ -210,13 +211,13 @@ public class KafkaConsumerWrapper {
*/
public ArrayList<byte[]> getMessages() {
- Log.d("kafka get all messages - " + mTopicName);
+ Log.debug("kafka get all messages - " + mTopicName);
String brokerHost = mBroker.substring(0, mBroker.indexOf(':'));
int brokerPort = Integer
.parseInt(mBroker.substring(mBroker.indexOf(':') + 1));
- Log.d("host " + brokerHost + ", port " + brokerPort);
+ Log.debug("host " + brokerHost + ", port " + brokerPort);
// TODO check options - Timeout: Int, bufferSize: Int
SimpleConsumer simpleConsumer = new SimpleConsumer(brokerHost,
@@ -233,7 +234,7 @@ public class KafkaConsumerWrapper {
if (fetchResponse == null || fetchResponse.hasError()) {
- Log.e("Error fetching data from the Broker");
+ Log.error("Error fetching data from the Broker");
return null;
}
@@ -247,7 +248,7 @@ public class KafkaConsumerWrapper {
long currentOffset = messageAndOffset.offset();
if (currentOffset < lastOffset) {
- Log.e("Found an old offset: " + currentOffset
+ Log.error("Found an old offset: " + currentOffset
+ " Expecting: " + lastOffset);
continue;
}
@@ -266,7 +267,7 @@ public class KafkaConsumerWrapper {
simpleConsumer.close();
- Log.d("kafka get all messages complete");
+ Log.debug("kafka get all messages complete");
return initialData;
}
@@ -301,7 +302,7 @@ public class KafkaConsumerWrapper {
OffsetResponse response = consumer.getOffsetsBefore(request);
if (response == null || response.hasError()) {
- Log.e("Error fetching data Offset Data the Broker");
+ Log.error("Error fetching data Offset Data the Broker");
return 0;
}
diff --git a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaProducerWrapper.java b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaProducerWrapper.java
index 164baf9..cf9d7d8 100644
--- a/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaProducerWrapper.java
+++ b/cloud/messagequeue/src/main/java/org/iotivity/cloud/mqserver/kafka/KafkaProducerWrapper.java
@@ -26,7 +26,8 @@ import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
-import org.iotivity.cloud.util.Log;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
@@ -35,7 +36,7 @@ import org.iotivity.cloud.util.Log;
*
*/
public class KafkaProducerWrapper {
-
+ private final static Logger Log = LoggerFactory.getLogger(KafkaProducerWrapper.class);
private String mTopicName = null;
private String mBroker = null;
@@ -61,7 +62,7 @@ public class KafkaProducerWrapper {
*/
public boolean publishMessage(byte[] message) {
- Log.d("kafka publishMessage - " + mTopicName);
+ Log.debug("kafka publishMessage - " + mTopicName);
ProducerRecord<byte[], byte[]> record = new ProducerRecord<>(
mTopicName, message);
diff --git a/cloud/messagequeue/src/main/resources/logback.xml b/cloud/messagequeue/src/main/resources/logback.xml
new file mode 100644
index 0000000..9f4a48c
--- /dev/null
+++ b/cloud/messagequeue/src/main/resources/logback.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <!-- To log coap message payload, include variable %X{coappayload} into pattern -->
+ <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5level | %class{0}.%method:%L | %msg%n</pattern>
+ </encoder>
+ </appender>
+ <root level="trace">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
diff --git a/cloud/messagequeue/src/test/java/org/iotivity/cloud/mqserver/resources/MQBrokerResourceTest.java b/cloud/messagequeue/src/test/java/org/iotivity/cloud/mqserver/resources/MQBrokerResourceTest.java
index 24f4392..9cd6dda 100644
--- a/cloud/messagequeue/src/test/java/org/iotivity/cloud/mqserver/resources/MQBrokerResourceTest.java
+++ b/cloud/messagequeue/src/test/java/org/iotivity/cloud/mqserver/resources/MQBrokerResourceTest.java
@@ -115,7 +115,11 @@ public class MQBrokerResourceTest {
String[] arr = { "--topic", topic };
TopicCommandOptions opts = new TopicCommandOptions(arr);
- TopicCommand.deleteTopic(zkUtils, opts);
+ try {
+ TopicCommand.deleteTopic(zkUtils, opts);
+ }catch (final Exception e){
+ e.printStackTrace();
+ }
zkClient.close();
zkUtils.close();
diff --git a/cloud/pom.xml b/cloud/pom.xml
index d1c12cd..cbbd2be 100644
--- a/cloud/pom.xml
+++ b/cloud/pom.xml
@@ -16,6 +16,10 @@
</modules>
<properties>
+
+ <!-- docker image version . In case of changes use mvn -Ddocker.image.version=1.3-20 -->
+ <docker.image.version>latest</docker.image.version>
+
<!-- Common configuration properties -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.source>1.8</java.source>
@@ -120,7 +124,7 @@
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
- <version>3.2.0</version>
+ <version>3.6.2</version>
</dependency>
@@ -199,13 +203,6 @@
<version>1.0.1</version>
</dependency>
- <!-- Logging -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
-
<!-- Testing -->
<dependency>
<groupId>junit</groupId>
@@ -244,18 +241,6 @@
<scope>test</scope>
</dependency>
- <!-- Plugins -->
- <!-- Not necessary -->
- <!--<dependency>-->
- <!--<groupId>org.apache.maven.plugins</groupId>-->
- <!--<artifactId>maven-resources-plugin</artifactId>-->
- <!--<version>2.4.3</version>-->
- <!--</dependency>-->
- <!--<dependency>-->
- <!--<groupId>org.apache.maven.plugins</groupId>-->
- <!--<artifactId>maven-compiler-plugin</artifactId>-->
- <!--<version>3.1</version>-->
- <!--</dependency>-->
</dependencies>
</dependencyManagement>
diff --git a/cloud/resourcedirectory/Dockerfile b/cloud/resourcedirectory/Dockerfile
index d778ea4..1fddd08 100644
--- a/cloud/resourcedirectory/Dockerfile
+++ b/cloud/resourcedirectory/Dockerfile
@@ -1,13 +1,32 @@
FROM openjdk:8-jre-alpine
+RUN apk add --update \
+ curl \
+ && rm -rf /var/cache/apk/*
+
ADD ./target/CloudResourceDirectory-0.0.1-SNAPSHOT.jar iotivity/ResourceDirectory.jar
ADD ./target/lib/* iotivity/lib/
WORKDIR iotivity/
ENV COAP_PORT 5684
+ENV HEALTH_CHECK_ENABLED 1
ENV TLS_MODE 0
ENV MONGODB_ADDRESS mongodb
ENV MONGODB_PORT 27017
-ENTRYPOINT ["java", "-jar", "ResourceDirectory.jar"] \ No newline at end of file
+ENV JMX_PORT 9004
+ENV JAVA_JMX_OPTS "-Dcom.sun.management.jmxremote \
+ -Dcom.sun.management.jmxremote.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT} \
+ -Dcom.sun.management.jmxremote.local.only=false \
+ -Dcom.sun.management.jmxremote.authenticate=false \
+ -Dcom.sun.management.jmxremote.ssl=false \
+ -Djava.rmi.server.hostname= \
+ -XX:MetaspaceSize=20m -XX:MaxMetaspaceSize=25m \
+ -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -server "
+
+EXPOSE 9004
+
+ENTRYPOINT exec java $JAVA_JMX_OPTS $JAVA_MEMORY_OPTS -jar ResourceDirectory.jar
+HEALTHCHECK --interval=30s --timeout=2s --retries=3 CMD curl -f http://localhost/api/healthcheck || exit 1
diff --git a/cloud/resourcedirectory/pom.xml b/cloud/resourcedirectory/pom.xml
index 5d6a28f..e5974c7 100644
--- a/cloud/resourcedirectory/pom.xml
+++ b/cloud/resourcedirectory/pom.xml
@@ -11,6 +11,11 @@
<groupId>org.iotivity.cloud</groupId>
<artifactId>CloudResourceDirectory</artifactId>
+
+ <properties>
+ <docker.image.name>iotivity/resourcedirectory</docker.image.name>
+ </properties>
+
<dependencies>
<!-- Local -->
<dependency>
@@ -81,7 +86,24 @@
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</plugin>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>docker-maven-plugin</artifactId>
+ <version>0.26.0</version>
+ <configuration>
+ <images>
+ <image>
+ <name>${docker.image.name}</name>
+ <build>
+ <dockerFileDir>${project.basedir}</dockerFileDir>
+ <tags>
+ <tag>${docker.image.version}</tag>
+ </tags>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ </plugin>
</plugins>
</build>
-
</project> \ No newline at end of file
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java
index 5667694..0f99c35 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/ResourceDirectoryServer.java
@@ -23,7 +23,13 @@ package org.iotivity.cloud.rdserver;
import java.net.InetSocketAddress;
import java.util.Scanner;
+import java.util.concurrent.TimeUnit;
+import org.iotivity.cloud.base.healthcheck.HealthHolder;
+import org.iotivity.cloud.base.healthcheck.SimpleHealthHolder;
+import org.iotivity.cloud.base.server.SimpleHttpServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.resource.CloudPingResource;
import org.iotivity.cloud.base.server.CoapServer;
@@ -32,7 +38,6 @@ import org.iotivity.cloud.rdserver.resources.directory.rd.ResourceDirectoryResou
import org.iotivity.cloud.rdserver.resources.directory.res.DiscoveryResource;
import org.iotivity.cloud.rdserver.resources.presence.device.DevicePresenceResource;
import org.iotivity.cloud.rdserver.resources.presence.resource.ResPresenceResource;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -40,31 +45,26 @@ import org.iotivity.cloud.util.Log;
*
*/
public class ResourceDirectoryServer {
-
- private static int coapServerPort;
- private static boolean tlsMode;
- private static String databaseHost;
- private static String webLogHost;
+ private final static Logger Log = LoggerFactory.getLogger(ResourceDirectoryServer.class);
+ private static int coapServerPort;
+ private static boolean tlsMode;
+ private static String databaseHost;
+ private static boolean healthCheckEnabled;
public static void main(String[] args) throws Exception {
- System.out.println("-----RD SERVER-----");
- Log.Init();
+ Log.info("Starting Resource Directory Server");
if (!parseConfiguration(args)) {
- Log.e("\nCoAP-server <Port> Database <Address> <Port> TLS-mode <0|1> are required. WebSocketLog-Server <Addres> <Port> is optional.\n"
+ Log.error("\nCoAP-server <Port> Database <Address> <Port> TLS-mode <0|1> are required.\n"
+ "ex) " + Constants.DEFAULT_COAP_PORT
+ " 127.0.0.1 27017 0\n");
return;
}
- if (webLogHost != null)
- Log.InitWebLog(webLogHost,
- ResourceDirectoryServer.class.getSimpleName().toString());
DBManager.createInstance(databaseHost);
-
+ HealthHolder healthHolder = new SimpleHealthHolder(TimeUnit.SECONDS,100);
ServerSystem serverSystem = new ServerSystem();
-
- serverSystem.addResource(new CloudPingResource());
+ serverSystem.addResource(new CloudPingResource(healthHolder));
serverSystem.addResource(new ResourceDirectoryResource());
serverSystem.addResource(new DiscoveryResource());
serverSystem.addResource(new DevicePresenceResource());
@@ -73,6 +73,10 @@ public class ResourceDirectoryServer {
serverSystem.addServer(
new CoapServer(new InetSocketAddress(coapServerPort)));
+ if(healthCheckEnabled){
+ serverSystem.addServer(new SimpleHttpServer(new InetSocketAddress(80),healthHolder));
+ }
+
serverSystem.startSystem(tlsMode);
Scanner in = new Scanner(System.in);
@@ -92,12 +96,11 @@ public class ResourceDirectoryServer {
private static boolean parseConfiguration(String[] args) {
// configuration provided by arguments
- if (args.length == 4 || args.length == 6) {
+ if (args.length == 4) {
coapServerPort = Integer.parseInt(args[0]);
databaseHost = args[1] + ":" + args[2];
tlsMode = Integer.parseInt(args[3]) == 1;
- if (args.length == 6)
- webLogHost = args[4] + ":" + args[5];
+ healthCheckEnabled = false;
return true;
}
// configuration provided by docker env
@@ -107,6 +110,7 @@ public class ResourceDirectoryServer {
databaseHost = System.getenv("MONGODB_ADDRESS") + ":"
+ System.getenv("MONGODB_PORT");
tlsMode = Integer.parseInt(tlsModeEnv) == 1;
+ healthCheckEnabled = Integer.parseInt(System.getenv("HEALTH_CHECK_ENABLED")) == 1;
return true;
}
return false;
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java
index a28f519..be3b567 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/DBManager.java
@@ -31,6 +31,8 @@ import java.util.Set;
import org.bson.Document;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.rdserver.Constants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
@@ -39,6 +41,8 @@ import org.iotivity.cloud.rdserver.Constants;
*/
public class DBManager {
+ private final static Logger Log = LoggerFactory.getLogger(DBManager.class);
+
private static DBManager mDBManager;
private MongoDB mMongoDB = null;
private HashMap<String, ArrayList<String>> mKeyField = new HashMap<>();
@@ -83,6 +87,7 @@ public class DBManager {
private void createTables() {
mMongoDB.createTable(Constants.RD_TABLE);
mMongoDB.createTable(Constants.PRESENCE_TABLE);
+ updatePresenceTable();
}
private void createIndexes() {
@@ -102,6 +107,30 @@ public class DBManager {
}
+ private void updatePresenceTable(){
+ Log.debug("Start update presence table. Update all devices to offline state");
+ final HashMap<String,Object> emptyCondition = new HashMap<>();
+ final HashMap<String,Object> updateEntry = new HashMap<>();
+ final HashMap<String,Object> stateUpdate = new HashMap<>();
+ stateUpdate.put(Constants.PRESENCE_STATE, Constants.PRESENCE_OFF);
+ updateEntry.put("$set",stateUpdate);
+ selectAndUpdate(Constants.PRESENCE_TABLE, emptyCondition, updateEntry);
+ Log.debug("Presence table was successfully updated");
+ }
+
+ /**
+ * API for selecting specific record and update in one operation
+ *
+ * @param tableName - table name to be updated
+ * @param condition - condition to match record
+ * @param update - data to be updated
+ */
+ public void selectAndUpdate(final String tableName, final HashMap<String, Object> condition, final HashMap<String, Object> update){
+ if (!_selectAndUpdate(tableName, condition, update))
+ throw new InternalServerErrorException(
+ "Database record insert failed");
+ }
+
/**
* API for inserting a record into DB table. the record will not be inserted
* if duplicated one.
@@ -213,6 +242,13 @@ public class DBManager {
}
+ private Boolean _selectAndUpdate(final String tableName, final HashMap<String, Object> condition, final HashMap<String, Object> update) {
+
+ final Document updateDoc = createDocument(update);
+ final Document filterDoc = createDocument(condition);
+ return mMongoDB.updateMany(tableName, filterDoc, updateDoc);
+ }
+
private Boolean _insertRecord(String tableName,
HashMap<String, Object> record) {
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java
index 8955edc..50e566c 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/db/MongoDB.java
@@ -28,8 +28,9 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.bson.Document;
-import org.iotivity.cloud.util.Log;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
@@ -43,7 +44,7 @@ import com.mongodb.client.model.IndexOptions;
*
*/
public class MongoDB {
-
+ private final static Logger Log = LoggerFactory.getLogger(MongoDB.class);
private MongoClient mongoClient = null;
private MongoDatabase db = null;
@@ -57,9 +58,7 @@ public class MongoDB {
* @throws Exception
*/
public MongoDB(String host, String dbname) throws Exception {
-
mongoClient = new MongoClient(host);
- mongoClient.dropDatabase(dbname);
db = mongoClient.getDatabase(dbname);
}
@@ -70,8 +69,37 @@ public class MongoDB {
* collection name
*/
public void createTable(String tableName) {
+ if (!collectionExists(tableName))
+ db.createCollection(tableName);
+ }
+
+ private boolean collectionExists(String tableName ) {
+ return db.listCollectionNames().into(new ArrayList<>()).contains(tableName);
+ }
+
+ /**
+ * API for dropping collection
+ *
+ * @param tableName
+ * collection name
+ */
+ public void dropTable(String tableName) {
+ if (collectionExists(tableName))
+ db.getCollection(tableName).drop();
+ }
- db.createCollection(tableName);
+ public boolean updateMany(final String tableName, final Document filter, final Document update){
+
+ if (tableName == null || filter == null || update == null)
+ return false;
+ final MongoCollection<Document> collection = db.getCollection(tableName);
+ try {
+ collection.updateMany(filter,update);
+ return true;
+ } catch (Exception e) {
+ Log.error("Error update many record", e);
+ return false;
+ }
}
/**
@@ -141,7 +169,7 @@ public class MongoDB {
} else {
- Log.w("DB insert failed due to duplecated one.");
+ Log.warn("DB insert failed due to duplecated one.");
return false;
}
@@ -151,8 +179,6 @@ public class MongoDB {
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -190,8 +216,6 @@ public class MongoDB {
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -217,12 +241,10 @@ public class MongoDB {
if (collection.findOneAndReplace(filter, record) == null) {
- Log.w("DB update failed due to no matched record!");
+ Log.warn("DB update failed due to no matched record!");
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -253,8 +275,6 @@ public class MongoDB {
return false;
}
- showRecord(tableName);
-
return true;
}
@@ -315,25 +335,4 @@ public class MongoDB {
return resourceMap;
}
-
- private void showRecord(String tableName) {
-
- MongoCollection<Document> collection = db.getCollection(tableName);
- MongoCursor<Document> cursor = collection.find().iterator();
-
- Log.i("<" + tableName + ">");
-
- HashMap<String, Object> records = null;
- int index = 0;
- while (cursor.hasNext()) {
-
- Document doc = cursor.next();
- records = convertDocumentToHashMap(doc);
-
- Log.i("[" + index + "] " + records.toString());
- index++;
- }
-
- cursor.close();
- }
}
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java
index 92f30d2..4212a83 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/RDManager.java
@@ -21,31 +21,38 @@
*/
package org.iotivity.cloud.rdserver.resources.directory;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.rdserver.Constants;
import org.iotivity.cloud.rdserver.db.DBManager;
import org.iotivity.cloud.rdserver.resources.directory.rd.InsManager;
-import org.iotivity.cloud.util.Log;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+import java.util.stream.Collectors;
/**
- *
+ *
* This class provides a set of APIs handle requests about resource information
*
*/
public class RDManager {
-
+ private final static Logger Log = LoggerFactory.getLogger(RDManager.class);
private InsManager mInsManager = new InsManager();
private PayloadManager mPayloadManager = new PayloadManager();
private ArrayList<HashMap<String, Object>> mResourcePresence = new ArrayList<>();
+ private static final RDManager INSTANCE = new RDManager();
+
+ public static RDManager getInstance(){
+ return INSTANCE;
+ }
+
+
/**
* API for handling resource-publish process
- *
+ *
* @param requestPayload
* request payload
* @return response payload
@@ -81,7 +88,7 @@ public class RDManager {
}
private void storeResource(ArrayList<HashMap<String, Object>> links,
- HashMap<String, Object> deviceInfo) {
+ HashMap<String, Object> deviceInfo) {
ArrayList<HashMap<String, Object>> resourcePresence = new ArrayList<>();
@@ -116,7 +123,7 @@ public class RDManager {
}
private void setResourceIns(String di,
- ArrayList<HashMap<String, Object>> links) {
+ ArrayList<HashMap<String, Object>> links) {
for (HashMap<String, Object> link : links) {
String href = link.get(Constants.HREF).toString();
@@ -148,10 +155,10 @@ public class RDManager {
/**
* API for handling resource-delete process
- *
+ *
* @param di
* device id
- * @param ins
+ * @param insList
* unique id of resource
*/
public void deleteResource(String di, List<String> insList) {
@@ -194,7 +201,7 @@ public class RDManager {
/**
* API for handling resource-discover process
- *
+ *
* @param diList
* list of device id
* @param rtList
@@ -204,9 +211,7 @@ public class RDManager {
* @return response payload
*/
public ArrayList<Object> discoverResource(List<String> diList,
- List<String> rtList, List<String> ifList) {
-
- HashMap<String, Object> condition = new HashMap<>();
+ List<String> rtList, List<String> ifList) {
ArrayList<Object> response = new ArrayList<>();
@@ -214,86 +219,76 @@ public class RDManager {
return response;
}
- if (rtList == null && ifList == null) {
- readResource(diList, condition, response);
+ final List<String> diFiltered = filterDeviceByStatus(diList);
+ if(diFiltered == null || diFiltered.size() == 0){
+ return response;
}
+ final HashMap<String,Object> conditions = new HashMap<>();
+ conditions.put("di",buildInQuery(diFiltered));
- if (rtList != null) {
- for (String rt : rtList) {
- condition.put(Constants.RESOURCE_TYPE, rt);
- readResource(diList, condition, response);
- }
+ if(rtList != null && rtList.size() > 0){
+ conditions.put("rt",buildInQuery(rtList));
}
- if (ifList != null) {
- for (String itf : ifList) {
- condition.put(Constants.INTERFACE, itf);
- readResource(diList, condition, response);
- }
+ if(ifList != null && ifList.size() > 0){
+ conditions.put("if",buildInQuery(rtList));
}
- Log.d("discovery payload : " + response);
+ readResource(conditions,response);
+
+ Log.debug("discovery payload : " + response);
return response;
}
- private void readResource(List<String> diList,
+ private void readResource(
HashMap<String, Object> condition, ArrayList<Object> response) {
- ArrayList<String> onDiList = getPresenceOnDevices(diList);
-
- for (String di : onDiList) {
- condition.put(Constants.DEVICE_ID, di);
- ArrayList<HashMap<String, Object>> records = DBManager.getInstance()
- .selectRecord(Constants.RD_TABLE, condition);
-
- if (!records.isEmpty()) {
- response.add(makeDiscoverResponseSegment(records));
- }
-
+ ArrayList<HashMap<String, Object>> records = DBManager.getInstance()
+ .selectRecord(Constants.RD_TABLE, condition);
+ if (!records.isEmpty()) {
+ response.addAll(makeDiscoverResponseSegment(records));
}
}
- private ArrayList<String> getPresenceOnDevices(List<String> diList) {
- ArrayList<String> onDiList = new ArrayList<>();
- HashMap<String, Object> condition = new HashMap<>();
-
- for (String di : diList) {
- condition.put(Constants.DEVICE_ID, di);
- HashMap<String, Object> record = DBManager.getInstance()
- .selectOneRecord(Constants.PRESENCE_TABLE, condition);
-
- if (!record.isEmpty() && record.get(Constants.PRESENCE_STATE)
- .equals(Constants.PRESENCE_ON)) {
- onDiList.add(di);
- }
+ private List<String> filterDeviceByStatus(final List<String> diList){
+ final HashMap<String,Object> query = new HashMap<>();
+ if(diList != null && diList.size() > 0){
+ query.put("di",buildInQuery(diList));
}
- return onDiList;
+ query.put("state",Constants.PRESENCE_ON);
+ ArrayList<HashMap<String, Object>> records = DBManager.getInstance()
+ .selectRecord(Constants.PRESENCE_TABLE, query);
+ return records.stream().map(record -> (String)record.get("di")).collect(Collectors.toList());
}
- private HashMap<String, Object> makeDiscoverResponseSegment(
+ private Collection<HashMap<String, Object>> makeDiscoverResponseSegment(
ArrayList<HashMap<String, Object>> records) {
- HashMap<String, Object> responseSegment = new HashMap<>();
-
- // make Tags
- HashMap<String, Object> discoverTag = mPayloadManager
- .setPayloadData(records.get(0), mPayloadManager.discoverTagKey);
- responseSegment.putAll(discoverTag);
-
- ArrayList<Object> links = new ArrayList<>();
- // make links
- for (HashMap<String, Object> record : records) {
- HashMap<String, Object> link = mPayloadManager
+ final Map<String, HashMap<String, Object>> result = new HashMap<>();
+ for (final HashMap<String, Object> record : records) {
+ final String di = (String) record.get(Constants.DEVICE_ID);
+ ArrayList<Object> links;
+ if (!result.containsKey(record.get(Constants.DEVICE_ID))) {
+ final HashMap<String, Object> discovered = createDevice(record);
+ result.put(di, discovered);
+ links = (ArrayList<Object>) discovered.get(Constants.LINKS);
+ } else {
+ links = (ArrayList<Object>) result.get(di).get(Constants.LINKS);
+ }
+ HashMap<String, Object> discoveredLinks = mPayloadManager
.setPayloadData(record, mPayloadManager.discoverLinkKey);
- mPayloadManager.changePolicyTypeToDiscover(link);
- links.add(link);
+ mPayloadManager.changePolicyTypeToDiscover(discoveredLinks);
+ links.add(discoveredLinks);
}
- responseSegment.put(Constants.LINKS, links);
-
- return responseSegment;
+ return result.values();
+ }
+ private HashMap<String,Object> createDevice(final HashMap<String, Object> record){
+ HashMap<String, Object> discoverTag = mPayloadManager.setPayloadData(record, mPayloadManager.discoverTagKey);
+ discoverTag.put(Constants.LINKS, new ArrayList<>());
+ return discoverTag;
}
private void setmResourcePresence(
@@ -303,11 +298,18 @@ public class RDManager {
/**
* API for getting resource information to notify
- *
+ *
* @return resource information
*/
public ArrayList<HashMap<String, Object>> getmResourcePresence() {
return mResourcePresence;
}
+
+ private <T extends Object> HashMap<String,Object> buildInQuery(final Collection<T> items){
+ final HashMap<String,Object> query = new HashMap<>();
+ query.put("$in",items);
+ return query;
+ }
+
} \ No newline at end of file
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java
index ce4877a..d09052e 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/directory/rd/ResourceDirectoryResource.java
@@ -26,6 +26,8 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
@@ -40,7 +42,6 @@ import org.iotivity.cloud.rdserver.Constants;
import org.iotivity.cloud.rdserver.resources.directory.RDManager;
import org.iotivity.cloud.rdserver.resources.presence.PresenceManager;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
/**
*
@@ -48,7 +49,7 @@ import org.iotivity.cloud.util.Log;
*
*/
public class ResourceDirectoryResource extends Resource {
-
+ private final static Logger Log = LoggerFactory.getLogger(ResourceDirectoryResource.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
private RDManager mRdManager = new RDManager();
@@ -104,7 +105,7 @@ public class ResourceDirectoryResource extends Resource {
HashMap<String, Object> payload = mCbor
.parsePayloadFromCbor(request.getPayload(), HashMap.class);
- Log.d("publish payload : " + payload);
+ Log.debug("publish payload : " + payload);
checkPayloadException(
Arrays.asList(Constants.DEVICE_ID, Constants.LINKS), payload);
@@ -114,7 +115,7 @@ public class ResourceDirectoryResource extends Resource {
HashMap<String, Object> response = mRdManager.publishResource(payload);
- Log.d("publish response : " + response);
+ Log.debug("publish response : " + response);
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED,
ContentFormat.APPLICATION_CBOR,
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java
index 5bb321f..9e4cae9 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/PresenceManager.java
@@ -22,11 +22,12 @@
package org.iotivity.cloud.rdserver.resources.presence;
import java.io.ByteArrayOutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
+import java.util.*;
+import org.bson.Document;
+import org.iotivity.cloud.rdserver.resources.directory.RDManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.base.protocols.IRequest;
@@ -36,7 +37,6 @@ import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.rdserver.Constants;
import org.iotivity.cloud.rdserver.db.DBManager;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
@@ -49,6 +49,7 @@ import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
*
*/
public class PresenceManager {
+ private final static Logger Log = LoggerFactory.getLogger(PresenceManager.class);
private static PresenceManager mPresenceManager = new PresenceManager();
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
@@ -63,7 +64,7 @@ public class PresenceManager {
public IRequest mRequest;
}
- private static class PresenceInfo {
+ private class PresenceInfo {
PresenceInfo() {
mSubscriber = new HashMap<>();
@@ -72,18 +73,117 @@ public class PresenceManager {
}
// di , token, Subscriber list
- private HashMap<String, HashMap<String, PresenceSubscriber>> mSubscriber;
+ protected HashMap<String, HashMap<String, PresenceSubscriber>> mSubscriber;
// token, di list
- private HashMap<String, List<String>> mSubscribedDevices;
- private HashMap<String, Long> mSequenceNumber;
+ protected HashMap<String, List<String>> mSubscribedDevices;
+ protected HashMap<String, Long> mSequenceNumber;
+
+
+ public void subscribe(Device srcDevice, IRequest request,
+ List<String> deviceIdList){
+ for (String deviceId : deviceIdList) {
+ HashMap<String, PresenceSubscriber> subscribers = mSubscriber
+ .get(deviceId);
+
+ if (subscribers == null) {
+ subscribers = new HashMap<>();
+ mSubscriber.put(deviceId, subscribers);
+ }
+
+ subscribers.put(request.getRequestId(),
+ new PresenceSubscriber(srcDevice, request));
+ }
+
+ mSubscribedDevices.put(request.getRequestId(),
+ deviceIdList);
+ mSequenceNumber.put(request.getRequestId(), (long) 1);
+ }
+
+ public void unSubscribe(IRequest request, List<String> deviceIdList) {
+
+ for (String deviceId : deviceIdList) {
+ HashMap<String, PresenceSubscriber> subscribers = mSubscriber
+ .get(deviceId);
+
+ if (subscribers == null) {
+ continue;
+ }
+
+ subscribers.remove(request.getRequestId());
+ }
+ }
+
+ public void notify(String deviceId) {
+
+ HashMap<String, PresenceSubscriber> tokenNSubscribers = mSubscriber
+ .get(deviceId);
+
+ if (tokenNSubscribers != null) {
+ byte[] payload = makeResponsePayload(Arrays.asList(deviceId));
+
+ for (PresenceSubscriber subscriber : tokenNSubscribers.values()) {
+
+ subscriber.mSubscriber.sendResponse(
+ MessageBuilder.createResponse(subscriber.mRequest,
+ ResponseStatus.CONTENT,
+ ContentFormat.APPLICATION_CBOR, payload));
+ }
+ }
+ }
+
+ }
+
+ private class CompletePresenceInfo extends PresenceInfo {
+
+ // di , token, Subscriber list
+ private Map<String, PresenceSubscriber> mAllSubscribers;
+
+ public CompletePresenceInfo() {
+ super();
+ this.mAllSubscribers = new HashMap<>();
+ }
+
+ @Override
+ public void subscribe(Device srcDevice, IRequest request, List<String> deviceIdList) {
+ if(deviceIdList != null && deviceIdList.size() > 0){
+ super.subscribe(srcDevice,request,deviceIdList);
+ }else {
+ mAllSubscribers.put(request.getRequestId(),
+ new PresenceSubscriber(srcDevice, request));
+ mSequenceNumber.put(request.getRequestId(), (long) 1);
+ }
+ }
+
+ @Override
+ public void unSubscribe(IRequest request, List<String> deviceIdList) {
+ if (deviceIdList != null && deviceIdList.size() > 0) {
+ super.unSubscribe(request, deviceIdList);
+ } else {
+ mAllSubscribers.remove(request.getRequestId());
+ }
+ }
+
+ @Override
+ public void notify(String deviceId) {
+
+ byte[] payload = makeResponsePayload(Arrays.asList(deviceId));
+ for (PresenceSubscriber subscriber : this.mAllSubscribers.values()) {
+ subscriber.mSubscriber.sendResponse(
+ MessageBuilder.createResponse(subscriber.mRequest,
+ ResponseStatus.CONTENT,
+ ContentFormat.APPLICATION_CBOR, payload));
+ }
+ }
}
private PresenceInfo mDevicePresence = null;
+ private PresenceInfo mAllDevicePresence = null;
private PresenceInfo mResourcePresence = null;
private PresenceManager() {
mDevicePresence = new PresenceInfo();
mResourcePresence = new PresenceInfo();
+ mAllDevicePresence = new CompletePresenceInfo();
}
/**
@@ -110,24 +210,8 @@ public class PresenceManager {
public void subscribePresence(Device srcDevice, IRequest request,
List<String> deviceIdList, String presenceType) {
- PresenceInfo presenceInfo = getPresenceInfo(presenceType);
-
- for (String deviceId : deviceIdList) {
- HashMap<String, PresenceSubscriber> subscribers = presenceInfo.mSubscriber
- .get(deviceId);
-
- if (subscribers == null) {
- subscribers = new HashMap<>();
- presenceInfo.mSubscriber.put(deviceId, subscribers);
- }
-
- subscribers.put(request.getRequestId(),
- new PresenceSubscriber(srcDevice, request));
- }
-
- presenceInfo.mSubscribedDevices.put(request.getRequestId(),
- deviceIdList);
- presenceInfo.mSequenceNumber.put(request.getRequestId(), (long) 1);
+ PresenceInfo presenceInfo = getPresenceInfo(presenceType,deviceIdList);
+ presenceInfo.subscribe(srcDevice,request,deviceIdList);
}
/**
@@ -143,18 +227,8 @@ public class PresenceManager {
public void unsubscribePresence(IRequest request, List<String> deviceIdList,
String presenceType) {
- PresenceInfo presenceInfo = getPresenceInfo(presenceType);
-
- for (String deviceId : deviceIdList) {
- HashMap<String, PresenceSubscriber> subscribers = presenceInfo.mSubscriber
- .get(deviceId);
-
- if (subscribers == null) {
- continue;
- }
-
- subscribers.remove(request.getRequestId());
- }
+ PresenceInfo presenceInfo = getPresenceInfo(presenceType,deviceIdList);
+ presenceInfo.unSubscribe(request,deviceIdList);
}
/**
@@ -164,21 +238,8 @@ public class PresenceManager {
* device id
*/
public void notifyToObservers(String deviceId) {
-
- HashMap<String, PresenceSubscriber> tokenNSubscribers = mDevicePresence.mSubscriber
- .get(deviceId);
-
- if (tokenNSubscribers != null) {
- byte[] payload = makeResponsePayload(Arrays.asList(deviceId));
-
- for (PresenceSubscriber subscriber : tokenNSubscribers.values()) {
-
- subscriber.mSubscriber.sendResponse(
- MessageBuilder.createResponse(subscriber.mRequest,
- ResponseStatus.CONTENT,
- ContentFormat.APPLICATION_CBOR, payload));
- }
- }
+ this.mDevicePresence.notify(deviceId);
+ this.mAllDevicePresence.notify(deviceId);
}
/**
@@ -209,7 +270,7 @@ public class PresenceManager {
prsList.add(payloadSegment);
}
getPayload.put(Constants.PRESENCE_LIST, prsList);
- Log.i("Device presence observe response : " + getPayload.toString());
+ Log.info("Device presence observe response : " + getPayload.toString());
return mCbor.encodingPayloadToCbor(getPayload);
@@ -233,12 +294,16 @@ public class PresenceManager {
return state;
}
- private PresenceInfo getPresenceInfo(String presenceType) {
+ private PresenceInfo getPresenceInfo(String presenceType,final List<String> deviceIds) {
PresenceInfo presenceInfo = null;
switch (presenceType) {
case Constants.DEVICE_PRESENCE:
- presenceInfo = mDevicePresence;
+ if(deviceIds == null || deviceIds.size() == 0){
+ presenceInfo = mAllDevicePresence;
+ }else {
+ presenceInfo = mDevicePresence;
+ }
break;
case Constants.RESOURCE_PRESENCE:
presenceInfo = mResourcePresence;
diff --git a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java
index fe4556f..56ce332 100644
--- a/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java
+++ b/cloud/resourcedirectory/src/main/java/org/iotivity/cloud/rdserver/resources/presence/device/DevicePresenceResource.java
@@ -21,9 +21,7 @@
*/
package org.iotivity.cloud.rdserver.resources.presence.device;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
+import java.util.*;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
@@ -35,8 +33,11 @@ import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.rdserver.Constants;
+import org.iotivity.cloud.rdserver.resources.directory.rd.ResourceDirectoryResource;
import org.iotivity.cloud.rdserver.resources.presence.PresenceManager;
import org.iotivity.cloud.util.Cbor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
@@ -45,6 +46,7 @@ import org.iotivity.cloud.util.Cbor;
*/
public class DevicePresenceResource extends Resource {
+ private final static Logger Log = LoggerFactory.getLogger(DevicePresenceResource.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
public DevicePresenceResource() {
@@ -68,6 +70,10 @@ public class DevicePresenceResource extends Resource {
response = handlePostRequest(request);
break;
+ case PUT:
+ response = handlePutRequest(request);
+ break;
+
default:
throw new BadRequestException(
request.getMethod() + " request type is not supported");
@@ -80,9 +86,11 @@ public class DevicePresenceResource extends Resource {
throws ServerException {
HashMap<String, List<String>> queryMap = request.getUriQueryMap();
- checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap);
-
- List<String> deviceList = queryMap.get(Constants.DEVICE_ID);
+// checkQueryException(Arrays.asList(Constants.DEVICE_ID), queryMap);
+ List<String> deviceList = new LinkedList<>();
+ if(queryMap != null){
+ deviceList.addAll(queryMap.getOrDefault(Constants.DEVICE_ID,new ArrayList<>()));
+ }
switch (request.getObserve()) {
case SUBSCRIBE:
@@ -116,7 +124,6 @@ public class DevicePresenceResource extends Resource {
Arrays.asList(Constants.DEVICE_ID, Constants.PRESENCE_STATE),
parsedPayload);
- // store db
PresenceManager.getInstance().updateDevicePresence(parsedPayload);
// notification to observers
@@ -126,4 +133,29 @@ public class DevicePresenceResource extends Resource {
return MessageBuilder.createResponse(request, ResponseStatus.CHANGED);
}
+
+ private IResponse handlePutRequest(IRequest request)
+ throws ServerException {
+ // check payload
+ byte[] payload = request.getPayload();
+ Log.debug("Update presence table");
+ HashMap<String, Object> parsedPayload = mCbor
+ .parsePayloadFromCbor(payload, HashMap.class);
+
+ checkPayloadException(
+ Arrays.asList(Constants.PRESENCE_LIST),
+ parsedPayload);
+ ArrayList<HashMap<String, String>> prsList = (ArrayList<HashMap<String, String>>) parsedPayload
+ .get(Constants.PRESENCE_LIST);
+
+ for(final Map<String,String> record: prsList) {
+ // store db
+ Log.debug("Update device presence state: {}", record);
+ PresenceManager.getInstance().updateDevicePresence(new HashMap<>(record));
+ }
+
+ return MessageBuilder.createResponse(request, ResponseStatus.CHANGED);
+
+ }
+
}
diff --git a/cloud/resourcedirectory/src/main/resources/logback.xml b/cloud/resourcedirectory/src/main/resources/logback.xml
new file mode 100644
index 0000000..9f4a48c
--- /dev/null
+++ b/cloud/resourcedirectory/src/main/resources/logback.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+ <!-- To log coap message payload, include variable %X{coappayload} into pattern -->
+ <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5level | %class{0}.%method:%L | %msg%n</pattern>
+ </encoder>
+ </appender>
+ <root level="trace">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java
index 1e60ce6..9c97d8f 100644
--- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java
+++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DevicePresenceResourceTest.java
@@ -58,6 +58,7 @@ public class DevicePresenceResourceTest {
@Before
public void setUp() throws Exception {
+ RDServerTestUtils.createRDDatabase();
mResponse = null;
mMockDevice = mock(CoapDevice.class);
mLatch = new CountDownLatch(1);
@@ -77,7 +78,7 @@ public class DevicePresenceResourceTest {
@After
public void tearDown() throws Exception {
- RDServerTestUtils.resetRDDatabase();
+ RDServerTestUtils.dropRDDatabase();
}
private IRequest makePresenceGetRequest(Observe obs) {
diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java
index 68b03f3..5582a25 100644
--- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java
+++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/DiscoveryResourceTest.java
@@ -58,6 +58,7 @@ public class DiscoveryResourceTest {
@Before
public void setUp() throws Exception {
+ RDServerTestUtils.createRDDatabase();
mResponse = null;
mockDevice = mock(CoapDevice.class);
mLatch = new CountDownLatch(1);
@@ -78,7 +79,7 @@ public class DiscoveryResourceTest {
@After
public void tearDown() throws Exception {
- RDServerTestUtils.resetRDDatabase();
+ RDServerTestUtils.dropRDDatabase();
}
@Test
diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java
index efbc44e..087c5c8 100644
--- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java
+++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/RDServerTestUtils.java
@@ -47,9 +47,15 @@ public class RDServerTestUtils {
return request;
}
- public static void resetRDDatabase() throws Exception {
+ public static void createRDDatabase() throws Exception {
MongoDB mongoDB = new MongoDB("127.0.0.1", Constants.RD_DB_NAME);
mongoDB.createTable(Constants.RD_TABLE);
mongoDB.createTable(Constants.PRESENCE_TABLE);
}
+
+ public static void dropRDDatabase() throws Exception {
+ MongoDB mongoDB = new MongoDB("127.0.0.1", Constants.RD_DB_NAME);
+ mongoDB.dropTable(Constants.RD_TABLE);
+ mongoDB.dropTable(Constants.PRESENCE_TABLE);
+ }
}
diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java
index 8acc787..a8210b3 100644
--- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java
+++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourceDirectoryResourceTest.java
@@ -54,6 +54,7 @@ public class ResourceDirectoryResourceTest {
@Before
public void setUp() throws Exception {
+ RDServerTestUtils.createRDDatabase();
mResponse = null;
mockDevice = mock(CoapDevice.class);
mLatch = new CountDownLatch(1);
@@ -73,7 +74,7 @@ public class ResourceDirectoryResourceTest {
@After
public void tearDown() throws Exception {
- RDServerTestUtils.resetRDDatabase();
+ RDServerTestUtils.dropRDDatabase();
}
@Test
diff --git a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java
index d2773fa..b0a7826 100644
--- a/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java
+++ b/cloud/resourcedirectory/src/test/java/org/iotivity/cloud/testrdserver/ResourcePresenceResourceTest.java
@@ -52,6 +52,7 @@ public class ResourcePresenceResourceTest {
@Before
public void setUp() throws Exception {
+ RDServerTestUtils.createRDDatabase();
mRDResource = new ResourceDirectoryResource();
mResPresenceResource = new ResPresenceResource();
mResponse = null;
@@ -72,7 +73,7 @@ public class ResourcePresenceResourceTest {
@After
public void tearDown() throws Exception {
- RDServerTestUtils.resetRDDatabase();
+ RDServerTestUtils.dropRDDatabase();
}
@Test
diff --git a/cloud/stack/pom.xml b/cloud/stack/pom.xml
index 8bf46ce..340fae4 100644
--- a/cloud/stack/pom.xml
+++ b/cloud/stack/pom.xml
@@ -63,8 +63,14 @@
<!-- Logging -->
<dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <version>1.2.3</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jul-to-slf4j</artifactId>
+ <version>1.7.25</version>
</dependency>
<!-- Testing -->
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/OICConstants.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/OICConstants.java
index f230829..b62b6a4 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/OICConstants.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/OICConstants.java
@@ -53,6 +53,7 @@ public class OICConstants {
public static final String CERT_URI = "cert";
+ public static final String SEC_URI = "sec";
/* resource url for acl */
public static final String ACL_URI = "acl";
@@ -101,6 +102,9 @@ public class OICConstants {
public static final String ACCOUNT_FULL_URI = "/"
+ OICConstants.PREFIX_OIC + "/" + OICConstants.ACCOUNT_URI;
+ public static final String SEC_ACCOUNT_FULL_URI = "/"
+ + OICConstants.PREFIX_OIC + "/" + OICConstants.SEC_URI + "/" + OICConstants.ACCOUNT_URI;
+
public static final String ACCOUNT_SEARCH_FULL_URI = "/"
+ OICConstants.PREFIX_OIC + "/" + OICConstants.ACCOUNT_URI + "/"
+ OICConstants.SEARCH_URI;
@@ -109,9 +113,15 @@ public class OICConstants {
+ OICConstants.PREFIX_OIC + "/" + OICConstants.ACCOUNT_URI + "/"
+ OICConstants.SESSION_URI;
+ public static final String SEC_ACCOUNT_SESSION_FULL_URI = "/"
+ + OICConstants.PREFIX_OIC + "/" + OICConstants.SEC_URI + "/"
+ + OICConstants.SESSION_URI;
+
public static final String ACCOUNT_TOKENREFRESH_FULL_URI = "/"
- + OICConstants.PREFIX_OIC + "/" + OICConstants.ACCOUNT_URI + "/"
- + OICConstants.TOKEN_REFRESH_URI;
+ + OICConstants.PREFIX_OIC + "/" + OICConstants.ACCOUNT_URI + "/" + OICConstants.TOKEN_REFRESH_URI;
+
+ public static final String SEC_ACCOUNT_TOKENREFRESH_FULL_URI = "/"
+ + OICConstants.PREFIX_OIC + "/" + OICConstants.SEC_URI + "/" + OICConstants.TOKEN_REFRESH_URI;
public static final String ACL_ID_FULL_URI = "/"
+ OICConstants.PREFIX_OIC + "/" + OICConstants.ACL_URI + "/"
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/ServerSystem.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/ServerSystem.java
index ddd8481..68caf19 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/ServerSystem.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/ServerSystem.java
@@ -29,6 +29,8 @@ import io.netty.util.AttributeKey;
import java.util.ArrayList;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.connector.CoapClient;
import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
@@ -47,16 +49,11 @@ import org.iotivity.cloud.base.server.CoapServer;
import org.iotivity.cloud.base.server.HttpServer;
import org.iotivity.cloud.base.server.Server;
import org.iotivity.cloud.base.server.WebSocketServer;
-import org.iotivity.cloud.util.Log;
-
-import io.netty.channel.ChannelHandler.Sharable;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.util.AttributeKey;
public class ServerSystem extends ResourceManager {
- private List<Server> mServerList = new ArrayList<>();
- public static AttributeKey<Device> keyDevice = AttributeKey
+ private final static Logger Log = LoggerFactory.getLogger(ServerSystem.class);
+ private List<Server> mServerList = new ArrayList<>();
+ public static AttributeKey<Device> keyDevice = AttributeKey
.newInstance("device");
@Sharable
@@ -101,16 +98,17 @@ public class ServerSystem extends ResourceManager {
}
} catch (ServerException e) {
- ctx.writeAndFlush(MessageBuilder.createResponse(msg,
- e.getErrorResponse()));
- Log.f(ctx.channel(), e);
+ ctx.writeAndFlush(MessageBuilder.createResponse(msg, e.getErrorResponse()));
+ if (e instanceof ServerException.ServiceUnavailableException)
+ Log.warn(e.getMessage());
+ else
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), e);
} catch (ClientException e) {
- Log.f(ctx.channel(), e);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), e);
} catch (Throwable t) {
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
if (msg instanceof CoapRequest) {
- ctx.writeAndFlush(MessageBuilder.createResponse(msg,
- ResponseStatus.INTERNAL_SERVER_ERROR));
+ ctx.writeAndFlush(MessageBuilder.createResponse(msg, ResponseStatus.INTERNAL_SERVER_ERROR));
}
}
}
@@ -140,11 +138,11 @@ public class ServerSystem extends ResourceManager {
onRequestReceived(targetDevice, msg);
} catch (ServerException e) {
- Log.f(ctx.channel(), e);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), e);
ctx.writeAndFlush(MessageBuilder.createResponse(msg,
e.getErrorResponse()));
} catch (Throwable t) {
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
ctx.writeAndFlush(MessageBuilder.createResponse(msg,
ResponseStatus.INTERNAL_SERVER_ERROR));
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapClient.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapClient.java
index 818914d..b0e2f64 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapClient.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapClient.java
@@ -23,6 +23,8 @@ package org.iotivity.cloud.base.connector;
import java.util.HashMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.OICConstants;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
@@ -34,7 +36,6 @@ import org.iotivity.cloud.base.protocols.coap.CoapRequest;
import org.iotivity.cloud.base.protocols.coap.CoapResponse;
import org.iotivity.cloud.base.protocols.enums.Observe;
import org.iotivity.cloud.util.Bytes;
-import org.iotivity.cloud.util.Log;
import io.netty.channel.Channel;
@@ -55,6 +56,9 @@ public class CoapClient implements IRequestChannel, IResponseEventHandler {
}
}
+
+
+ private final static Logger Log = LoggerFactory.getLogger(CoapClient.class);
private HashMap<Long, RequestInfo> mTokenExchanger = new HashMap<>();
private Long mToken = 0L;
private Channel mChannel = null;
@@ -111,7 +115,7 @@ public class CoapClient implements IRequestChannel, IResponseEventHandler {
mChannel.writeAndFlush(request);
} catch (Exception e) {
- Log.f(mChannel, e);
+ Log.error("Problem occured on channel " + mChannel.id().asLongText().substring(26), e);
}
}
@@ -137,7 +141,7 @@ public class CoapClient implements IRequestChannel, IResponseEventHandler {
// Subscription response should stored
if (reqInfo.observe != Observe.SUBSCRIBE) {
mTokenExchanger.remove(Bytes.bytesToLong(coapResponse.getToken()));
- if (mSubscription
+ if (reqInfo.originToken != null && mSubscription
.containsKey(Bytes.bytesToLong(reqInfo.originToken))) {
mSubscription.remove(Bytes.bytesToLong(reqInfo.originToken));
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapConnector.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapConnector.java
index 281082a..a7c45a8 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapConnector.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapConnector.java
@@ -33,18 +33,21 @@ import io.netty.handler.ssl.SslProvider;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.OICConstants;
import org.iotivity.cloud.base.protocols.coap.*;
import org.iotivity.cloud.base.protocols.coap.PingMessage;
-import org.iotivity.cloud.util.Log;
import javax.net.ssl.SSLException;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
public class CoapConnector {
-
+ private final static Logger Log = LoggerFactory.getLogger(CoapConnector.class);
public CoapConnector() {
mBootstrap.group(mConnectorGroup);
@@ -72,10 +75,10 @@ public class CoapConnector {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.WRITER_IDLE) {
- ctx.writeAndFlush(PingMessage.build());
+ mChannelMap.get(ctx.channel()).sendRequest(PingMessage.build(),null);
}
if (event.state() == IdleState.READER_IDLE) {
- Log.d("Connection with" + ctx.channel().remoteAddress().toString() + "is idle. Closing connection.");
+ Log.debug("Connection with" + ctx.channel().remoteAddress().toString() + "is idle. Closing connection.");
ctx.close();
}
}
@@ -151,13 +154,13 @@ public class CoapConnector {
}
}
- HashMap<Channel, CoapClient> mChannelMap = new HashMap<>();
+ private static ConcurrentMap<Channel, CoapClient> mChannelMap = new ConcurrentHashMap<>();
Bootstrap mBootstrap = new Bootstrap();
EventLoopGroup mConnectorGroup = new NioEventLoopGroup();
Timer mTimer = new Timer();
public void connect(final String connectionName, final InetSocketAddress inetSocketAddress,
- boolean tlsMode, boolean keepAlive) {
+ boolean tlsMode, boolean keepAlive, final ConnectionEstablishedListener listener) {
CoapConnectorInitializer initializer = new CoapConnectorInitializer();
@@ -170,44 +173,50 @@ public class CoapConnector {
initializer.setKeepAlive(keepAlive);
initializer.addHandler(new CoapPacketHandler());
mBootstrap.handler(initializer);
- doConnect(connectionName, inetSocketAddress, tlsMode);
+ doConnect(connectionName, inetSocketAddress, tlsMode, listener);
}
- private void doConnect(final String connectionName, final InetSocketAddress inetSocketAddress, final boolean tlsMode) {
+ private void doConnect(final String connectionName, final InetSocketAddress inetSocketAddress, final boolean tlsMode,
+ final ConnectionEstablishedListener listener) {
mBootstrap.connect(inetSocketAddress).addListener(new ChannelFutureListener() {
@Override public void operationComplete(ChannelFuture future) throws Exception {
if(!future.isSuccess()) {
- Log.d("Connection to " + inetSocketAddress.getHostString() + " was not successful. Retrying...");
+ Log.debug("Connection to " + inetSocketAddress.getHostString() + " was not successful. Retrying...");
future.channel().close();
- scheduleConnect(connectionName, inetSocketAddress, tlsMode, 5000);
+ scheduleConnect(connectionName, inetSocketAddress, tlsMode, 5000, listener);
} else {
- connectionEstablished(connectionName, future.channel());
+ connectionEstablished(connectionName, future.channel(), listener);
addCloseDetectListener(future.channel());
}
}
private void addCloseDetectListener(Channel channel) {
channel.closeFuture().addListener((ChannelFutureListener) future -> {
- Log.d("Connection to " + inetSocketAddress.getHostString() + " was lost. Retrying...");
- scheduleConnect(connectionName, inetSocketAddress, tlsMode, 5);
+ ConnectorPool.removeConnection(connectionName);
+ Log.debug("Connection to " + inetSocketAddress.getHostString() + " was lost. Retrying...");
+ scheduleConnect(connectionName, inetSocketAddress, tlsMode, 5, listener);
});
}
});
}
- private void scheduleConnect(String connectionName, InetSocketAddress inetSocketAddress, boolean tlsMode, long millis) {
+ private void scheduleConnect(String connectionName, InetSocketAddress inetSocketAddress, boolean tlsMode, long millis,
+ final ConnectionEstablishedListener listener) {
mTimer.schedule( new TimerTask() {
@Override
public void run() {
- doConnect(connectionName, inetSocketAddress, tlsMode);
+ doConnect(connectionName, inetSocketAddress, tlsMode, listener);
}
}, millis );
}
- public void connectionEstablished(String connectionName, Channel channel) {
+ public void connectionEstablished(String connectionName, Channel channel, final ConnectionEstablishedListener listener) {
CoapClient coapClient = new CoapClient(channel);
mChannelMap.put(channel, coapClient);
ConnectorPool.addConnection(connectionName, coapClient);
+ if(listener != null){
+ listener.onConnectionEstablished(coapClient);
+ }
}
public void disconenct() throws Exception {
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectionEstablishedListener.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectionEstablishedListener.java
new file mode 100644
index 0000000..2c6ef6b
--- /dev/null
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectionEstablishedListener.java
@@ -0,0 +1,9 @@
+package org.iotivity.cloud.base.connector;
+
+import org.iotivity.cloud.base.device.IRequestChannel;
+
+public interface ConnectionEstablishedListener {
+
+ void onConnectionEstablished(final IRequestChannel requestChannel);
+
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectorPool.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectorPool.java
index 84f4eac..25fe3d6 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectorPool.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectorPool.java
@@ -26,6 +26,7 @@ import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import org.iotivity.cloud.base.device.IRequestChannel;
+import org.iotivity.cloud.base.exception.ServerException;
public class ConnectorPool {
@@ -39,11 +40,26 @@ public class ConnectorPool {
public static void requestConnection(String connectionName, InetSocketAddress inetAddr,
boolean tlsMode, boolean keepAlive) throws InterruptedException {
- mConnector.connect(connectionName, inetAddr, tlsMode, keepAlive);
+ mConnector.connect(connectionName, inetAddr, tlsMode, keepAlive, null);
+ }
+
+ public static void requestConnection(final String connectionName, final InetSocketAddress inetAddr,
+ final boolean tlsMode, final boolean keepAlive, final ConnectionEstablishedListener listener) throws InterruptedException {
+ mConnector.connect(connectionName, inetAddr, tlsMode, keepAlive, listener);
}
public static IRequestChannel getConnection(String name) {
- return mConnection.get(name);
+ if (mConnection.containsKey(name))
+ return mConnection.get(name);
+ throw new ServerException.ServiceUnavailableException("Requested connection to service " + name + " is not available");
+ }
+
+ public static void removeConnection(String name) {
+ mConnection.remove(name);
+ }
+
+ public static boolean containConnection(String name) {
+ return mConnection.containsKey(name);
}
public static ArrayList<IRequestChannel> getConnectionList() {
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/device/CoapDevice.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/device/CoapDevice.java
index 05535d5..5d22eaf 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/device/CoapDevice.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/device/CoapDevice.java
@@ -23,9 +23,12 @@ package org.iotivity.cloud.base.device;
import java.util.ArrayList;
import java.util.Date;
-import java.util.HashMap;
import java.util.Iterator;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.connector.CoapClient;
import org.iotivity.cloud.base.connector.ConnectorPool;
import org.iotivity.cloud.base.exception.ClientException;
@@ -37,11 +40,11 @@ import org.iotivity.cloud.base.protocols.coap.CoapResponse;
import org.iotivity.cloud.base.protocols.enums.Observe;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Bytes;
-import org.iotivity.cloud.util.Log;
import io.netty.channel.ChannelHandlerContext;
public class CoapDevice extends Device {
+ private final static Logger Log = LoggerFactory.getLogger(CoapDevice.class);
private CoapClient mCoapClient = null;
private String mUserId = null;
private String mDeviceId = null;
@@ -49,7 +52,7 @@ public class CoapDevice extends Device {
private Date mIssuedTime = null;
private int mExpiredPolicy = 0;
private ArrayList<IRequestChannel> mObserveChannelList = new ArrayList<>();
- private HashMap<Long, IRequest> mObserveRequestList = new HashMap<>();
+ private ConcurrentMap<Long, IRequest> mObserveRequestList = new ConcurrentHashMap<>();
private static final int INFINITE_TIME = -1;
@@ -112,7 +115,6 @@ public class CoapDevice extends Device {
Long token = iterator.next();
CoapClient coapClient = (CoapClient) channel;
if (coapClient.isObserveRequest(token) != null) {
- coapClient.removeObserve(token);
CoapRequest coapRequest = (CoapRequest) mObserveRequestList
.get(token);
coapRequest.setObserve(Observe.UNSUBSCRIBE);
@@ -173,7 +175,7 @@ public class CoapDevice extends Device {
if (remainTime < 0) {
- Log.w("accessToken is expired..");
+ Log.warn("accessToken is expired..");
return true;
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/device/Device.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/device/Device.java
index 39774b2..9e22afa 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/device/Device.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/device/Device.java
@@ -25,9 +25,14 @@ import org.iotivity.cloud.base.protocols.IResponse;
import io.netty.channel.ChannelHandlerContext;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
public abstract class Device implements IResponseEventHandler {
protected ChannelHandlerContext ctx;
+ private Map<String,Object> params = new ConcurrentHashMap<>();
+
public Device(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@@ -54,4 +59,18 @@ public abstract class Device implements IResponseEventHandler {
public abstract String getUserId();
public abstract String getAccessToken();
+
+
+ public void setParameter(final String key, final Object value){
+ this.params.put(key,value);
+ }
+
+ public <T> T getParameter(final String key){
+ return (T)this.params.get(key);
+ }
+
+ public boolean existParameter(final String key){
+ return this.params.containsKey(key);
+ }
+
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/exception/ServerException.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/exception/ServerException.java
index fb33b1e..e7c01f1 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/exception/ServerException.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/exception/ServerException.java
@@ -116,15 +116,15 @@ public class ServerException extends RuntimeException {
}
}
- public static class NotImplementedException extends ServerException {
- private static final long serialVersionUID = 5699911106834702025L;
+ public static class ServiceUnavailableException extends ServerException {
+ private static final long serialVersionUID = -112373218973982719L;
- public NotImplementedException() {
- super(ResponseStatus.NOT_IMPLEMENTED);
+ public ServiceUnavailableException() {
+ super(ResponseStatus.SERVICE_UNAVAILABLE);
}
- public NotImplementedException(String msg) {
- super(ResponseStatus.NOT_IMPLEMENTED, msg);
+ public ServiceUnavailableException(String msg) {
+ super(ResponseStatus.SERVICE_UNAVAILABLE, msg);
}
}
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/HealthHolder.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/HealthHolder.java
new file mode 100644
index 0000000..fda252e
--- /dev/null
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/HealthHolder.java
@@ -0,0 +1,9 @@
+package org.iotivity.cloud.base.healthcheck;
+
+public interface HealthHolder {
+
+ boolean isHealthy();
+
+ void pingAccepted();
+
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/SimpleHealthHolder.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/SimpleHealthHolder.java
new file mode 100644
index 0000000..d7a087e
--- /dev/null
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/healthcheck/SimpleHealthHolder.java
@@ -0,0 +1,26 @@
+package org.iotivity.cloud.base.healthcheck;
+
+import java.util.concurrent.TimeUnit;
+
+public class SimpleHealthHolder implements HealthHolder {
+
+
+ private final Long intervalMs;
+
+ private Long pingAccepted;
+
+ public SimpleHealthHolder(TimeUnit timeUnit, Integer interval) {
+ this.intervalMs = timeUnit.toMillis(interval);
+ pingAccepted();
+ }
+
+ @Override
+ public synchronized boolean isHealthy() {
+ return (System.currentTimeMillis() - pingAccepted) < intervalMs;
+ }
+
+ @Override
+ public synchronized void pingAccepted() {
+ pingAccepted = System.currentTimeMillis();
+ }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java
index 9bf0332..35d9ebb 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java
@@ -23,10 +23,11 @@ package org.iotivity.cloud.base.protocols.coap;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
-import org.iotivity.cloud.util.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
@@ -38,6 +39,7 @@ public class CoapDecoder extends ByteToMessageDecoder {
SHIM_HEADER, OPTION_PAYLOAD_LENGTH, CODE_TOKEN_OPTION, PAYLOAD, FINISH
}
+ private final static Logger Log = LoggerFactory.getLogger(CoapDecoder.class);
private ParsingState nextState = ParsingState.SHIM_HEADER;
private int bufferToRead = 1;
private int tokenLength = 0;
@@ -108,7 +110,9 @@ public class CoapDecoder extends ByteToMessageDecoder {
case CODE_TOKEN_OPTION:
int code = in.readByte() & 0xFF;
- if (code <= 31) {
+ if (code == 0) {
+ partialMsg = new CoapResponse(code);
+ } else if (code <= 31) {
partialMsg = new CoapRequest(code);
} else if (code > 224) {
partialMsg = new CoapSignaling(code);
@@ -166,7 +170,7 @@ public class CoapDecoder extends ByteToMessageDecoder {
ResponseStatus responseStatus = t instanceof ServerException
? ((ServerException) t).getErrorResponse()
: ResponseStatus.INTERNAL_SERVER_ERROR;
- Log.f(ctx.channel(), t);
+ Log.error("[{}] channel error", ctx.channel().id().asLongText().substring(26), t);
ctx.writeAndFlush(
MessageBuilder.createResponse(partialMsg, responseStatus));
ctx.close();
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapLogHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapLogHandler.java
index be43be5..b7e52a4 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapLogHandler.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapLogHandler.java
@@ -23,10 +23,11 @@ package org.iotivity.cloud.base.protocols.coap;
import java.util.ArrayList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.OICConstants;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import com.google.gson.Gson;
@@ -34,6 +35,7 @@ import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
+import org.slf4j.MDC;
/**
*
@@ -43,26 +45,23 @@ import io.netty.channel.ChannelPromise;
*/
@Sharable
public class CoapLogHandler extends ChannelDuplexHandler {
-
- private Cbor<Object> mCbor = new Cbor<>();
- private Gson mGson = new Gson();
-
- static final int MAX_LOGLEN = 100;
+ private final static Logger Log = LoggerFactory.getLogger(CoapLogHandler.class);
+ public static final String COAP_MESSAGE_PAYLOAD = "coappayload";
+ private Cbor<Object> mCbor = new Cbor<>();
+ private Gson mGson = new Gson();
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " Connected, Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.trace("[{}] Connected, Address: {}", ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " Disconnected, Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.trace("[{}] Disconnected, Address: {}", ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
ctx.fireChannelInactive();
}
@@ -83,7 +82,7 @@ public class CoapLogHandler extends ChannelDuplexHandler {
}
if (log != null) {
- Log.v(log);
+ Log.trace(log);
}
ctx.writeAndFlush(msg);
@@ -105,7 +104,7 @@ public class CoapLogHandler extends ChannelDuplexHandler {
}
if (log != null) {
- Log.v(log);
+ Log.trace(log);
}
ctx.fireChannelRead(msg);
@@ -114,31 +113,31 @@ public class CoapLogHandler extends ChannelDuplexHandler {
private String composeCoapRequest(String channelId, CoapRequest request) {
StringBuilder strBuilder = new StringBuilder();
- strBuilder.append(channelId);
- strBuilder.append(" " + request.getTokenString());
+ strBuilder.append("[" + channelId + "]");
+ strBuilder.append(" [" + request.getTokenString() + "]");
switch (request.getMethod()) {
case DELETE:
- strBuilder.append(" DELETE ");
+ strBuilder.append(" [DELETE] ");
break;
case GET:
switch (request.getObserve()) {
case SUBSCRIBE:
- strBuilder.append(" GET OBSERVE ");
+ strBuilder.append(" [GET OBSERVE] ");
break;
case UNSUBSCRIBE:
- strBuilder.append(" GET OBSERVE CANCEL ");
+ strBuilder.append(" [GET OBSERVE CANCEL] ");
break;
default:
- strBuilder.append(" GET ");
+ strBuilder.append(" [GET] ");
break;
}
break;
case POST:
- strBuilder.append(" POST ");
+ strBuilder.append(" [POST] ");
break;
case PUT:
- strBuilder.append(" PUT ");
+ strBuilder.append(" [PUT] ");
break;
}
@@ -150,8 +149,8 @@ public class CoapLogHandler extends ChannelDuplexHandler {
if (request.getPayloadSize() > 0) {
strBuilder.append(" CT:" + request.getContentFormat());
- strBuilder.append(" SZ:" + request.getPayloadSize() + " P:"
- + getJsonPayloadString(request));
+ strBuilder.append(" SZ:" + request.getPayloadSize());
+ MDC.put(COAP_MESSAGE_PAYLOAD, "P: " + getJsonPayloadString(request));
}
return strBuilder.toString();
@@ -161,8 +160,8 @@ public class CoapLogHandler extends ChannelDuplexHandler {
CoapResponse response) {
StringBuilder strBuilder = new StringBuilder();
- strBuilder.append(channelId);
- strBuilder.append(" " + response.getTokenString());
+ strBuilder.append("[" + channelId + "]");
+ strBuilder.append(" [" + response.getTokenString() + "]");
switch (response.getStatus()) {
case BAD_GATEWAY:
@@ -249,8 +248,8 @@ public class CoapLogHandler extends ChannelDuplexHandler {
if (response.getPayloadSize() > 0) {
strBuilder.append(" CT:" + response.getContentFormat());
- strBuilder.append(" SZ:" + response.getPayloadSize() + " P:"
- + getJsonPayloadString(response));
+ strBuilder.append(" SZ:" + response.getPayloadSize());
+ MDC.put(COAP_MESSAGE_PAYLOAD, "P: " + getJsonPayloadString(response));
}
return strBuilder.toString();
@@ -264,13 +263,9 @@ public class CoapLogHandler extends ChannelDuplexHandler {
coapMessage.getPayload(), Object.class);
if (coapMessage.getUriPath()
.contains(OICConstants.WELL_KNOWN_FULL_URI)) {
- jsonPayload = mGson.toJson((ArrayList<Object>) mapPayload);
- return jsonPayload.length() <= MAX_LOGLEN ? jsonPayload
- : jsonPayload.substring(0, MAX_LOGLEN);
+ return mGson.toJson((ArrayList<Object>) mapPayload);
}
- jsonPayload = mGson.toJson(mapPayload);
- return jsonPayload.length() <= MAX_LOGLEN ? jsonPayload
- : jsonPayload.substring(0, MAX_LOGLEN);
+ return mGson.toJson(mapPayload);
}
return jsonPayload;
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java
index 8f6e3d1..f018c87 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapResponse.java
@@ -34,6 +34,9 @@ public class CoapResponse extends CoapMessage {
public CoapResponse(int code) {
switch (code) {
+ case 0:
+ mResponseStatus = ResponseStatus.EMPTY;
+ break;
case 65:
mResponseStatus = ResponseStatus.CREATED;
break;
@@ -108,6 +111,8 @@ public class CoapResponse extends CoapMessage {
public int getCode() {
// TODO Auto-generated method stub
switch (mResponseStatus) {
+ case EMPTY:
+ return 0;
case BAD_GATEWAY:
return 162;
case BAD_OPTION:
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/websocket/WebSocketFrameHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/websocket/WebSocketFrameHandler.java
index f10efb2..03810f9 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/websocket/WebSocketFrameHandler.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/websocket/WebSocketFrameHandler.java
@@ -25,6 +25,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.base.protocols.coap.CoapDecoder;
@@ -33,7 +35,6 @@ import org.iotivity.cloud.base.protocols.coap.CoapMessage;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.util.Cbor;
import org.iotivity.cloud.util.JSONUtil;
-import org.iotivity.cloud.util.Log;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -49,21 +50,20 @@ import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
public class WebSocketFrameHandler extends ChannelDuplexHandler {
+ private final static Logger Log = LoggerFactory.getLogger(WebSocketFrameHandler.class);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " WebSocket Connected, Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.trace("[{}] WebSocket Connected, Address: {}", ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " WebSocket Disconnected, Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.trace("[{}] WebSocket Disconnected, Address: {}", ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
ctx.fireChannelInactive();
}
@@ -114,9 +114,8 @@ public class WebSocketFrameHandler extends ChannelDuplexHandler {
@Override
public void operationComplete(ChannelFuture future)
throws Exception {
- Log.v(future.channel().id().asLongText().substring(26)
- + " WebSocket Handshake done, Address: "
- + future.channel().remoteAddress().toString());
+ Log.trace("[{}] WebSocket Handshake done, Address: {}", future.channel().id().asLongText().substring(26),
+ future.channel().remoteAddress().toString());
// remove http encoder/decoder after handshake done.
future.channel().pipeline().remove(HttpServerCodec.class);
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/enums/ResponseStatus.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/enums/ResponseStatus.java
index 602c005..e9c7e13 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/enums/ResponseStatus.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/enums/ResponseStatus.java
@@ -21,7 +21,12 @@
*/
package org.iotivity.cloud.base.protocols.enums;
+import java.util.Arrays;
+import java.util.List;
+
public enum ResponseStatus {
+ // Empty response
+ EMPTY,
// Success 2.xx
CREATED, DELETED, VALID, CHANGED, CONTENT,
// Client Error 4.xx
@@ -36,4 +41,10 @@ public enum ResponseStatus {
INTERNAL_SERVER_ERROR, NOT_IMPLEMENTED, BAD_GATEWAY,
//
SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT, PROXY_NOT_SUPPORTED;
+
+ private static final List<ResponseStatus> successResponseStatuses = Arrays.asList(ResponseStatus.CREATED, ResponseStatus.DELETED, ResponseStatus.VALID, ResponseStatus.CHANGED, ResponseStatus.CONTENT);
+
+ public boolean isSuccess() {
+ return successResponseStatuses.contains(this);
+ }
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyHandler.java
index d8e93bf..97baf12 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyHandler.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyHandler.java
@@ -23,9 +23,10 @@ package org.iotivity.cloud.base.protocols.http;
import java.util.concurrent.ConcurrentHashMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.Message;
-import org.iotivity.cloud.util.Log;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
@@ -45,7 +46,7 @@ import io.netty.util.CharsetUtil;
* and translate them into CoAP request and HTTP response accordingly.
*/
public class HCProxyHandler extends ChannelDuplexHandler {
-
+ private final static Logger Log = LoggerFactory.getLogger(HCProxyHandler.class);
private static ConcurrentHashMap<String, HCProxyProcessor> hcProxyProcessorMap
= new ConcurrentHashMap<String, HCProxyProcessor>();
@@ -106,7 +107,7 @@ public class HCProxyHandler extends ChannelDuplexHandler {
if (errorStatusCode != null) {
- Log.v("HTTP Error: " + errorStatusCode);
+ Log.trace("HTTP Error: " + errorStatusCode);
HttpResponse httpResponse = hcProxyProcessor
.getErrorResponse(errorStatusCode);
@@ -127,7 +128,7 @@ public class HCProxyHandler extends ChannelDuplexHandler {
errorStatusCode = "500 Internal Server Error: "
+ "HTTP-Method does not recognized.";
- Log.v("HTTP Error: " + errorStatusCode);
+ Log.trace("HTTP Error: " + errorStatusCode);
HttpResponse httpResponse = hcProxyProcessor
.getErrorResponse(errorStatusCode);
@@ -165,7 +166,7 @@ public class HCProxyHandler extends ChannelDuplexHandler {
String errorStatusCode = "500 Internal Server Error: "
+ "HTTP response could not be generated.";
- Log.v("HTTP Error: " + errorStatusCode);
+ Log.trace("HTTP Error: " + errorStatusCode);
httpResponse = hcProxyProcessor
.getErrorResponse(errorStatusCode);
@@ -186,9 +187,9 @@ public class HCProxyHandler extends ChannelDuplexHandler {
if (future.isSuccess()) {
future.channel().close();
} else {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " HTTP Disconnected (Unexpectedly), Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.warn("[{}] HTTP Disconnected (Unexpectedly), Address: {}",
+ ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
}
}
});
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyProcessor.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyProcessor.java
index c5b29ee..5e2d82e 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyProcessor.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HCProxyProcessor.java
@@ -28,6 +28,8 @@ import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.HttpDevice;
@@ -40,7 +42,6 @@ import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.server.HttpServer;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -66,7 +67,7 @@ import io.netty.util.AttributeKey;
* described in https://tools.ietf.org/html/draft-ietf-core-http-mapping-13.
*/
public class HCProxyProcessor {
-
+ private final static Logger Log = LoggerFactory.getLogger(HCProxyProcessor.class);
public final static String COAP_FORMAT_TYPE = "application/coap-payload;cf=";
public final static String APPLICATION_JSON = "application/json";
public final static String APPLICATION_CBOR = "application/cbor";
@@ -283,7 +284,7 @@ public class HCProxyProcessor {
if (mContentType.equalsIgnoreCase(APPLICATION_JSON)) {
byte[] cborData = null;
try { // Cbor: JSON string to Map
- Log.v("Cbor encoding using HashMap.class");
+ Log.trace("Cbor encoding using HashMap.class");
ObjectMapper cborMapper = new ObjectMapper();
HashMap<String, Object> cborMap
= cborMapper.readValue(content,
@@ -497,14 +498,14 @@ public class HCProxyProcessor {
try { // Cbor: Map to JSON string
if (getTargetCoapPath().contains(DISCOVER_URI)) {
- Log.v("Cbor decoding using ArrayList.class");
+ Log.trace("Cbor decoding using ArrayList.class");
ArrayList<Object> cborMap = mStackCborArray
.parsePayloadFromCbor(coapPayload, ArrayList.class);
ObjectMapper cborMapper = new ObjectMapper();
payloadString = cborMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(cborMap);
} else {
- Log.v("Cbor decoding using HashMap.class");
+ Log.trace("Cbor decoding using HashMap.class");
HashMap<String, Object> cborMap = mStackCborMap
.parsePayloadFromCbor(coapPayload, HashMap.class);
ObjectMapper cborMapper = new ObjectMapper();
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HttpLogHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HttpLogHandler.java
index 630eca3..6e10413 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HttpLogHandler.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/HttpLogHandler.java
@@ -21,8 +21,6 @@
*/
package org.iotivity.cloud.base.protocols.http;
-import org.iotivity.cloud.util.Log;
-
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.handler.codec.http.HttpContent;
@@ -34,6 +32,8 @@ import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* This class provides a set of APIs to print out logs
@@ -41,21 +41,20 @@ import io.netty.channel.ChannelPromise;
*/
@Sharable
public class HttpLogHandler extends ChannelDuplexHandler {
+ private final static Logger Log = LoggerFactory.getLogger(HttpLogHandler.class);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " HTTP Connected, Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.trace("[{}] HTTP Connected, Address: {}", ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Log.v(ctx.channel().id().asLongText().substring(26)
- + " HTTP Disconnected, Address: "
- + ctx.channel().remoteAddress().toString());
+ Log.trace("[{}] HTTP Disconnected, Address: {}", ctx.channel().id().asLongText().substring(26),
+ ctx.channel().remoteAddress().toString());
ctx.fireChannelInactive();
}
@@ -65,7 +64,7 @@ public class HttpLogHandler extends ChannelDuplexHandler {
throws Exception {
if (!(msg instanceof HttpObject)) {
- Log.v("Non-HTTP message has been received to the HC proxy:\n"
+ Log.trace("Non-HTTP message has been received to the HC proxy:\n"
+ msg.toString());
}
@@ -77,12 +76,12 @@ public class HttpLogHandler extends ChannelDuplexHandler {
HttpRequest httpRequest = (HttpRequest) msg;
- Log.v(httpRequest.toString());
+ Log.trace(httpRequest.toString());
if (HttpUtil.isTransferEncodingChunked(httpRequest)) {
- Log.v("BEGINNING OF HTTP CHUNKED CONTENT");
+ Log.trace("BEGINNING OF HTTP CHUNKED CONTENT");
} else {
- Log.v("BEGINNING OF HTTP CONTENT");
+ Log.trace("BEGINNING OF HTTP CONTENT");
}
}
@@ -97,9 +96,9 @@ public class HttpLogHandler extends ChannelDuplexHandler {
if (content instanceof LastHttpContent) {
- Log.v(contentStrBuilder.toString());
+ Log.trace(contentStrBuilder.toString());
- Log.v("END OF HTTP CONTENT");
+ Log.trace("END OF HTTP CONTENT");
contentStrBuilder.setLength(0);
}
@@ -113,7 +112,7 @@ public class HttpLogHandler extends ChannelDuplexHandler {
ChannelPromise promise) {
if (!(msg instanceof HttpObject)) {
- Log.v("Non-HTTP message has been sent from the HC proxy:\n"
+ Log.trace("Non-HTTP message has been sent from the HC proxy:\n"
+ msg.toString());
}
@@ -125,10 +124,10 @@ public class HttpLogHandler extends ChannelDuplexHandler {
HttpResponse httpResponse = (HttpResponse) msg;
if (contentStrBuilder.length() > 0) {
- Log.v(httpResponse.toString() + "\n\n"
+ Log.trace(httpResponse.toString() + "\n\n"
+ contentStrBuilder.toString());
} else {
- Log.v(httpResponse.toString());
+ Log.trace(httpResponse.toString());
}
}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/SimpleHttpHandler.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/SimpleHttpHandler.java
new file mode 100644
index 0000000..ba27db1
--- /dev/null
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/http/SimpleHttpHandler.java
@@ -0,0 +1,53 @@
+package org.iotivity.cloud.base.protocols.http;
+
+import io.netty.channel.*;
+import io.netty.handler.codec.http.*;
+import io.netty.util.CharsetUtil;
+import org.iotivity.cloud.base.healthcheck.HealthHolder;
+import org.iotivity.cloud.base.protocols.IResponse;
+import org.iotivity.cloud.base.protocols.Message;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.ConcurrentHashMap;
+
+public class SimpleHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
+
+ private final static Logger Log = LoggerFactory.getLogger(SimpleHttpHandler.class);
+
+ private final HealthHolder healthHolder;
+
+ public SimpleHttpHandler(HealthHolder healthHolder) {
+ this.healthHolder = healthHolder;
+ }
+
+ @Override
+ protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
+
+ if (msg instanceof HttpRequest) {
+ final HttpRequest request = (HttpRequest) msg;
+ Log.debug("HTTP uri: {}",request.uri());
+ if(request.uri().compareTo("/api/healthcheck") == 0){
+ if(healthHolder.isHealthy()){
+ ctx.writeAndFlush(createResponse(HttpResponseStatus.OK)).addListener(ChannelFutureListener.CLOSE);
+ }else {
+ ctx.writeAndFlush(createResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR)).addListener(ChannelFutureListener.CLOSE);
+ }
+ }else {
+ ctx.writeAndFlush(createResponse(HttpResponseStatus.NOT_FOUND)).addListener(ChannelFutureListener.CLOSE);
+ }
+ }
+ }
+
+ @Override
+ public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
+ ctx.flush();
+ }
+
+ private HttpResponse createResponse(final HttpResponseStatus status){
+ return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
+ }
+
+
+
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/CloudPingResource.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/CloudPingResource.java
index bee2f04..96ee43e 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/CloudPingResource.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/CloudPingResource.java
@@ -3,6 +3,7 @@ package org.iotivity.cloud.base.resource;
import org.iotivity.cloud.base.OICConstants;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.healthcheck.HealthHolder;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
@@ -11,8 +12,17 @@ import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import java.util.Arrays;
public class CloudPingResource extends Resource {
+
+ private final HealthHolder healthHolder;
+
public CloudPingResource() {
super(Arrays.asList(OICConstants.PREFIX_OIC, OICConstants.KEEP_ALIVE_URI));
+ this.healthHolder = null;
+ }
+
+ public CloudPingResource(final HealthHolder healthHolder) {
+ super(Arrays.asList(OICConstants.PREFIX_OIC, OICConstants.KEEP_ALIVE_URI));
+ this.healthHolder = healthHolder;
}
@Override
@@ -23,6 +33,9 @@ public class CloudPingResource extends Resource {
switch (request.getMethod()) {
case PUT:
response = MessageBuilder.createResponse(request, ResponseStatus.VALID);
+ if(healthHolder != null){
+ healthHolder.pingAccepted();
+ }
break;
default:
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/Resource.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/Resource.java
index 9fe4326..b45b816 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/Resource.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/resource/Resource.java
@@ -120,7 +120,7 @@ public class Resource implements IRequestEventHandler {
for (String property : propertyList) {
if (!payloadData.containsKey(property))
throw new PreconditionFailedException(
- "payload does not contain" + property + " property");
+ "payload does not contain " + property + " property");
if (payloadData.get(property) == null)
throw new PreconditionFailedException(
property + " param is null in the payload");
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/server/HttpServer.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/server/HttpServer.java
index 0fad1f7..41aa021 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/server/HttpServer.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/server/HttpServer.java
@@ -25,23 +25,24 @@ import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.device.HttpDevice;
import org.iotivity.cloud.base.protocols.http.HCProxyHandler;
import org.iotivity.cloud.base.protocols.http.HttpLogHandler;
-import org.iotivity.cloud.util.Log;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
public class HttpServer extends Server {
-
+ private final static Logger Log = LoggerFactory.getLogger(HttpServer.class);
public static ConcurrentHashMap<String, HttpDevice> httpDeviceMap
= new ConcurrentHashMap<String, HttpDevice>(); //Key=SID, Value=HttpDevice
public HttpServer(InetSocketAddress inetSocketAddress) {
super(inetSocketAddress);
- Log.i("HTTP-to-CoAP Proxy is enabled.");
+ Log.info("HTTP-to-CoAP Proxy is enabled.");
Thread sessionTimeoutCheckThread
= new Thread(new SessionTimeoutCheck());
@@ -57,7 +58,7 @@ public class HttpServer extends Server {
public void run() {
while (true) {
- Log.v("HTTP Session registry check is started");
+ Log.trace("HTTP Session registry check is started");
Enumeration<String> sessionIdList = httpDeviceMap.keys();
@@ -70,7 +71,7 @@ public class HttpServer extends Server {
}
}
- Log.v("HTTP Session registry check is ended");
+ Log.trace("HTTP Session registry check is ended");
try { // Sleep for 1 day
Thread.sleep(1000L * 3600L * 24L);
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/server/Server.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/server/Server.java
index 3272fe8..1a5716d 100644
--- a/cloud/stack/src/main/java/org/iotivity/cloud/base/server/Server.java
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/server/Server.java
@@ -29,8 +29,9 @@ import java.util.List;
import javax.net.ssl.SSLException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.iotivity.cloud.base.OICConstants;
-import org.iotivity.cloud.util.Log;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
@@ -46,6 +47,7 @@ import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
public abstract class Server {
+ Logger Log = LoggerFactory.getLogger(Server.class);
EventLoopGroup acceptorGroup = new NioEventLoopGroup(1);
@@ -92,7 +94,7 @@ public abstract class Server {
try {
if (tlsMode)
- Log.i("Server starts with TLS!");
+ Log.info("Server starts with TLS!");
if (tlsMode == true) {
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/base/server/SimpleHttpServer.java b/cloud/stack/src/main/java/org/iotivity/cloud/base/server/SimpleHttpServer.java
new file mode 100644
index 0000000..74503aa
--- /dev/null
+++ b/cloud/stack/src/main/java/org/iotivity/cloud/base/server/SimpleHttpServer.java
@@ -0,0 +1,52 @@
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2016 Samsung Electronics All Rights Reserved.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // Licensed under the Apache License, Version 2.0 (the "License");
+ * // you may not use this file except in compliance with the License.
+ * // You may obtain a copy of the License at
+ * //
+ * // http://www.apache.org/licenses/LICENSE-2.0
+ * //
+ * // Unless required by applicable law or agreed to in writing, software
+ * // distributed under the License is distributed on an "AS IS" BASIS,
+ * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * // See the License for the specific language governing permissions and
+ * // limitations under the License.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.cloud.base.server;
+
+import io.netty.channel.ChannelHandler;
+import io.netty.handler.codec.http.HttpRequestDecoder;
+import io.netty.handler.codec.http.HttpResponseEncoder;
+import org.iotivity.cloud.base.healthcheck.HealthHolder;
+import org.iotivity.cloud.base.protocols.http.SimpleHttpHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.InetSocketAddress;
+
+public class SimpleHttpServer extends Server {
+ private final static Logger Log = LoggerFactory.getLogger(SimpleHttpServer.class);
+
+ private final HealthHolder healthHolder;
+
+ public SimpleHttpServer(InetSocketAddress inetSocketAddress, HealthHolder healthHolder) {
+ super(inetSocketAddress);
+ this.healthHolder = healthHolder;
+ Log.info("HTTP server listening on {}",inetSocketAddress);
+ }
+
+ @Override
+ protected ChannelHandler[] onQueryDefaultHandler() {
+
+ return new ChannelHandler[] { new HttpRequestDecoder(),
+ new HttpResponseEncoder(),
+ new SimpleHttpHandler(healthHolder) };
+ }
+}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/util/Log.java b/cloud/stack/src/main/java/org/iotivity/cloud/util/Log.java
deleted file mode 100644
index c054fa3..0000000
--- a/cloud/stack/src/main/java/org/iotivity/cloud/util/Log.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * //******************************************************************
- * //
- * // Copyright 2016 Samsung Electronics All Rights Reserved.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- * //
- * // Licensed under the Apache License, Version 2.0 (the "License");
- * // you may not use this file except in compliance with the License.
- * // You may obtain a copy of the License at
- * //
- * // http://www.apache.org/licenses/LICENSE-2.0
- * //
- * // Unless required by applicable law or agreed to in writing, software
- * // distributed under the License is distributed on an "AS IS" BASIS,
- * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * // See the License for the specific language governing permissions and
- * // limitations under the License.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.cloud.util;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.PrintStream;
-import java.net.URI;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-
-import org.apache.log4j.Logger;
-
-import io.netty.channel.Channel;
-
-public class Log {
-
- public static final int VERBOSE = 0;
- public static final int DEBUG = 1;
- public static final int INFO = 2;
- public static final int WARNING = 3;
- public static final int ERROR = 4;
-
- private static int logLevel = VERBOSE;
-
- private static FileOutputStream fos = null;
- private static PrintStream ps = null;
-
- private final static Logger logger = Logger
- .getLogger(Log.class);
- private static WebsocketLog websocketpoint = null;
- private static String mServerName = null;
-
- public static void Init() throws FileNotFoundException {
- System.setOut(Log.createLoggingProxy(System.out));
- createfile();
- }
-
- public static void InitWebLog(String webLogHost, String serverName) {
- mServerName = serverName;
- if (webLogHost != null) {
- try {
- websocketpoint = new WebsocketLog(new URI("ws://" + webLogHost));
- websocketpoint.start();
- } catch (Exception e) {
- System.out.println(e.getMessage());
- websocketpoint = null;
- }
- }
- }
-
- public static PrintStream createLoggingProxy(
- final PrintStream realPrintStream) {
- // TODO Auto-generated method stub
- return new PrintStream(realPrintStream) {
- public void print(final String string) {
- realPrintStream.print(string);
- logger.fatal(string);
- }
- };
- }
-
- public static void createfile() throws FileNotFoundException {
- File dir = new File("..//errLog//");
- if (!dir.isDirectory()) {
- dir.mkdirs();
- }
- fos = new FileOutputStream("../errLog/[" + getDate() + "] error.log",
- true);
- ps = new PrintStream(fos);
- }
-
- static public void f(Channel channel, Throwable t) {
- String log = channel.id().asLongText().substring(26) + " "
- + t.getMessage();
- ps.println(getTime() + " " + log);
- t.printStackTrace(ps);
- Log.v(log);
- }
-
- public static void setLogLevel(int level) {
- logLevel = level;
- }
-
- public static void v(String log) {
- printLog(VERBOSE, log);
- }
-
- public static void d(String log) {
- printLog(DEBUG, log);
- }
-
- public static void i(String log) {
- printLog(INFO, log);
- }
-
- public static void w(String log) {
- printLog(WARNING, log);
- }
-
- public static void e(String log) {
- printLog(ERROR, log);
- }
-
- public static void w(String log, Exception ex) {
- printLog(WARNING, log);
- ex.printStackTrace();
- }
-
- public static void w(String log, Throwable th) {
- printLog(WARNING, log);
- th.printStackTrace();
- }
-
- public static void e(String log, Exception ex) {
- printLog(ERROR, log);
- ex.printStackTrace();
- }
-
- public static void e(String log, Throwable th) {
- printLog(ERROR, log);
- th.printStackTrace();
- }
-
- private static void printLog(int level, String log) {
-
- if (logLevel > level)
- return;
-
- String format = "";
- format += getTime();
- format += " [" + getLogLevelString(level) + "]";
-
- if (level >= ERROR) {
- format += " [" + getDetailInfo() + "]";
- }
-
- format += " " + log;
-
- System.out.println(format);
-
- if (websocketpoint != null && websocketpoint.getUserSession() != null) {
- websocketpoint.sendMessage("[" + mServerName + "]" + format);
- }
- }
-
- private static String getDetailInfo() {
-
- String res = "";
-
- StackTraceElement ste = Thread.currentThread().getStackTrace()[4];
- String className = ste.getClassName()
- .substring(ste.getClassName().lastIndexOf(".") + 1);
-
- res += ste.getFileName() + ", " + className + "." + ste.getMethodName()
- + "(), line:" + ste.getLineNumber();
-
- return res;
- }
-
- protected static String getTime() {
- Calendar calendar = Calendar.getInstance();
- SimpleDateFormat dateFormat = new SimpleDateFormat(
- "yyyy-MM-dd HH:mm:ss:SSS");
-
- return dateFormat.format(calendar.getTime());
- }
-
- protected static String getDate() {
- Calendar calendar = Calendar.getInstance();
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- return dateFormat.format(calendar.getTime());
- }
-
- private static String getLogLevelString(int level) {
-
- String res = "";
-
- if (level == VERBOSE) {
- res = "V";
- } else if (level == DEBUG) {
- res = "D";
- } else if (level == INFO) {
- res = "I";
- } else if (level == WARNING) {
- res = "W";
- } else if (level == ERROR) {
- res = "E";
- }
-
- return res;
- }
-}
diff --git a/cloud/stack/src/main/java/org/iotivity/cloud/util/WebsocketLog.java b/cloud/stack/src/main/java/org/iotivity/cloud/util/WebsocketLog.java
deleted file mode 100644
index 1e59023..0000000
--- a/cloud/stack/src/main/java/org/iotivity/cloud/util/WebsocketLog.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * //******************************************************************
- * //
- * // Copyright 2016 Samsung Electronics All Rights Reserved.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- * //
- * // Licensed under the Apache License, Version 2.0 (the "License");
- * // you may not use this file except in compliance with the License.
- * // You may obtain a copy of the License at
- * //
- * // http://www.apache.org/licenses/LICENSE-2.0
- * //
- * // Unless required by applicable law or agreed to in writing, software
- * // distributed under the License is distributed on an "AS IS" BASIS,
- * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * // See the License for the specific language governing permissions and
- * // limitations under the License.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.cloud.util;
-
-import java.io.IOException;
-import java.net.URI;
-
-import javax.websocket.ClientEndpoint;
-import javax.websocket.CloseReason;
-import javax.websocket.ContainerProvider;
-import javax.websocket.DeploymentException;
-import javax.websocket.OnClose;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.WebSocketContainer;
-
-@ClientEndpoint
-public class WebsocketLog extends Thread {
- private Session userSession = null;
- private MessageHandler messageHandler;
- private WebSocketContainer container;
- private URI endpointURI;
-
- public WebsocketLog(URI endpointURI)
- throws DeploymentException, IOException {
- container = ContainerProvider.getWebSocketContainer();
- this.endpointURI = endpointURI;
- }
-
- @Override
- public void run() {
- startConnect();
- }
-
- @OnOpen
- public void onOpen(Session userSession) {
- this.userSession = userSession;
- }
-
- @OnClose
- public void onClose(Session userSession, CloseReason reason)
- throws InterruptedException {
- this.userSession = null;
- Log.d("Disconnected to websocket for Web Log");
- startConnect();
- }
-
- @OnMessage
- public void onMessage(String message) {
- if (this.messageHandler != null)
- this.messageHandler.handleMessage(message);
- }
-
- public void addMessageHandler(MessageHandler msgHandler) {
- this.messageHandler = msgHandler;
- }
-
- public void sendMessage(String message) {
- this.userSession.getAsyncRemote().sendText(message);
- }
-
- public static interface MessageHandler {
- public void handleMessage(String message);
- }
-
- public Session getUserSession() {
- return userSession;
- }
-
- public void startConnect() {
- int retryCount = 0;
- do {
- if (retryCount != 0) {
- Log.d("retry to Connecting... " + retryCount);
- }
-
- try {
- container.connectToServer(this, endpointURI);
- Log.d("Success to websocket for Web Log");
- } catch (DeploymentException | IOException e) {
- Log.d("Skip Connect to websocket for Web Log");
- }
- retryCount++;
- } while (userSession == null && retryCount < 4);
- }
-}