Added rest api for DSM. Added tests.
authorYevhen Zozulia <y.zozulia@surc.local>
Tue, 18 Jul 2017 18:00:38 +0000 (21:00 +0300)
committerYevhen Zozulia <y.zozulia@surc.local>
Tue, 18 Jul 2017 18:00:38 +0000 (21:00 +0300)
21 files changed:
servermq/pom.xml
servermq/src/main/java/com/samsung/servermq/dao/UserDetailsRepository.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/dao/UserRepository.java
servermq/src/main/java/com/samsung/servermq/domain/CustomUserDetails.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/iotivity/KafkaProducerWrapper.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/iotivity/MessageQueuePublisher.java
servermq/src/main/java/com/samsung/servermq/rest/DSMRestController.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/rest/model/MQPolicy.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/rest/model/Notification.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/service/UserService.java [new file with mode: 0644]
servermq/src/main/java/com/samsung/servermq/service/UserServiceImpl.java [new file with mode: 0644]
servermq/src/test/java/com/samsung/servermq/dao/AgentRepositoryTest.java [new file with mode: 0644]
servermq/src/test/java/com/samsung/servermq/dao/DeviceRepositoryTest.java [new file with mode: 0644]
servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/DeviceRegistrationPostDataExtractorTest.java [new file with mode: 0644]
servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/DeviceUnRegistrationPostDataExtractorTest.java [new file with mode: 0644]
servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/PolicyPostDataExtractorTest.java [new file with mode: 0644]
servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/ReportPostDataExtractorTest.java [new file with mode: 0644]
servermq/src/test/resources/iotivity.xml [new file with mode: 0644]
servermq/src/test/resources/root-context.xml [new file with mode: 0644]
servermq/src/test/resources/spring-database.xml [new file with mode: 0644]
servermq/src/test/resources/sql/init.sql [new file with mode: 0644]

index 33a6c5f..ba10162 100644 (file)
@@ -1,13 +1,16 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
-  <groupId>com.samsung.mqserver</groupId>
-  <artifactId>mqserver</artifactId>
-  <version>0.0.1-SNAPSHOT</version>
+    <groupId>com.samsung.mqserver</groupId>
+    <artifactId>mqserver</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
     <properties>
         <jdk.version>1.8</jdk.version>
         <spring-framework-version>4.3.8.RELEASE</spring-framework-version>
-                <hibernate-version>5.2.10.Final</hibernate-version>
+        <spring-security-version>3.2.10.RELEASE</spring-security-version>
+        <version.spring.security.oauth2>2.1.0.RELEASE</version.spring.security.oauth2>
+        <hibernate-version>5.2.10.Final</hibernate-version>
+        <dbh2.version>1.4.187</dbh2.version>
     </properties>
 
     <parent>
         <version>1.5.4.RELEASE</version>
     </parent>
     <dependencies>
+        <!-- OAuth 2.0 dependencies -->
+        <dependency>
+            <groupId>org.springframework.security.oauth</groupId>
+            <artifactId>spring-security-oauth2</artifactId>
+            <version>${version.spring.security.oauth2}</version>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <version>1.5.4.RELEASE</version>
+            <scope>test</scope>
+        </dependency>
+
+        <!--spring security -->
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-core</artifactId>
+            <version>${spring-security-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-web</artifactId>
+            <version>${spring-security-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-config</artifactId>
+            <version>${spring-security-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-taglibs</artifactId>
+            <version>${spring-security-version}</version>
+        </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
             <artifactId>spring-web</artifactId>
             <version>${spring-framework-version}</version>
         </dependency>
-
         <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-web</artifactId>
-        </dependency>
-        
-<dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-tx</artifactId>
             <version>${spring-framework-version}</version>
             <artifactId>spring-orm</artifactId>
             <version>${spring-framework-version}</version>
         </dependency>
-        
-         <dependency>
+
+        <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-core</artifactId>
             <version>${hibernate-version}</version>
             <version>1.2.0.Final</version>
         </dependency>
         <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
-<dependency>
-    <groupId>org.springframework.data</groupId>
-    <artifactId>spring-data-commons</artifactId>
-    <version>1.13.4.RELEASE</version>
-</dependency>
-        
+        <dependency>
+            <groupId>org.springframework.data</groupId>
+            <artifactId>spring-data-commons</artifactId>
+            <version>1.13.4.RELEASE</version>
+        </dependency>
+
         <dependency>
             <groupId>org.postgresql</groupId>
             <artifactId>postgresql</artifactId>
                 </exclusion>
             </exclusions>
         </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-test</artifactId>
+            <version>${spring-framework-version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.12</version>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <artifactId>hamcrest-core</artifactId>
+                    <groupId>org.hamcrest</groupId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <version>1.10.19</version>
+            <scope>test</scope>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <version>1.10.19</version>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.powermock</groupId>
+            <artifactId>powermock-core</artifactId>
+            <version>1.7.0</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.powermock</groupId>
+            <artifactId>powermock-module-junit4</artifactId>
+            <version>1.7.0</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.powermock</groupId>
+            <artifactId>powermock-api-mockito</artifactId>
+            <version>1.7.0</version>
+            <scope>test</scope>
+        </dependency>
+
+        <!-- H2 DB -->
+        <dependency>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
+            <version>${dbh2.version}</version>
+        </dependency>
     </dependencies>
 
     <build>
diff --git a/servermq/src/main/java/com/samsung/servermq/dao/UserDetailsRepository.java b/servermq/src/main/java/com/samsung/servermq/dao/UserDetailsRepository.java
new file mode 100644 (file)
index 0000000..6e5a063
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * In Samsung Ukraine R&D Center (SRK under a contract between)
+ * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+package com.samsung.servermq.dao;
+
+import org.springframework.data.repository.CrudRepository;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+import com.samsung.servermq.domain.CustomUserDetails;
+
+
+/**
+ * <h1> User Details repository</h1>
+ * UserDetailsRepository for security template.
+ * @see CustomUserDetails
+ *
+ * @author <A HREF="mailto:a.motchanyi@samsung.com">Artem Motchanyi</A>
+ * @version 1.0
+ * @since 2016-09-01
+ */
+@Repository
+public interface UserDetailsRepository extends CrudRepository<CustomUserDetails, Long> {
+
+    /**
+     * Get user details by user ID.
+     *
+     * @param id the id
+     * @return the custom user details
+     */
+    CustomUserDetails findByUserId(Long id);
+
+    /**
+     * Delete user by ID.
+     *
+     * @param userId the user id
+     */
+    @Transactional
+    void deleteByUserId(Long userId);
+}
index 2f0eaf5..525d675 100644 (file)
@@ -27,6 +27,14 @@ import com.samsung.servermq.domain.User;
 @Repository
 public interface UserRepository extends CrudRepository<User, Long> {
     /**
+     * Get user by username
+     *
+     * @param username user name
+     * @return user instance
+     */
+    User findByUsername(String username);
+
+    /**
      * Check is email nonexistent in DB
      *
      * @param email email address
diff --git a/servermq/src/main/java/com/samsung/servermq/domain/CustomUserDetails.java b/servermq/src/main/java/com/samsung/servermq/domain/CustomUserDetails.java
new file mode 100644 (file)
index 0000000..f179874
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * In Samsung Ukraine R&D Center (SRK under a contract between)
+ * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+package com.samsung.servermq.domain;
+
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import javax.persistence.*;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * <h1> CustomUserDetails DAO table</h1>
+ * DAO representation of CastomUserDetails. Is used by Security template
+ * @see org.springframework.security.core.userdetails.UserDetails
+ *
+ * @author <A HREF="mailto:s.shram@samsung.com">Sergii Shram</A>
+ * @version 1.0
+ * @since 2016-09-01
+ */
+@Entity
+@Table(name = "user_details")
+public class CustomUserDetails implements Serializable, UserDetails {
+
+    private static final long serialVersionUID = 5060863782901753096L;
+
+    /** The id. */
+    @Id
+    @SequenceGenerator(name = "user_details_id_seq", sequenceName = "user_details_id_seq", allocationSize = 1)
+    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_details_id_seq")
+    @Column
+    private Long   id;
+
+    /** The password. */
+    @Column
+    private String password;
+
+    /** The restore password link. */
+    @Column(name = "restore_password_link")
+    private String restorePasswordLink;
+
+    /** The user. */
+    @OneToOne(cascade = CascadeType.REMOVE)
+    @JoinColumn(name = "user_id")
+    private User   user;
+
+    /**
+     * Instantiates a new custom user details.
+     */
+    public CustomUserDetails() {
+    }
+
+    /**
+     * Instantiates a new custom user details.
+     *
+     * @param password the password
+     * @param restorePasswordLink the restore password link
+     * @param user the user
+     */
+    public CustomUserDetails(String password, String restorePasswordLink, User user) {
+        super();
+        this.password = password;
+        this.restorePasswordLink = restorePasswordLink;
+        this.user = user;
+    }
+
+    /**
+     * Gets the id.
+     *
+     * @return the id
+     */
+    public Long getId() {
+        return id;
+    }
+
+    /**
+     * Sets the id.
+     *
+     * @param id the new id
+     */
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#getPassword()
+     */
+    public String getPassword() {
+        return password;
+    }
+
+    /**
+     * Sets the password.
+     *
+     * @param password the new password
+     */
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    /**
+     * Gets the restore password link.
+     *
+     * @return the restore password link
+     */
+    public String getRestorePasswordLink() {
+        return restorePasswordLink;
+    }
+
+    /**
+     * Sets the restore password link.
+     *
+     * @param restorePasswordLink the new restore password link
+     */
+    public void setRestorePasswordLink(String restorePasswordLink) {
+        this.restorePasswordLink = restorePasswordLink;
+    }
+
+    /**
+     * Gets the user.
+     *
+     * @return the user
+     */
+    public User getUser() {
+        return user;
+    }
+
+    /**
+     * Sets the user.
+     *
+     * @param user the new user
+     */
+    public void setUser(User user) {
+        this.user = user;
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#getAuthorities()
+     */
+    @Override
+    public Collection<? extends GrantedAuthority> getAuthorities() {
+        return new ArrayList<>();
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#getUsername()
+     */
+    @Override
+    public String getUsername() {
+        return user.getUsername();
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired()
+     */
+    @Override
+    public boolean isAccountNonExpired() {
+        return false;
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked()
+     */
+    @Override
+    public boolean isAccountNonLocked() {
+        return !user.getLocked();
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired()
+     */
+    @Override
+    public boolean isCredentialsNonExpired() {
+        return false;
+    }
+
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.userdetails.UserDetails#isEnabled()
+     */
+    @Override
+    public boolean isEnabled() {
+        return !user.getLocked();
+    }
+}
diff --git a/servermq/src/main/java/com/samsung/servermq/iotivity/KafkaProducerWrapper.java b/servermq/src/main/java/com/samsung/servermq/iotivity/KafkaProducerWrapper.java
new file mode 100644 (file)
index 0000000..52e7f75
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * //******************************************************************
+ * //
+ * // 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 com.samsung.servermq.iotivity;
+
+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.apache.log4j.Logger;
+
+/**
+ *
+ * This class provides a set of APIs to use Kafka producer APIs for publishing
+ * messages.
+ *
+ */
+public class KafkaProducerWrapper {
+
+    private static final Logger log = Logger.getLogger(KafkaProducerWrapper.class);
+
+    private String                   mTopicName = null;
+    private String                   mBroker    = null;
+
+    private Producer<byte[], byte[]> mProducer  = null;
+
+    public KafkaProducerWrapper(String brokerAddress, String topic) {
+
+        mTopicName = topic.replace("/", ".");
+
+        mBroker = brokerAddress;
+
+        mProducer = new KafkaProducer<>(buildPropertiesForPublish());
+    }
+
+    /**
+     * API to publish message to Kafka topic
+     * 
+     * @param message
+     *            message to publish
+     * 
+     * @return returns true if the message is successfully published, otherwise
+     *         false
+     */
+    public boolean publishMessage(byte[] message) {
+
+        log.debug("kafka publishMessage - " + mTopicName);
+
+        ProducerRecord<byte[], byte[]> record = new ProducerRecord<>(
+                mTopicName, message);
+
+        mProducer.send(record);
+        mProducer.flush();
+
+        return true;
+    }
+
+    /**
+     * API to close Kafka producer connection
+     */
+    public void closeConnection() {
+
+        mProducer.close();
+    }
+
+    private Properties buildPropertiesForPublish() {
+
+        // TODO check property settings
+        Properties props = new Properties();
+
+        props.put("bootstrap.servers", mBroker);
+        props.put("acks", "all");
+        props.put("retries", 0);
+        props.put("batch.size", 16384);
+        props.put("linger.ms", 1);
+        props.put("buffer.memory", 33554432);
+        props.put("key.serializer",
+                "org.apache.kafka.common.serialization.ByteArraySerializer");
+        props.put("value.serializer",
+                "org.apache.kafka.common.serialization.ByteArraySerializer");
+
+        return props;
+    }
+
+}
\ No newline at end of file
diff --git a/servermq/src/main/java/com/samsung/servermq/rest/DSMRestController.java b/servermq/src/main/java/com/samsung/servermq/rest/DSMRestController.java
new file mode 100644 (file)
index 0000000..8ea2f5d
--- /dev/null
@@ -0,0 +1,66 @@
+package com.samsung.servermq.rest;
+
+import static org.springframework.http.HttpStatus.BAD_REQUEST;
+import static org.springframework.http.HttpStatus.OK;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.validation.Valid;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.samsung.servermq.iotivity.MessageQueuePublisher;
+import com.samsung.servermq.rest.model.MQPolicy;
+import com.samsung.servermq.rest.model.Notification;
+
+@RestController
+@RequestMapping("/dsmmq")
+public class DSMRestController {
+    private static final String MAIN_TOPIC = ".oic.ps.";
+    private static final String NOTIFICATION_TOPIC = ".notification";
+    private static final String POLICY_TOPIC = ".policy";
+
+    private static final String NOTIFICATION_TIME = "time";
+    private static final String NOTIFICATION_MESSAGE = "message";
+    private static final String NOTIFICATION_TITLE = "title";
+    private static final String NOTIFICATION_CODE = "code";
+    private static final String POLICY = "policy"; 
+
+    @Autowired
+    MessageQueuePublisher publisher;
+
+    @RequestMapping(value = "/notification", method = RequestMethod.POST)
+    public ResponseEntity<Void> sendNotification(@Valid Notification notification, BindingResult result) {
+        if(result.hasErrors()){
+            return new ResponseEntity<>(BAD_REQUEST);
+        }
+        Map<String, String> map = new HashMap<>();
+        map.put(NOTIFICATION_CODE, notification.getCode());
+        map.put(NOTIFICATION_TITLE, notification.getTitle());
+        map.put(NOTIFICATION_MESSAGE, notification.getMessage());
+        map.put(NOTIFICATION_TIME, Long.toString(notification.getCurrentTime()));
+        map.put(POLICY, notification.getPolicy());
+        String userUUID = notification.getCloudUserId();
+        publisher.sendMessage(MAIN_TOPIC + userUUID + NOTIFICATION_TOPIC, map);
+        return new ResponseEntity<>(OK);
+    }
+
+    @RequestMapping(value = "/policy", method = RequestMethod.POST)
+    public ResponseEntity<Void> sendPolicy(@Valid MQPolicy policy, BindingResult result) {
+        if(result.hasErrors()){
+            return new ResponseEntity<>(BAD_REQUEST);
+        }
+        Map<String, String> map = new HashMap<>();
+        map.put(POLICY, policy.getPolicy());
+        String userUUID = policy.getCloudUserId();
+        publisher.sendMessage(MAIN_TOPIC + userUUID + POLICY_TOPIC, map);
+        return new ResponseEntity<>(OK);
+    }
+
+}
diff --git a/servermq/src/main/java/com/samsung/servermq/rest/model/MQPolicy.java b/servermq/src/main/java/com/samsung/servermq/rest/model/MQPolicy.java
new file mode 100644 (file)
index 0000000..954af97
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * In Samsung Ukraine R&D Center (SRK under a contract between)
+ * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+package com.samsung.servermq.rest.model;
+
+import javax.validation.constraints.NotNull;
+
+/**
+ * 
+ * Model for Message Queue.
+ *
+ * @author <A HREF="mailto:y.zozulia@samsung.com">Yevhen Zozulia</A>
+ * @version 1.0
+ * @since 2017-07-18
+ */
+public class MQPolicy {
+
+    /**
+     * Cloud user id
+     */
+    @NotNull(message = "required field")
+    private String cloudUserId;
+    
+    /**
+     * Policy for user
+     */
+    @NotNull(message = "required field")
+    private String policy;
+
+    /**
+     * Create policy model to send Message Queue
+     */
+    public MQPolicy(){}
+    
+    /**
+     * Create policy model to send Message Queue  with parameters:
+     * @param cloudUserId - Cloud user id
+     * @param policy - Policy for user
+     */
+    public MQPolicy(String cloudUserId, String policy) {
+        this.cloudUserId = cloudUserId;
+        this.policy = policy;
+    }
+
+    /**
+     * Get cloud user id
+     * @return cloudUserId
+     */
+    public String getCloudUserId() {
+        return cloudUserId;
+    }
+
+    /**
+     * Set cloud user id
+     * @param cloudUserId - cloud user id
+     */
+    public void setCloudUserId(String cloudUserId) {
+        this.cloudUserId = cloudUserId;
+    }
+
+    /**
+     * Get Policy for user
+     * @return policy
+     */
+    public String getPolicy() {
+        return policy;
+    }
+
+    /**
+     * Set policy
+     * @param policy - policy
+     */
+    public void setPolicy(String policy) {
+        this.policy = policy;
+    }
+
+    /**
+     * Method provides reflection to print names and values of all fields
+     * <em>declared in this class</em>. Note that superclass fields are left out
+     * of this implementation.
+     * 
+     * @return String with names and values of all fields declared in this
+     *         class.
+     */
+    @Override
+    public String toString() {
+        return "MQPolicy [cloudUserId=" + cloudUserId + ", policy=" + policy + "]";
+    }
+
+}
diff --git a/servermq/src/main/java/com/samsung/servermq/rest/model/Notification.java b/servermq/src/main/java/com/samsung/servermq/rest/model/Notification.java
new file mode 100644 (file)
index 0000000..2f8e152
--- /dev/null
@@ -0,0 +1,190 @@
+/*
+ * In Samsung Ukraine R&D Center (SRK under a contract between)
+ * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+package com.samsung.servermq.rest.model;
+
+import javax.validation.constraints.NotNull;
+
+/**
+ * 
+ * Model for Message Queue.
+ *
+ * @author <A HREF="mailto:y.zozulia@samsung.com">Yevhen Zozulia</A>
+ * @version 1.0
+ * @since 2017-07-18
+ */
+public class Notification {
+
+    /**
+     * Cloud user id
+     */
+    @NotNull(message = "required field")
+    private String cloudUserId;
+    
+    /**
+     * Current time in milliseconds
+     */
+    @NotNull(message = "required field")
+    private Long currentTime;
+    
+    /**
+     * Error code
+     */
+    @NotNull(message = "required field")
+    private String code;
+    
+    /**
+     * Message title
+     */
+    @NotNull(message = "required field")
+    private String title;
+    
+    /**
+     * Message
+     */
+    @NotNull(message = "required field")
+    private String message;
+    
+    /**
+     * Policy for user
+     */
+    @NotNull(message = "required field")
+    private String policy;
+
+    /**
+     * Create notification model to send Message Queue
+     */
+    public Notification(){}
+
+    /**
+     * Create notification model to send Message Queue with parameters:
+     * @param cloudUserId - Cloud user id
+     * @param currentTime - Current time in milliseconds
+     * @param code - Error code
+     * @param title - Message title
+     * @param message - Message
+     * @param policy - Policy for user
+     */
+    public Notification(String cloudUserId, Long currentTime, String code, String title, String message,
+            String policy) {
+        super();
+        this.cloudUserId = cloudUserId;
+        this.currentTime = currentTime;
+        this.code = code;
+        this.title = title;
+        this.message = message;
+        this.policy = policy;
+    }
+
+    /**
+     * Get cloud user id
+     * @return cloudUserId
+     */
+    public String getCloudUserId() {
+        return cloudUserId;
+    }
+
+    /**
+     * Set cloud user id
+     * @param cloudUserId - cloud user id
+     */
+    public void setCloudUserId(String cloudUserId) {
+        this.cloudUserId = cloudUserId;
+    }
+
+    /**
+     * Get current time
+     * @return currentTime
+     */
+    public Long getCurrentTime() {
+        return currentTime;
+    }
+
+    /**
+     * Set current time
+     * @param currentTime - current time in milliseconds
+     */
+    public void setCurrentTime(Long currentTime) {
+        this.currentTime = currentTime;
+    }
+
+    /**
+     * Get error code
+     * @return code
+     */
+    public String getCode() {
+        return code;
+    }
+
+    /**
+     * Set error code
+     * @param code - error code
+     */
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    /**
+     * Get message title
+     * @return title
+     */
+    public String getTitle() {
+        return title;
+    }
+
+    /**
+     * Set message title
+     * @param title - message title
+     */
+    public void setTitle(String title) {
+        this.title = title;
+    }
+
+    /**
+     * Get notification message
+     * @return message
+     */
+    public String getMessage() {
+        return message;
+    }
+
+    /**
+     * Set notification message
+     * @param message - notification message
+     */
+    public void setMessage(String message) {
+        this.message = message;
+    }
+
+    /**
+     * Get Policy for user
+     * @return policy
+     */
+    public String getPolicy() {
+        return policy;
+    }
+
+    /**
+     * Set policy
+     * @param policy - policy
+     */
+    public void setPolicy(String policy) {
+        this.policy = policy;
+    }
+
+    /**
+     * Method provides reflection to print names and values of all fields
+     * <em>declared in this class</em>. Note that superclass fields are left out
+     * of this implementation.
+     * 
+     * @return String with names and values of all fields declared in this
+     *         class.
+     */
+    @Override
+    public String toString() {
+        return "Notification [cloudUserId=" + cloudUserId + ", currentTime=" + currentTime + ", code=" + code
+                + ", title=" + title + ", message=" + message + ", policy=" + policy + "]";
+    }
+}
diff --git a/servermq/src/main/java/com/samsung/servermq/service/UserService.java b/servermq/src/main/java/com/samsung/servermq/service/UserService.java
new file mode 100644 (file)
index 0000000..12cbf9a
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * In Samsung Ukraine R&D Center (SRK under a contract between)
+ * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+package com.samsung.servermq.service;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import com.samsung.servermq.domain.User;
+
+
+/**
+ * <h1> User service</h1>
+ * UserService for Security template.
+ * @see Role
+ *
+ * @author <A HREF="mailto:s.shram@samsung.com">Sergii Shram</A>
+ * @version 1.0
+ * @since 2016-09-01
+ */
+public interface UserService extends CommonService<User> {
+
+    /**
+     * Service method provides search user in DB by username.
+     * @param username user's username.
+     * @return object User with current username.
+     */
+    User findByUsername(String username);
+
+    /**
+     * Service method provides checking if e-mail is available for registration(not used for others accounts).
+     * @param request http request from client-side, contains e-mail for search.
+     * @return true is available/false already exist.
+     */
+    boolean isEmailAvailable(HttpServletRequest request);
+
+    /**
+     * Service method provides checking if e-mail is available for registration(not used for others accounts).
+     * @param email for checking.
+     * @return true is available/false already exist.
+     */
+    boolean isEmailAvailable(String email);
+
+    /**
+     * Service method provides getting List of all users in DB.
+     * @return List of all users in DB
+     */
+    List<User> getAll(boolean isDateAsc);
+
+    /**
+     * Service method provides inverting of locked/unlocked state for user by ID.
+     * @param id of user for changing users's state.
+     * @return updated user state.
+     */
+    boolean changeLockedState(Long id);
+
+    /**
+     * Service method provides user removal by ID.
+     * @param id of user for removal.
+     * @throws self removal Exception 
+     */
+    void remove(Long id) throws Exception;
+
+    /**
+     * Service method removes all users from.
+     */
+    void removeAll();
+
+    /**
+     * Service method provides searching user in DB by e-mail.
+     * @param email email of user being searched.
+     * @return object User with current e-mail.
+     */
+    User getUserByEmail(String email);
+
+    /**
+     * Service method provides editing the user account.
+     * @param user edited user.
+     * @return updated user object.
+     */
+    User editUser(User user);
+}
diff --git a/servermq/src/main/java/com/samsung/servermq/service/UserServiceImpl.java b/servermq/src/main/java/com/samsung/servermq/service/UserServiceImpl.java
new file mode 100644 (file)
index 0000000..b862e73
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+ * In Samsung Ukraine R&D Center (SRK under a contract between)
+ * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+package com.samsung.servermq.service;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.stereotype.Service;
+
+import com.samsung.servermq.dao.UserDetailsRepository;
+import com.samsung.servermq.dao.UserRepository;
+import com.samsung.servermq.domain.User;
+
+
+/**
+ * <h1> User service</h1>
+ * Implementation of the service for the User repository.
+ * @see Role
+ *
+ * @author <A HREF="mailto:s.shram@samsung.com">Sergii Shram</A>
+ * @version 1.0
+ * @since 2016-09-01
+ */
+@Service("userService")
+public class UserServiceImpl implements UserService {
+    @Autowired
+    private UserRepository        userRepository;
+    @Autowired
+    private UserDetailsRepository userDetailsRepository;
+
+    @Override
+    public User getUserByEmail(String email) {
+        return userRepository.findByEmail(email);
+    }
+
+    @Override
+    public User save(User user) {
+        return userRepository.save(user);
+    }
+
+    /**
+     * user can't remove himself
+     */
+    @Override
+    public void remove(User user) {
+        // do not allow suicide :)
+        if (isSelf(user)) {
+            return;
+        }
+
+        if (userDetailsRepository.findByUserId(user.getId()) != null) {
+            //cascade remove of user details and user
+            userDetailsRepository.deleteByUserId(user.getId());
+        } else {
+            // there is no user details for this user
+            // so just remove user
+            userRepository.delete(user);
+        }
+    }
+
+    @Override
+    public User findById(Long id) {
+        return userRepository.findOne(id);
+    }
+
+    @Override
+    public User findByUsername(String username) {
+        return userRepository.findByUsername(username);
+    }
+
+    @Override
+    public long count() {
+        return userRepository.count();
+    }
+
+    @Override
+    public boolean isEmailAvailable(HttpServletRequest request) {
+        return userRepository.isEmailAvailable(request.getParameter("email"));
+    }
+
+    @Override
+    public boolean isEmailAvailable(String email) {
+        return userRepository.isEmailAvailable(email);
+    }
+
+    @Override
+    public List<User> getAll(boolean isDateAsc) {
+        if (isDateAsc) {
+            return (List<User>) userRepository.findAllByOrderByDateAsc();
+        } else {
+            return (List<User>) userRepository.findAll();
+        }
+    }
+
+    @Override
+    public boolean changeLockedState(Long id) {
+        User user = userRepository.findOne(id);
+
+        // user can't lock/unlock himself
+        if (isSelf(user)) {
+            return user.getLocked();
+        }
+
+        user.setLocked(!user.getLocked());
+        user = userRepository.save(user);
+
+        return user.getLocked();
+    }
+
+    @Override
+    public void remove(Long id) throws Exception {
+        User user = userRepository.findOne(id);
+
+        if (isSelf(user)) {
+            throw new Exception("Self removement prohibited");
+        }
+
+        remove(user);
+    }
+
+    @Override
+    public User editUser(User editedUser) {
+        // user should not change role/loacked_state to himself
+        if (isSelf(editedUser)) {
+            // read previous User state
+            User user = userRepository.findOne(editedUser.getId());
+
+            // set previous role to user
+            editedUser.setRole(user.getRole());
+            // set previous locked_state to user
+            editedUser.setLocked(user.getLocked());
+        }
+
+        return userRepository.save(editedUser);
+    }
+
+    private boolean isSelf(final User user) {
+        final String secContextUserName = ((UserDetails) SecurityContextHolder.getContext().getAuthentication()
+                .getPrincipal()).getUsername();
+
+        // to guarantee uniqueness - userEMAIL is stored in secContectUserNAME
+        return secContextUserName.equals(user.getEmail());
+    }
+
+    @Override
+    public void removeAll() {
+        List<User> users = getAll(false);
+
+        for (User user : users) {
+            remove(user);
+        }
+    }
+}
\ No newline at end of file
diff --git a/servermq/src/test/java/com/samsung/servermq/dao/AgentRepositoryTest.java b/servermq/src/test/java/com/samsung/servermq/dao/AgentRepositoryTest.java
new file mode 100644 (file)
index 0000000..b1c0b41
--- /dev/null
@@ -0,0 +1,68 @@
+package com.samsung.servermq.dao;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.samsung.servermq.domain.Agent;
+import com.samsung.servermq.domain.Policy;
+
+
+
+/**
+ * @author Mail to: <A HREF="mailto:a.motchanyi@samsung.com">Artem Motchanyi</A>
+ * @version 1.0
+ * @file AgentRepositoryTest.java
+ * @brief Unit tests for Agent repository
+ * @date Created: 29/06/17
+ * @copyright In Samsung Ukraine R&D Center (SRK under a contract between)
+ * @par LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * @par Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@ImportResource("classpath:root-context.xml")
+@EnableAutoConfiguration
+public class AgentRepositoryTest {
+    @Autowired
+    private AgentRepository agentRepository;
+
+    @Autowired
+    private PolicyRepository policyRepository;
+
+    @Test
+    public void saveAgent() {
+        String name = "name";
+        String uuid = "uuid";
+        Agent agent = new Agent(uuid, name, policyRepository.save(new Policy()));
+        assertNull(agent.getId());
+        agent = agentRepository.save(agent);
+        assertNotNull(agent.getId());
+        assertNotNull(agentRepository.findOne(agent.getId()));
+
+        agentRepository.delete(agent);
+    }
+
+    @Test
+    public void getByUuidTest() {
+        String name = "name";
+        String uuid = "uuid";
+        Agent agent = new Agent(uuid, name, policyRepository.save(new Policy()));
+        agent = agentRepository.save(agent);
+        assertNotNull(agent);
+        agent = agentRepository.findByUuid(uuid);
+        assertNotNull(agent);
+        assertEquals(uuid, agent.getUuid());
+        assertEquals(name, agent.getName());
+
+        agentRepository.delete(agent);
+    }
+}
diff --git a/servermq/src/test/java/com/samsung/servermq/dao/DeviceRepositoryTest.java b/servermq/src/test/java/com/samsung/servermq/dao/DeviceRepositoryTest.java
new file mode 100644 (file)
index 0000000..2b097db
--- /dev/null
@@ -0,0 +1,92 @@
+package com.samsung.servermq.dao;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.samsung.servermq.domain.Device;
+import com.samsung.servermq.domain.Policy;
+import com.samsung.servermq.domain.User;
+import com.samsung.servermq.service.UserService;
+
+
+/**
+ * @author Mail to: <A HREF="mailto:a.motchanyi@samsung.com">Artem Motchanyi</A>
+ * @version 1.0
+ * @file DeviceRepositoryTest.java
+ * @brief Unit tests for Device repository
+ * @date Created: 27/06/17
+ * @copyright In Samsung Ukraine R&D Center (SRK under a contract between)
+ * @par LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
+ * @par Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
+ */
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@ImportResource("classpath:root-context.xml")
+@EnableAutoConfiguration
+public class DeviceRepositoryTest {
+    @Autowired
+    private DeviceRepository deviceRepository;
+
+    @Autowired
+    private PolicyRepository policyRepository;
+
+    @Autowired
+    private UserService userService;
+
+    private User user;
+
+    private Policy policy;
+
+    @Before
+    public void before() {
+        user = userService.getUserByEmail("admin@samsung.com");
+        policy = policyRepository.save(new Policy());
+    }
+
+    @Test
+    public void saveDevice() {
+        String name = "name";
+        String uuid = "uuid";
+        String type = "type";
+        String model = "model";
+        Integer status = 0;
+        Device device = new Device(uuid, name, type, model, status, policy, user);
+        assertNull(device.getId());
+        device = deviceRepository.save(device);
+        assertNotNull(device.getId());
+        assertNotNull(deviceRepository.findOne(device.getId()));
+
+        deviceRepository.delete(device);
+    }
+
+    @Test
+    public void getByUuidTest() {
+        String name = "name";
+        String uuid = "uuid";
+        String type = "type";
+        String model = "model";
+        Integer status = 0;
+        Device device = new Device(uuid, name, type, model, status, policy, user);
+        device = deviceRepository.save(device);
+        assertNotNull(device);
+        device = deviceRepository.findByUuid(uuid);
+        assertNotNull(device);
+        assertEquals(uuid, device.getUuid());
+        assertEquals(name, device.getName());
+        assertEquals(type, device.getType());
+        assertEquals(model, device.getModel());
+        assertEquals(status, device.getStatus());
+
+        deviceRepository.delete(device);
+    }
+}
diff --git a/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/DeviceRegistrationPostDataExtractorTest.java b/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/DeviceRegistrationPostDataExtractorTest.java
new file mode 100644 (file)
index 0000000..1bea491
--- /dev/null
@@ -0,0 +1,65 @@
+package com.samsung.servermq.iotivity.extractor.impl;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.util.HashMap;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.samsung.servermq.service.DeviceService;
+import com.samsung.servermq.service.IotCloudService;
+import com.samsung.servermq.utils.Cbor;
+import com.samsung.servermq.utils.MessageQueueKeys;
+import com.samsung.servermq.utils.MessageQueueUtils;
+
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@ImportResource("classpath:root-context.xml")
+@EnableAutoConfiguration
+public class DeviceRegistrationPostDataExtractorTest {
+    
+    private static final String DUID = "testduid";
+    private static final String UUID = "testuuid";
+    private static final String NAME = "testDevice";
+    private static final String TYPE = "tv";
+    private static final String MODEL = "MySmartTV";
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private IotCloudService iotCloudService;
+
+    @Test
+    public void testExtractor() throws Exception {
+        iotCloudService.createAndSaveUser("admin@samsung.com", UUID);
+        Cbor<HashMap<String, String>> cbor = new Cbor<>();
+        HashMap<String, String> map = new HashMap<>();
+        map.put(MessageQueueKeys.DUID.getKey(), DUID);
+        map.put(MessageQueueKeys.UUID.getKey(), UUID);
+        map.put(MessageQueueKeys.DEVICE_NAME.getKey(), NAME);
+        map.put(MessageQueueKeys.DEVICE_TYPE.getKey(), TYPE);
+        map.put(MessageQueueKeys.DEVICE_MODEL.getKey(), MODEL);
+        byte[] data = cbor.encodingPayloadToCbor(map);
+        DeviceRegistrationPostDataExtractor extractor = new DeviceRegistrationPostDataExtractor();
+        extractor.deviceService = deviceService;
+        extractor.iotCloudService = iotCloudService;
+        extractor.extract(data);
+        assertNotNull(deviceService.findByUUID(DUID));
+        deviceService.remove(deviceService.findByUUID(DUID));
+    }
+
+    public void testFaildExtractor() throws Exception {
+        byte[] data = MessageQueueUtils.buildPayload(MessageQueueKeys.DUID.getKey(), UUID);
+        DeviceRegistrationPostDataExtractor extractor = new DeviceRegistrationPostDataExtractor();
+        extractor.extract(data);
+    }
+
+}
diff --git a/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/DeviceUnRegistrationPostDataExtractorTest.java b/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/DeviceUnRegistrationPostDataExtractorTest.java
new file mode 100644 (file)
index 0000000..f7570e0
--- /dev/null
@@ -0,0 +1,70 @@
+package com.samsung.servermq.iotivity.extractor.impl;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.samsung.servermq.domain.Device;
+import com.samsung.servermq.domain.Policy;
+import com.samsung.servermq.domain.User;
+import com.samsung.servermq.service.DeviceService;
+import com.samsung.servermq.service.PolicyService;
+import com.samsung.servermq.service.UserService;
+import com.samsung.servermq.utils.MessageQueueKeys;
+import com.samsung.servermq.utils.MessageQueueUtils;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@ImportResource("classpath:root-context.xml")
+@EnableAutoConfiguration
+public class DeviceUnRegistrationPostDataExtractorTest {
+
+    private static final String DUID = "testuuid";
+    private static final String NAME = "testDevice";
+    private static final String TYPE = "tv";
+    private static final String MODEL = "MySmartTV";
+    private static final Integer STATUS = 1;
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private UserService userService;
+
+    @Autowired
+    private PolicyService policyService;
+
+    @Test(expected = Exception.class)
+    public void testExtractor() throws Exception {
+        Policy policy = policyService.initPolicy();
+        User user = userService.getUserByEmail("admin@samsung.com");
+        Device device = new Device(DUID, NAME, TYPE, MODEL, STATUS, policy, user);
+        deviceService.save(device);
+        byte[] data = MessageQueueUtils.buildPayload(MessageQueueKeys.DUID.getKey(), DUID);
+        assertNotNull(deviceService.findByUUID(DUID));
+        DeviceUnRegistrationPostDataExtractor extractor = new DeviceUnRegistrationPostDataExtractor();
+        extractor.deviceService = deviceService;
+        extractor.extract(data);
+        assertNull(deviceService.findByUUID(DUID));
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testFaildExtractor() throws Exception {
+        DeviceService mockDeviceService = Mockito.mock(DeviceService.class);
+        Mockito.when(mockDeviceService.findByUUID(DUID)).thenThrow(Exception.class);
+        byte[] data = MessageQueueUtils.buildPayload(MessageQueueKeys.DUID.getKey(), DUID);
+        DeviceUnRegistrationPostDataExtractor extractor = new DeviceUnRegistrationPostDataExtractor();
+        extractor.deviceService = mockDeviceService;
+        extractor.extract(data);
+    }
+
+}
diff --git a/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/PolicyPostDataExtractorTest.java b/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/PolicyPostDataExtractorTest.java
new file mode 100644 (file)
index 0000000..ea79aaa
--- /dev/null
@@ -0,0 +1,83 @@
+package com.samsung.servermq.iotivity.extractor.impl;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.util.HashMap;
+
+import org.iotivity.cloud.util.Cbor;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.samsung.servermq.domain.Device;
+import com.samsung.servermq.domain.Policy;
+import com.samsung.servermq.domain.User;
+import com.samsung.servermq.service.DeviceService;
+import com.samsung.servermq.service.PolicyService;
+import com.samsung.servermq.service.UserService;
+import com.samsung.servermq.utils.MessageQueueKeys;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@ImportResource("classpath:root-context.xml")
+@EnableAutoConfiguration
+public class PolicyPostDataExtractorTest {
+
+    private static final String DUID = "testuuid";
+    private static final String NAME = "testDevice";
+    private static final String TYPE = "tv";
+    private static final String MODEL = "MySmartTV";
+    private static final Integer STATUS = 1;
+
+    private String policyConf = "[{" + "\"group\": \"tv-extension\"," + "\"policies\": [" + "{" + "\"name\": \"usb\","
+            + "\"state\": 0," + "\"items\": [ ]" + "}," + "{" + "\"name\": \"screen-capture\"," + "\"state\": 1,"
+            + "\"items\": [ ]" + "}," + "{" + "\"name\": \"bluetooth\"," + "\"state\": 1," + "\"items\": []" + "},"
+            + "{" + "\"name\": \"iptables\"," + "\"state\": 0," + "\"items\": [" + "\"127.0.0.0/24|UDP|10-1024\","
+            + "\"1.1.1.1|TCP|80,443\"," + "\"8.8.8.8\"" + "]" + "}" + "]" + "}," + "{"
+            + "\"group\": \"mobile-extension\"," + "\"policies\": []" + "}]";
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private UserService userService;
+
+    @Autowired
+    private PolicyService policyService;
+
+    @Test(expected = Exception.class)
+    public void testDeviceNotFoundExtractor() {
+        Cbor<HashMap<String, String>> cbor = new Cbor<>();
+        HashMap<String, String> map = new HashMap<>();
+        map.put(MessageQueueKeys.DUID.getKey(), DUID);
+        map.put(MessageQueueKeys.POLICY.getKey(), policyConf);
+        byte[] data = cbor.encodingPayloadToCbor(map);
+        PolicyPostDataExtractor extractor = new PolicyPostDataExtractor();
+        extractor.extract(data);
+        assertNull(deviceService.findByUUID(DUID));
+    }
+
+    @Test
+    public void testExtractor() {
+        Policy policy = policyService.initPolicy();
+        User user = userService.getUserByEmail("admin@samsung.com");
+        Device device = new Device(DUID, NAME, TYPE, MODEL, STATUS, policy, user);
+        deviceService.save(device);
+        assertNotNull(deviceService.findByUUID(DUID));
+        Cbor<HashMap<String, String>> cbor = new Cbor<>();
+        HashMap<String, String> map = new HashMap<>();
+        map.put(MessageQueueKeys.DUID.getKey(), DUID);
+        map.put(MessageQueueKeys.POLICY.getKey(), policyConf);
+        byte[] data = cbor.encodingPayloadToCbor(map);
+        PolicyPostDataExtractor extractor = new PolicyPostDataExtractor();
+        extractor.extract(data);
+        assertNotNull(deviceService.findByUUID(DUID));
+        deviceService.remove(deviceService.findByUUID(DUID));
+    }
+
+}
diff --git a/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/ReportPostDataExtractorTest.java b/servermq/src/test/java/com/samsung/servermq/iotivity/extractor/impl/ReportPostDataExtractorTest.java
new file mode 100644 (file)
index 0000000..6e71987
--- /dev/null
@@ -0,0 +1,88 @@
+package com.samsung.servermq.iotivity.extractor.impl;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashMap;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.samsung.servermq.domain.Device;
+import com.samsung.servermq.domain.Policy;
+import com.samsung.servermq.domain.Report;
+import com.samsung.servermq.domain.User;
+import com.samsung.servermq.service.DeviceService;
+import com.samsung.servermq.service.PolicyService;
+import com.samsung.servermq.service.ReportService;
+import com.samsung.servermq.service.UserService;
+import com.samsung.servermq.utils.Cbor;
+import com.samsung.servermq.utils.MessageQueueKeys;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@ImportResource("classpath:root-context.xml")
+@EnableAutoConfiguration
+public class ReportPostDataExtractorTest {
+
+    private static final String DUID = "testuuid";
+    private static final String NAME = "testDevice";
+    private static final String TYPE = "tv";
+    private static final String MODEL = "MySmartTV";
+    private static final Integer STATUS = 1;
+
+    private static final String testInputData = "{" + "\"did\": \"1234\"," + "\"date\": \"12:25 PM; May 08, 2017\","
+            + "\"name\": \"sim\"," + "\"result\": 0," + "\"data\": {}" + "}";
+
+    @Autowired
+    private ReportService reportService;
+
+    @Autowired
+    private DeviceService deviceService;
+
+    @Autowired
+    private PolicyService policyService;
+
+    @Autowired
+    private UserService userService;
+
+    @Test
+    public void testExtractor() throws Exception {
+        Policy policy = policyService.initPolicy();
+        User user = userService.getUserByEmail("admin@samsung.com");
+        Device device = deviceService.save(new Device(DUID, NAME, TYPE, MODEL, STATUS, policy, user));
+        assertNotNull(deviceService.findByUUID(DUID));
+        Cbor<HashMap<String, String>> cbor = new Cbor<>();
+        HashMap<String, String> map = new HashMap<>();
+        map.put(MessageQueueKeys.DUID.getKey(), DUID);
+        map.put(MessageQueueKeys.REPORT.getKey(), testInputData);
+        byte[] data = cbor.encodingPayloadToCbor(map);
+        ReportPostDataExtractor extractor = new ReportPostDataExtractor();
+        extractor.deviceService = deviceService;
+        extractor.reportService = reportService;
+        extractor.extract(data);
+        List<Report> list = reportService.getReports(device.getId());
+        assertTrue(list.size() == 1);
+        deviceService.remove(device);
+    }
+
+    @Test
+    public void testDeviceNotFoundExtractor() throws Exception {
+        Cbor<HashMap<String, String>> cbor = new Cbor<>();
+        HashMap<String, String> map = new HashMap<>();
+        map.put(MessageQueueKeys.DUID.getKey(), DUID);
+        map.put(MessageQueueKeys.REPORT.getKey(), testInputData);
+        byte[] data = cbor.encodingPayloadToCbor(map);
+        ReportPostDataExtractor extractor = new ReportPostDataExtractor();
+        extractor.deviceService = deviceService;
+        extractor.reportService = reportService;
+        extractor.extract(data);
+    }
+
+}
diff --git a/servermq/src/test/resources/iotivity.xml b/servermq/src/test/resources/iotivity.xml
new file mode 100644 (file)
index 0000000..f79f139
--- /dev/null
@@ -0,0 +1,65 @@
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
+       http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
+
+<bean id="reportExtractor"
+               class="com.samsung.servermq.iotivity.extractor.impl.ReportPostDataExtractor" />
+       <bean id="policyExtractor"
+               class="com.samsung.servermq.iotivity.extractor.impl.PolicyPostDataExtractor" />
+       <bean id="deviceRegExtractor"
+               class="com.samsung.servermq.iotivity.extractor.impl.DeviceRegistrationPostDataExtractor" />
+       <bean id="deviceUnRegExtractor"
+               class="com.samsung.servermq.iotivity.extractor.impl.DeviceUnRegistrationPostDataExtractor" />
+
+       <!-- <task:scheduled-tasks scheduler="listenerScheduler">
+               <task:scheduled ref="reportListener" method="getMessages"
+                       fixed-delay="5000" />
+               <task:scheduled ref="policytListener" method="getMessages"
+                       fixed-delay="5000" />
+               <task:scheduled ref="deviceRegListener" method="getMessages"
+                       fixed-delay="5000" />
+               <task:scheduled ref="deviceUnRegListener" method="getMessages"
+                       fixed-delay="5000" />
+       </task:scheduled-tasks> 
+
+       <task:scheduler id="listenerScheduler" />
+
+       <bean id="reportListener" class="com.samsung.servermq.iotivity.MessageQueueListener">
+               <constructor-arg name="zookeperHost" value="106.125.46.44:2181" />
+               <constructor-arg name="kafkaHost" value="106.125.46.44:9092" />
+               <constructor-arg name="topicName" value="/oic/ps/srv/report" />
+               <constructor-arg name="extractor" ref="reportExtractor" />
+               <constructor-arg name="listenerName" value="Report Listener" />
+       </bean>
+
+       <bean id="policytListener" class="com.samsung.servermq.iotivity.MessageQueueListener">
+               <constructor-arg name="zookeperHost" value="106.125.46.44:2181" />
+               <constructor-arg name="kafkaHost" value="106.125.46.44:9092" />
+               <constructor-arg name="topicName" value="/oic/ps/srv/policy" />
+               <constructor-arg name="extractor" ref="policyExtractor" />
+               <constructor-arg name="listenerName" value="Policy Listener" />
+       </bean>
+
+       <bean id="deviceRegListener" class="com.samsung.servermq.iotivity.MessageQueueListener">
+               <constructor-arg name="zookeperHost" value="106.125.46.44:2181" />
+               <constructor-arg name="kafkaHost" value="106.125.46.44:9092" />
+               <constructor-arg name="topicName" value="/oic/ps/srv/reg" />
+               <constructor-arg name="extractor" ref="deviceRegExtractor" />
+               <constructor-arg name="listenerName" value="Device Registretion Listener" />
+       </bean>
+
+       <bean id="deviceUnRegListener" class="com.samsung.servermq.iotivity.MessageQueueListener">
+               <constructor-arg name="zookeperHost" value="106.125.46.44:2181" />
+               <constructor-arg name="kafkaHost" value="106.125.46.44:9092" />
+               <constructor-arg name="topicName" value="/oic/ps/srv/unreg" />
+               <constructor-arg name="extractor" ref="deviceUnRegExtractor" />
+               <constructor-arg name="listenerName" value="Device UnRegistretion Listener" />
+       </bean>
+       -->
+       <bean id="messageQueuePublisher" class="com.samsung.servermq.iotivity.MessageQueuePublisher">
+               <constructor-arg name="kafkaHost" value="106.125.46.44:9092" />
+       </bean>
+</beans>
\ No newline at end of file
diff --git a/servermq/src/test/resources/root-context.xml b/servermq/src/test/resources/root-context.xml
new file mode 100644 (file)
index 0000000..48bb1e2
--- /dev/null
@@ -0,0 +1,12 @@
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
+       http://www.springframework.org/schema/context
+       http://www.springframework.org/schema/context/spring-context-3.2.xsd">
+
+    <import resource="iotivity.xml" />
+    <import resource="spring-database.xml" />
+    <context:component-scan base-package="com.samsung" />
+</beans>
\ No newline at end of file
diff --git a/servermq/src/test/resources/spring-database.xml b/servermq/src/test/resources/spring-database.xml
new file mode 100644 (file)
index 0000000..22c56c1
--- /dev/null
@@ -0,0 +1,50 @@
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:tx="http://www.springframework.org/schema/tx"
+       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
+       http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.1.xsd
+       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
+
+
+    <tx:annotation-driven transaction-manager="transactionManager" />
+    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
+        <property name="entityManagerFactory" ref="emf" />
+    </bean>
+
+    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
+        <property name="driverClass" value="org.h2.Driver" />
+        <property name="jdbcUrl" value="jdbc:h2:~/test" />
+        <property name="user" value="sa" />
+        <property name="password" value="" />
+
+        <!-- C3P0 properties -->
+        <property name="acquireIncrement" value="1" />
+        <property name="minPoolSize" value="2" />
+        <property name="maxPoolSize" value="5" />
+        <property name="maxIdleTime" value="1" />
+    </bean>
+
+    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
+        <property name="dataSource" ref="dataSource" />
+        <property name="packagesToScan" value="com.samsung, com.samsung.dsm.domain" />
+        <property name="jpaVendorAdapter">
+            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
+        </property>
+        <property name="jpaProperties">
+            <props>
+                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
+                <prop key="hibernate.show_sql">true</prop>
+                <prop key="hibernate.hbm2ddl.auto">create</prop>
+                <prop key="hibernate.hbm2ddl.import_files">sql/init.sql</prop>
+            </props>
+        </property>
+    </bean>
+
+    <jpa:repositories
+            base-package="com.samsung"
+            entity-manager-factory-ref="emf"
+            transaction-manager-ref="transactionManager" />
+
+</beans>
\ No newline at end of file
diff --git a/servermq/src/test/resources/sql/init.sql b/servermq/src/test/resources/sql/init.sql
new file mode 100644 (file)
index 0000000..dc595a1
--- /dev/null
@@ -0,0 +1,16 @@
+--Role table setup
+INSERT INTO roles (id, name) VALUES (nextval('roles_id_seq'), 'ROLE_ADMIN');
+INSERT INTO roles (id, name) VALUES (nextval('roles_id_seq'), 'ROLE_USER');
+
+--Report types setup
+INSERT INTO report_type (id, type) VALUES (nextval('report_type_id_seq'), 'sim');
+INSERT INTO report_type (id, type) VALUES (nextval('report_type_id_seq'), 'smart-security');
+INSERT INTO report_type (id, type) VALUES (nextval('report_type_id_seq'), 'smack');
+INSERT INTO report_type (id, type) VALUES (nextval('report_type_id_seq'), 'wbs');
+
+--Add admin user to the system
+-- login:    admin@samsung.com
+-- password: 111111
+INSERT INTO users(id, username, email, locked, date, role_id) VALUES (nextval('users_id_seq'), 'admin', 'admin@samsung.com', false, now(), 1);
+INSERT INTO user_details(id, password, restore_password_link, user_id) VALUES (nextval('user_details_id_seq'), '$2a$12$hrhsmzoFyO24LmyOaBgLnu4wZv1QS18oOv/vTRpo7upTlpPK9IS3a', 'link', 1);
+INSERT INTO iot_cloud_user(id, uuid, user_id) VALUES (nextval('iot_cloud_user_id_seq'), '1234567890', 1);
\ No newline at end of file