From a9f432b2e47a72107e6531a1e3d427daa3a9c065 Mon Sep 17 00:00:00 2001 From: Yevhen Zozulia Date: Thu, 21 Sep 2017 20:43:19 +0300 Subject: [PATCH] [SECIOTSRK-557] Fix SVACE issues and cascade user remove --- .../java/com/samsung/commons/domain/Agent.java | 2 + .../samsung/commons/domain/CustomUserDetails.java | 56 ++- .../java/com/samsung/commons/domain/Device.java | 3 +- .../samsung/commons/domain/GrantedApplication.java | 9 +- .../java/com/samsung/commons/domain/Policy.java | 35 +- .../java/com/samsung/commons/domain/Report.java | 5 +- .../com/samsung/commons/domain/ReportType.java | 18 +- .../main/java/com/samsung/commons/domain/Role.java | 18 +- .../main/java/com/samsung/commons/domain/User.java | 39 +- .../java/com/samsung/commons/model/MQPolicy.java | 16 +- .../com/samsung/commons/model/Notification.java | 23 +- .../commons/repository/AgentRepository.java | 3 +- .../commons/repository/DeviceRepository.java | 3 +- .../repository/GrantedApplicationRepository.java | 3 +- .../commons/repository/IotCloudUserRepository.java | 6 +- .../commons/repository/PolicyRepository.java | 2 +- .../commons/repository/ReportRepository.java | 8 +- .../commons/repository/ReportTypeRepository.java | 4 +- .../samsung/commons/repository/RoleRepository.java | 6 +- .../commons/repository/UserDetailsRepository.java | 2 +- .../samsung/commons/repository/UserRepository.java | 3 +- .../com/samsung/commons/service/AgentService.java | 3 +- .../com/samsung/commons/service/CommonService.java | 2 +- .../com/samsung/commons/service/DeviceService.java | 20 +- .../samsung/commons/service/IotCloudService.java | 4 +- .../com/samsung/commons/service/PolicyService.java | 8 +- .../com/samsung/commons/service/ReportService.java | 14 +- .../samsung/commons/service/ReportTypeService.java | 4 +- .../com/samsung/commons/service/RoleService.java | 6 +- .../commons/service/UserDetailsService.java | 3 +- .../com/samsung/commons/service/UserService.java | 12 +- .../commons/service/impl/AgentServiceImpl.java | 3 +- .../commons/service/impl/DeviceServiceImpl.java | 3 +- .../commons/service/impl/IotCloudServiceImpl.java | 1 + .../commons/service/impl/PolicyServiceImpl.java | 9 +- .../commons/service/impl/ReportServiceImpl.java | 15 +- .../service/impl/ReportTypeServiceImpl.java | 3 +- .../service/impl/UserDetailsServiceImpl.java | 7 +- .../commons/service/impl/UserServiceImpl.java | 57 ++- .../java/com/samsung/commons/utils/TestUtils.java | 22 +- .../main/java/com/samsung/commons/utils/Utils.java | 17 +- .../samsung/commons/DomainEqualsHashCodeTest.java | 29 +- .../com/samsung/commons/DomainToStringTest.java | 22 +- .../com/samsung/commons/EqualsVerfierTest.java | 55 ++- .../com/samsung/commons/IncreaseCoverageTest.java | 22 +- .../test/java/com/samsung/commons/UtilsTest.java | 9 +- .../samsung/commons/domain/agent/AgentTest.java | 7 +- .../samsung/commons/domain/device/DeviceTest.java | 8 +- .../domain/device/statistics/ReportTest.java | 7 +- .../domain/device/statistics/ReportTypeTest.java | 3 +- .../samsung/commons/domain/policy/PolicyTest.java | 3 +- .../commons/domain/user/CustomUserDetailsTest.java | 22 +- .../com/samsung/commons/domain/user/UserTest.java | 8 +- .../commons/pojo/PojoTestForMQRestDomain.java | 17 +- .../commons/pojo/PojoTestForMQRestModel.java | 42 +- .../commons/repository/AgentRepositoryTest.java | 1 + .../commons/repository/DeviceRepositoryTest.java | 1 + .../commons/repository/RoleRepositoryTest.java | 4 +- .../samsung/commons/service/AgentServiceTest.java | 20 +- .../samsung/commons/service/DeviceServiceTest.java | 493 ++++++++++----------- .../commons/service/IoTCloudServiceTest.java | 4 +- .../samsung/commons/service/PolicyServiceTest.java | 10 +- .../commons/service/ReportTypeServiceTest.java | 11 +- .../samsung/commons/service/RoleServiceTest.java | 8 +- .../commons/service/UserDetailsServiceTest.java | 24 +- .../samsung/commons/service/UserServiceTest.java | 136 +++--- .../commons/service/impl/ReportServiceTest.java | 111 ++++- .../com/samsung/commons/utils/TestUtilsTest.java | 3 +- .../samsung/dsm/controller/AccountController.java | 4 +- .../samsung/dsm/controller/AdminController.java | 12 +- .../dsm/controller/DashboardController.java | 16 +- .../dsm/controller/DashboardDevicesController.java | 40 +- .../com/samsung/dsm/controller/HomeController.java | 4 +- .../com/samsung/dsm/controller/UserController.java | 3 +- .../samsung/dsm/domain/oauth/OAuthAccessToken.java | 6 +- .../samsung/dsm/domain/oauth/OAuthClientToken.java | 6 +- .../com/samsung/dsm/domain/oauth/OAuthCode.java | 6 +- .../dsm/domain/oauth/OAuthRefreshToken.java | 6 +- .../com/samsung/dsm/model/request/ApplyPolicy.java | 7 +- .../com/samsung/dsm/model/request/EditUser.java | 4 +- .../com/samsung/dsm/model/request/NewUser.java | 16 +- .../samsung/dsm/model/request/ResetPassword.java | 2 +- .../com/samsung/dsm/model/restapi/RestDevice.java | 1 + .../model/restapi/converter/AgentConverter.java | 5 +- .../model/restapi/converter/DeviceConverter.java | 10 +- .../java/com/samsung/dsm/model/view/BaseView.java | 19 +- .../com/samsung/dsm/model/view/DeviceOverview.java | 8 +- .../java/com/samsung/dsm/model/view/ViewAgent.java | 11 +- .../com/samsung/dsm/model/view/ViewDashboard.java | 4 + .../com/samsung/dsm/model/view/ViewDevice.java | 1 + .../samsung/dsm/model/view/ViewPolicyGroup.java | 12 +- .../com/samsung/dsm/model/view/ViewReport.java | 7 +- .../java/com/samsung/dsm/policy/PolicyConfig.java | 3 + .../dsm/policy/parser/JSONPolicyConfigParser.java | 7 +- .../dsm/policy/parser/PolicyConfigParser.java | 3 +- .../dsm/policy/parser/PolicyParserFactory.java | 15 +- .../java/com/samsung/dsm/report/ReportConfig.java | 17 +- .../dsm/report/analyzer/ReportAnalyzer.java | 5 +- .../dsm/report/analyzer/ReportAnalyzerFactory.java | 6 +- .../dsm/report/analyzer/ReportAnalyzerKeys.java | 12 +- .../report/analyzer/impl/DACReportAnalyzer.java | 43 +- .../report/analyzer/impl/MACReportAnalyzer.java | 114 ++--- .../analyzer/impl/SYSCALLReportAnalyzer.java | 50 +-- .../dsm/report/parser/JSONReportConfigParser.java | 4 +- .../dsm/report/parser/ReportConfigParser.java | 3 +- .../dsm/repository/OAuthAccessTokenRepository.java | 2 +- .../dsm/rest/accesstoken/AccessTokenApi.java | 14 +- .../com/samsung/dsm/rest/device/DeviceApi.java | 14 +- .../com/samsung/dsm/rest/iotcloud/IotCloudApi.java | 44 +- .../iotcloud/IotCloudAssociatedUserNotExists.java | 1 + .../java/com/samsung/dsm/rest/mq/MQSenderImpl.java | 21 +- .../com/samsung/dsm/rest/policy/PolicyApi.java | 21 +- .../com/samsung/dsm/rest/report/ReportApi.java | 18 +- .../security/authentication/PasswordEncoder.java | 3 +- .../authentication/impl/BCPasswordEncoder.java | 6 +- .../dsm/service/GrantedApplicationService.java | 1 - .../samsung/dsm/service/LoginAuthCodeService.java | 4 +- .../dsm/service/OAuth2AuthorizationService.java | 6 +- .../dsm/service/impl/AccessTokenServiceImpl.java | 6 +- .../impl/GrantedApplicationServiceImpl.java | 2 +- .../impl/OAuth2AuthorizationServiceImpl.java | 29 +- .../LoginAuthCodeServiceClientCredentials.java | 1 + .../impl/auth/LoginAuthCodeServiceImpl.java | 7 +- .../java/com/samsung/dsm/EqualsHashCodeTest.java | 142 +++--- .../java/com/samsung/dsm/IncreaseCoverageTest.java | 39 +- .../test/java/com/samsung/dsm/ToStringTest.java | 68 +-- .../dsm/controller/AccountControllerTest.java | 59 +-- .../dsm/controller/AdminControllerTest.java | 6 +- .../dsm/controller/DashboardControllerTest.java | 14 +- .../controller/DashboardDevicesControllerTest.java | 93 ++-- .../samsung/dsm/controller/HomeControllerTest.java | 10 +- .../samsung/dsm/controller/UserControllerTest.java | 7 +- .../dsm/domain/oauth/OAuthAccessTokenTest.java | 5 +- .../dsm/domain/oauth/OAuthClientDetailsTest.java | 103 ++--- .../dsm/domain/oauth/OAuthClientTokenTest.java | 3 - .../samsung/dsm/domain/oauth/OAuthCodeTest.java | 3 +- .../dsm/domain/oauth/OAuthRefreshTokenTest.java | 47 +- .../samsung/dsm/model/request/ApplyPolicyTest.java | 1 + .../samsung/dsm/model/request/EditUserTest.java | 1 + .../com/samsung/dsm/model/request/NewUserTest.java | 1 + .../dsm/model/request/ResetPasswordTest.java | 1 + .../com/samsung/dsm/model/view/BaseViewTest.java | 54 ++- .../dsm/model/view/ViewPolicyGroupTest.java | 1 + .../com/samsung/dsm/model/view/ViewReportTest.java | 43 +- .../samsung/dsm/pojo/PojoTestForModelRequest.java | 38 +- .../com/samsung/dsm/pojo/PojoTestForModelRest.java | 35 +- .../samsung/dsm/policy/parser/JSONParserTest.java | 16 +- .../report/analyzer/ReportAnalyzerFactoryTest.java | 10 +- .../report/analyzer/ReportAnalyzerKeysTest.java | 2 +- .../analyzer/impl/DACReportAnalyzerTest.java | 75 ++-- .../analyzer/impl/MACReportAnalyzerTest.java | 215 ++++----- .../analyzer/impl/SYSCALLReportAnalyzerTest.java | 271 +++++------ .../java/com/samsung/dsm/rest/DeviceApiTest.java | 44 +- .../java/com/samsung/dsm/rest/IotCloudApiTest.java | 20 +- .../java/com/samsung/dsm/rest/PolicyApiTest.java | 34 +- .../java/com/samsung/dsm/rest/ReportApiTest.java | 418 +++++++++-------- .../dsm/rest/accesstoken/AccessTokenApiTest.java | 30 +- .../com/samsung/dsm/rest/mq/MQSenderImplMock.java | 14 +- .../java/com/samsung/dsm/rest/mq/MQSenderTest.java | 4 +- .../dsm/service/AccessTokenServiceTest.java | 13 +- .../impl/GrantedApplicationServiceTest.java | 2 +- .../impl/OAuth2AuthorizationServiceTest.java | 3 +- 162 files changed, 2122 insertions(+), 2072 deletions(-) diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/Agent.java b/servers/commons/src/main/java/com/samsung/commons/domain/Agent.java index cc3863a..fd30166 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/Agent.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/Agent.java @@ -19,6 +19,7 @@ import java.io.Serializable; @Entity @Table(name = "agent") public class Agent implements Serializable { + private static final long serialVersionUID = 2007572980069957750L; @Id @@ -185,6 +186,7 @@ public class Agent implements Serializable { if (this == o) { return true; } + if (o == null || getClass() != o.getClass()) { return false; } diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/CustomUserDetails.java b/servers/commons/src/main/java/com/samsung/commons/domain/CustomUserDetails.java index d3b35ad..d920e18 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/CustomUserDetails.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/CustomUserDetails.java @@ -14,7 +14,7 @@ import java.util.ArrayList; import java.util.Collection; /** - *

CustomUserDetails DAO table

+ *

CustomUserDetails DAO table

* DAO representation of CustomUserDetails. Is used by Security template * @see org.springframework.security.core.userdetails.UserDetails * @@ -33,7 +33,7 @@ public class CustomUserDetails implements Serializable, UserDetails { @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; + private Long id; /** The password. */ @Column @@ -46,7 +46,7 @@ public class CustomUserDetails implements Serializable, UserDetails { /** The user. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn(name = "user_id") - private User user; + private User user; /** * Instantiates a new custom user details. @@ -86,8 +86,11 @@ public class CustomUserDetails implements Serializable, UserDetails { this.id = id; } - /* (non-Javadoc) - * @see org.springframework.security.core.userdetails.UserDetails#getPassword() + /* + * (non-Javadoc) + * + * @see + * org.springframework.security.core.userdetails.UserDetails#getPassword() */ public String getPassword() { return password; @@ -138,48 +141,67 @@ public class CustomUserDetails implements Serializable, UserDetails { this.user = user; } - /* (non-Javadoc) - * @see org.springframework.security.core.userdetails.UserDetails#getAuthorities() + /* + * (non-Javadoc) + * + * @see + * org.springframework.security.core.userdetails.UserDetails#getAuthorities( + * ) */ @Override public Collection getAuthorities() { return new ArrayList<>(); } - /* (non-Javadoc) - * @see org.springframework.security.core.userdetails.UserDetails#getUsername() + /* + * (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() + /* + * (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() + /* + * (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() + /* + * (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() + /* + * (non-Javadoc) + * + * @see + * org.springframework.security.core.userdetails.UserDetails#isEnabled() */ @Override public boolean isEnabled() { diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/Device.java b/servers/commons/src/main/java/com/samsung/commons/domain/Device.java index a489461..10bc24f 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/Device.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/Device.java @@ -23,6 +23,7 @@ import static javax.persistence.CascadeType.ALL; @Entity @Table(name = "device") public class Device implements Serializable { + private static final long serialVersionUID = -8288082449066888034L; private static final List deviceTypeList; @@ -44,7 +45,7 @@ public class Device implements Serializable { } public enum Status { - DISCONNECTED(0), CONNECTED(1), ISSUES(2); + DISCONNECTED(0), CONNECTED(1), ISSUES(2); /** * The device status. diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/GrantedApplication.java b/servers/commons/src/main/java/com/samsung/commons/domain/GrantedApplication.java index 9a757ef..612c1ba 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/GrantedApplication.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/GrantedApplication.java @@ -8,10 +8,11 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.constraints.NotNull; + @Entity @Table(name = "granted_app") public class GrantedApplication { - + /** * The unique identifier in DB. */ @@ -25,14 +26,14 @@ public class GrantedApplication { * Granted command */ @NotNull - @Column(name="comm") + @Column(name = "comm") private String command; - + /** * Granted parent command */ @NotNull - @Column(name="p_comm") + @Column(name = "p_comm") private String parentCommand; public GrantedApplication() { diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/Policy.java b/servers/commons/src/main/java/com/samsung/commons/domain/Policy.java index 7a0c667..e40038c 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/Policy.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/Policy.java @@ -5,16 +5,23 @@ */ package com.samsung.commons.domain; -import com.samsung.commons.utils.Utils; -import org.hibernate.annotations.Type; - -import javax.persistence.*; import java.io.IOException; import java.io.Serializable; -import java.nio.charset.StandardCharsets; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.hibernate.annotations.Type; + +import com.samsung.commons.utils.Utils; /** - *

DAO class for Policy table

+ *

DAO class for Policy table

* Domain class for Policy. * * @author Andriy Petrov @@ -37,13 +44,16 @@ public class Policy implements Serializable { @Column private Long id; - /** The Policy file - * Contain list of Rules. Based on Policy format. */ + /** + * The Policy file + * Contain list of Rules. Based on Policy format. + */ @Column @Type(type = "text") private String policy; - /** The hash. + /** + * The hash. * Is used as checker of actual policy being applied on device. * Send 4bytes of hash is cheaper then sending all policy file. */ @@ -96,7 +106,7 @@ public class Policy implements Serializable { /** * Sets the policy * @param policy - the new policy - * @param route - route for + * @param route - route for */ public void setPolicy(String policy) { this.policy = policy.replace("\n", "").replace("\r", "").replace("\t", "").replace("\r", ""); @@ -131,7 +141,8 @@ public class Policy implements Serializable { * @throws IOException Signals that an I/O exception has occurred. */ public static String getDefaultPolicy() throws IOException { - return Utils.readAllFile(DEFAULT_POLICY_PATH, StandardCharsets.UTF_8).replace("\n", "").replace("\r", "").replace("\t", "").replace("\r", ""); + return Utils.readAllFile(DEFAULT_POLICY_PATH).replace("\n", "").replace("\r", "").replace("\t", "") + .replace("\r", ""); } /** @@ -195,6 +206,4 @@ public class Policy implements Serializable { return result; } - - } diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/Report.java b/servers/commons/src/main/java/com/samsung/commons/domain/Report.java index b591fbc..621e9bc 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/Report.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/Report.java @@ -22,6 +22,7 @@ import javax.persistence.*; @Entity @Table(name = "report") public class Report { + /** The unique ID in database table. */ @Id @SequenceGenerator(name = "report_id_seq", sequenceName = "report_id_seq", allocationSize = 1) @@ -48,7 +49,7 @@ public class Report { private Device device; /** - * Report generation date + * Report generation date */ @Column private String date; @@ -58,7 +59,7 @@ public class Report { */ @Column private Integer result; - + /** * Instantiates a new report. */ diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/ReportType.java b/servers/commons/src/main/java/com/samsung/commons/domain/ReportType.java index 58bf25a..dba44ce 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/ReportType.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/ReportType.java @@ -8,14 +8,14 @@ package com.samsung.commons.domain; import javax.persistence.*; /** - *

ReportType DAO table

+ *

ReportType DAO table

* DAO representation of all various of existing reports. *

* Reports are typically produced by various TV security services: *

* * @author Artem Motchanyi @@ -30,9 +30,7 @@ public class ReportType { * Enumeration of supported reports. */ public enum Type { - DAC("dac"), - SMACK("smack"), - SYSCALL("syscall"); + DAC("dac"), SMACK("smack"), SYSCALL("syscall"); /** The type. */ public final String type; @@ -61,7 +59,9 @@ public class ReportType { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Enum#toString() */ @Override @@ -76,7 +76,7 @@ public class ReportType { @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "report_type_id_seq") @Column private Long id; - + /** The type. */ @Column(unique = true) private String type; diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/Role.java b/servers/commons/src/main/java/com/samsung/commons/domain/Role.java index 730ccbf..81257b6 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/Role.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/Role.java @@ -9,7 +9,7 @@ import javax.persistence.*; import java.io.Serializable; /** - *

Role DAO table

+ *

Role DAO table

* DAO representation of role types for {@link User}. * @see User * @@ -26,14 +26,14 @@ public class Role implements Serializable { */ public enum Type { - /** Admin role.*/ - ADMIN("ROLE_ADMIN"), + /** Admin role. */ + ADMIN("ROLE_ADMIN"), - /** User role.*/ - USER("ROLE_USER"), + /** User role. */ + USER("ROLE_USER"), - /** Guest role (default).*/ - GUEST("ROLE_GUEST"); + /** Guest role (default). */ + GUEST("ROLE_GUEST"); /** The type. */ public final String type; @@ -47,7 +47,9 @@ public class Role implements Serializable { this.type = type; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Enum#toString() */ @Override diff --git a/servers/commons/src/main/java/com/samsung/commons/domain/User.java b/servers/commons/src/main/java/com/samsung/commons/domain/User.java index b480332..feffe25 100644 --- a/servers/commons/src/main/java/com/samsung/commons/domain/User.java +++ b/servers/commons/src/main/java/com/samsung/commons/domain/User.java @@ -10,8 +10,9 @@ import java.io.Serializable; import java.util.Date; /** - *

User DAO table

- * DAO representation of user table, used for account management in SecurityTemplate. + *

User DAO table

+ * DAO representation of user table, used for account management in + * SecurityTemplate. * * @author Sergii Shram * @version 1.0 @@ -35,11 +36,13 @@ public class User implements Serializable { private String username; /** The email. */ - @Column(unique=true) + @Column(unique = true) private String email; - - /** True if user is Locked. - * False otherwise */ + + /** + * True if user is Locked. + * False otherwise + */ @Column private Boolean locked; @@ -53,7 +56,8 @@ public class User implements Serializable { private Role role; /** - * Public constructor for class User. Creates object User with field locked = false; + * Public constructor for class User. Creates object User with field + * locked = false; */ public User() { locked = false; @@ -61,7 +65,8 @@ public class User implements Serializable { } /** - * Public constructor for class User with parameters. Creates object User with setting parameters + * Public constructor for class User with parameters. Creates object User + * with setting parameters * and locked = false; * @param username username of user. * @param email e-mail of user. @@ -126,7 +131,8 @@ public class User implements Serializable { /** * Method provides setting information is user locked or not. - * @param locked TRUE - setting user as locked; FALSE - setting user as isn't locked. + * @param locked TRUE - setting user as locked; FALSE - setting user as + * isn't locked. */ public void setLocked(Boolean locked) { this.locked = locked; @@ -140,7 +146,6 @@ public class User implements Serializable { return role; } - /** * Method provides setting role for user. * @param role {@link Role} of user (ROLE_ADMIN, ROLE_USER) @@ -193,18 +198,12 @@ public class User implements Serializable { * Method provides reflection to print * names and values of all fields declared in this class. Note that * superclass fields are left out of this implementation. - * @return String with names and values of all fields declared in this class. + * @return String with names and values of all fields declared in this + * class. */ @Override public String toString() { - return "User{" + - "id=" + id + - ", username='" + username + '\'' + - ", email='" + email + '\'' + - ", date='" + date + '\'' + - ", locked=" + locked + - ", role=" + role + - '}'; + return "User{" + "id=" + id + ", username='" + username + '\'' + ", email='" + email + '\'' + ", date='" + date + + '\'' + ", locked=" + locked + ", role=" + role + '}'; } } - diff --git a/servers/commons/src/main/java/com/samsung/commons/model/MQPolicy.java b/servers/commons/src/main/java/com/samsung/commons/model/MQPolicy.java index 23db314..5446471 100644 --- a/servers/commons/src/main/java/com/samsung/commons/model/MQPolicy.java +++ b/servers/commons/src/main/java/com/samsung/commons/model/MQPolicy.java @@ -27,15 +27,15 @@ public class MQPolicy { */ @NotNull(message = "required field") private String deviceId; - + /** * Policy for user */ @NotNull(message = "required field") private String policy; - + /** - *Route for HUB + * Route for HUB */ private String parentUuid; @@ -43,10 +43,11 @@ public class MQPolicy { * Create policy model to send Message Queue * */ - public MQPolicy(){} - + public MQPolicy() { + } + /** - * Create policy model to send Message Queue with parameters: + * Create policy model to send Message Queue with parameters: * @param agentId - agent id * @param deviceId - Device id * @param policy - Policy for user @@ -133,7 +134,8 @@ public class MQPolicy { */ @Override public String toString() { - return "MQPolicy [agentId=" + agentId + ", deviceId=" + deviceId + ", policy=" + policy + ", parentUuid=" + parentUuid + "]"; + return "MQPolicy [agentId=" + agentId + ", deviceId=" + deviceId + ", policy=" + policy + ", parentUuid=" + + parentUuid + "]"; } } diff --git a/servers/commons/src/main/java/com/samsung/commons/model/Notification.java b/servers/commons/src/main/java/com/samsung/commons/model/Notification.java index 13d51af..f834c07 100644 --- a/servers/commons/src/main/java/com/samsung/commons/model/Notification.java +++ b/servers/commons/src/main/java/com/samsung/commons/model/Notification.java @@ -30,31 +30,31 @@ public class Notification { */ @NotNull(message = "required field") private String deviceId; - + /** * 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 */ @@ -65,10 +65,12 @@ public class Notification { * Additional map for reports */ private Map additionalMap; + /** * Create notification model to send Message Queue */ - public Notification(){} + public Notification() { + } /** * Create notification model to send Message Queue with parameters: @@ -81,8 +83,8 @@ public class Notification { * @param policy - Policy for user * @param additionalMap - additional map */ - public Notification(String cloudUserId, String deviceId, Long currentTime, String code, String title, String message, - String policy, Map additionalMap) { + public Notification(String cloudUserId, String deviceId, Long currentTime, String code, String title, + String message, String policy, Map additionalMap) { super(); this.cloudUserId = cloudUserId; this.currentTime = currentTime; @@ -232,7 +234,8 @@ public class Notification { */ @Override public String toString() { - return "Notification [cloudUserId=" + cloudUserId + ", deviceId=" + deviceId + ", currentTime=" + currentTime + ", code=" + code - + ", title=" + title + ", message=" + message + ", policy=" + policy + ", additionalMap = " + additionalMap + "]"; + return "Notification [cloudUserId=" + cloudUserId + ", deviceId=" + deviceId + ", currentTime=" + currentTime + + ", code=" + code + ", title=" + title + ", message=" + message + ", policy=" + policy + + ", additionalMap = " + additionalMap + "]"; } } diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/AgentRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/AgentRepository.java index 9c0e769..cc2a83b 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/AgentRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/AgentRepository.java @@ -12,7 +12,7 @@ import org.springframework.stereotype.Repository; import java.util.List; /** - *

Agent repository

+ *

Agent repository

* Repository for Agent domain class. * @see Agent * @@ -22,6 +22,7 @@ import java.util.List; */ @Repository public interface AgentRepository extends CrudRepository { + /** * Get Agent by UUID * diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/DeviceRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/DeviceRepository.java index 126312d..8ab7cc3 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/DeviceRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/DeviceRepository.java @@ -14,7 +14,7 @@ import org.springframework.stereotype.Repository; import java.util.List; /** - *

Device repository

+ *

Device repository

* Repository for Device domain class. * * @author Artem Motchanyi @@ -24,6 +24,7 @@ import java.util.List; */ @Repository public interface DeviceRepository extends CrudRepository { + /** * Get Device by UUID * diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/GrantedApplicationRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/GrantedApplicationRepository.java index 4bc6801..b6f50e0 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/GrantedApplicationRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/GrantedApplicationRepository.java @@ -6,10 +6,9 @@ import com.samsung.commons.domain.GrantedApplication; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; - @Repository public interface GrantedApplicationRepository extends CrudRepository { - + /** * Get Granted Application by parent command and command * diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/IotCloudUserRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/IotCloudUserRepository.java index bff13db..fea3b8d 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/IotCloudUserRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/IotCloudUserRepository.java @@ -12,7 +12,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** - *

IotCloudUser repository

+ *

IotCloudUser repository

* * @author Oleksandr Abakumov * @version 1.0 @@ -20,7 +20,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Repository public interface IotCloudUserRepository extends CrudRepository { - + /** * Find Iot cloud user by UUID * @@ -28,7 +28,7 @@ public interface IotCloudUserRepository extends CrudRepository Policy repository + *

Policy repository

* Repository for Policy domain class. * @see Policy * diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/ReportRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/ReportRepository.java index 98cbb7d..f27c3d1 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/ReportRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/ReportRepository.java @@ -15,7 +15,7 @@ import org.springframework.stereotype.Repository; import java.util.List; /** - *

Report repository

+ *

Report repository

* Repository for reports. * * @author Artem Motchanyi @@ -26,13 +26,14 @@ import java.util.List; */ @Repository public interface ReportRepository extends CrudRepository { + /** * Get all Device's reports * * @param device_id Device's id in DB: {@link Device#getId()} * @return List of reports */ - List findByDeviceId(long device_id); + List findByDeviceId(long deviceId); /** * Get reports by device UUID @@ -50,5 +51,6 @@ public interface ReportRepository extends CrudRepository { * @return reports */ @Query(value = "select * from report r where r.device_id= :device_id and r.type_id= :type_id order by id desc limit :limit", nativeQuery = true) - List findByIdAndTypeOrderByIdDesc(@Param("device_id") long device_id, @Param("type_id") long type_id, @Param("limit") int limit); + List findByIdAndTypeOrderByIdDesc(@Param("device_id") long deviceId, @Param("type_id") long typeId, + @Param("limit") int limit); } diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/ReportTypeRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/ReportTypeRepository.java index 5952660..24812ad 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/ReportTypeRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/ReportTypeRepository.java @@ -9,9 +9,8 @@ import com.samsung.commons.domain.ReportType; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; - /** - *

ReportType repository

+ *

ReportType repository

* Repository for report types. * @see ReportType * @@ -21,6 +20,7 @@ import org.springframework.stereotype.Repository; */ @Repository public interface ReportTypeRepository extends CrudRepository { + /** * Get report type by name * diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/RoleRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/RoleRepository.java index 4e3f6de..9fce388 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/RoleRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/RoleRepository.java @@ -5,12 +5,12 @@ */ package com.samsung.commons.repository; -import com.samsung.commons.domain.Role; +import java.util.List; + import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; -import java.util.ArrayList; -import java.util.List; +import com.samsung.commons.domain.Role; /** *

Role repository

Repository for user roles. diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/UserDetailsRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/UserDetailsRepository.java index 8fae0ab..25f28d3 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/UserDetailsRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/UserDetailsRepository.java @@ -11,7 +11,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** - *

User Details repository

+ *

User Details repository

* UserDetailsRepository for security template. * @see CustomUserDetails * diff --git a/servers/commons/src/main/java/com/samsung/commons/repository/UserRepository.java b/servers/commons/src/main/java/com/samsung/commons/repository/UserRepository.java index 05b8544..51cb2aa 100644 --- a/servers/commons/src/main/java/com/samsung/commons/repository/UserRepository.java +++ b/servers/commons/src/main/java/com/samsung/commons/repository/UserRepository.java @@ -15,7 +15,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; /** - *

User Details repository

+ *

User Details repository

* CRUD repository for User class. * @see User * @@ -25,6 +25,7 @@ import java.util.List; */ @Repository public interface UserRepository extends CrudRepository { + /** * Get user by username * diff --git a/servers/commons/src/main/java/com/samsung/commons/service/AgentService.java b/servers/commons/src/main/java/com/samsung/commons/service/AgentService.java index 84ccbc2..99955e9 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/AgentService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/AgentService.java @@ -11,7 +11,7 @@ import com.samsung.commons.domain.Device; import java.util.List; /** - *

Agent service

+ *

Agent service

* Service interface for Agent repository. * * @author Artem Motchanyi @@ -20,6 +20,7 @@ import java.util.List; * @since 2017-06-29 */ public interface AgentService extends CommonService { + /** * Service method provides getting List of all agents in DB. * diff --git a/servers/commons/src/main/java/com/samsung/commons/service/CommonService.java b/servers/commons/src/main/java/com/samsung/commons/service/CommonService.java index 374700f..031ae9b 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/CommonService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/CommonService.java @@ -8,7 +8,7 @@ package com.samsung.commons.service; import com.samsung.commons.domain.Device; /** - *

Common service

+ *

Common service

* Common Service Provides common methods for all services. * @see Device * diff --git a/servers/commons/src/main/java/com/samsung/commons/service/DeviceService.java b/servers/commons/src/main/java/com/samsung/commons/service/DeviceService.java index 859176e..74d990f 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/DeviceService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/DeviceService.java @@ -13,7 +13,7 @@ import java.util.List; import java.util.Set; /** - *

Device service

+ *

Device service

* Service interface for Device repository. * * @author Artem Motchanyi @@ -22,6 +22,7 @@ import java.util.Set; * @since 2017-06-26 */ public interface DeviceService extends CommonService { + /** * Service method provides getting List of all devices in DB. * @@ -60,7 +61,7 @@ public interface DeviceService extends CommonService { * Get devices by user id and device status * * @param userId the user id - * @param type the device type + * @param type the device type * @return list of devices */ List findUserDevicesByType(long userId, String type); @@ -69,7 +70,7 @@ public interface DeviceService extends CommonService { * Add new agent to device * * @param deviceUuid device UUID - * @param agent agent + * @param agent agent * @throws IllegalArgumentException wrong UUID, or agent is null */ Device setDeviceAgents(String deviceUuid, Agent agent); @@ -77,16 +78,17 @@ public interface DeviceService extends CommonService { /** * Service method to create new Device in DB. * - * @param uuid unique device id - * @param name device name - * @param type device type - * @param model device model + * @param uuid unique device id + * @param name device name + * @param type device type + * @param model device model * @param status device status - * @param user user + * @param user user * @return {@link Device} * @throws Exception the empty name exception. */ - Device init(String uuid, String name, String type, String model, int status, User user, String route) throws Exception; + Device init(String uuid, String name, String type, String model, int status, User user, String route) + throws Exception; /** * Remove all devices diff --git a/servers/commons/src/main/java/com/samsung/commons/service/IotCloudService.java b/servers/commons/src/main/java/com/samsung/commons/service/IotCloudService.java index e4d7e25..2eaee84 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/IotCloudService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/IotCloudService.java @@ -11,7 +11,7 @@ import com.samsung.commons.domain.User; import java.util.List; /** - *

IotCloud service

+ *

IotCloud service

* * @author Oleksandr Abakumov * @version 1.0 @@ -22,7 +22,7 @@ public interface IotCloudService { /** * Save IOT Cloud user to table * - * @param email email + * @param email email * @param iotCloudUserUuid uuid UUID of IotCloud user * @return saved user or null if iot cloud user already exists * @throws IllegalArgumentException user can't be found by it's email diff --git a/servers/commons/src/main/java/com/samsung/commons/service/PolicyService.java b/servers/commons/src/main/java/com/samsung/commons/service/PolicyService.java index 9109df2..2e4de1b 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/PolicyService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/PolicyService.java @@ -8,7 +8,7 @@ package com.samsung.commons.service; import com.samsung.commons.domain.Policy; /** - *

Policy service

+ *

Policy service

* Service interface for Policy repository. * * @author Artem Motchanyi @@ -38,7 +38,7 @@ public interface PolicyService extends CommonService { * Get policy by device UUID and agent UUID * * @param deviceUuId device uuid - * @param agentUuId agent uuid + * @param agentUuId agent uuid * @return policy */ Policy findByDeviceUuidAndByAgentUuid(String deviceUuId, String agentUuId); @@ -47,7 +47,7 @@ public interface PolicyService extends CommonService { * Set device policy * * @param deviceUuid of the device - * @param policy to set + * @param policy to set * @return {@link Policy} * @throws Exception device doesn't exist exception. */ @@ -57,7 +57,7 @@ public interface PolicyService extends CommonService { * Set agent policy * * @param agentUuid of the agent - * @param policy to set + * @param policy to set * @return {@link Policy} * @throws Exception agent doesn't exist exception. */ diff --git a/servers/commons/src/main/java/com/samsung/commons/service/ReportService.java b/servers/commons/src/main/java/com/samsung/commons/service/ReportService.java index 3fb27bc..9b98f64 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/ReportService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/ReportService.java @@ -10,9 +10,8 @@ import java.util.List; import com.samsung.commons.domain.Report; import com.samsung.commons.domain.ReportType; - /** - *

Report service

+ *

Report service

* Service for device's reports. * * @author Artem Motchanyi @@ -21,14 +20,15 @@ import com.samsung.commons.domain.ReportType; * @since 2016-09-01 */ public interface ReportService extends CommonService { + /** * Service method saves report. * * @param deviceId id of Device - * @param type report type string - * @param date report date generation - * @param result report result - * @param report report + * @param type report type string + * @param date report date generation + * @param result report result + * @param report report * @return Report saved report. */ Report save(long deviceId, String type, String date, int result, String report); @@ -66,7 +66,7 @@ public interface ReportService extends CommonService { * @param limit * @return reports */ - List findByIdAndTypeOrderByIdDesc(long device_id, long type_id, int limit); + List findByIdAndTypeOrderByIdDesc(long deviceId, long typeId, int limit); /** * Get device's generated report types diff --git a/servers/commons/src/main/java/com/samsung/commons/service/ReportTypeService.java b/servers/commons/src/main/java/com/samsung/commons/service/ReportTypeService.java index f8183ff..0734073 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/ReportTypeService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/ReportTypeService.java @@ -5,11 +5,10 @@ */ package com.samsung.commons.service; - import com.samsung.commons.domain.ReportType; /** - *

ReportType service

+ *

ReportType service

* Service for report types. * @see ReportType * @@ -18,6 +17,7 @@ import com.samsung.commons.domain.ReportType; * @since 2016-09-01 */ public interface ReportTypeService extends CommonService { + /** * Service method returns ReportType by name in DB. * @param name unique report name diff --git a/servers/commons/src/main/java/com/samsung/commons/service/RoleService.java b/servers/commons/src/main/java/com/samsung/commons/service/RoleService.java index 309e28e..fd84641 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/RoleService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/RoleService.java @@ -5,11 +5,10 @@ */ package com.samsung.commons.service; -import com.samsung.commons.domain.Role; - -import java.util.ArrayList; import java.util.List; +import com.samsung.commons.domain.Role; + /** *

User Role service

Service for user roles. * @@ -20,6 +19,7 @@ import java.util.List; * @since 2016-09-01 */ public interface RoleService extends CommonService { + /** * Service method provides getting List of all roles in DB * diff --git a/servers/commons/src/main/java/com/samsung/commons/service/UserDetailsService.java b/servers/commons/src/main/java/com/samsung/commons/service/UserDetailsService.java index 1dd279d..d797b88 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/UserDetailsService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/UserDetailsService.java @@ -8,7 +8,7 @@ package com.samsung.commons.service; import com.samsung.commons.domain.CustomUserDetails; /** - *

User Details service

+ *

User Details service

* UserDetailsService for Security template * @see CustomUserDetails * @@ -17,6 +17,7 @@ import com.samsung.commons.domain.CustomUserDetails; * @since 2016-09-01 */ public interface UserDetailsService extends CommonService { + /** * Get user details by user ID * @param id of the user diff --git a/servers/commons/src/main/java/com/samsung/commons/service/UserService.java b/servers/commons/src/main/java/com/samsung/commons/service/UserService.java index 9dca920..f690486 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/UserService.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/UserService.java @@ -5,7 +5,6 @@ */ package com.samsung.commons.service; - import com.samsung.commons.domain.Role; import com.samsung.commons.domain.User; @@ -13,7 +12,7 @@ import javax.servlet.http.HttpServletRequest; import java.util.List; /** - *

User service

+ *

User service

* UserService for Security template. * * @author Sergii Shram @@ -32,7 +31,8 @@ public interface UserService extends CommonService { User findByUsername(String username); /** - * Service method provides checking if e-mail is available for registration(not used for others accounts). + * 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. @@ -40,7 +40,8 @@ public interface UserService extends CommonService { boolean isEmailAvailable(HttpServletRequest request); /** - * Service method provides checking if e-mail is available for registration(not used for others accounts). + * 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. @@ -55,7 +56,8 @@ public interface UserService extends CommonService { List getAll(boolean isDateAsc); /** - * Service method provides inverting of locked/unlocked state for user by ID. + * 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. diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/AgentServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/AgentServiceImpl.java index 0a037b5..2823ffc 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/AgentServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/AgentServiceImpl.java @@ -17,7 +17,7 @@ import org.springframework.stereotype.Service; import java.util.List; /** - *

Agent service

+ *

Agent service

* Service implementation for Agent repository. * @see Agent * @@ -81,6 +81,7 @@ public class AgentServiceImpl implements AgentService { @Override public Agent init(String uuid, String name, Device device) { + if (name.isEmpty() || uuid.isEmpty()) { throw new RuntimeException("Cannot create agent with empty fields"); } diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/DeviceServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/DeviceServiceImpl.java index a643c74..669a0f2 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/DeviceServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/DeviceServiceImpl.java @@ -19,7 +19,7 @@ import java.util.List; import java.util.Set; /** - *

Device service

+ *

Device service

* Service implementation for Device repository. * * @author Artem Motchanyi @@ -29,6 +29,7 @@ import java.util.Set; */ @Service("deviceService") public class DeviceServiceImpl implements DeviceService { + @Autowired private DeviceRepository deviceRepository; diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/IotCloudServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/IotCloudServiceImpl.java index 84ef1db..ea0796a 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/IotCloudServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/IotCloudServiceImpl.java @@ -29,6 +29,7 @@ public class IotCloudServiceImpl implements IotCloudService { } IotCloudUser iotCloudUser = new IotCloudUser(user, iotCloudUserUuid); + try { return repository.save(iotCloudUser); } catch (DataIntegrityViolationException e) { diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/PolicyServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/PolicyServiceImpl.java index 3f2b633..c9e846a 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/PolicyServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/PolicyServiceImpl.java @@ -17,7 +17,7 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; /** - *

Policy service

+ *

Policy service

* Service implementation for Policy repository. * * @author Andriy Petrov @@ -54,6 +54,7 @@ public class PolicyServiceImpl implements PolicyService { @Override public void remove(Policy policy) { + try { policyRepository.delete(policy); } catch (DataIntegrityViolationException e) { @@ -64,20 +65,22 @@ public class PolicyServiceImpl implements PolicyService { @Override public Policy findByDeviceId(long deviceId) { + try { return deviceRepository.findOne(deviceId).getPolicy(); } catch (NullPointerException e) { - //no device with such ID + // no device with such ID return null; } } @Override public Policy findByAgentId(long agentId) { + try { return agentRepository.findOne(agentId).getPolicy(); } catch (NullPointerException e) { - //no device with such ID + // no device with such ID return null; } } diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportServiceImpl.java index 6815a4e..039d63a 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportServiceImpl.java @@ -20,7 +20,7 @@ import java.util.ArrayList; import java.util.List; /** - *

Report service

+ *

Report service

* Implementation of the service for the Report repository. * * @author Artem Motchanyi @@ -48,14 +48,15 @@ public class ReportServiceImpl implements ReportService { t.setReport(strip(t.getReport())); return reportRepository.save(t); } - - private String strip(String str){ + + private String strip(String str) { return str.replace("\n", "").replace("\b", "").replace("\t", "").replace("\r", ""); } @Override public Report save(long deviceId, String type, String date, int result, String report) { - Report r = new Report(reportTypeRepository.findByType(ReportType.Type.getType(type).toString()), report, date, result, deviceRepository.findOne(deviceId)); + Report r = new Report(reportTypeRepository.findByType(ReportType.Type.getType(type) + .toString()), report, date, result, deviceRepository.findOne(deviceId)); return save(r); } @@ -96,8 +97,8 @@ public class ReportServiceImpl implements ReportService { } @Override - public List findByIdAndTypeOrderByIdDesc(long device_id, long type_id, int limit) { - return reportRepository.findByIdAndTypeOrderByIdDesc(device_id, type_id, limit); + public List findByIdAndTypeOrderByIdDesc(long deviceId, long typeId, int limit) { + return reportRepository.findByIdAndTypeOrderByIdDesc(deviceId, typeId, limit); } @Override @@ -107,7 +108,7 @@ public class ReportServiceImpl implements ReportService { for (ReportType.Type type : ReportType.Type.values()) { long reportTypeId = reportTypeService.findByName(type.toString()).getId(); - if (findByIdAndTypeOrderByIdDesc(deviceId, reportTypeId, 1).size() > 0) { + if (!findByIdAndTypeOrderByIdDesc(deviceId, reportTypeId, 1).isEmpty()) { reportTypes.add(type); } } diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportTypeServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportTypeServiceImpl.java index 0b11b9f..91d6353 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportTypeServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/ReportTypeServiceImpl.java @@ -12,7 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - *

ReportType service

+ *

ReportType service

* Implementation of the service for the ReportType repository. * @see ReportType * @@ -22,6 +22,7 @@ import org.springframework.stereotype.Service; */ @Service("reportTypeService") public class ReportTypeServiceImpl implements ReportTypeService { + @Autowired private ReportTypeRepository reportTypeRepository; diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/UserDetailsServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/UserDetailsServiceImpl.java index 1c437d3..402a45f 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/UserDetailsServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/UserDetailsServiceImpl.java @@ -21,7 +21,7 @@ import java.util.ArrayList; import java.util.List; /** - *

User Details service

+ *

User Details service

* Implementation of the service for the UserDetails repository. * @see CustomUserDetails * @@ -31,6 +31,7 @@ import java.util.List; */ @Service("userDetailsService") public class UserDetailsServiceImpl implements UserDetailsService, org.springframework.security.core.userdetails.UserDetailsService { + @Autowired private UserRepository userRepository; @Autowired @@ -73,8 +74,8 @@ public class UserDetailsServiceImpl implements UserDetailsService, org.springfra List authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(user.getRole().getName())); - return new org.springframework.security.core.userdetails.User(s, userDetails.getPassword(), true, true, true, - userDetails.isAccountNonLocked(), authorities); + return new org.springframework.security.core.userdetails.User(s, userDetails + .getPassword(), true, true, true, userDetails.isAccountNonLocked(), authorities); } @Override diff --git a/servers/commons/src/main/java/com/samsung/commons/service/impl/UserServiceImpl.java b/servers/commons/src/main/java/com/samsung/commons/service/impl/UserServiceImpl.java index 627884a..30ab05b 100644 --- a/servers/commons/src/main/java/com/samsung/commons/service/impl/UserServiceImpl.java +++ b/servers/commons/src/main/java/com/samsung/commons/service/impl/UserServiceImpl.java @@ -5,22 +5,27 @@ */ package com.samsung.commons.service.impl; -import com.samsung.commons.domain.Role; -import com.samsung.commons.domain.User; -import com.samsung.commons.repository.UserDetailsRepository; -import com.samsung.commons.repository.UserRepository; -import com.samsung.commons.service.UserService; +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 javax.servlet.http.HttpServletRequest; -import java.util.List; +import com.samsung.commons.domain.Agent; +import com.samsung.commons.domain.Device; +import com.samsung.commons.domain.Role; +import com.samsung.commons.domain.User; +import com.samsung.commons.repository.UserDetailsRepository; +import com.samsung.commons.repository.UserRepository; +import com.samsung.commons.service.AgentService; +import com.samsung.commons.service.DeviceService; +import com.samsung.commons.service.UserService; /** - *

User service

- * Implementation of the service for the User repository. + *

User service

Implementation of the service for the User repository. * * @author Sergii Shram * @version 1.0 @@ -29,12 +34,19 @@ import java.util.List; */ @Service("userService") public class UserServiceImpl implements UserService { + @Autowired private UserRepository userRepository; @Autowired private UserDetailsRepository userDetailsRepository; + @Autowired + private DeviceService deviceService; + + @Autowired + private AgentService agentService; + @Override public User getUserByEmail(String email) { return userRepository.findByEmail(email); @@ -55,9 +67,30 @@ public class UserServiceImpl implements UserService { return; } + List deivces = deviceService.findByUser(user); + + if (deivces != null && !deivces.isEmpty()) { + + for (Device device : deivces) { + List agents = agentService.findDeviceAgents(device.getUuid()); + + if (agents != null && !agents.isEmpty()) { + + for (Agent agent : agents) { + + agentService.remove(agent); + } + } + + deviceService.remove(device); + } + + } + if (userDetailsRepository.findByUserId(user.getId()) != null) { - //cascade remove of user details and user + // cascade remove of user details and user userDetailsRepository.deleteByUserId(user.getId()); + } else { // there is no user details for this user // so just remove user @@ -92,8 +125,10 @@ public class UserServiceImpl implements UserService { @Override public List getAll(boolean isDateAsc) { + if (isDateAsc) { - return (List) userRepository.findAllByOrderByDateAsc(); + return userRepository.findAllByOrderByDateAsc(); + } else { return (List) userRepository.findAll(); } diff --git a/servers/commons/src/main/java/com/samsung/commons/utils/TestUtils.java b/servers/commons/src/main/java/com/samsung/commons/utils/TestUtils.java index 9f2f481..fce5aae 100644 --- a/servers/commons/src/main/java/com/samsung/commons/utils/TestUtils.java +++ b/servers/commons/src/main/java/com/samsung/commons/utils/TestUtils.java @@ -13,20 +13,22 @@ import org.springframework.stereotype.Service; import java.util.Date; - /** * Collection of methods that helps to prepare data for tests */ @Service public class TestUtils { - private static final String testInputDataBegin = "{" + "\"did\": \"1234\"," + "\"date\": \"12:25 PM; May 08, 2017\"," - + "\"name\": \"dac\"," + "\"result\": 0," + "\"data\": {log:\""; - private static final String testInputDataEnd = "\"}}"; + private static final String TEST_INPUT_DATA_BEGIN = "{" + "\"did\": \"1234\"," + + "\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"dac\"," + "\"result\": 0," + "\"data\": {log:\""; + + private static final String TEST_INPUT_DATA_END = "\"}}"; - private static final String dacReport = testInputDataBegin + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String DAC_REPORT = TEST_INPUT_DATA_BEGIN + + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; private final DeviceService deviceService; @@ -44,9 +46,8 @@ public class TestUtils { @Autowired public TestUtils(DeviceService deviceService, ReportService reportService, AgentService agentService, - PolicyService policyService, - UserService userService, RoleService roleService, - ReportTypeService reportTypeService) { + PolicyService policyService, UserService userService, RoleService roleService, + ReportTypeService reportTypeService) { this.deviceService = deviceService; this.reportService = reportService; @@ -70,7 +71,7 @@ public class TestUtils { public Report createAndSaveReport(Device device) { ReportType type = reportTypeService.findByName("dac"); - return reportService.save(new Report(type, dacReport, "date", 1, device)); + return reportService.save(new Report(type, DAC_REPORT, "date", 1, device)); } public Agent createAndSaveAgent(Device device) { @@ -83,4 +84,3 @@ public class TestUtils { return userService.save(new User("user", "user1@mail", false, new Date(), userRole)); } } - diff --git a/servers/commons/src/main/java/com/samsung/commons/utils/Utils.java b/servers/commons/src/main/java/com/samsung/commons/utils/Utils.java index 027e6c1..c2c8ff0 100644 --- a/servers/commons/src/main/java/com/samsung/commons/utils/Utils.java +++ b/servers/commons/src/main/java/com/samsung/commons/utils/Utils.java @@ -2,8 +2,6 @@ package com.samsung.commons.utils; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; @@ -18,9 +16,6 @@ import org.springframework.core.io.Resource; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; -import com.google.gson.Gson; -import com.google.gson.JsonObject; - /** *

Utils

* Common utils methods. @@ -30,6 +25,7 @@ import com.google.gson.JsonObject; * @since 2016-09-01 */ public class Utils { + /** * Parse validation object into the new format Map<key,value>. * @@ -48,22 +44,26 @@ public class Utils { } public static Optional> ofEmpty(Collection collection) { + if (collection.isEmpty()) { return Optional.empty(); + } else { return Optional.of(collection); } } public static Optional> ofEmpty(List collection) { + if (collection.isEmpty()) { return Optional.empty(); + } else { return Optional.of(collection); } } - public static String readAllFile(String path, Charset encoding) throws IOException { + public static String readAllFile(String path) throws IOException { Resource resource = new ClassPathResource(path); InputStream resourceInputStream = resource.getInputStream(); @@ -73,14 +73,17 @@ public class Utils { } public static String returnView(HttpServletRequest request) { + if (request.isUserInRole("ROLE_ADMIN")) { return "redirect:/admin"; + } else if (request.isUserInRole("ROLE_USER")) { return "redirect:/user"; } return "login"; } - private Utils(){} + private Utils() { + } } diff --git a/servers/commons/src/test/java/com/samsung/commons/DomainEqualsHashCodeTest.java b/servers/commons/src/test/java/com/samsung/commons/DomainEqualsHashCodeTest.java index 9740215..7c5f7dd 100644 --- a/servers/commons/src/test/java/com/samsung/commons/DomainEqualsHashCodeTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/DomainEqualsHashCodeTest.java @@ -37,32 +37,25 @@ public class DomainEqualsHashCodeTest { Agent agent = new Agent(); IotCloudUser cloudUser = new IotCloudUser(); - Object[][] data = new Object[][]{ - {new Agent(), new Agent(), 0, true}, - {new Agent(), null, 0, false}, - {new Agent(), "", 0, false}, - {agent, agent, 0, true}, - - {new IotCloudUser(), new IotCloudUser(), 0, true}, - {new IotCloudUser(), null, 0, false}, - {new IotCloudUser(), "", 0, false}, - {cloudUser, cloudUser, 0, true}, - - {new Policy(), new Policy(), 29791, true}, - {new Policy(), null, 29791, false}, - {new Policy(), "", 29791, false}, - {new Policy("policy"), new Policy("policy"), -435733949, true}, - {new Policy(), new Policy("policy"), 29791, false}, - {policy, policy, 29791, true}, - }; + Object[][] data = new Object[][] { { new Agent(), new Agent(), 0, true }, { new Agent(), null, 0, false }, + { new Agent(), "", 0, false }, { agent, agent, 0, true }, + + { new IotCloudUser(), new IotCloudUser(), 0, true }, { new IotCloudUser(), null, 0, false }, + { new IotCloudUser(), "", 0, false }, { cloudUser, cloudUser, 0, true }, + + { new Policy(), new Policy(), 29791, true }, { new Policy(), null, 29791, false }, + { new Policy(), "", 29791, false }, { new Policy("policy"), new Policy("policy"), -435733949, true }, + { new Policy(), new Policy("policy"), 29791, false }, { policy, policy, 29791, true }, }; return Arrays.asList(data); } @Test public void equalsTest() { + if (mustBeEqual) { assertThat("Instances must be equal", thiz, is(that)); + } else { assertThat("Instances mustn't be equal", thiz, is(not(that))); } diff --git a/servers/commons/src/test/java/com/samsung/commons/DomainToStringTest.java b/servers/commons/src/test/java/com/samsung/commons/DomainToStringTest.java index 7bce686..4997baf 100644 --- a/servers/commons/src/test/java/com/samsung/commons/DomainToStringTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/DomainToStringTest.java @@ -38,16 +38,18 @@ public class DomainToStringTest { Role role = new Role(); User userWithParams = new User("username", "email", true, date, role); - Object[][] data = new Object[][]{ - {new Agent(), "Agent{id=null, uuid='null', name='null', policy=null, device=null}"}, - {new GrantedApplication(), "GrantedApplication [id=null, command=null, parrentCommand=null]"}, - {new GrantedApplication("command", "parentCommand"), "GrantedApplication [id=null, command=command, parrentCommand=parentCommand]"}, - {new Policy(), "Policy [id=null, policy=null, hash=0]"}, - {new Report(), "Report [id=null, type=null, report=null, device=null]"}, - - {user, format("User{id=null, username='null', email='null', date='%s', locked=false, role=null}", user.getDate())}, - {userWithParams, format("User{id=null, username='%s', email='%s', date='%s', locked=true, role=%s}", "username", "email", date, role)}, - }; + Object[][] data = new Object[][] { + { new Agent(), "Agent{id=null, uuid='null', name='null', policy=null, device=null}" }, + { new GrantedApplication(), "GrantedApplication [id=null, command=null, parrentCommand=null]" }, + { new GrantedApplication("command", "parentCommand"), + "GrantedApplication [id=null, command=command, parrentCommand=parentCommand]" }, + { new Policy(), "Policy [id=null, policy=null, hash=0]" }, + { new Report(), "Report [id=null, type=null, report=null, device=null]" }, + + { user, format("User{id=null, username='null', email='null', date='%s', locked=false, role=null}", user + .getDate()) }, + { userWithParams, + format("User{id=null, username='%s', email='%s', date='%s', locked=true, role=%s}", "username", "email", date, role) }, }; return Arrays.asList(data); } diff --git a/servers/commons/src/test/java/com/samsung/commons/EqualsVerfierTest.java b/servers/commons/src/test/java/com/samsung/commons/EqualsVerfierTest.java index b1cf464..795e575 100644 --- a/servers/commons/src/test/java/com/samsung/commons/EqualsVerfierTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/EqualsVerfierTest.java @@ -1,6 +1,5 @@ package com.samsung.commons; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -20,44 +19,42 @@ public class EqualsVerfierTest { @Test public void equalsContract() { EqualsVerifier.forClass(GrantedApplication.class) - .withPrefabValues(GrantedApplication.class, new GrantedApplication(), new GrantedApplication("","")) - .withPrefabValues(GrantedApplication.class, new GrantedApplication(), new GrantedApplication(null,"")) - .withPrefabValues(GrantedApplication.class, new GrantedApplication(), new GrantedApplication("",null)) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",""), new GrantedApplication("",null)) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",""), new GrantedApplication(null,"")) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",""), new GrantedApplication()) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",null), new GrantedApplication()) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",null), new GrantedApplication("1", null)) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",null), new GrantedApplication(null, "1111")) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("111",null), new GrantedApplication("111", "1111")) - .withPrefabValues(GrantedApplication.class, new GrantedApplication(null,""), new GrantedApplication()) - .withPrefabValues(GrantedApplication.class, new GrantedApplication(null,""), new GrantedApplication(null, "1")) - .withPrefabValues(GrantedApplication.class, new GrantedApplication("",null), new GrantedApplication(null, null)) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT).suppress(Warning.NONFINAL_FIELDS).suppress(Warning.STRICT_INHERITANCE) - .withIgnoredFields("id") - .usingGetClass().verify(); + .withPrefabValues(GrantedApplication.class, new GrantedApplication(), new GrantedApplication("", "")) + .withPrefabValues(GrantedApplication.class, new GrantedApplication(), new GrantedApplication(null, "")) + .withPrefabValues(GrantedApplication.class, new GrantedApplication(), new GrantedApplication("", null)) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", ""), new GrantedApplication("", null)) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", ""), new GrantedApplication(null, "")) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", ""), new GrantedApplication()) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", null), new GrantedApplication()) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", null), new GrantedApplication("1", null)) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", null), new GrantedApplication(null, "1111")) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("111", null), new GrantedApplication("111", "1111")) + .withPrefabValues(GrantedApplication.class, new GrantedApplication(null, ""), new GrantedApplication()) + .withPrefabValues(GrantedApplication.class, new GrantedApplication(null, ""), new GrantedApplication(null, "1")) + .withPrefabValues(GrantedApplication.class, new GrantedApplication("", null), new GrantedApplication(null, null)) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT).suppress(Warning.NONFINAL_FIELDS) + .suppress(Warning.STRICT_INHERITANCE).withIgnoredFields("id").usingGetClass().verify(); EqualsVerifier.forClass(IotCloudUser.class).usingGetClass().verify(); - EqualsVerifier.forClass(Agent.class) - .withIgnoredFields("id", "name", "policy", "device") - .withPrefabValues(Agent.class, new Agent("uuid1", "name1", new Policy("test")), new Agent("uuid2", "name2", new Policy())) - .withPrefabValues(Agent.class, new Agent(null, "name1", new Policy("test")), new Agent("uuid", "name2", new Policy())) - .withPrefabValues(Agent.class, new Agent("uuid", "name1", new Policy("test")), new Agent(null, "name2", new Policy())) - .withPrefabValues(Device.class, new Device("uuid1", "name1", "tv", "model1", 1, new Policy(), new User(),"parentUuid"), new Device("uuid2", "name2", "tv", "model2", 1,new Policy(), new User(),"parentUuid")) - .usingGetClass().verify(); - + EqualsVerifier.forClass(Agent.class).withIgnoredFields("id", "name", "policy", "device") + .withPrefabValues(Agent.class, new Agent("uuid1", "name1", new Policy("test")), new Agent("uuid2", "name2", new Policy())) + .withPrefabValues(Agent.class, new Agent(null, "name1", new Policy("test")), new Agent("uuid", "name2", new Policy())) + .withPrefabValues(Agent.class, new Agent("uuid", "name1", new Policy("test")), new Agent(null, "name2", new Policy())) + .withPrefabValues(Device.class, new Device("uuid1", "name1", "tv", "model1", 1, new Policy(), new User(), "parentUuid"), new Device("uuid2", "name2", "tv", "model2", 1, new Policy(), new User(), "parentUuid")) + .usingGetClass().verify(); + EqualsVerifier.forClass(Policy.class).usingGetClass().verify(); - + } - + @Test - public void testEqualsGrantedApplication(){ + public void testEqualsGrantedApplication() { GrantedApplication g1 = new GrantedApplication(); GrantedApplication g2 = new GrantedApplication(); assertTrue(g1.equals(g2)); } @Test - public void testHashCodeGrantedApplication(){ + public void testHashCodeGrantedApplication() { GrantedApplication g1 = new GrantedApplication(); GrantedApplication g2 = new GrantedApplication(); assertTrue(g1.hashCode() == g2.hashCode()); diff --git a/servers/commons/src/test/java/com/samsung/commons/IncreaseCoverageTest.java b/servers/commons/src/test/java/com/samsung/commons/IncreaseCoverageTest.java index 287a8d0..97fbd38 100644 --- a/servers/commons/src/test/java/com/samsung/commons/IncreaseCoverageTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/IncreaseCoverageTest.java @@ -1,6 +1,5 @@ package com.samsung.commons; - import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -8,7 +7,6 @@ import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; -import java.nio.charset.StandardCharsets; import org.junit.Test; @@ -41,14 +39,12 @@ public class IncreaseCoverageTest { Policy policy = new Policy(""); policy.setId(null); policy.setDefaultPolicy(); - } private static void role() { new Role(null, null); } - @SuppressWarnings("ConstantConditions") private static void device() { Device device = new Device(); device.setId(null); @@ -95,7 +91,7 @@ public class IncreaseCoverageTest { } @Test - public void testEnum(){ + public void testEnum() { superficialEnumCodeCoverage(Device.Status.class); assertTrue(Role.Type.valueOf("ADMIN") == Role.Type.ADMIN); assertTrue(Role.Type.valueOf("GUEST") == Role.Type.GUEST); @@ -116,7 +112,8 @@ public class IncreaseCoverageTest { } @Test - public void testPrivateConstructors() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + public void testPrivateConstructors() + throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final Constructor[] constructors = Utils.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { assertTrue(Modifier.isPrivate(constructor.getModifiers())); @@ -125,16 +122,17 @@ public class IncreaseCoverageTest { assertNotNull(utils); } } - + @Test - public void testEnumValues(){ + public void testEnumValues() { assertNotNull(Role.Type.values()); assertNotNull(ReportType.Type.values()); } - + @Test - public void testUtilsReadFiles() throws IOException{ - assertNotNull(Utils.readAllFile("", StandardCharsets.UTF_8)); - assertNotNull(Utils.readAllFile("default-policy.json", StandardCharsets.UTF_8)); + public void testUtilsReadFiles() throws IOException { + assertNotNull(Utils.readAllFile("")); + assertNotNull(Utils.readAllFile("default-policy.json")); + assertNotNull(Utils.readAllFile("\\sql\\")); } } diff --git a/servers/commons/src/test/java/com/samsung/commons/UtilsTest.java b/servers/commons/src/test/java/com/samsung/commons/UtilsTest.java index b4ad8c8..4e6731e 100644 --- a/servers/commons/src/test/java/com/samsung/commons/UtilsTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/UtilsTest.java @@ -28,6 +28,7 @@ import com.samsung.commons.utils.Utils; * Created by o.abakumov on 6/30/2017. */ public class UtilsTest { + @Mock private HttpServletRequest request; @@ -36,7 +37,6 @@ public class UtilsTest { initMocks(this); } - @Test public void ofEmpty() { List list = new ArrayList<>(); @@ -58,6 +58,7 @@ public class UtilsTest { @Test @SuppressWarnings(value = "unchecked") public void ofEmptyCollection() { + @SuppressWarnings("rawtypes") Collection collection = new ArrayList<>(); collection.add(new Object()); @@ -65,13 +66,13 @@ public class UtilsTest { } @Test - @SuppressWarnings(value = "unchecked") + @SuppressWarnings(value = { "unchecked", "rawtypes" }) public void ofEmptyCollectionEmpty() { - assertThat(Utils.ofEmpty((Collection)new ArrayList<>()).isPresent(), is(false)); + assertThat(Utils.ofEmpty((Collection) new ArrayList<>()).isPresent(), is(false)); } @Test(expected = NullPointerException.class) - @SuppressWarnings(value = "unchecked") + @SuppressWarnings(value = { "unchecked", "rawtypes" }) public void ofEmptyNullCollection() { Utils.ofEmpty((Collection) null); } diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/agent/AgentTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/agent/AgentTest.java index 0e0687b..fe0b9dc 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/agent/AgentTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/agent/AgentTest.java @@ -29,6 +29,7 @@ import org.mockito.MockitoAnnotations; @RunWith(Parameterized.class) public class AgentTest { + private String name; private String uuid; @@ -39,11 +40,7 @@ public class AgentTest { @Parameters public static Collection data() { - Object[][] data = new Object[][] { - { "uuid1", "name1"}, - { "uuid2", "name2"}, - { "uuid3", "name3"} - }; + Object[][] data = new Object[][] { { "uuid1", "name1" }, { "uuid2", "name2" }, { "uuid3", "name3" } }; return Arrays.asList(data); } diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/device/DeviceTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/device/DeviceTest.java index e020415..b0d5678 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/device/DeviceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/device/DeviceTest.java @@ -30,6 +30,7 @@ import org.mockito.MockitoAnnotations; @RunWith(Parameterized.class) public class DeviceTest { + private String name; private String uuid; private String type; @@ -46,11 +47,8 @@ public class DeviceTest { @Parameters public static Collection data() { - Object[][] data = new Object[][] { - { "uuid1", "name1", "type1", "model1", 1 }, - { "uuid2", "name2", "type2", "model2", 2 }, - { "uuid3", "name3", "type3", "model3", 3 } - }; + Object[][] data = new Object[][] { { "uuid1", "name1", "type1", "model1", 1 }, + { "uuid2", "name2", "type2", "model2", 2 }, { "uuid3", "name3", "type3", "model3", 3 } }; return Arrays.asList(data); } diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTest.java index e52ca41..8e76a0b 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTest.java @@ -15,7 +15,8 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** - * @author Mail to: Artem Motchanyi, a.motchanyi@samsung.com + * @author Mail to: Artem Motchanyi, + * a.motchanyi@samsung.com * @version 1.0 * @file Report.java * @brief Tests for Report domain class. @@ -109,13 +110,13 @@ public class ReportTest { obj.addProperty("name", "name"); s.append(gson.toJson(obj).replace("}", ",date:{t:1, t2:2}}") + ","); obj.addProperty("data", "{t:1, t2:2}"); - + arr.add(obj); JsonObject obj1 = new JsonObject(); obj1.addProperty("name", "name"); s = s.append(gson.toJson(obj1).replace("}", ",date:{t:1, t2:2}},")); obj1.addProperty("data", "{t:1, t2:2}"); - + s.deleteCharAt(s.length() - 1).append(']'); System.out.println(s); arr.add(obj1); diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTypeTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTypeTest.java index 24f0b0a..d142993 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTypeTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/device/statistics/ReportTypeTest.java @@ -9,7 +9,6 @@ import com.samsung.commons.domain.ReportType; import org.junit.Before; import org.junit.Test; - public class ReportTypeTest { private ReportType reportType; @@ -48,5 +47,5 @@ public class ReportTypeTest { assertNotEquals(old, reportType.getType()); assertEquals(newType, reportType.getType()); } - + } diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/policy/PolicyTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/policy/PolicyTest.java index 205d46b..a0a26c7 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/policy/PolicyTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/policy/PolicyTest.java @@ -32,6 +32,7 @@ import com.samsung.commons.domain.Policy; @RunWith(Parameterized.class) public class PolicyTest { + private String policyJSON; private int hash; @@ -105,7 +106,7 @@ public class PolicyTest { } @Test - public void testSetDefaultPolicy() throws Exception{ + public void testSetDefaultPolicy() throws Exception { Policy policy = Mockito.spy(new Policy()); String str = Policy.getDefaultPolicy(); Mockito.doThrow(IOException.class).when(policy).setPolicy(str); diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/user/CustomUserDetailsTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/user/CustomUserDetailsTest.java index 7a9a07e..390693a 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/user/CustomUserDetailsTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/user/CustomUserDetailsTest.java @@ -97,7 +97,8 @@ public class CustomUserDetailsTest { } /** - * Checks {@link CustomUserDetails#getAuthorities()} returns empty collection + * Checks {@link CustomUserDetails#getAuthorities()} returns empty + * collection */ @Test public void getAuthoritiesTest() { @@ -109,7 +110,8 @@ public class CustomUserDetailsTest { } /** - * Checks {@link CustomUserDetails#getUsername()} invokes {@link User#getUsername()} and returns its userName + * Checks {@link CustomUserDetails#getUsername()} invokes + * {@link User#getUsername()} and returns its userName */ @Test public void getUserNameTest() { @@ -139,7 +141,8 @@ public class CustomUserDetailsTest { } /** - * Checks {@link CustomUserDetails#isAccountNonLocked()} invokes {@link User#getLocked()} and returns lock status + * Checks {@link CustomUserDetails#isAccountNonLocked()} invokes + * {@link User#getLocked()} and returns lock status */ @Test public void isAccountNonLockedTest() { @@ -153,9 +156,10 @@ public class CustomUserDetailsTest { assertEquals(expected, details.isAccountNonLocked()); verify(mockedUser).getLocked(); } - + /** - * Checks {@link CustomUserDetails#isAccountNonLocked()} invokes {@link User#getLocked()} and returns lock status + * Checks {@link CustomUserDetails#isAccountNonLocked()} invokes + * {@link User#getLocked()} and returns lock status */ @Test public void isAccountNonLocked_falseTest() { @@ -183,7 +187,8 @@ public class CustomUserDetailsTest { } /** - * Checks {@link CustomUserDetails#isEnabled()} invokes {@link User#getLocked()} and returns lock status + * Checks {@link CustomUserDetails#isEnabled()} invokes + * {@link User#getLocked()} and returns lock status */ @Test public void isEnabledTest() { @@ -197,9 +202,10 @@ public class CustomUserDetailsTest { assertEquals(expected, details.isEnabled()); verify(mockedUser).getLocked(); } - + /** - * Checks {@link CustomUserDetails#isEnabled()} invokes {@link User#getLocked()} and returns lock status + * Checks {@link CustomUserDetails#isEnabled()} invokes + * {@link User#getLocked()} and returns lock status */ @Test public void isEnabled_falseTest() { diff --git a/servers/commons/src/test/java/com/samsung/commons/domain/user/UserTest.java b/servers/commons/src/test/java/com/samsung/commons/domain/user/UserTest.java index 7d71b69..f845155 100644 --- a/servers/commons/src/test/java/com/samsung/commons/domain/user/UserTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/domain/user/UserTest.java @@ -120,12 +120,12 @@ public class UserTest { String toString = user.toString(); - //User{id=1, username='user', email='user@company.com', - //date='Tue Jul 19 13:16:53 EEST 2016', locked=false, role=role} + // User{id=1, username='user', email='user@company.com', + // date='Tue Jul 19 13:16:53 EEST 2016', locked=false, role=role} assertTrue(toString.contains("User{")); assertTrue(toString.contains("id=" + user.getId())); - assertTrue(toString.contains("email='" + user.getEmail()+"'")); - assertTrue(toString.contains("date='" + user.getDate()+"'")); + assertTrue(toString.contains("email='" + user.getEmail() + "'")); + assertTrue(toString.contains("date='" + user.getDate() + "'")); assertTrue(toString.contains("locked=" + user.getLocked())); assertTrue(toString.contains("role=" + user.getRole())); } diff --git a/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestDomain.java b/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestDomain.java index a1f5d2c..28996f1 100644 --- a/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestDomain.java +++ b/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestDomain.java @@ -13,7 +13,9 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; public class PojoTestForMQRestDomain { - // Configured for expectation, so we know when a class gets added or removed. + + // Configured for expectation, so we know when a class gets added or + // removed. private static final int EXPECTED_CLASS_COUNT = 13; // The package to test @@ -21,19 +23,16 @@ public class PojoTestForMQRestDomain { @Test public void ensureExpectedPojoCount() { - List pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); - Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); + List pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); + Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); } @Test public void testPojoStructureAndBehavior() { - Validator validator = ValidatorBuilder.create() - .with(new TestClassMustBeProperlyNamedRule()) - .with(new SetterTester()) - .with(new GetterTester()) - .build(); + Validator validator = ValidatorBuilder.create().with(new TestClassMustBeProperlyNamedRule()) + .with(new SetterTester()).with(new GetterTester()).build(); - validator.validate(POJO_PACKAGE, new FilterPackageInfo()); + validator.validate(POJO_PACKAGE, new FilterPackageInfo()); } } diff --git a/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestModel.java b/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestModel.java index 9c73ff3..2519650 100644 --- a/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestModel.java +++ b/servers/commons/src/test/java/com/samsung/commons/pojo/PojoTestForMQRestModel.java @@ -4,9 +4,6 @@ import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.List; -import java.util.Map; - -import javax.validation.constraints.AssertTrue; import org.junit.Test; @@ -16,16 +13,18 @@ import com.openpojo.reflection.impl.PojoClassFactory; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; import com.openpojo.validation.affirm.Affirm; -import com.openpojo.validation.rule.impl.TestClassMustBeProperlyNamedRule; import com.openpojo.validation.rule.impl.GetterMustExistRule; import com.openpojo.validation.rule.impl.SetterMustExistRule; +import com.openpojo.validation.rule.impl.TestClassMustBeProperlyNamedRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; import com.samsung.commons.model.MQPolicy; import com.samsung.commons.model.Notification; public class PojoTestForMQRestModel { - // Configured for expectation, so we know when a class gets added or removed. + + // Configured for expectation, so we know when a class gets added or + // removed. private static final int EXPECTED_CLASS_COUNT = 2; // The package to test @@ -33,32 +32,31 @@ public class PojoTestForMQRestModel { @Test public void ensureExpectedPojoCount() { - List pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); - Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); + List pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); + Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); } @Test public void testPojoStructureAndBehavior() { - Validator validator = ValidatorBuilder.create() - // Add Rules to validate structure for POJO_PACKAGE - // See com.openpojo.validation.rule.impl for more ... - .with(new GetterMustExistRule()) - .with(new SetterMustExistRule()) - .with(new TestClassMustBeProperlyNamedRule()) - // Add Testers to validate behaviour for POJO_PACKAGE - // See com.openpojo.validation.test.impl for more ... - .with(new SetterTester()) - .with(new GetterTester()) - .build(); - - validator.validate(POJO_PACKAGE, new FilterPackageInfo()); + Validator validator = ValidatorBuilder.create() + // Add Rules to validate structure for POJO_PACKAGE + // See com.openpojo.validation.rule.impl for more ... + .with(new GetterMustExistRule()).with(new SetterMustExistRule()) + .with(new TestClassMustBeProperlyNamedRule()) + // Add Testers to validate behaviour for POJO_PACKAGE + // See com.openpojo.validation.test.impl for more ... + .with(new SetterTester()).with(new GetterTester()).build(); + + validator.validate(POJO_PACKAGE, new FilterPackageInfo()); } @Test public void testToString() { MQPolicy policy = new MQPolicy("agentId", "deviceId", "policy", "parentUuid"); - assertTrue(policy.toString().equals("MQPolicy [agentId=agentId, deviceId=deviceId, policy=policy, parentUuid=parentUuid]")); + assertTrue(policy.toString() + .equals("MQPolicy [agentId=agentId, deviceId=deviceId, policy=policy, parentUuid=parentUuid]")); Notification notification = new Notification("cloudUserId", "deviceId", 1l, "code", "title", "message", "policy", new HashMap()); - assertTrue(notification.toString().equals("Notification [cloudUserId=cloudUserId, deviceId=deviceId, currentTime=1, code=code, title=title, message=message, policy=policy, additionalMap = {}]")); + assertTrue(notification.toString() + .equals("Notification [cloudUserId=cloudUserId, deviceId=deviceId, currentTime=1, code=code, title=title, message=message, policy=policy, additionalMap = {}]")); } } diff --git a/servers/commons/src/test/java/com/samsung/commons/repository/AgentRepositoryTest.java b/servers/commons/src/test/java/com/samsung/commons/repository/AgentRepositoryTest.java index 74bd007..4d47474 100644 --- a/servers/commons/src/test/java/com/samsung/commons/repository/AgentRepositoryTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/repository/AgentRepositoryTest.java @@ -28,6 +28,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @WebAppConfiguration @ContextConfiguration(locations = { "classpath:root-context.xml" }) public class AgentRepositoryTest { + @Autowired private AgentRepository agentRepository; diff --git a/servers/commons/src/test/java/com/samsung/commons/repository/DeviceRepositoryTest.java b/servers/commons/src/test/java/com/samsung/commons/repository/DeviceRepositoryTest.java index f7a705c..e738abc 100644 --- a/servers/commons/src/test/java/com/samsung/commons/repository/DeviceRepositoryTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/repository/DeviceRepositoryTest.java @@ -31,6 +31,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @WebAppConfiguration @ContextConfiguration(locations = { "classpath:root-context.xml" }) public class DeviceRepositoryTest { + @Autowired private DeviceRepository deviceRepository; diff --git a/servers/commons/src/test/java/com/samsung/commons/repository/RoleRepositoryTest.java b/servers/commons/src/test/java/com/samsung/commons/repository/RoleRepositoryTest.java index 07f2855..77c57bf 100644 --- a/servers/commons/src/test/java/com/samsung/commons/repository/RoleRepositoryTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/repository/RoleRepositoryTest.java @@ -3,10 +3,8 @@ package com.samsung.commons.repository; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import java.util.ArrayList; import java.util.List; -import com.samsung.commons.domain.Role; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,6 +12,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import com.samsung.commons.domain.Role; + @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:root-context.xml" }) diff --git a/servers/commons/src/test/java/com/samsung/commons/service/AgentServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/AgentServiceTest.java index d2fc5a8..3ea957c 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/AgentServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/AgentServiceTest.java @@ -19,7 +19,6 @@ import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.*; - /** * @author Mail to: Artem Motchanyi * @version 1.0 @@ -33,8 +32,9 @@ import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class AgentServiceTest { + private static final String AGENT_UUID = "uuid"; @Autowired @@ -49,17 +49,18 @@ public class AgentServiceTest { @Autowired private DeviceService deviceService; - @Before public void before() { Policy policy = policyService.initPolicy(); agentService.save(new Agent(AGENT_UUID, "name", policy)); User user = userService.getUserByEmail("admin@samsung.com"); - Device device1 = new Device("uuid1", "name1", "type", "model", 1, policyService.initPolicy(), user, "parentUuid"); + Device device1 = new Device("uuid1", "name1", "type", "model", 1, policyService + .initPolicy(), user, "parentUuid"); device1.setAgents(createAgents(device1)); - Device device2 = new Device("uuid2", "name2", "type", "model", 1, policyService.initPolicy(), user, "parentUuid"); + Device device2 = new Device("uuid2", "name2", "type", "model", 1, policyService + .initPolicy(), user, "parentUuid"); deviceService.save(device1); deviceService.save(device2); @@ -80,7 +81,6 @@ public class AgentServiceTest { agentService.removeAll(); } - @Test public void testGetAll() { List agentList = agentService.getAll(); @@ -168,13 +168,13 @@ public class AgentServiceTest { assertTrue(agentService.findDeviceAgents("unexistent-uuid").isEmpty()); } - @Test(expected=Exception.class) - public void testAgentNameIsEmpty() throws Exception{ + @Test(expected = Exception.class) + public void testAgentNameIsEmpty() throws Exception { agentService.init("uuid", ""); } - @Test(expected=Exception.class) - public void testAgentUuidIsEmpty() throws Exception{ + @Test(expected = Exception.class) + public void testAgentUuidIsEmpty() throws Exception { agentService.init("", "name"); } } diff --git a/servers/commons/src/test/java/com/samsung/commons/service/DeviceServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/DeviceServiceTest.java index 8d4034d..ed842f3 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/DeviceServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/DeviceServiceTest.java @@ -50,276 +50,275 @@ import com.samsung.commons.repository.ReportTypeRepository; @ContextConfiguration(locations = { "classpath:root-context.xml" }) public class DeviceServiceTest { - private static final String NEWMODEL = "newmodel"; + private static final String NEWMODEL = "newmodel"; - private static final String NEWTYPE = "newtype"; + private static final String NEWTYPE = "newtype"; - private static final String NEWNAME = "newname"; + private static final String NEWNAME = "newname"; - private static final String NEWUUID = "newuuid"; + private static final String NEWUUID = "newuuid"; - private static final String ROUTE = "route"; + private static final String ROUTE = "route"; - private static final String TYPE = "type"; + private static final String TYPE = "type"; - private static final String NAME = "name"; + private static final String NAME = "name"; - private static final String MODEL = "model"; + private static final String MODEL = "model"; - private static final String PARENT_UUID = "parentUuid"; + private static final String PARENT_UUID = "parentUuid"; - private static final String DEVICE_UUID = "uuid"; + private static final String DEVICE_UUID = "uuid"; - private static final String DEVICE_UUID_WITHOUT_AGENTS = "uuid-no-agents"; + private static final String DEVICE_UUID_WITHOUT_AGENTS = "uuid-no-agents"; - private static final String IN_EXISTENT_UUID = "in-existent-uuid"; + private static final String IN_EXISTENT_UUID = "in-existent-uuid"; - private User user; + private User user; - @Autowired - private UserService userService; + @Autowired + private UserService userService; - @Autowired - private DeviceService deviceService; + @Autowired + private DeviceService deviceService; - @Autowired - private PolicyService policyService; + @Autowired + private PolicyService policyService; - @Autowired - private AgentService agentService; + @Autowired + private AgentService agentService; - @Autowired - private ReportService reportService; + @Autowired + private ReportService reportService; - @Autowired - private ReportTypeRepository reportTypeRepository; + @Autowired + private ReportTypeRepository reportTypeRepository; - @Before - public void before() { - user = userService.getUserByEmail("admin@samsung.com"); - Device device = new Device(DEVICE_UUID, NAME, TYPE, MODEL, 1, policyService.initPolicy(), user, - PARENT_UUID); - device.setReports(createReports(device)); - device.setAgents(createAgents(device)); + @Before + public void before() { + user = userService.getUserByEmail("admin@samsung.com"); + Device device = new Device(DEVICE_UUID, NAME, TYPE, MODEL, 1, policyService.initPolicy(), user, PARENT_UUID); + device.setReports(createReports(device)); + device.setAgents(createAgents(device)); - deviceService.save(device); - deviceService.save(new Device(DEVICE_UUID_WITHOUT_AGENTS, "name2", TYPE, MODEL, 1, - policyService.initPolicy(), user, PARENT_UUID)); + deviceService.save(device); + deviceService.save(new Device(DEVICE_UUID_WITHOUT_AGENTS, "name2", TYPE, MODEL, 1, policyService + .initPolicy(), user, PARENT_UUID)); - // Alone agent. No device. - agentService.save(new Agent("789", "agent3", policyService.initPolicy())); - } + // Alone agent. No device. + agentService.save(new Agent("789", "agent3", policyService.initPolicy())); + } - private List createReports(Device device) { - List reports = new ArrayList<>(); - Report report = new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), "report", "date", 1, - device); - report.setDevice(device); - reports.add(report); + private List createReports(Device device) { + List reports = new ArrayList<>(); + Report report = new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), "report", "date", 1, device); + report.setDevice(device); + reports.add(report); - return reports; - } + return reports; + } - private List createAgents(Device device) { - List agents = new ArrayList<>(); - Agent agent1 = new Agent("123", "agent1", policyService.initPolicy()); - agent1.setDevice(device); - agents.add(agent1); - - Agent agent2 = new Agent("456", "agent2", policyService.initPolicy()); - agent2.setDevice(device); - agents.add(agent2); - - return agents; - } - - @After - public void after() { - deviceService.removeAll(); - - // Some agents aren't bound to device - agentService.removeAll(); - } + private List createAgents(Device device) { + List agents = new ArrayList<>(); + Agent agent1 = new Agent("123", "agent1", policyService.initPolicy()); + agent1.setDevice(device); + agents.add(agent1); - @Test - public void testGetByUserAndStatus() { - List deviceList = deviceService.findUserDevicesByStatus(user.getId(), 1); - assertEquals(deviceList.size(), 2); - - deviceList = deviceService.findUserDevicesByStatus(user.getId(), 0); - assertEquals(deviceList.size(), 0); - } - - @Test - public void testGetByUserAndType() { - List deviceList = deviceService.findUserDevicesByType(user.getId(), TYPE); - assertEquals(deviceList.size(), 2); - - deviceList = deviceService.findUserDevicesByType(user.getId(), "wrong-type"); - assertEquals(deviceList.size(), 0); - } - - @Test - public void testGetAll() { - List deviceList = deviceService.getAll(); - assertEquals(deviceList.size(), 2); - } - - @Test - public void testSave() { - Policy policy = policyService.initPolicy(); - Device newDevice = new Device(NEWUUID, NEWNAME, NEWTYPE, NEWMODEL, 0, policy, user, PARENT_UUID); - - Device savedDevice = deviceService.save(newDevice); - - assertNotNull("ID should appear after save", savedDevice.getId()); - assertEquals(deviceService.findByUUID(savedDevice.getUuid()).getId(), savedDevice.getId()); - } - - @Test - public void testRemove() { - Policy policy = policyService.initPolicy(); - Device newDevice = deviceService - .save(new Device(NEWUUID, NEWNAME, NEWTYPE, NEWMODEL, 0, policy, user, false, PARENT_UUID)); - deviceService.remove(deviceService.findById(newDevice.getId())); - assertNull(deviceService.findById(newDevice.getId())); - } - - @Test - public void testNullParentIdMustBeEmpty() { - Policy policy = policyService.initPolicy(); - Device newDevice = deviceService - .save(new Device(NEWUUID, NEWNAME, NEWTYPE, NEWMODEL, 0, policy, user, false, null)); - Device testDevice = deviceService.findById(newDevice.getId()); - assertNotNull(testDevice.getParentUuid()); - testDevice.setParentUuid(null); - assertNotNull(testDevice.getParentUuid()); - testDevice.setParentUuid(""); - assertNotNull(testDevice.getParentUuid()); - deviceService.remove(testDevice); - assertNull(deviceService.findById(newDevice.getId())); - } - - @Test - public void testFindByUUID() { - assertEquals(DEVICE_UUID, deviceService.findByUUID(DEVICE_UUID).getUuid()); - } - - @Test - public void testCount() { - assertEquals(deviceService.count(), 2); - } - - @Test(expected = IllegalArgumentException.class) - public void testAddAgentToNotFoundDevice() { - deviceService.setDeviceAgents(IN_EXISTENT_UUID, new Agent()); - } - - @Test(expected = IllegalArgumentException.class) - public void testAddNullAgentToDevice() { - deviceService.setDeviceAgents(DEVICE_UUID, null); - } - - @Test - public void testAddAgentToDeviceWithAgents() { - Agent agent = agentService.findByUUID("789"); - Device device = deviceService.setDeviceAgents(DEVICE_UUID, agent); - assertTrue("Device agents contains added agent", device.getAgents().contains(agent)); - } - - @Test - public void testAddAgentToDeviceWithoutAgents() { - Agent agent = agentService.findByUUID("789"); - Device device = deviceService.setDeviceAgents(DEVICE_UUID_WITHOUT_AGENTS, agent); - assertTrue("Device agents contains added agent", device.getAgents().contains(agent)); - } - - @Test - public void testAgentsAndReportsMustBeRemovedWithDevice() { - Device device = deviceService.findByUUID(DEVICE_UUID); - - deviceService.remove(device); - - // Device removed - assertNull(deviceService.findByUUID(DEVICE_UUID)); - - // Agents removed - Agent agent1 = agentService.findByUUID("123"); - Agent agent2 = agentService.findByUUID("456"); - assertThat(agent1, is(nullValue())); - assertThat(agent2, is(nullValue())); - - // Reports removed - List reports = reportService.findReportsByDeviceUuid(DEVICE_UUID); - assertTrue(reports.isEmpty()); - } - - @Test - public void testInit() throws Exception { - String route = ROUTE; - String initUuid = "inituuid"; - assertEquals(2, deviceService.count()); - deviceService.init(initUuid, "initname", "inittype", "initmodel", 0, user, route); - assertEquals(3, deviceService.count()); - - Device initedDevice = deviceService.findByUUID(initUuid); - assertNotNull(initedDevice); - assertNotNull(initedDevice.getPolicy()); - } - - @Test - public void testSameInit() throws Exception { - String route = ROUTE; - String initUuid = "init-uuid"; - assertEquals(2, deviceService.count()); - deviceService.init(initUuid, "init-name", "init-type", "init-model", 0, user, route); - assertEquals(3, deviceService.count()); - - Device initializedDevice = deviceService.findByUUID(initUuid); - assertNotNull(initializedDevice); - assertNotNull(initializedDevice.getPolicy()); - - try { - deviceService.init(initUuid, "duplicate-name", "duplicate-type", "duplicate-model", 0, user, route); - - fail(); - } catch (Exception e) { - // ignore - } finally { - deviceService.remove(initializedDevice); - } - } - - @Test - public void findByUser() { - assertThat(deviceService.findByUser(user), is(notNullValue())); - } - - @Test - @Transactional - public void removeSet() { - deviceService.remove(new HashSet<>(deviceService.getAll())); - - assertThat(deviceService.count(), is(0L)); - } - - @Test(expected = Exception.class) - public void testDeviceNameIsEmpty() throws Exception { - deviceService.init(DEVICE_UUID, "", TYPE, MODEL, 0, new User(), ROUTE); - } - - @Test(expected = Exception.class) - public void testDeviceUuidIsEmpty() throws Exception { - deviceService.init("", NAME, TYPE, MODEL, 0, new User(), ROUTE); - } - - @Test(expected = Exception.class) - public void testDeviceTypeIsEmpty() throws Exception { - deviceService.init(DEVICE_UUID, NAME, "", MODEL, 0, new User(), ROUTE); - } - - @Test(expected = Exception.class) - public void testDeviceModelIsEmpty() throws Exception { - deviceService.init(DEVICE_UUID, NAME, TYPE, "", 0, new User(), ROUTE); - } + Agent agent2 = new Agent("456", "agent2", policyService.initPolicy()); + agent2.setDevice(device); + agents.add(agent2); + + return agents; + } + + @After + public void after() { + deviceService.removeAll(); + + // Some agents aren't bound to device + agentService.removeAll(); + } + + @Test + public void testGetByUserAndStatus() { + List deviceList = deviceService.findUserDevicesByStatus(user.getId(), 1); + assertEquals(deviceList.size(), 2); + + deviceList = deviceService.findUserDevicesByStatus(user.getId(), 0); + assertEquals(deviceList.size(), 0); + } + + @Test + public void testGetByUserAndType() { + List deviceList = deviceService.findUserDevicesByType(user.getId(), TYPE); + assertEquals(deviceList.size(), 2); + + deviceList = deviceService.findUserDevicesByType(user.getId(), "wrong-type"); + assertEquals(deviceList.size(), 0); + } + + @Test + public void testGetAll() { + List deviceList = deviceService.getAll(); + assertEquals(deviceList.size(), 2); + } + + @Test + public void testSave() { + Policy policy = policyService.initPolicy(); + Device newDevice = new Device(NEWUUID, NEWNAME, NEWTYPE, NEWMODEL, 0, policy, user, PARENT_UUID); + + Device savedDevice = deviceService.save(newDevice); + + assertNotNull("ID should appear after save", savedDevice.getId()); + assertEquals(deviceService.findByUUID(savedDevice.getUuid()).getId(), savedDevice.getId()); + } + + @Test + public void testRemove() { + Policy policy = policyService.initPolicy(); + Device newDevice = deviceService + .save(new Device(NEWUUID, NEWNAME, NEWTYPE, NEWMODEL, 0, policy, user, false, PARENT_UUID)); + deviceService.remove(deviceService.findById(newDevice.getId())); + assertNull(deviceService.findById(newDevice.getId())); + } + + @Test + public void testNullParentIdMustBeEmpty() { + Policy policy = policyService.initPolicy(); + Device newDevice = deviceService + .save(new Device(NEWUUID, NEWNAME, NEWTYPE, NEWMODEL, 0, policy, user, false, null)); + Device testDevice = deviceService.findById(newDevice.getId()); + assertNotNull(testDevice.getParentUuid()); + testDevice.setParentUuid(null); + assertNotNull(testDevice.getParentUuid()); + testDevice.setParentUuid(""); + assertNotNull(testDevice.getParentUuid()); + deviceService.remove(testDevice); + assertNull(deviceService.findById(newDevice.getId())); + } + + @Test + public void testFindByUUID() { + assertEquals(DEVICE_UUID, deviceService.findByUUID(DEVICE_UUID).getUuid()); + } + + @Test + public void testCount() { + assertEquals(deviceService.count(), 2); + } + + @Test(expected = IllegalArgumentException.class) + public void testAddAgentToNotFoundDevice() { + deviceService.setDeviceAgents(IN_EXISTENT_UUID, new Agent()); + } + + @Test(expected = IllegalArgumentException.class) + public void testAddNullAgentToDevice() { + deviceService.setDeviceAgents(DEVICE_UUID, null); + } + + @Test + public void testAddAgentToDeviceWithAgents() { + Agent agent = agentService.findByUUID("789"); + Device device = deviceService.setDeviceAgents(DEVICE_UUID, agent); + assertTrue("Device agents contains added agent", device.getAgents().contains(agent)); + } + + @Test + public void testAddAgentToDeviceWithoutAgents() { + Agent agent = agentService.findByUUID("789"); + Device device = deviceService.setDeviceAgents(DEVICE_UUID_WITHOUT_AGENTS, agent); + assertTrue("Device agents contains added agent", device.getAgents().contains(agent)); + } + + @Test + public void testAgentsAndReportsMustBeRemovedWithDevice() { + Device device = deviceService.findByUUID(DEVICE_UUID); + + deviceService.remove(device); + + // Device removed + assertNull(deviceService.findByUUID(DEVICE_UUID)); + + // Agents removed + Agent agent1 = agentService.findByUUID("123"); + Agent agent2 = agentService.findByUUID("456"); + assertThat(agent1, is(nullValue())); + assertThat(agent2, is(nullValue())); + + // Reports removed + List reports = reportService.findReportsByDeviceUuid(DEVICE_UUID); + assertTrue(reports.isEmpty()); + } + + @Test + public void testInit() throws Exception { + String route = ROUTE; + String initUuid = "inituuid"; + assertEquals(2, deviceService.count()); + deviceService.init(initUuid, "initname", "inittype", "initmodel", 0, user, route); + assertEquals(3, deviceService.count()); + + Device initedDevice = deviceService.findByUUID(initUuid); + assertNotNull(initedDevice); + assertNotNull(initedDevice.getPolicy()); + } + + @Test + public void testSameInit() throws Exception { + String route = ROUTE; + String initUuid = "init-uuid"; + assertEquals(2, deviceService.count()); + deviceService.init(initUuid, "init-name", "init-type", "init-model", 0, user, route); + assertEquals(3, deviceService.count()); + + Device initializedDevice = deviceService.findByUUID(initUuid); + assertNotNull(initializedDevice); + assertNotNull(initializedDevice.getPolicy()); + + try { + deviceService.init(initUuid, "duplicate-name", "duplicate-type", "duplicate-model", 0, user, route); + + fail(); + } catch (Exception e) { + // ignore + } finally { + deviceService.remove(initializedDevice); + } + } + + @Test + public void findByUser() { + assertThat(deviceService.findByUser(user), is(notNullValue())); + } + + @Test + @Transactional + public void removeSet() { + deviceService.remove(new HashSet<>(deviceService.getAll())); + + assertThat(deviceService.count(), is(0L)); + } + + @Test(expected = Exception.class) + public void testDeviceNameIsEmpty() throws Exception { + deviceService.init(DEVICE_UUID, "", TYPE, MODEL, 0, new User(), ROUTE); + } + + @Test(expected = Exception.class) + public void testDeviceUuidIsEmpty() throws Exception { + deviceService.init("", NAME, TYPE, MODEL, 0, new User(), ROUTE); + } + + @Test(expected = Exception.class) + public void testDeviceTypeIsEmpty() throws Exception { + deviceService.init(DEVICE_UUID, NAME, "", MODEL, 0, new User(), ROUTE); + } + + @Test(expected = Exception.class) + public void testDeviceModelIsEmpty() throws Exception { + deviceService.init(DEVICE_UUID, NAME, TYPE, "", 0, new User(), ROUTE); + } } \ No newline at end of file diff --git a/servers/commons/src/test/java/com/samsung/commons/service/IoTCloudServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/IoTCloudServiceTest.java index 7b15693..9e485c1 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/IoTCloudServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/IoTCloudServiceTest.java @@ -40,7 +40,7 @@ import org.junit.Before; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class IoTCloudServiceTest { @Autowired @@ -54,7 +54,7 @@ public class IoTCloudServiceTest { @Mock private UserRepository userRepository; - + @InjectMocks private IotCloudServiceImpl iotCloudServiceImpl; diff --git a/servers/commons/src/test/java/com/samsung/commons/service/PolicyServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/PolicyServiceTest.java index 3403462..9de00cf 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/PolicyServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/PolicyServiceTest.java @@ -30,7 +30,6 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.*; - /** * @author Mail to: Andriy Petrov, * an.petrov@samsung.com @@ -44,8 +43,9 @@ import static org.junit.Assert.*; */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class PolicyServiceTest { + static final String newPolicyJson = "new policy"; @Autowired @@ -90,7 +90,8 @@ public class PolicyServiceTest { @Before public void init() { user = userService.getUserByEmail("admin@samsung.com"); - Device device = new Device("deviceuuid", "name", "type", "model", 0, policyService.initPolicy(), user, "parentUuid"); + Device device = new Device("deviceuuid", "name", "type", "model", 0, policyService + .initPolicy(), user, "parentUuid"); List agents = new ArrayList<>(); policy1 = policyService.initPolicy(); Agent agent1 = new Agent("agent1uuid", "name1", policy1); @@ -134,7 +135,8 @@ public class PolicyServiceTest { policyService.remove(policyService.findById(policy.getId())); assertNull(policyService.findById(policy.getId())); policy = policyService.initPolicy(); - Device newDevice = deviceService.save(new Device("newuuid", "name", "type", "model", 0, policy, user, "parentUuid")); + Device newDevice = deviceService + .save(new Device("newuuid", "name", "type", "model", 0, policy, user, "parentUuid")); assertNotNull(policyService.findByDeviceId(newDevice.getId())); policyService.remove(policyService.findByDeviceId(newDevice.getId())); assertEquals("", policyService.findByDeviceId(newDevice.getId()).getPolicy()); diff --git a/servers/commons/src/test/java/com/samsung/commons/service/ReportTypeServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/ReportTypeServiceTest.java index 145b9d1..22d63f5 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/ReportTypeServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/ReportTypeServiceTest.java @@ -22,10 +22,9 @@ import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.*; - @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class ReportTypeServiceTest { @Autowired @@ -33,7 +32,6 @@ public class ReportTypeServiceTest { private final String NAME = "TestReportTypeName"; - @Test public void testFindByName() { ReportType dacReportType = reportTypeService.findByName(ReportType.Type.DAC.toString()); @@ -55,7 +53,6 @@ public class ReportTypeServiceTest { reportTypeService.remove(newReportType); } - @Test public void testRemove() { ReportType newReportType = new ReportType(NAME); @@ -70,7 +67,6 @@ public class ReportTypeServiceTest { assertNull(reportTypeService.findById(foundReportType.getId())); } - @Test public void testFindById() { ReportType newReportType = new ReportType(NAME); @@ -84,10 +80,11 @@ public class ReportTypeServiceTest { reportTypeService.remove(newReportType); } - @Test public void testCount() { - assertEquals(reportTypeService.count(), 3); // hardcoded in init.sql script (not changed in runtime) + assertEquals(reportTypeService.count(), 3); // hardcoded in init.sql + // script (not changed in + // runtime) } } diff --git a/servers/commons/src/test/java/com/samsung/commons/service/RoleServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/RoleServiceTest.java index 42c8a0d..24b29b4 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/RoleServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/RoleServiceTest.java @@ -24,23 +24,20 @@ import java.util.List; import static org.junit.Assert.*; - @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class RoleServiceTest { @Autowired private RoleService roleService; - @Test public void testGetAll() { List roleList = roleService.getAll(); assertTrue(roleList.size() == 2); // hardcoded in init.sql file } - @Test public void testSave() { String roleName = "TestSave"; @@ -58,7 +55,6 @@ public class RoleServiceTest { roleService.remove(savedRole); } - @Test public void testRemove() { String roleName = "TestDelete"; @@ -73,7 +69,6 @@ public class RoleServiceTest { assertNull(foundRole); } - @Test public void testFindById() { Role adminRole = roleService.findById(1l); // hardcoded in init.sql file @@ -85,7 +80,6 @@ public class RoleServiceTest { assertEquals("ROLE_USER", userRole.getName()); } - @Test public void testCount() { assertEquals(2, roleService.count()); // hardcoded in init.sql file diff --git a/servers/commons/src/test/java/com/samsung/commons/service/UserDetailsServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/UserDetailsServiceTest.java index e0e8c9b..86b3f6a 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/UserDetailsServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/UserDetailsServiceTest.java @@ -41,13 +41,14 @@ import com.samsung.commons.service.impl.UserDetailsServiceImpl; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class UserDetailsServiceTest { - //WARNING: UserDetailsServiceImpl implements two interfaces - //1. UserDetailsService - //2. org.springframework.security.core.userdetails.UserDetailsService - //UT will test UserDetailsServiceImpl class instead of UserDetailsService (interface) + // WARNING: UserDetailsServiceImpl implements two interfaces + // 1. UserDetailsService + // 2. org.springframework.security.core.userdetails.UserDetailsService + // UT will test UserDetailsServiceImpl class instead of UserDetailsService + // (interface) @Autowired private UserDetailsServiceImpl customUserDetailsService; @@ -104,7 +105,7 @@ public class UserDetailsServiceTest { @After public void cleanDB() { - //cascade remove + // cascade remove customUserDetailsService.remove(details); } @@ -129,10 +130,12 @@ public class UserDetailsServiceTest { @Test public void testRemove() { - User userToSave = userService.save(new User("userToSave", "userToSave@email.com", roleService.findById(roleId))); + User userToSave = userService + .save(new User("userToSave", "userToSave@email.com", roleService.findById(roleId))); Long userId = userToSave.getId(); assertNotNull(userId); - CustomUserDetails detailsToSave = customUserDetailsService.save(new CustomUserDetails("passToSave", "restorePassLinkToSave.com", userToSave)); + CustomUserDetails detailsToSave = customUserDetailsService + .save(new CustomUserDetails("passToSave", "restorePassLinkToSave.com", userToSave)); Long detailsId = detailsToSave.getId(); assertNotNull(detailsId); assertNotNull(customUserDetailsService.findById(detailsId)); @@ -149,11 +152,10 @@ public class UserDetailsServiceTest { assertEquals(details.getId(), foundDetails.getId()); } - @Test public void testCount() { - //admin user detials is predefined in init.sql - //another user was made by @Before annotation + // admin user detials is predefined in init.sql + // another user was made by @Before annotation assertEquals(2, customUserDetailsService.count()); } diff --git a/servers/commons/src/test/java/com/samsung/commons/service/UserServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/UserServiceTest.java index a57384c..9f7ba8e 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/UserServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/UserServiceTest.java @@ -12,12 +12,22 @@ package com.samsung.commons.service; -import com.samsung.commons.domain.CustomUserDetails; -import com.samsung.commons.domain.Role; -import com.samsung.commons.domain.User; -import com.samsung.commons.repository.UserDetailsRepository; -import com.samsung.commons.repository.UserRepository; -import com.samsung.commons.service.impl.UserServiceImpl; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; @@ -25,8 +35,6 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; @@ -39,44 +47,47 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.*; +import com.samsung.commons.domain.CustomUserDetails; +import com.samsung.commons.domain.Role; +import com.samsung.commons.domain.User; +import com.samsung.commons.repository.UserDetailsRepository; +import com.samsung.commons.repository.UserRepository; +import com.samsung.commons.service.impl.UserServiceImpl; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class UserServiceTest { - private static final String TEST_EMAIL = "testSave@email.com"; - private static final String NEW_USER = "NewUser"; - - private static final String EMAIL = "email"; + private static final String EDITED_USER_EMAIL = "edited@email.com"; + private static final String EDITED_USER_NAME = "editedName"; + private static final String TEST_SAVE_EMAIL = "testSave@email.com"; + private static final String NEW_USER_NAME = "NewUser"; + // admin properties are hardcoded in USERS tab by init.sql script + private static final Long ADMIN_ID = 1L; + private static final String ADMIN_NAME = "admin"; + private static final String ADMIN_EMAIL = "admin@samsung.com"; + private static final String UNIQUE_EMAIL = "some@uniquie.email"; + private static final String EMAIL = "email"; - @Autowired + @Autowired private UserService userService; @Autowired private RoleService roleService; - + @Mock private UserRepository userRepository; @Mock private UserDetailsRepository userDetailsRepository; + @Mock + private DeviceService deviceService; + @InjectMocks private UserServiceImpl userServiceImpl; - // admin properties are hardcoded in USERS tab by init.sql script - private final Long ADMIN_ID = 1L; - private final String ADMIN_NAME = "admin"; - private final String ADMIN_EMAIL = "admin@samsung.com"; - private final String UNIQUI_EMAIL = "some@uniquie.email"; - private Role adminRole; @Before @@ -100,16 +111,14 @@ public class UserServiceTest { @Test public void testFindByUsername() { - // default user - admin, hardcoded in init.sql User user = userService.getUserByEmail(ADMIN_EMAIL); assertNotNull(user); } @Test - public void testIsEmailAvailableHttpServletRequest_ok() { + public void testIsEmailAvailableHttpServletRequestOk() { HttpServletRequest httpServleteRequest = Mockito.mock(HttpServletRequest.class); - // Mockito.whens() for your authorization object Mockito.when(httpServleteRequest.getParameter(EMAIL)).thenReturn("uniqueEmail"); @@ -117,9 +126,8 @@ public class UserServiceTest { } @Test - public void testIsEmailAvailableHttpServletRequest_notUniqueEmail() { + public void testIsEmailAvailableHttpServletRequestNotUniqueEmail() { HttpServletRequest httpServleteRequest = Mockito.mock(HttpServletRequest.class); - // Mockito.whens() for your authorization object Mockito.when(httpServleteRequest.getParameter(EMAIL)).thenReturn(ADMIN_EMAIL); @@ -128,7 +136,7 @@ public class UserServiceTest { @Test public void testIsEmailAvailableStringOk() { - assertTrue(userService.isEmailAvailable(UNIQUI_EMAIL)); + assertTrue(userService.isEmailAvailable(UNIQUE_EMAIL)); } @Test @@ -136,27 +144,26 @@ public class UserServiceTest { assertFalse(userService.isEmailAvailable(ADMIN_EMAIL)); } - @Test public void testGetAll() { List userList = userService.getAll(true); - assertEquals(1, userList.size()); // hardcoded in init.sql file + assertEquals(1, userList.size()); } @Test public void testChangeLockedStateShouldLock() { - String name = NEW_USER; - String email = TEST_EMAIL; + String name = NEW_USER_NAME; + String email = TEST_SAVE_EMAIL; User newUser = new User(name, email, adminRole); assertNull(newUser.getId()); - assertFalse(newUser.getLocked()); // by default user is not locked + assertFalse(newUser.getLocked()); User savedUser = userService.save(newUser); assertNotNull(savedUser); boolean res = userService.changeLockedState(savedUser.getId()); - assertTrue(res); // should be locked + assertTrue(res); User lockedUser = userService.findById(savedUser.getId()); assertTrue(lockedUser.getLocked()); @@ -166,8 +173,8 @@ public class UserServiceTest { @Test public void testChangeLockedStateShouldUnlock() { - String name = NEW_USER; - String email = TEST_EMAIL; + String name = NEW_USER_NAME; + String email = TEST_SAVE_EMAIL; User newUser = new User(name, email, adminRole); newUser.setLocked(true); @@ -179,7 +186,8 @@ public class UserServiceTest { assertTrue(savedUser.getLocked()); boolean res = userService.changeLockedState(savedUser.getId()); - assertFalse(res); // should be unlocked + // should be unlocked + assertFalse(res); User lockedUser = userService.findById(savedUser.getId()); assertFalse(lockedUser.getLocked()); @@ -189,10 +197,8 @@ public class UserServiceTest { @Test public void testChangeLockedStateShouldNotLock() { - // admin user is in security context - // should not lock (self lock protection) boolean res = userService.changeLockedState(ADMIN_ID); - assertFalse(res); // should be unlocked + assertFalse(res); User adminUser = userService.findById(ADMIN_ID); assertFalse(adminUser.getLocked()); @@ -200,7 +206,7 @@ public class UserServiceTest { @Test public void testRemoveById() throws Exception { - User newUser = new User(NEW_USER, TEST_EMAIL, adminRole); + User newUser = new User(NEW_USER_NAME, TEST_SAVE_EMAIL, adminRole); User savedUser = userService.save(newUser); @@ -210,7 +216,7 @@ public class UserServiceTest { } @Test(expected = Exception.class) - public void testRemoveById_Self() throws Exception { + public void testRemoveByIdSelf() throws Exception { userService.remove(ADMIN_ID); assertNotNull(userService.findById(ADMIN_ID)); } @@ -224,10 +230,10 @@ public class UserServiceTest { @Test public void testEditUserShouldChande() { - String newUserName = NEW_USER; - String newUserEmail = TEST_EMAIL; - String editedUserName = "editedName"; - String editedUserEmail = "edited@email.com"; + String newUserName = NEW_USER_NAME; + String newUserEmail = TEST_SAVE_EMAIL; + String editedUserName = EDITED_USER_NAME; + String editedUserEmail = EDITED_USER_EMAIL; User newUser = new User(newUserName, newUserEmail, adminRole); assertNull(newUser.getId()); @@ -238,7 +244,6 @@ public class UserServiceTest { assertNotNull(editedUser); - // change all user fields editedUser.setUsername(editedUserName); editedUser.setEmail(editedUserEmail); editedUser.setRole(roleService.findById(2l)); @@ -265,7 +270,7 @@ public class UserServiceTest { @Test public void testEditUserSelfShouldNotChandeRoleAndLocked() { - String updatedUserName = "editedName"; + String updatedUserName = EDITED_USER_NAME; User adminDefaults = userService.findById(ADMIN_ID); User adminToChange = userService.findById(ADMIN_ID); @@ -273,16 +278,9 @@ public class UserServiceTest { assertNotNull(adminDefaults); assertNotNull(adminToChange); - // change all admin fields adminToChange.setUsername(updatedUserName); - // FIXME user is able to change his profile details (role, locked) is he - // change his email in same transaction! - // - // uncommenting this \|/ will set tests to fail - // adminToChange.setEmail(updapedUserEmail); - - adminToChange.setRole(roleService.findById(2l)); // ROLE_USER + adminToChange.setRole(roleService.findById(2l)); adminToChange.setLocked(!adminDefaults.getLocked()); Long adminToChangeRoleId = adminToChange.getRole().getId(); @@ -291,19 +289,17 @@ public class UserServiceTest { assertNotNull(editedAdmin); assertEquals(updatedUserName, editedAdmin.getUsername()); - // assertEquals(updapedUserEmail, editedAdmin.getEmail()); assertNotEquals(adminToChange.getRole().getId(), adminToChangeRoleId); assertNotEquals(adminToChange.getLocked(), adminToChangeLockedState); - // restore defaults assertNotNull(userService.save(adminDefaults)); } @Test public void testSave() { - String name = NEW_USER; - String email = TEST_EMAIL; + String name = NEW_USER_NAME; + String email = TEST_SAVE_EMAIL; User newUser = new User(name, email, adminRole); assertNull(newUser.getId()); @@ -320,8 +316,8 @@ public class UserServiceTest { @Test public void testRemove() { - String name = NEW_USER; - String email = TEST_EMAIL; + String name = NEW_USER_NAME; + String email = TEST_SAVE_EMAIL; User newUser = new User(name, email, adminRole); assertNull(newUser.getId()); @@ -389,12 +385,12 @@ public class UserServiceTest { } @Test - public void testRemoveWithMocks(){ + public void testRemoveWithMocks() { User user = mock(User.class); - CustomUserDetails customUserDetails = mock(CustomUserDetails.class); + CustomUserDetails customUserDetails = mock(CustomUserDetails.class); when(user.getId()).thenReturn(1L); when(userDetailsRepository.findByUserId(1L)).thenReturn(customUserDetails); userServiceImpl.remove(user); } - + } diff --git a/servers/commons/src/test/java/com/samsung/commons/service/impl/ReportServiceTest.java b/servers/commons/src/test/java/com/samsung/commons/service/impl/ReportServiceTest.java index 247f3e9..c4464c7 100644 --- a/servers/commons/src/test/java/com/samsung/commons/service/impl/ReportServiceTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/service/impl/ReportServiceTest.java @@ -30,7 +30,7 @@ import com.samsung.commons.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @Transactional public class ReportServiceTest { @@ -64,7 +64,8 @@ public class ReportServiceTest { String report = "report\n\t1\t\b2\r"; User user = userService.findByUsername("admin"); Policy policy = policyService.initPolicy(); - long deviceId = deviceService.save(new Device("uuid", "name", "type", "model", 1, policy, user, "parentId")).getId(); + long deviceId = deviceService.save(new Device("uuid", "name", "type", "model", 1, policy, user, "parentId")) + .getId(); Report saved = reportService.save(deviceId, "dac", "date", 1, report); assertThat(saved, is(notNullValue())); @@ -123,29 +124,29 @@ public class ReportServiceTest { } @Test - public void testGetLimitTopReportsTypeDac(){ + public void testGetLimitTopReportsTypeDac() { Policy policy = policyService.initPolicy(); User user = userService.findByUsername("admin"); Device device = deviceService.save(new Device("uuid", "name", "type", "model", 1, policy, user, "parentUuid")); ReportType type1 = reportTypeService.findByName("dac"); - for(int i = 0; i < 15; i++){ + for (int i = 0; i < 15; i++) { reportService.save(new Report(type1, "dacReport" + i, "date" + i, 1, device)); } ReportType type2 = reportTypeService.findByName("smack"); - for(int i = 0; i < 15; i++){ + for (int i = 0; i < 15; i++) { reportService.save(new Report(type2, "smackReport" + i, "date" + i, 1, device)); } - for(Report report: reportService.findReportsByDeviceUuid(device.getUuid())){ + for (Report report : reportService.findReportsByDeviceUuid(device.getUuid())) { System.out.println(report); } int i = 14; - for(Report report: reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type1.getId(), 10)){ + for (Report report : reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type1.getId(), 10)) { assertTrue(report.getReport().equals("dacReport" + i)); i--; reportService.remove(report); } i = 14; - for(Report report: reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type2.getId(), 10)){ + for (Report report : reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type2.getId(), 10)) { assertTrue(report.getReport().equals("smackReport" + i)); i--; reportService.remove(report); @@ -188,6 +189,7 @@ public class ReportServiceTest { } public static class Params { + private Report report; private Device device; @@ -207,4 +209,97 @@ public class ReportServiceTest { return params.device; } } + + @Test + public void testGetDeviceReportTypes() { + Policy policy = policyService.initPolicy(); + User user = userService.findByUsername("admin"); + Device device = deviceService.save(new Device("uuid", "name", "type", "model", 1, policy, user, "parentUuid")); + ReportType type1 = reportTypeService.findByName("dac"); + for (int i = 0; i < 15; i++) { + reportService.save(new Report(type1, "dacReport" + i, "date" + i, 1, device)); + } + ReportType type2 = reportTypeService.findByName("smack"); + for (int i = 0; i < 15; i++) { + reportService.save(new Report(type2, "smackReport" + i, "date" + i, 1, device)); + } + ReportType type3 = reportTypeService.findByName("syscall"); + for (int i = 0; i < 15; i++) { + reportService.save(new Report(type3, "syscallReport" + i, "date" + i, 1, device)); + } + for (Report report : reportService.findReportsByDeviceUuid(device.getUuid())) { + System.out.println(report); + } + System.out.println("====================================================================="); + + List types = reportService.getDeviceReportTypes(device.getId()); + assertTrue(types.size() == 3); + assertTrue(types.contains(ReportType.Type.DAC)); + assertTrue(types.contains(ReportType.Type.SMACK)); + assertTrue(types.contains(ReportType.Type.SYSCALL)); + int i = 14; + for (Report report : reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type1.getId(), 10)) { + System.out.println(report); + assertTrue(report.getReport().equals("dacReport" + i)); + i--; + reportService.remove(report); + } + System.out.println("====================================================================="); + i = 14; + for (Report report : reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type2.getId(), 10)) { + System.out.println(report); + assertTrue(report.getReport().equals("smackReport" + i)); + i--; + reportService.remove(report); + } + + System.out.println("====================================================================="); + i = 14; + for (Report report : reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type3.getId(), 10)) { + System.out.println(report); + assertTrue(report.getReport().equals("syscallReport" + i)); + i--; + reportService.remove(report); + } + + List list = reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type1.getId(), 10); + assertTrue(!list.isEmpty()); + assertTrue(list.size() == 5); + System.out.println("====================================================================="); + i = 4; + for (Report report : list) { + System.out.println(report); + assertTrue(report.getReport().equals("dacReport" + i)); + i--; + reportService.remove(report); + } + list = reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type1.getId(), 10); + assertTrue(list.isEmpty()); + + list = reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type2.getId(), 10); + assertTrue(!list.isEmpty()); + assertTrue(list.size() == 5); + System.out.println("====================================================================="); + i = 4; + for (Report report : list) { + System.out.println(report); + assertTrue(report.getReport().equals("smackReport" + i)); + i--; + reportService.remove(report); + } + list = reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type3.getId(), 10); + assertTrue(!list.isEmpty()); + assertTrue(list.size() == 5); + System.out.println("====================================================================="); + i = 4; + for (Report report : list) { + System.out.println(report); + assertTrue(report.getReport().equals("syscallReport" + i)); + i--; + reportService.remove(report); + } + list = reportService.findByIdAndTypeOrderByIdDesc(device.getId(), type2.getId(), 10); + assertTrue(list.isEmpty()); + + } } \ No newline at end of file diff --git a/servers/commons/src/test/java/com/samsung/commons/utils/TestUtilsTest.java b/servers/commons/src/test/java/com/samsung/commons/utils/TestUtilsTest.java index 0cb8dec..11fa712 100644 --- a/servers/commons/src/test/java/com/samsung/commons/utils/TestUtilsTest.java +++ b/servers/commons/src/test/java/com/samsung/commons/utils/TestUtilsTest.java @@ -14,7 +14,7 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @Transactional public class TestUtilsTest { @@ -46,5 +46,4 @@ public class TestUtilsTest { assertThat(testUtils.createAndSaveUser(), is(notNullValue())); } - } \ No newline at end of file diff --git a/servers/dsm/src/main/java/com/samsung/dsm/controller/AccountController.java b/servers/dsm/src/main/java/com/samsung/dsm/controller/AccountController.java index 543ffdc..b7609e2 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/controller/AccountController.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/controller/AccountController.java @@ -5,7 +5,6 @@ */ package com.samsung.dsm.controller; - import java.util.HashMap; import java.util.Map; @@ -43,6 +42,7 @@ import static com.samsung.commons.utils.Utils.returnView; @Controller @RequestMapping(value = "/") public class AccountController { + @Autowired private RoleService roleService; @@ -81,7 +81,7 @@ public class AccountController { /** * (Async) Create a new user and add it to the DB. * - * @param user model for new user. + * @param user model for new user. * @param result analyze the model for errors. * @return report of the creation of the new user. */ diff --git a/servers/dsm/src/main/java/com/samsung/dsm/controller/AdminController.java b/servers/dsm/src/main/java/com/samsung/dsm/controller/AdminController.java index ad5d468..405843f 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/controller/AdminController.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/controller/AdminController.java @@ -33,7 +33,7 @@ import com.samsung.dsm.model.request.ResetPassword; import com.samsung.dsm.security.authentication.PasswordEncoder; /** - *

Admin controller

+ *

Admin controller

* Provides request handlers for interaction with users with role "ROLE_ADMIN". * * @author Artem Motchanyi @@ -44,13 +44,13 @@ import com.samsung.dsm.security.authentication.PasswordEncoder; @RequestMapping(value = "/admin") public class AdminController { - private static final Logger log = Logger.getLogger(AdminController.class); + private static final Logger LOG = Logger.getLogger(AdminController.class); @Autowired UserService userService; @Autowired - PasswordEncoder passEncoder; + PasswordEncoder passEncoder; @Autowired RoleService roleService; @@ -78,7 +78,7 @@ public class AdminController { public String users(Model model) { model.addAttribute("roles", roleService.getAll()); model.addAttribute("users", userService.getAll(true)); - log.debug("Show admin home page. Get users list: " + model); + LOG.debug("Show admin home page. Get users list: " + model); return "users"; } @@ -92,7 +92,7 @@ public class AdminController { @ResponseBody public String getUser(@PathVariable Long id) { User user = userService.findById(id); - log.debug(" Return user by id : " + id + " - " + user); + LOG.debug(" Return user by id : " + id + " - " + user); return new Gson().toJson(user); } @@ -181,7 +181,7 @@ public class AdminController { // validation if (result.hasErrors()) { // send hash map as a response and show validation messages - Map map = Utils.getRejectedFields(result.getAllErrors()); + Map map = Utils.getRejectedFields(result.getAllErrors()); return gson.toJson(map); } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardController.java b/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardController.java index e6bee69..8275e5d 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardController.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardController.java @@ -22,7 +22,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import com.samsung.dsm.model.view.ViewDashboard; /** - *

Dashboard controller

+ *

Dashboard controller

* Provides Dashboard management methods. * * @author Artem Motchanyi @@ -32,6 +32,7 @@ import com.samsung.dsm.model.view.ViewDashboard; @Controller @RequestMapping(value = "/dashboard") public class DashboardController { + @Autowired private DeviceService deviceService; @@ -49,13 +50,14 @@ public class DashboardController { User currentUser = userService.getUserByEmail(request.getUserPrincipal().getName()); ViewDashboard dashboard = new ViewDashboard(); - dashboard.setDeviceStatus( - deviceService.findUserDevicesByStatus(currentUser.getId(), Device.Status.CONNECTED.getIntStatus()), - deviceService.findUserDevicesByStatus(currentUser.getId(), Device.Status.DISCONNECTED.getIntStatus()), - deviceService.findUserDevicesByStatus(currentUser.getId(), Device.Status.ISSUES.getIntStatus()) - ); + dashboard.setDeviceStatus(deviceService + .findUserDevicesByStatus(currentUser.getId(), Device.Status.CONNECTED.getIntStatus()), deviceService + .findUserDevicesByStatus(currentUser.getId(), Device.Status.DISCONNECTED + .getIntStatus()), deviceService + .findUserDevicesByStatus(currentUser.getId(), Device.Status.ISSUES + .getIntStatus())); - List> devicesByType = new ArrayList>(); + List> devicesByType = new ArrayList<>(); List allDeviceTypes = Device.getDeviceTypeList(); for (String type : allDeviceTypes) { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardDevicesController.java b/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardDevicesController.java index c85965f..d0ee699 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardDevicesController.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/controller/DashboardDevicesController.java @@ -43,7 +43,7 @@ import com.samsung.dsm.policy.parser.PolicyParserFactory; import com.samsung.dsm.rest.mq.MQSenderImpl; /** - *

Dashboard Devices controller

+ *

Dashboard Devices controller

* Provides IoT Devices management methods. * * @author Artem Motchanyi @@ -56,11 +56,11 @@ public class DashboardDevicesController { private static final String DEVICE = "device"; - private static final String ERROR_MESSAGE = "There is no user with such id"; + private static final String ERROR_MESSAGE = "There is no user with such id"; - private static final String REDIRECT_DASHBOARD_DEVICES = "redirect:/dashboard/devices"; + private static final String REDIRECT_DASHBOARD_DEVICES = "redirect:/dashboard/devices"; - private static final Logger log = Logger.getLogger(DashboardDevicesController.class); + private static final Logger LOG = Logger.getLogger(DashboardDevicesController.class); @Autowired private UserService userService; @@ -75,7 +75,7 @@ public class DashboardDevicesController { private ReportService reportService; @Autowired - private PolicyService policyService; + private PolicyService policyService; @Autowired private ReportTypeService reportTypeService; @@ -111,12 +111,11 @@ public class DashboardDevicesController { try { viewDevice = new ViewDevice(device); - viewDevice.setOverview(new DeviceOverview(device.getPolicy().getPolicy(), - PolicyParserFactory.Type.JSON, - reportService.getDeviceReportTypes(id), - agentService.findDeviceAgents(device.getUuid()))); + viewDevice.setOverview(new DeviceOverview(device.getPolicy() + .getPolicy(), PolicyParserFactory.Type.JSON, reportService + .getDeviceReportTypes(id), agentService.findDeviceAgents(device.getUuid()))); } catch (NullPointerException e) { - log.error(ERROR_MESSAGE, e); + LOG.error(ERROR_MESSAGE, e); return REDIRECT_DASHBOARD_DEVICES; } @@ -135,7 +134,7 @@ public class DashboardDevicesController { */ @RequestMapping(value = "/reports/{id}", method = RequestMethod.GET) public String iotDeviceReports(Model model, @PathVariable Long id) { - //FIXME: returns only 10 last reports for each report type + // FIXME: returns only 10 last reports for each report type int limit = 10; ViewDevice viewDevice; Device device = deviceService.findById(id); @@ -143,7 +142,7 @@ public class DashboardDevicesController { try { viewDevice = new ViewDevice(device); } catch (NullPointerException e) { - log.error(ERROR_MESSAGE, e); + LOG.error(ERROR_MESSAGE, e); return REDIRECT_DASHBOARD_DEVICES; } @@ -177,7 +176,7 @@ public class DashboardDevicesController { try { viewDevice = new ViewDevice(device); } catch (NullPointerException e) { - log.error(ERROR_MESSAGE, e); + LOG.error(ERROR_MESSAGE, e); return REDIRECT_DASHBOARD_DEVICES; } @@ -201,7 +200,7 @@ public class DashboardDevicesController { ViewDevice device = new ViewDevice(deviceService.findById(id), PolicyParserFactory.Type.JSON); model.addAttribute(DEVICE, device); } catch (NullPointerException e) { - log.error(ERROR_MESSAGE, e); + LOG.error(ERROR_MESSAGE, e); return REDIRECT_DASHBOARD_DEVICES; } @@ -226,18 +225,19 @@ public class DashboardDevicesController { PolicyConfigParser parser = new PolicyParserFactory().getParser(PolicyParserFactory.Type.JSON); parser.toPolicyObject(policy.getPolicies()); Device device = deviceService.findByUUID(policy.getUuid()); - //TODO: call policy checker API to check policy may be enforced - //policy.getUuid() - device uid - //Get route for HUB - boolean isOk = mqSender.sendPolicy(new MQPolicy(null, policy.getUuid(), policy.getPolicies(), device.getParentUuid())); + // TODO: call policy checker API to check policy may be enforced + // policy.getUuid() - device uid + // Get route for HUB + boolean isOk = mqSender + .sendPolicy(new MQPolicy(null, policy.getUuid(), policy.getPolicies(), device.getParentUuid())); if (isOk) { policyService.setDevicePolicy(policy.getUuid(), policy.getPolicies()); return new ResponseEntity<>(HttpStatus.OK); } } catch (JsonSyntaxException e) { - log.error("Wrong policies format", e); + LOG.error("Wrong policies format", e); } catch (Exception e) { - log.error("There is no user with such UUID", e); + LOG.error("There is no user with such UUID", e); } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/controller/HomeController.java b/servers/dsm/src/main/java/com/samsung/dsm/controller/HomeController.java index 9c46244..3ed2999 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/controller/HomeController.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/controller/HomeController.java @@ -5,7 +5,6 @@ */ package com.samsung.dsm.controller; - import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; @@ -14,7 +13,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import static com.samsung.commons.utils.Utils.returnView; /** - *

Home controller

+ *

Home controller

* Provides request handlers for interaction with users with role "ROLE_GUEST". * * @author Artem Motchanyi @@ -24,6 +23,7 @@ import static com.samsung.commons.utils.Utils.returnView; @Controller @RequestMapping(value = "/") public class HomeController { + /** * (Sync) Show home page for each roles. * diff --git a/servers/dsm/src/main/java/com/samsung/dsm/controller/UserController.java b/servers/dsm/src/main/java/com/samsung/dsm/controller/UserController.java index 0be17d1..b39894f 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/controller/UserController.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/controller/UserController.java @@ -9,7 +9,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** - *

User controller

+ *

User controller

* Provides request handlers for interaction with users with role "ROLE_USER". * * @author Artem Motchanyi @@ -19,6 +19,7 @@ import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(value = "/user") public class UserController { + /** * (Sync) Show user home page. * diff --git a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthAccessToken.java b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthAccessToken.java index f07ad25..fd727d4 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthAccessToken.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthAccessToken.java @@ -246,10 +246,12 @@ public class OAuthAccessToken implements Serializable { /** * Method provides reflection to print names and values of all fields - * declared in this class. Note that superclass fields are left out of + * declared in this class. Note that superclass fields are left out + * of * this implementation. * - * @return String with names and values of all fields declared in this class. + * @return String with names and values of all fields declared in this + * class. */ @Override public String toString() { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthClientToken.java b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthClientToken.java index 95d0b38..061bdea 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthClientToken.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthClientToken.java @@ -189,10 +189,12 @@ public class OAuthClientToken implements Serializable { /** * Method provides reflection to print names and values of all fields - * declared in this class. Note that superclass fields are left out of + * declared in this class. Note that superclass fields are left out + * of * this implementation. * - * @return String with names and values of all fields declared in this class. + * @return String with names and values of all fields declared in this + * class. */ @Override public String toString() { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthCode.java b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthCode.java index a8ac1a3..c86b683 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthCode.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthCode.java @@ -104,10 +104,12 @@ public class OAuthCode implements Serializable { /** * Method provides reflection to print names and values of all fields - * declared in this class. Note that superclass fields are left out of + * declared in this class. Note that superclass fields are left out + * of * this implementation. * - * @return String with names and values of all fields declared in this class. + * @return String with names and values of all fields declared in this + * class. */ @Override public String toString() { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthRefreshToken.java b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthRefreshToken.java index f953617..0a2b498 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthRefreshToken.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/domain/oauth/OAuthRefreshToken.java @@ -132,10 +132,12 @@ public class OAuthRefreshToken implements Serializable { /** * Method provides reflection to print names and values of all fields - * declared in this class. Note that superclass fields are left out of + * declared in this class. Note that superclass fields are left out + * of * this implementation. * - * @return String with names and values of all fields declared in this class. + * @return String with names and values of all fields declared in this + * class. */ @Override public String toString() { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/request/ApplyPolicy.java b/servers/dsm/src/main/java/com/samsung/dsm/model/request/ApplyPolicy.java index af18498..6340d62 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/request/ApplyPolicy.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/request/ApplyPolicy.java @@ -10,20 +10,21 @@ import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; /** - *

Set policy

+ *

Set policy

* Model for policy setting. * * @author Artem Motchanyi * @since 2017-07-13 */ public class ApplyPolicy { + /** Device uuid. */ @NotEmpty - private String uuid; + private String uuid; /** New device policies. */ @NotNull - private String policies; + private String policies; /** * Gets the device UUID. diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/request/EditUser.java b/servers/dsm/src/main/java/com/samsung/dsm/model/request/EditUser.java index c0a544f..05ad557 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/request/EditUser.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/request/EditUser.java @@ -11,7 +11,7 @@ import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; /** - *

Edit user

+ *

Edit user

* Model of the edited user. * * @author Artem Motchanyi @@ -34,7 +34,7 @@ public class EditUser { /** User role (ID) */ @NotNull(message = "required field") - private Long roleId; + private Long roleId; /** * Gets the id. diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/request/NewUser.java b/servers/dsm/src/main/java/com/samsung/dsm/model/request/NewUser.java index 72437e0..79da677 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/request/NewUser.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/request/NewUser.java @@ -12,7 +12,7 @@ import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; /** - *

New user

+ *

New user

* Model for new users registration. * * @author Artem Motchanyi @@ -21,13 +21,15 @@ import org.hibernate.validator.constraints.Length; */ public class NewUser { - /** User name. + /** + * User name. * Must be more than 2 characters and less than 50. */ @Length(min = 2, max = 50, message = "must be more than 2 characters") private String name; - /** Email string. + /** + * Email string. * Can't be empty */ @Email(message = "required field") @@ -35,15 +37,17 @@ public class NewUser { /** The role id. */ @NotNull(message = "required field") - private Long roleId; + private Long roleId; - /** User password. + /** + * User password. * Must be more than 6 characters and less than 50. */ @Size(min = 6, max = 50, message = "must be more than 6 characters") private String password; - /** Password confirmation (repeat) + /** + * Password confirmation (repeat) * Can't be empty. */ @NotNull(message = "paswords do not match") diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/request/ResetPassword.java b/servers/dsm/src/main/java/com/samsung/dsm/model/request/ResetPassword.java index af41d46..3c7d6b3 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/request/ResetPassword.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/request/ResetPassword.java @@ -9,7 +9,7 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** - *

Reset password

+ *

Reset password

* Model for password reseting. * * @author Artem Motchanyi diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/RestDevice.java b/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/RestDevice.java index 4958ef6..27f111a 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/RestDevice.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/RestDevice.java @@ -6,6 +6,7 @@ package com.samsung.dsm.model.restapi; * @since 2017-07-13 */ public class RestDevice implements RestEntity { + private final String uuid; private final String name; private final String type; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/AgentConverter.java b/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/AgentConverter.java index ceb59f3..4d7105d 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/AgentConverter.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/AgentConverter.java @@ -17,9 +17,6 @@ public class AgentConverter extends DomainToRestConverter { @Override public RestAgent convert(Agent entity) { - return new RestAgent( - entity.getUuid(), - entity.getName() - ); + return new RestAgent(entity.getUuid(), entity.getName()); } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/DeviceConverter.java b/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/DeviceConverter.java index 9c76ec8..4a55c5e 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/DeviceConverter.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/restapi/converter/DeviceConverter.java @@ -16,13 +16,7 @@ public class DeviceConverter extends DomainToRestConverter { @Override public RestDevice convert(Device entity) { - return new RestDevice( - entity.getUuid(), - entity.getName(), - entity.getType(), - entity.getModel(), - entity.getStatus(), - entity.getParentUuid() - ); + return new RestDevice(entity.getUuid(), entity.getName(), entity.getType(), entity.getModel(), entity + .getStatus(), entity.getParentUuid()); } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/BaseView.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/BaseView.java index 8791917..b67e7ae 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/BaseView.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/BaseView.java @@ -20,19 +20,20 @@ import java.util.Map; * @since 2017-07-18 */ public class BaseView { + /** The constant for policy group name displaying. */ - protected static final Map uiPolicyGroupNameMap; + protected static final Map UI_POLICY_GROUP_NAME_MAP; static { - uiPolicyGroupNameMap = new HashMap<>(); - uiPolicyGroupNameMap.put("tv-extension", "TV-specific Settings"); + UI_POLICY_GROUP_NAME_MAP = new HashMap<>(); + UI_POLICY_GROUP_NAME_MAP.put("tv-extension", "TV-specific Settings"); } /** The constant for report name displaying */ - protected static final Map uiDisplayNameMap; + protected static final Map UI_DISPLAY_NAME_MAP; static { - uiDisplayNameMap = new HashMap<>(); - uiDisplayNameMap.put(ReportType.Type.DAC.toString(), "DAC"); - uiDisplayNameMap.put(ReportType.Type.SMACK.toString(), "SMACK"); + UI_DISPLAY_NAME_MAP = new HashMap<>(); + UI_DISPLAY_NAME_MAP.put(ReportType.Type.DAC.toString(), "DAC"); + UI_DISPLAY_NAME_MAP.put(ReportType.Type.SMACK.toString(), "SMACK"); } public String getDeviceType(String type) { @@ -49,7 +50,8 @@ public class BaseView { * @param type * device type * @param forDisplaying - * flag, if true - return type to display on view, if false - return + * flag, if true - return type to display on view, if false - + * return * device type class * * @return view redirect to. @@ -89,6 +91,7 @@ public class BaseView { } public static class DeviceStatusView { + private String status; private String statusText; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/DeviceOverview.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/DeviceOverview.java index cd4fb05..b11f630 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/DeviceOverview.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/DeviceOverview.java @@ -55,8 +55,8 @@ public class DeviceOverview extends BaseView { for (PolicyGroup policyGroup : policyConfig.getPoliciesGroups()) { this.policies.add( - new OverviewPolicy(uiPolicyGroupNameMap.get(policyGroup.getName()) == null ? policyGroup.getName() - : uiPolicyGroupNameMap.get(policyGroup.getName()))); + new OverviewPolicy(UI_POLICY_GROUP_NAME_MAP.get(policyGroup.getName()) == null ? policyGroup.getName() + : UI_POLICY_GROUP_NAME_MAP.get(policyGroup.getName()))); } } @@ -68,8 +68,8 @@ public class DeviceOverview extends BaseView { this.reports = new ArrayList<>(); for (ReportType.Type type : reportTypes) { - String reportName = uiDisplayNameMap.get(type.toString()) == null ? type.toString() - : uiDisplayNameMap.get(type.toString()); + String reportName = UI_DISPLAY_NAME_MAP.get(type.toString()) == null ? type.toString() + : UI_DISPLAY_NAME_MAP.get(type.toString()); this.reports.add(new OverviewReport(reportName)); } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewAgent.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewAgent.java index 9d581b6..d8f4d6c 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewAgent.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewAgent.java @@ -13,7 +13,7 @@ import com.samsung.commons.domain.Agent; import com.samsung.dsm.policy.parser.PolicyParserFactory; /** - *

Agent view model

+ *

Agent view model

* Model to represent agent on the view. * * @author Artem Motchanyi @@ -21,6 +21,7 @@ import com.samsung.dsm.policy.parser.PolicyParserFactory; * @since 2017-07-05 */ public class ViewAgent { + /** * The agent's ID */ @@ -46,7 +47,7 @@ public class ViewAgent { } public static List getViewAgentsList(List agents, PolicyParserFactory.Type policyType) { - List viewAgents = new ArrayList(); + List viewAgents = new ArrayList<>(); for (Agent agent : agents) { viewAgents.add(new ViewAgent(agent, policyType)); @@ -127,11 +128,7 @@ public class ViewAgent { @Override public String toString() { - return Objects.toStringHelper(this) - .add("id", id) - .add("uuid", uuid) - .add("name", name) - .add("policies", policies) + return Objects.toStringHelper(this).add("id", id).add("uuid", uuid).add("name", name).add("policies", policies) .toString(); } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDashboard.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDashboard.java index c2698c8..7d1eaec 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDashboard.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDashboard.java @@ -19,6 +19,7 @@ import java.util.List; * @since 2017-07-18 */ public class ViewDashboard extends BaseView { + /** The total devices counter */ private long totalDevices; /** The devices status list */ @@ -86,6 +87,7 @@ public class ViewDashboard extends BaseView { } public class DeviceStatus { + /** The device's status */ private String status; /** The device's status displayed text */ @@ -114,6 +116,7 @@ public class ViewDashboard extends BaseView { } public class DeviceType { + /** The device's name. */ private String name; /** The device's type */ @@ -141,6 +144,7 @@ public class ViewDashboard extends BaseView { } public class UserStatus { + /** The user's status */ private String status; /** The user's status displayed text */ diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDevice.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDevice.java index b27ad77..588af0c 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDevice.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewDevice.java @@ -23,6 +23,7 @@ import com.samsung.dsm.policy.parser.PolicyParserFactory; * @since 2017-07-05 */ public class ViewDevice extends BaseView { + /** The device's ID */ private long id; /** The device's UUID */ diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewPolicyGroup.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewPolicyGroup.java index d99c155..4a3b149 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewPolicyGroup.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewPolicyGroup.java @@ -25,6 +25,7 @@ import com.samsung.dsm.policy.parser.PolicyParserFactory; * @since 2017-07-05 */ public class ViewPolicyGroup extends BaseView { + /** * The group name. */ @@ -54,13 +55,13 @@ public class ViewPolicyGroup extends BaseView { public ViewPolicyGroup(PolicyGroup policyGroup) { this.name = policyGroup.getName(); this.policyList = ViewPolicy.getViewPolicyList(policyGroup); - this.displayName = uiPolicyGroupNameMap.get(policyGroup.getName()) == null ? policyGroup.getName() - : uiPolicyGroupNameMap.get(policyGroup.getName()); + this.displayName = UI_POLICY_GROUP_NAME_MAP.get(policyGroup.getName()) == null ? policyGroup + .getName() : UI_POLICY_GROUP_NAME_MAP.get(policyGroup.getName()); this.isDisplay = policyGroup.getPolicies().length > 0 ? true : false; } public static List getViewPolicyGroupList(PolicyConfig policyConfig) { - List viewPolicies = new ArrayList(); + List viewPolicies = new ArrayList<>(); for (PolicyGroup policyGroup : policyConfig.getPoliciesGroups()) { viewPolicies.add(new ViewPolicyGroup(policyGroup)); @@ -108,13 +109,14 @@ public class ViewPolicyGroup extends BaseView { } public static class ViewPolicy { + /** * The Constant uiPolicyNameMap. */ private static final Map uiPolicyNameMap; static { - uiPolicyNameMap = new HashMap(); + uiPolicyNameMap = new HashMap<>(); uiPolicyNameMap.put("iptables", "IP Tables"); uiPolicyNameMap.put("bluetooth", "Bluetooth"); uiPolicyNameMap.put("sound", "Sound"); @@ -136,7 +138,7 @@ public class ViewPolicyGroup extends BaseView { } public static List getViewPolicyList(PolicyConfig.PolicyGroup policyGroup) { - List viewPolicies = new ArrayList(); + List viewPolicies = new ArrayList<>(); for (PolicyGroup.Policy policy : policyGroup.getPolicies()) { viewPolicies.add(new ViewPolicy(policy)); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewReport.java b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewReport.java index 660dc90..a73b5a0 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewReport.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/model/view/ViewReport.java @@ -26,7 +26,8 @@ import com.samsung.dsm.report.analyzer.ReportAnalyzerFactory; * @since 2017-07-06 */ public class ViewReport extends BaseView { - private static final Logger log = Logger.getLogger(DashboardDevicesController.class); + + private static final Logger LOG = Logger.getLogger(DashboardDevicesController.class); /** * The reports array of current type */ @@ -50,7 +51,7 @@ public class ViewReport extends BaseView { dataMap.put("date", report.getDate()); reportsData.add(dataMap); } catch (Exception e) { - log.error("Wrong report format: " + report.getReport()); + LOG.error("Wrong report format: " + report.getReport()); } } @@ -76,7 +77,7 @@ public class ViewReport extends BaseView { } private void setName(String type) { - this.name = uiDisplayNameMap.get(type) == null ? type : uiDisplayNameMap.get(type); + this.name = UI_DISPLAY_NAME_MAP.get(type) == null ? type : UI_DISPLAY_NAME_MAP.get(type); } @Override diff --git a/servers/dsm/src/main/java/com/samsung/dsm/policy/PolicyConfig.java b/servers/dsm/src/main/java/com/samsung/dsm/policy/PolicyConfig.java index 978f44d..9c8e434 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/policy/PolicyConfig.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/policy/PolicyConfig.java @@ -21,6 +21,7 @@ import org.apache.commons.lang3.builder.HashCodeBuilder; * @since 2017-06-16 */ public class PolicyConfig { + private PolicyGroup[] policiesGroups; public PolicyConfig(PolicyGroup[] policiesGroups) { @@ -35,6 +36,7 @@ public class PolicyConfig { * Policy group class Contains group name and policies list */ public static class PolicyGroup { + private String group; private Policy[] policies; @@ -55,6 +57,7 @@ public class PolicyConfig { * Policy class Contains policy name, state and rules list */ public static class Policy { + private String name; private int state; private String[] items; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/JSONPolicyConfigParser.java b/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/JSONPolicyConfigParser.java index aa4dd7a..b873544 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/JSONPolicyConfigParser.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/JSONPolicyConfigParser.java @@ -9,7 +9,7 @@ import com.google.gson.Gson; import com.samsung.dsm.policy.PolicyConfig; /** - *

JSON policy parser

+ *

JSON policy parser

* Parser for policies stored in JSON format. * * @author Artem Motchanyi @@ -17,6 +17,7 @@ import com.samsung.dsm.policy.PolicyConfig; * @since 2017-06-15 */ public class JSONPolicyConfigParser implements PolicyConfigParser { + /** * Parse JSON string into object * @param jsonPolicies policy config in JSON format. @@ -24,9 +25,7 @@ public class JSONPolicyConfigParser implements PolicyConfigParser { */ @Override public PolicyConfig toPolicyObject(String jsonPolicies) { - PolicyConfig pc = new PolicyConfig(new Gson().fromJson(jsonPolicies, PolicyConfig.PolicyGroup[].class)); - - return pc; + return new PolicyConfig(new Gson().fromJson(jsonPolicies, PolicyConfig.PolicyGroup[].class)); } /** diff --git a/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyConfigParser.java b/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyConfigParser.java index e9173a3..169e757 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyConfigParser.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyConfigParser.java @@ -8,7 +8,7 @@ package com.samsung.dsm.policy.parser; import com.samsung.dsm.policy.PolicyConfig; /** - *

Policy JSON parser

+ *

Policy JSON parser

* Parser for policy configuration which are represented by strings. * * @author Anton Komandyr @@ -16,6 +16,7 @@ import com.samsung.dsm.policy.PolicyConfig; * @since 2016-09-01 */ public interface PolicyConfigParser { + /** * Parse string to policyConfig object. * @param policyConfig policy in string. diff --git a/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyParserFactory.java b/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyParserFactory.java index 00e1080..ac6f065 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyParserFactory.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/policy/parser/PolicyParserFactory.java @@ -6,26 +6,27 @@ package com.samsung.dsm.policy.parser; /** - *

Policy parser factory

+ *

Policy parser factory

* Create instance of the corresponding parser depending on policy type. * * @author Artem Motchanyi * @since 2017-07-13 */ public class PolicyParserFactory { + public enum Type { - JSON + JSON } public PolicyConfigParser getParser(Type type) { PolicyConfigParser parser = null; switch (type) { - case JSON: - parser = new JSONPolicyConfigParser(); - break; - default: - break; + case JSON: + parser = new JSONPolicyConfigParser(); + break; + default: + break; } return parser; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/ReportConfig.java b/servers/dsm/src/main/java/com/samsung/dsm/report/ReportConfig.java index dd375d3..76afd93 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/ReportConfig.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/ReportConfig.java @@ -8,7 +8,7 @@ package com.samsung.dsm.report; import java.util.Arrays; /** - *

Report model

+ *

Report model

* Class, describes inner condition of ReportConfig object. * * @author Yevhen Zozulia @@ -30,12 +30,13 @@ public class ReportConfig { /** * Report class * Contains: - * did - device id [string] - * date - report generation date in human readable format [string] - * name - report name; unique name or tag to identify report provider, e.g. "dac", - * "smart-security" [string] - * result - report verdict, 0 - ok, others - error code [int] - * data - report data in JSON format [string] + * did - device id [string] + * date - report generation date in human readable format [string] + * name - report name; unique name or tag to identify report provider, e.g. + * "dac", + * "smart-security" [string] + * result - report verdict, 0 - ok, others - error code [int] + * data - report data in JSON format [string] */ public static class Report { @@ -43,7 +44,7 @@ public class ReportConfig { private String date; private String name; private int result; - + private transient String data; public Report(String did, String date, String name, int result, String data) { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzer.java b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzer.java index 7d7878e..b623318 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzer.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzer.java @@ -6,6 +6,7 @@ import com.samsung.commons.model.Notification; import com.samsung.dsm.service.GrantedApplicationService; public interface ReportAnalyzer { + Map extractReportData(String report); String getCode(); @@ -14,7 +15,5 @@ public interface ReportAnalyzer { String getMessage(); - void analyze(Map map, GrantedApplicationService grantedApplicationService); - - Notification createNotification(Map map, GrantedApplicationService grantedApplicationService); + Notification createNotification(Map map, GrantedApplicationService grantedApplicationService); } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactory.java b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactory.java index bceda2a..eb9a9ed 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactory.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactory.java @@ -10,11 +10,11 @@ public class ReportAnalyzerFactory { public static ReportAnalyzer getAnalyzer(String type) { ReportAnalyzer analyzer = null; - if(ReportType.Type.DAC.type.equals(type)){ + if (ReportType.Type.DAC.type.equals(type)) { analyzer = new DACReportAnalyzer(); - }else if(ReportType.Type.SMACK.type.equals(type)){ + } else if (ReportType.Type.SMACK.type.equals(type)) { analyzer = new MACReportAnalyzer(); - }else if(ReportType.Type.SYSCALL.type.equals(type)){ + } else if (ReportType.Type.SYSCALL.type.equals(type)) { analyzer = new SYSCALLReportAnalyzer(); } return analyzer; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeys.java b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeys.java index e2c5310..f6b2ac2 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeys.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeys.java @@ -1,6 +1,7 @@ package com.samsung.dsm.report.analyzer; public class ReportAnalyzerKeys { + public static final String DEVICE_ID = "deviceId"; public static final String CLOUD_USER_ID = "cloudId"; public static final String POLICY = "policy"; @@ -28,9 +29,9 @@ public class ReportAnalyzerKeys { public static final String MAC_REPORT_ACTION = "action"; public static final String MAC_REPORT_FN = "fn"; public static final String MAC_REPORT_LSM = "lsm"; - //FIXME: solution for smack_test detection + // FIXME: solution for smack_test detection public static final String MAC_REPORT_NAME = "name"; - + /** * Keys for DAC reports */ @@ -61,11 +62,12 @@ public class ReportAnalyzerKeys { public static final String DAC_REPORT_COMM = "comm"; public static final String DAC_REPORT_EXE = "exe"; public static final String DAC_REPORT_SUBJ = "subj"; - + /** * Keys for syscall reports */ - public static final String SYSCALL = "[syscall]"; + public static final String SYSCALL = "[syscall]"; - private ReportAnalyzerKeys() {} + private ReportAnalyzerKeys() { + } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzer.java b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzer.java index 8e28d84..28b5429 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzer.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzer.java @@ -14,7 +14,8 @@ import com.samsung.dsm.service.GrantedApplicationService; public class DACReportAnalyzer extends MACReportAnalyzer implements ReportAnalyzer { - private static final Logger log = Logger.getLogger(DACReportAnalyzer.class); + private static final String SMACK_TEST = "smack_test"; + private static final Logger LOG = Logger.getLogger(DACReportAnalyzer.class); @Override protected boolean isValid(String currentRow) { @@ -22,32 +23,29 @@ public class DACReportAnalyzer extends MACReportAnalyzer implements ReportAnalyz } @Override - public Notification createNotification(Map map, GrantedApplicationService grantedApplicationService) { + public Notification createNotification(Map map, + GrantedApplicationService grantedApplicationService) { Notification notification = new Notification(); notification.setCloudUserId(map.get(ReportAnalyzerKeys.CLOUD_USER_ID)); notification.setDeviceId(map.get(ReportAnalyzerKeys.DEVICE_ID)); notification.setPolicy(map.get(ReportAnalyzerKeys.POLICY)); - Map mapResult = new HashMap<>(); + Map mapResult = new HashMap<>(); String parentCommand = map.get(ReportAnalyzerKeys.DAC_REPORT_COMM); String command = map.get(ReportAnalyzerKeys.DAC_REPORT_EXE); String parentUuid = map.get(ReportAnalyzerKeys.DEVICE_PARENT_UUID); + String ppid = map.get(ReportAnalyzerKeys.DAC_REPORT_PPID); + String pid = map.get(ReportAnalyzerKeys.DAC_REPORT_PID); mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, command); mapResult.put(ReportAnalyzerKeys.DEVICE_PARENT_UUID, parentUuid); - ///////////////////////////////////////////////////// FIXME Stub for demos///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// FIXME Stub for + ///////////////////////////////////////////////////// demos///////////////////////////////////////////////////// boolean find = false; - if(parentCommand.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")){ - notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); + if (parentCommand.equalsIgnoreCase(SMACK_TEST) || command.equalsIgnoreCase(SMACK_TEST)) { + notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); notification.setMessage(getNotTrustedMessage(parentCommand, command)); notification.setCode(CODE_NOT_GRANTED); notification.setCurrentTime(System.currentTimeMillis()); - notification.setAdditionalMap(mapResult); - log.debug(notification.getMessage()); - return notification; - } - String ppid = map.get(ReportAnalyzerKeys.DAC_REPORT_PPID); - String pid = map.get(ReportAnalyzerKeys.DAC_REPORT_PID); - if (parentCommand.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")) { - if (parentCommand.equalsIgnoreCase("smack_test")) { + if (parentCommand.equalsIgnoreCase(SMACK_TEST)) { mapResult.put(ReportAnalyzerKeys.DAC_REPORT_PID, ppid); mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, parentCommand); } else { @@ -55,14 +53,16 @@ public class DACReportAnalyzer extends MACReportAnalyzer implements ReportAnalyz mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, command); } notification.setAdditionalMap(mapResult); + LOG.debug(notification.getMessage()); + return notification; } find = false; Set keys = map.keySet(); for (String key : keys) { String value = map.get(key); - log.debug("(key = " + key + ", value = " + value + ")"); - if (value.contains("smack_test")) { - log.debug("Find in key = " + key + ", value = " + value); + LOG.debug("(key = " + key + ", value = " + value + ")"); + if (value.contains(SMACK_TEST)) { + LOG.debug("Find in key = " + key + ", value = " + value); find = true; } } @@ -70,8 +70,9 @@ public class DACReportAnalyzer extends MACReportAnalyzer implements ReportAnalyz mapResult.put(ReportAnalyzerKeys.DAC_REPORT_PID, pid); String subject = map.get(ReportAnalyzerKeys.DAC_REPORT_SUBJ); String[] arr = subject.split(":"); - log.debug("============================= subject =========================================="); - log.debug("============================= Array: " + Arrays.toString(arr) + " =========================================="); + LOG.debug("============================= subject =========================================="); + LOG.debug("============================= Array: " + Arrays.toString(arr) + + " =========================================="); mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, arr[arr.length - 1]); notification.setAdditionalMap(mapResult); notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); @@ -79,12 +80,12 @@ public class DACReportAnalyzer extends MACReportAnalyzer implements ReportAnalyz notification.setMessage(getNotTrustedMessage(mapResult.get(ReportAnalyzerKeys.REPORT_APPNAME))); notification.setCurrentTime(System.currentTimeMillis()); return notification; - } + } notification.setTitle(PROBLEM_WITH_PERMISSIONS_TITLE); notification.setMessage(getNoPermissionMessage(parentCommand, command)); notification.setCode(CODE_GRANTED); notification.setCurrentTime(System.currentTimeMillis()); - log.debug(getMessage()); + LOG.debug(getMessage()); notification.setAdditionalMap(map); return notification; } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzer.java b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzer.java index b2963fa..b0c7554 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzer.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzer.java @@ -22,7 +22,7 @@ public class MACReportAnalyzer implements ReportAnalyzer { public static final String CODE_GRANTED = "1"; public static final String CODE_NOT_GRANTED = "2"; - private static final Logger log = Logger.getLogger(MACReportAnalyzer.class); + private static final Logger LOG = Logger.getLogger(MACReportAnalyzer.class); private String code; private String title; @@ -32,14 +32,14 @@ public class MACReportAnalyzer implements ReportAnalyzer { public Map extractReportData(String report) { String logData = extractLog(report); String[] rows = logData.trim().split("\n"); - log.trace("----------------------------------------------------------------------------------------------------------------"); - log.trace("Input report:"); - log.trace(report); - //[MAC] - int iRow = 0; - for(String row:rows){ + LOG.trace("----------------------------------------------------------------------------------------------------------------"); + LOG.trace("Input report:"); + LOG.trace(report); + // [MAC] + int iRow = 0; + for (String row : rows) { iRow++; - log.trace("row #" + iRow +" : " + row); + LOG.trace("row #" + iRow + " : " + row); } // extract message String reportMessage = ""; @@ -50,14 +50,14 @@ public class MACReportAnalyzer implements ReportAnalyzer { } reportMessage = reportMessage + " " + currentRow; } - log.trace("Message : " + reportMessage); - //extract data from message + LOG.trace("Message : " + reportMessage); + // extract data from message String[] extractedData = reportMessage.split(" "); - //create map + // create map Map map = new HashMap<>(); fillMap(extractedData, map); - log.trace(map.toString()); - log.trace("----------------------------------------------------------------------------------------------------------------"); + LOG.trace(map.toString()); + LOG.trace("----------------------------------------------------------------------------------------------------------------"); return map; } @@ -65,26 +65,26 @@ public class MACReportAnalyzer implements ReportAnalyzer { return !currentRow.startsWith(ReportAnalyzerKeys.MAC) && currentRow.startsWith("["); } - private String extractLog(String report){ - JsonParser parser = new JsonParser(); + private String extractLog(String report) { + JsonParser parser = new JsonParser(); JsonObject mainObject = parser.parse(report).getAsJsonObject(); JsonObject data = mainObject.get("data").getAsJsonObject(); return data.get("log").getAsString(); } - + private void fillMap(String[] extractedData, Map map) { - for(String data: extractedData){ - log.trace(data); + for (String data : extractedData) { + LOG.trace(data); String[] items = data.split("="); - if(items.length < 2){ + if (items.length < 2) { continue; } String key = items[0].trim(); String value = ""; - for(int i = 1; i < items.length; i++){ + for (int i = 1; i < items.length; i++) { value = value + items[i] + "="; } - value = value.substring(0, value.length()-1).split("\\[")[0]; + value = value.substring(0, value.length() - 1).split("\\[")[0]; map.put(key, value); } } @@ -104,35 +104,6 @@ public class MACReportAnalyzer implements ReportAnalyzer { return message; } - @Override - //FIXME remove after tests - public void analyze(Map map, GrantedApplicationService grantedApplicationService) { - String parentCommand = map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM); - String command = map.get(ReportAnalyzerKeys.MAC_REPORT_COMM); - map.put(ReportAnalyzerKeys.MAC_REPORT_APPNAME, command); - boolean find = false; - Set keys = map.keySet(); - for(String key: keys){ - String value = map.get(key); - log.info("(key = " + key + ", value = " + value+ ")"); - if( value != null && value.contains("smack_test")){ - log.info("Find in key = " + key + ", value = " + value); - find = true; - } - } - if(find){ - title = APPLICATION_IS_NOT_TRUSTED_TITLE; - message = getNotTrustedMessage(parentCommand, command); - code = CODE_NOT_GRANTED; - log.info(message); - return; - } - title = PROBLEM_WITH_PERMISSIONS_TITLE; - message = getNoPermissionMessage(parentCommand, command); - code = CODE_GRANTED; - log.info(message); - } - protected String getNoPermissionMessage(String parentCommand, String command) { return "App \"" + parentCommand + "\" try execute \"" + command + "\", but hasn't permissions."; } @@ -146,37 +117,35 @@ public class MACReportAnalyzer implements ReportAnalyzer { } @Override - public Notification createNotification(Map map, GrantedApplicationService grantedApplicationService) { + public Notification createNotification(Map map, + GrantedApplicationService grantedApplicationService) { Notification notification = new Notification(); notification.setCloudUserId(map.get(ReportAnalyzerKeys.CLOUD_USER_ID)); notification.setDeviceId(map.get(ReportAnalyzerKeys.DEVICE_ID)); notification.setPolicy(map.get(ReportAnalyzerKeys.POLICY)); - Map mapResult = new HashMap<>(); - //String parentCommand = map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM); + Map mapResult = new HashMap<>(); + // String parentCommand = + // map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM); String command = map.getOrDefault(ReportAnalyzerKeys.MAC_REPORT_COMM, ""); String parentUuid = map.get(ReportAnalyzerKeys.DEVICE_PARENT_UUID); - //FIXME: solution for smack_test detection + String ppid = map.get(ReportAnalyzerKeys.MAC_REPORT_PPID); + String pid = map.get(ReportAnalyzerKeys.MAC_REPORT_PID); + // FIXME: solution for smack_test detection String subject = map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT); String[] arr = subject.split(":"); mapResult.put(ReportAnalyzerKeys.MAC_REPORT_APPNAME, arr[arr.length - 1]); mapResult.put(ReportAnalyzerKeys.DEVICE_PARENT_UUID, parentUuid); - //FIXME: solution for smack_test detection + // FIXME: solution for smack_test detection String name = map.getOrDefault(ReportAnalyzerKeys.MAC_REPORT_NAME, ""); - ///////////////////////////////////////////////////// FIXME Stub for demos///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// FIXME Stub for + ///////////////////////////////////////////////////// demos///////////////////////////////////////////////////// boolean find = false; - if(name.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")){ - notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); + if (name.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")) { + notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); notification.setMessage(getNotTrustedMessage(name, command)); notification.setCode(CODE_NOT_GRANTED); notification.setCurrentTime(System.currentTimeMillis()); - notification.setAdditionalMap(mapResult); - log.debug(notification.getMessage()); - return notification; - } - String ppid = map.get(ReportAnalyzerKeys.MAC_REPORT_PPID); - String pid = map.get(ReportAnalyzerKeys.MAC_REPORT_PID); - if (name.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")) { if (name.equalsIgnoreCase("smack_test")) { mapResult.put(ReportAnalyzerKeys.MAC_REPORT_PID, ppid); mapResult.put(ReportAnalyzerKeys.MAC_REPORT_APPNAME, name); @@ -185,14 +154,16 @@ public class MACReportAnalyzer implements ReportAnalyzer { mapResult.put(ReportAnalyzerKeys.MAC_REPORT_APPNAME, command); } notification.setAdditionalMap(mapResult); + LOG.debug(notification.getMessage()); + return notification; } find = false; Set keys = map.keySet(); for (String key : keys) { String value = map.get(key); - log.debug("(key = " + key + ", value = " + value + ")"); + LOG.debug("(key = " + key + ", value = " + value + ")"); if (value.contains("smack_test")) { - log.debug("Find in key = " + key + ", value = " + value); + LOG.debug("Find in key = " + key + ", value = " + value); find = true; } } @@ -200,8 +171,9 @@ public class MACReportAnalyzer implements ReportAnalyzer { mapResult.put(ReportAnalyzerKeys.MAC_REPORT_PID, pid); subject = map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT); arr = subject.split(":"); - log.debug("============================= subject =========================================="); - log.debug("============================= Array: " + Arrays.toString(arr) + " =========================================="); + LOG.debug("============================= subject =========================================="); + LOG.debug("============================= Array: " + Arrays.toString(arr) + + " =========================================="); mapResult.put(ReportAnalyzerKeys.MAC_REPORT_APPNAME, arr[arr.length - 1]); notification.setAdditionalMap(mapResult); notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); @@ -209,12 +181,12 @@ public class MACReportAnalyzer implements ReportAnalyzer { notification.setMessage(getNotTrustedMessage(mapResult.get(ReportAnalyzerKeys.MAC_REPORT_APPNAME))); notification.setCurrentTime(System.currentTimeMillis()); return notification; - } + } notification.setTitle(PROBLEM_WITH_PERMISSIONS_TITLE); notification.setMessage(getNoPermissionMessage(name, command)); notification.setCode(CODE_GRANTED); notification.setCurrentTime(System.currentTimeMillis()); - log.debug(message); + LOG.debug(message); notification.setAdditionalMap(map); return notification; } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzer.java b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzer.java index 9fcef56..7ab6a86 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzer.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzer.java @@ -14,45 +14,42 @@ import com.samsung.dsm.service.GrantedApplicationService; public class SYSCALLReportAnalyzer extends MACReportAnalyzer implements ReportAnalyzer { - private static final Logger log = Logger.getLogger(DACReportAnalyzer.class); - + private static final Logger LOG = Logger.getLogger(DACReportAnalyzer.class); + @Override protected boolean isValid(String currentRow) { return !currentRow.startsWith(ReportAnalyzerKeys.SYSCALL) && currentRow.startsWith("["); } - + @Override - public Notification createNotification(Map map, GrantedApplicationService grantedApplicationService) { + public Notification createNotification(Map map, + GrantedApplicationService grantedApplicationService) { Notification notification = new Notification(); notification.setCloudUserId(map.get(ReportAnalyzerKeys.CLOUD_USER_ID)); notification.setDeviceId(map.get(ReportAnalyzerKeys.DEVICE_ID)); notification.setPolicy(map.get(ReportAnalyzerKeys.POLICY)); - Map mapResult = new HashMap<>(); + Map mapResult = new HashMap<>(); String parentCommand = map.get(ReportAnalyzerKeys.DAC_REPORT_COMM); String command = map.get(ReportAnalyzerKeys.DAC_REPORT_EXE); - if(parentCommand == null || parentCommand.isEmpty()){ + String ppid = map.get(ReportAnalyzerKeys.DAC_REPORT_PPID); + String pid = map.get(ReportAnalyzerKeys.DAC_REPORT_PID); + if (parentCommand == null || parentCommand.isEmpty()) { parentCommand = map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM); } - if(command == null || command.isEmpty()){ + if (command == null || command.isEmpty()) { command = map.get(ReportAnalyzerKeys.MAC_REPORT_COMM); } String parentUuid = map.get(ReportAnalyzerKeys.DEVICE_PARENT_UUID); mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, command); mapResult.put(ReportAnalyzerKeys.DEVICE_PARENT_UUID, parentUuid); - ///////////////////////////////////////////////////// FIXME Stub for demos///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// FIXME Stub for + ///////////////////////////////////////////////////// demos///////////////////////////////////////////////////// boolean find = false; - if(parentCommand.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")){ - notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); + if (parentCommand.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")) { + notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); notification.setMessage(getNotTrustedMessage(parentCommand, command)); notification.setCode(CODE_NOT_GRANTED); notification.setCurrentTime(System.currentTimeMillis()); - notification.setAdditionalMap(mapResult); - log.debug(notification.getMessage()); - return notification; - } - String ppid = map.get(ReportAnalyzerKeys.DAC_REPORT_PPID); - String pid = map.get(ReportAnalyzerKeys.DAC_REPORT_PID); - if (parentCommand.equalsIgnoreCase("smack_test") || command.equalsIgnoreCase("smack_test")) { if (parentCommand.equalsIgnoreCase("smack_test")) { mapResult.put(ReportAnalyzerKeys.DAC_REPORT_PID, ppid); mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, parentCommand); @@ -61,26 +58,29 @@ public class SYSCALLReportAnalyzer extends MACReportAnalyzer implements ReportAn mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, command); } notification.setAdditionalMap(mapResult); + LOG.debug(notification.getMessage()); + return notification; } find = false; Set keys = map.keySet(); for (String key : keys) { String value = map.get(key); - log.debug("(key = " + key + ", value = " + value + ")"); + LOG.debug("(key = " + key + ", value = " + value + ")"); if (value.contains("smack_test")) { - log.debug("Find in key = " + key + ", value = " + value); + LOG.debug("Find in key = " + key + ", value = " + value); find = true; } } if (find) { mapResult.put(ReportAnalyzerKeys.DAC_REPORT_PID, pid); String subject = map.get(ReportAnalyzerKeys.DAC_REPORT_SUBJ); - if(subject == null || subject.isEmpty()){ + if (subject == null || subject.isEmpty()) { subject = map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT); } String[] arr = subject.split(":"); - log.debug("============================= subject =========================================="); - log.debug("============================= Array: " + Arrays.toString(arr) + " =========================================="); + LOG.debug("============================= subject =========================================="); + LOG.debug("============================= Array: " + Arrays.toString(arr) + + " =========================================="); mapResult.put(ReportAnalyzerKeys.REPORT_APPNAME, arr[arr.length - 1]); notification.setAdditionalMap(mapResult); notification.setTitle(APPLICATION_IS_NOT_TRUSTED_TITLE); @@ -88,14 +88,14 @@ public class SYSCALLReportAnalyzer extends MACReportAnalyzer implements ReportAn notification.setMessage(getNotTrustedMessage(mapResult.get(ReportAnalyzerKeys.REPORT_APPNAME))); notification.setCurrentTime(System.currentTimeMillis()); return notification; - } + } notification.setTitle(PROBLEM_WITH_PERMISSIONS_TITLE); notification.setMessage(getNoPermissionMessage(parentCommand, command)); notification.setCode(CODE_GRANTED); notification.setCurrentTime(System.currentTimeMillis()); - log.debug(getMessage()); + LOG.debug(getMessage()); notification.setAdditionalMap(map); return notification; } - + } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/parser/JSONReportConfigParser.java b/servers/dsm/src/main/java/com/samsung/dsm/report/parser/JSONReportConfigParser.java index 4a9dcfa..5e8b2a4 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/parser/JSONReportConfigParser.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/parser/JSONReportConfigParser.java @@ -9,7 +9,7 @@ import com.google.gson.Gson; import com.samsung.dsm.report.ReportConfig; /** - *

JSON report parser

+ *

JSON report parser

* Parser for reports stored in JSON format. * * @author Yevhen Zozulia @@ -34,7 +34,7 @@ public class JSONReportConfigParser implements ReportConfigParser { * @return JSON string. */ @Override - public String toString(ReportConfig config) { + public String toString(ReportConfig config) { return new Gson().toJson(config.getReportsSet()); } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/report/parser/ReportConfigParser.java b/servers/dsm/src/main/java/com/samsung/dsm/report/parser/ReportConfigParser.java index f20e9d5..06171ce 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/report/parser/ReportConfigParser.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/report/parser/ReportConfigParser.java @@ -8,7 +8,7 @@ package com.samsung.dsm.report.parser; import com.samsung.dsm.report.ReportConfig; /** - *

Report JSON parser

+ *

Report JSON parser

* Parser for Report configuration which are represented by strings. * * @author Yevhen Zozulia @@ -16,6 +16,7 @@ import com.samsung.dsm.report.ReportConfig; * @since 2017-06-19 */ public interface ReportConfigParser { + /** * Parse string to reportConfig object. * @param reportConfig report in string. diff --git a/servers/dsm/src/main/java/com/samsung/dsm/repository/OAuthAccessTokenRepository.java b/servers/dsm/src/main/java/com/samsung/dsm/repository/OAuthAccessTokenRepository.java index c46ba20..8ee05f0 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/repository/OAuthAccessTokenRepository.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/repository/OAuthAccessTokenRepository.java @@ -11,7 +11,7 @@ import org.springframework.stereotype.Repository; import com.samsung.dsm.domain.oauth.OAuthAccessToken; /** - *

OAuth Access Token repository

+ *

OAuth Access Token repository

* CRUD repository for OAuthAccessToken class. * @see OAuthAccessToken * diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/accesstoken/AccessTokenApi.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/accesstoken/AccessTokenApi.java index 4777c1d..0de40b0 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/accesstoken/AccessTokenApi.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/accesstoken/AccessTokenApi.java @@ -51,16 +51,20 @@ public class AccessTokenApi { /** * Login and return authorization code * - * @param login login + * @param login login * @param password password * @return (OK) auth code - * @throws LoginServiceGeneralException (UNAUTHORIZED) in case if credentials are wrong or auth code can't be generated for some - * other reason (database connection problems, database table was absent/corrupted etc.) + * @throws LoginServiceGeneralException (UNAUTHORIZED) in case if + * credentials are wrong or auth code can't be generated for + * some + * other reason (database connection problems, database table + * was absent/corrupted etc.) */ @RequestMapping(value = "/login") @ResponseBody public String login(@RequestParam String login, @RequestParam String password) { - return ofNullable(loginAuthCodeService.loginAndGenerate(login, password)).orElseThrow(LoginServiceGeneralException::new); + return ofNullable(loginAuthCodeService.loginAndGenerate(login, password)) + .orElseThrow(LoginServiceGeneralException::new); } /** @@ -69,7 +73,7 @@ public class AccessTokenApi { * * @param access_token access token * @return (OK) response status - * (UNAUTHORIZED) wrong credentials + * (UNAUTHORIZED) wrong credentials */ @RequestMapping(value = "/access_token", method = RequestMethod.GET) public ResponseEntity getUserDetailsByAccessToken(@RequestParam String access_token) { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/device/DeviceApi.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/device/DeviceApi.java index 4e7932c..a75c3ce 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/device/DeviceApi.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/device/DeviceApi.java @@ -38,7 +38,7 @@ import static org.springframework.http.HttpStatus.OK; @RestController @RequestMapping(value = "/restapi/device") public class DeviceApi { - + @Autowired private DeviceService deviceService; @@ -84,11 +84,13 @@ public class DeviceApi { * * @param deviceUuId device UUID * @return (OK) policy has been successfully got - * @throws DeviceNotFoundByUuid (NOT_FOUND) device has't been found by it's UUID + * @throws DeviceNotFoundByUuid (NOT_FOUND) device has't been found by it's + * UUID */ @RequestMapping(value = "/{deviceUuId}/policy") public String findPolicyByUUID(@PathVariable String deviceUuId) { - Policy policy = ofNullable(deviceService.findByUUID(deviceUuId)).orElseThrow(DeviceNotFoundByUuid::new).getPolicy(); + Policy policy = ofNullable(deviceService.findByUUID(deviceUuId)).orElseThrow(DeviceNotFoundByUuid::new) + .getPolicy(); return policy.getPolicy(); } @@ -97,11 +99,13 @@ public class DeviceApi { * * @param iotCloudUserUuId IoT Cloud user's UUID * @return (OK) devices have been successfully got - * @throws IotCloudAssociatedUserNotExists (NOT_FOUND) IOT Cloud user hasn't been found by it's UUID + * @throws IotCloudAssociatedUserNotExists (NOT_FOUND) IOT Cloud user hasn't + * been found by it's UUID */ @RequestMapping(value = "/{iotCloudUserUuId}/byCloudUserUuid") public ResponseEntity> findByCloudUserUuid(@PathVariable String iotCloudUserUuId) { - User user = ofNullable(iotCloudService.findAssociatedUserByUuid(iotCloudUserUuId)).orElseThrow(IotCloudAssociatedUserNotExists::new); + User user = ofNullable(iotCloudService.findAssociatedUserByUuid(iotCloudUserUuId)) + .orElseThrow(IotCloudAssociatedUserNotExists::new); return new ResponseEntity<>(deviceConverter.convert(deviceService.findByUser(user)), OK); } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudApi.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudApi.java index 982a43f..a129f5a 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudApi.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudApi.java @@ -5,10 +5,11 @@ */ package com.samsung.dsm.rest.iotcloud; -import com.google.gson.Gson; -import com.samsung.commons.domain.IotCloudUser; -import com.samsung.commons.service.IotCloudService; -import com.samsung.dsm.rest.device.DeviceApi; +import static java.lang.String.format; +import static java.util.Optional.ofNullable; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; + import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; @@ -17,11 +18,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import static java.lang.String.format; -import static java.util.Optional.ofNullable; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; -import static org.springframework.http.HttpStatus.METHOD_FAILURE; -import static org.springframework.http.HttpStatus.OK; +import com.samsung.commons.domain.IotCloudUser; +import com.samsung.commons.service.IotCloudService; /** *

ICloud API

@@ -33,7 +31,8 @@ import static org.springframework.http.HttpStatus.OK; @RestController @RequestMapping(value = "/restapi/iotcloud") public class IotCloudApi { - private final static Logger log = Logger.getLogger(DeviceApi.class); + + private static final Logger LOG = Logger.getLogger(IotCloudApi.class); @Autowired private IotCloudService iotCloudService; @@ -42,34 +41,37 @@ public class IotCloudApi { * Create IoT user * * @param email email - * @param uuid UUID + * @param uuid UUID * @return (OK) created - * @throws IotCloudAssociatedUserNotExists (NOT_FOUND) no associated user found by UUID - * @throws IotCloudUserExists (CONFLICT) IoT user (with such email and uuid) already exists + * @throws IotCloudAssociatedUserNotExists (NOT_FOUND) no associated user + * found by UUID + * @throws IotCloudUserExists (CONFLICT) IoT user (with such email and uuid) + * already exists */ @RequestMapping(value = "/createUser") public ResponseEntity createUser(@RequestParam String email, @RequestParam String uuid) { try { - IotCloudUser user = ofNullable(iotCloudService.createAndSaveUser(email, uuid)).orElseThrow(IotCloudUserExists::new); + IotCloudUser user = ofNullable(iotCloudService.createAndSaveUser(email, uuid)) + .orElseThrow(IotCloudUserExists::new); - log.debug(format("User saved [%s]", user.toString())); + LOG.debug(format("User saved [%s]", user.toString())); return new ResponseEntity<>(OK); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new IotCloudAssociatedUserNotExists(); } } - @RequestMapping(value = "/deleteUser", method=RequestMethod.DELETE) + @RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE) public ResponseEntity deleteUser(@RequestParam String uuid) { try { iotCloudService.delete(uuid); - log.debug(format("Delete user [%s]", uuid)); + LOG.debug(format("Delete user [%s]", uuid)); return new ResponseEntity("true", OK); - } catch(Exception e) { - log.error(e.getMessage(), e); + } catch (Exception e) { + LOG.error(e.getMessage(), e); return new ResponseEntity<>(INTERNAL_SERVER_ERROR); - } + } } public void setIotCloudService(IotCloudService iotCloudService) { diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudAssociatedUserNotExists.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudAssociatedUserNotExists.java index 9105014..f85ad0a 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudAssociatedUserNotExists.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/iotcloud/IotCloudAssociatedUserNotExists.java @@ -6,6 +6,7 @@ import static org.springframework.http.HttpStatus.NOT_FOUND; @ResponseStatus(value = NOT_FOUND, reason = "No associated user found by email") public class IotCloudAssociatedUserNotExists extends RuntimeException { + public IotCloudAssociatedUserNotExists() { super(); } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/mq/MQSenderImpl.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/mq/MQSenderImpl.java index 5e320ae..4284506 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/mq/MQSenderImpl.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/mq/MQSenderImpl.java @@ -17,7 +17,8 @@ import com.samsung.commons.model.MQPolicy; import com.samsung.commons.model.Notification; public class MQSenderImpl implements MQSender { - private static final Logger log = Logger.getLogger(MQSenderImpl.class); + + private static final Logger LOG = Logger.getLogger(MQSenderImpl.class); private static final String REST_FOR_POLICY = "/dsmmq/policy"; private static final String REST_FOR_NOTIFICATION = "/dsmmq/notification"; private final RestTemplate restTemplate; @@ -26,26 +27,26 @@ public class MQSenderImpl implements MQSender { public MQSenderImpl(String host) { this.restTemplate = new RestTemplate(); this.host = host; - log.info("MQ Sender connect to : " + host); + LOG.info("MQ Sender connect to : " + host); } @Override public boolean sendNotification(Notification notification) { try { - log.info("Send notification" + notification); + LOG.info("Send notification" + notification); List acceptableMediaTypes = new ArrayList<>(); acceptableMediaTypes.add(MediaType.TEXT_PLAIN); HttpHeaders headers = new HttpHeaders(); headers.setAccept(acceptableMediaTypes); HttpEntity entity = new HttpEntity<>(notification, headers); URI url = new URI(host + REST_FOR_NOTIFICATION); - log.info("Send to " + url); + LOG.info("Send to " + url); @SuppressWarnings("rawtypes") ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST, entity, ResponseEntity.class); - log.info("Response " + result); + LOG.info("Response " + result); return result.getStatusCode() == HttpStatus.OK; } catch (Exception e) { - log.error(e.getMessage(), e); + LOG.error(e.getMessage(), e); } return false; } @@ -53,20 +54,20 @@ public class MQSenderImpl implements MQSender { @Override public boolean sendPolicy(MQPolicy policy) { try { - log.info("Send policy" + policy); + LOG.info("Send policy" + policy); List acceptableMediaTypes = new ArrayList<>(); acceptableMediaTypes.add(MediaType.TEXT_PLAIN); HttpHeaders headers = new HttpHeaders(); headers.setAccept(acceptableMediaTypes); HttpEntity entity = new HttpEntity<>(policy, headers); URI url = new URI(host + REST_FOR_POLICY); - log.info("Send to " + url); + LOG.info("Send to " + url); @SuppressWarnings("rawtypes") ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST, entity, ResponseEntity.class); - log.info("Response " + result); + LOG.info("Response " + result); return result.getStatusCode() == HttpStatus.OK; } catch (Exception e) { - log.error(e.getMessage(), e); + LOG.error(e.getMessage(), e); } return false; } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/policy/PolicyApi.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/policy/PolicyApi.java index 2916377..ea345f0 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/policy/PolicyApi.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/policy/PolicyApi.java @@ -33,7 +33,7 @@ import com.samsung.dsm.rest.mq.MQSenderImpl; @RequestMapping(value = "/restapi/policy") public class PolicyApi { - private final static Logger log = Logger.getLogger(PolicyApi.class); + private static final Logger LOG = Logger.getLogger(PolicyApi.class); @Autowired private PolicyService policyService; @@ -41,7 +41,7 @@ public class PolicyApi { private AgentService agentService; @Autowired - private DeviceService deviceService; + private DeviceService deviceService; @Autowired private MQSenderImpl mqSender; @@ -50,20 +50,22 @@ public class PolicyApi { * Find agent's policy by it's UUID and by device's UUID * * @param deviceUuId device UUID - * @param agentUuId agent UUID + * @param agentUuId agent UUID * @return (OK) agent's policy - * @throws PolicyNotFoundByDeviceUuidAndAgentUuid (NOT_FOUND) policy hasn't been found by given device UUID and agent UUID + * @throws PolicyNotFoundByDeviceUuidAndAgentUuid (NOT_FOUND) policy hasn't + * been found by given device UUID and agent UUID */ @RequestMapping(value = "/device/{deviceUuId}/agent/{agentUuId}") public String findByUUID(@PathVariable String deviceUuId, @PathVariable String agentUuId) { - Policy policy = ofNullable(policyService.findByDeviceUuidAndByAgentUuid(deviceUuId, agentUuId)).orElseThrow(PolicyNotFoundByDeviceUuidAndAgentUuid::new); + Policy policy = ofNullable(policyService.findByDeviceUuidAndByAgentUuid(deviceUuId, agentUuId)) + .orElseThrow(PolicyNotFoundByDeviceUuidAndAgentUuid::new); return policy.getPolicy(); } @RequestMapping(value = "/request/{policyId}/device/{deviceId}") public void requestPolicy(@PathVariable Long policyId, @PathVariable String deviceId) { - log.info("Request policy - " + policyId); - //TODO add check for policy + LOG.info("Request policy - " + policyId); + // TODO add check for policy Policy policy = policyService.findById(policyId); Device device = deviceService.findByUUID(deviceId); mqSender.sendPolicy(new MQPolicy(null, deviceId, policy.getPolicy(), device.getParentUuid())); @@ -71,8 +73,9 @@ public class PolicyApi { @RequestMapping(value = "/request/{policyId}/agent/{agentId}") public void requestAgentPolicy(@PathVariable Long policyId, @PathVariable String agentId) { - log.info("Request policy - " + policyId); + LOG.info("Request policy - " + policyId); Agent agent = agentService.findByUUID(agentId); - mqSender.sendPolicy(new MQPolicy(agent.getUuid(), agent.getDevice().getUuid(), agent.getPolicy().getPolicy(), agent.getDevice().getParentUuid())); + mqSender.sendPolicy(new MQPolicy(agent.getUuid(), agent.getDevice().getUuid(), agent.getPolicy() + .getPolicy(), agent.getDevice().getParentUuid())); } } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/rest/report/ReportApi.java b/servers/dsm/src/main/java/com/samsung/dsm/rest/report/ReportApi.java index 66ffdcc..1480715 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/rest/report/ReportApi.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/rest/report/ReportApi.java @@ -20,7 +20,6 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; -import com.google.gson.JsonObject; import com.samsung.commons.domain.Device; import com.samsung.commons.domain.IotCloudUser; import com.samsung.commons.domain.Report; @@ -46,7 +45,8 @@ import com.samsung.dsm.service.GrantedApplicationService; @RestController @RequestMapping(value = "/restapi/report") public class ReportApi { - private static final Logger log = Logger.getLogger(ReportApi.class); + + private static final Logger LOG = Logger.getLogger(ReportApi.class); public static final String FOR_STUB = "smack_test"; @@ -93,13 +93,13 @@ public class ReportApi { dataMap.put("date", report.getDate()); reportsData.add(dataMap); } catch (Exception e) { - log.error("Wrong report format: " + report.getReport()); + LOG.error("Wrong report format: " + report.getReport()); } } mapReports.put(type.type, reportsData); } } - log.debug(format("Reports - %s by device UUID %s", mapReports, deviceUuId)); + LOG.debug(format("Reports - %s by device UUID %s", mapReports, deviceUuId)); return new Gson().toJson(mapReports); } @@ -110,11 +110,11 @@ public class ReportApi { */ @RequestMapping(value = "/newreport/{reportId}") public void newReportNotification(@PathVariable Long reportId) { - log.info("Get new report" + reportId); + LOG.info("Get new report" + reportId); Report report = reportService.findById(reportId); - log.info("============================REPORT====================================="); - log.info(report); - log.info("======================================================================="); + LOG.info("============================REPORT====================================="); + LOG.info(report); + LOG.info("======================================================================="); Device device = report.getDevice(); IotCloudUser iotCloudUser = iotCloudService.findByUser(device.getUser()); Notification notification = new Notification(); @@ -126,7 +126,7 @@ public class ReportApi { map.put(ReportAnalyzerKeys.DEVICE_PARENT_UUID, device.getParentUuid()); analyzer.createNotification(map, grantedApplicationService); notification = analyzer.createNotification(map, grantedApplicationService); - log.info("======================================================================="); + LOG.info("======================================================================="); if (notification.getCode().equals("2")) { mqSender.sendNotification(notification); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/PasswordEncoder.java b/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/PasswordEncoder.java index 7e7d113..00d55b6 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/PasswordEncoder.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/PasswordEncoder.java @@ -6,7 +6,7 @@ package com.samsung.dsm.security.authentication; /** - *

Password encoder interface

+ *

Password encoder interface

* Interface for password encoder. * * @author Artem Motchanyi @@ -14,6 +14,7 @@ package com.samsung.dsm.security.authentication; * @since 2016-09-01 */ public interface PasswordEncoder { + /** * Encode the plain string. * @param plain plain text to encoding. diff --git a/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/impl/BCPasswordEncoder.java b/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/impl/BCPasswordEncoder.java index daa4968..6a8f15e 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/impl/BCPasswordEncoder.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/security/authentication/impl/BCPasswordEncoder.java @@ -11,7 +11,7 @@ import org.springframework.stereotype.Service; import com.samsung.dsm.security.authentication.PasswordEncoder; /** - *

Password encoder

+ *

Password encoder

* Password encoder that uses BCryptPasswordEncoder as a core. * * @author Artem Motchanyi @@ -19,10 +19,10 @@ import com.samsung.dsm.security.authentication.PasswordEncoder; * @since 2016-09-01 */ @Service("passwordEncoder") -public class BCPasswordEncoder implements PasswordEncoder{ +public class BCPasswordEncoder implements PasswordEncoder { private BCryptPasswordEncoder encoder; - private static final int STRENGTH = 12; //2^12 rounds + private static final int STRENGTH = 12; // 2^12 rounds public BCPasswordEncoder() { encoder = new BCryptPasswordEncoder(STRENGTH); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/GrantedApplicationService.java b/servers/dsm/src/main/java/com/samsung/dsm/service/GrantedApplicationService.java index 4559373..1119bd0 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/GrantedApplicationService.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/GrantedApplicationService.java @@ -5,7 +5,6 @@ import com.samsung.commons.service.CommonService; import java.util.List; - public interface GrantedApplicationService extends CommonService { List findByParentCommandAndCommand(String parentCommand, String command); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/LoginAuthCodeService.java b/servers/dsm/src/main/java/com/samsung/dsm/service/LoginAuthCodeService.java index ddd5690..4b83f0f 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/LoginAuthCodeService.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/LoginAuthCodeService.java @@ -5,8 +5,8 @@ public interface LoginAuthCodeService { /** * Login and then return auth code * - * @param login login - * @param password password + * @param login - login + * @param password - password * @return auth code */ String loginAndGenerate(String login, String password); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/OAuth2AuthorizationService.java b/servers/dsm/src/main/java/com/samsung/dsm/service/OAuth2AuthorizationService.java index 58dda36..c568904 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/OAuth2AuthorizationService.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/OAuth2AuthorizationService.java @@ -12,9 +12,9 @@ public interface OAuth2AuthorizationService { /** * OAuth2 authorization code generator * - * @param clientId client ID - * @param clientSecret client secret - * @param authentication authentication + * @param clientId - client ID + * @param clientSecret - client secret + * @param authentication - authentication * @return authorization code */ String generateAuthCode(String clientId, String clientSecret, Authentication authentication); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/AccessTokenServiceImpl.java b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/AccessTokenServiceImpl.java index 005a671..08411d0 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/AccessTokenServiceImpl.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/AccessTokenServiceImpl.java @@ -13,7 +13,7 @@ import org.springframework.stereotype.Service; @Service("accessTokenService") public class AccessTokenServiceImpl implements AccessTokenService { - private static final Logger log = Logger.getLogger(AccessTokenServiceImpl.class); + private static final Logger LOG = Logger.getLogger(AccessTokenServiceImpl.class); @Autowired private OAuthAccessTokenRepository accessTokenRepository; @@ -48,11 +48,11 @@ public class AccessTokenServiceImpl implements AccessTokenService { @Override public Authentication readAuthenticationByAccessToken(String accessToken) { - log.debug("Reading authentication by access token " + accessToken); + LOG.debug("Reading authentication by access token " + accessToken); OAuth2Authentication authentication = getTokenStore().readAuthentication(accessToken); - log.debug("Read authentication " + (authentication != null ? "[auth]" : "null")); + LOG.debug("Read authentication " + (authentication != null ? "[auth]" : "null")); return authentication != null ? authentication.getUserAuthentication() : null; } diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/GrantedApplicationServiceImpl.java b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/GrantedApplicationServiceImpl.java index 4c470cb..d1ec850 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/GrantedApplicationServiceImpl.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/GrantedApplicationServiceImpl.java @@ -15,7 +15,7 @@ public class GrantedApplicationServiceImpl implements GrantedApplicationService @Autowired GrantedApplicationRepository repository; - + @Override public GrantedApplication save(GrantedApplication grantedApplication) { return repository.save(grantedApplication); diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceImpl.java b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceImpl.java index 32e2977..1003c8c 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceImpl.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceImpl.java @@ -25,12 +25,14 @@ import static java.lang.String.format; * Simple implementation of OAuth2AuthorizationService * * @see OAuth2AuthorizationService - * Created by o.abakumov on 7/7/2017. + * Created by o.abakumov on 7/7/2017. */ @Service public class OAuth2AuthorizationServiceImpl implements OAuth2AuthorizationService { - private static final Logger log = Logger.getLogger(OAuth2AuthorizationServiceImpl.class); - private static final String REDIRECT_URL = "http://localhost:8080/dsm/oauth/callback";//Don't change + + private static final Logger LOG = Logger.getLogger(OAuth2AuthorizationServiceImpl.class); + private static final String REDIRECT_URL = "http://localhost:8080/dsm/oauth/callback";// Don't + // change @Autowired @Qualifier(value = "clientAuthenticationManager") @@ -46,7 +48,6 @@ public class OAuth2AuthorizationServiceImpl implements OAuth2AuthorizationServic private AuthorizationCodeServices authorizationCodeServices; - @SuppressWarnings(value = "unused") public OAuth2AuthorizationServiceImpl() { } @@ -55,7 +56,9 @@ public class OAuth2AuthorizationServiceImpl implements OAuth2AuthorizationServic authorizationCodeServices = new JdbcAuthorizationCodeServices(dataSource); } - OAuth2AuthorizationServiceImpl(AuthenticationManager authenticationManager, ClientDetailsService clientDetailsService, OAuth2RequestFactory oAuth2RequestFactory, AuthorizationCodeServices authorizationCodeServices) { + OAuth2AuthorizationServiceImpl(AuthenticationManager authenticationManager, + ClientDetailsService clientDetailsService, OAuth2RequestFactory oAuth2RequestFactory, + AuthorizationCodeServices authorizationCodeServices) { this.authenticationManager = authenticationManager; this.clientDetailsService = clientDetailsService; this.oAuth2RequestFactory = oAuth2RequestFactory; @@ -65,20 +68,18 @@ public class OAuth2AuthorizationServiceImpl implements OAuth2AuthorizationServic @Override public String generateAuthCode(String clientId, String clientSecret, Authentication authentication) { if (authentication == null) { - authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(clientId, clientSecret)); + authentication = authenticationManager + .authenticate(new UsernamePasswordAuthenticationToken(clientId, clientSecret)); } - AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(of( - "client_id", clientId, - "client_secret", clientSecret, - "response_type", "code", - "grant_type", "password", - "redirect_uri", REDIRECT_URL)); + AuthorizationRequest authorizationRequest = getOAuth2RequestFactory() + .createAuthorizationRequest(of("client_id", clientId, "client_secret", clientSecret, "response_type", "code", "grant_type", "password", "redirect_uri", REDIRECT_URL)); return generateCode(authorizationRequest, authentication); } - private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) throws AuthenticationException { + private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) + throws AuthenticationException { try { OAuth2Request oAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); OAuth2Authentication combinedAuth = new OAuth2Authentication(oAuth2Request, authentication); @@ -86,7 +87,7 @@ public class OAuth2AuthorizationServiceImpl implements OAuth2AuthorizationServic return authorizationCodeServices.createAuthorizationCode(combinedAuth); } catch (OAuth2Exception e) { if (authorizationRequest.getState() != null) { - log.warn(format("State %s", authorizationRequest.getState())); + LOG.warn(format("State %s", authorizationRequest.getState())); } return null; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceClientCredentials.java b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceClientCredentials.java index 5ce1ea7..4358af6 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceClientCredentials.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceClientCredentials.java @@ -1,6 +1,7 @@ package com.samsung.dsm.service.impl.auth; public class LoginAuthCodeServiceClientCredentials { + private String clientName; private String clientSecret; diff --git a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceImpl.java b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceImpl.java index 5b84024..115de26 100644 --- a/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceImpl.java +++ b/servers/dsm/src/main/java/com/samsung/dsm/service/impl/auth/LoginAuthCodeServiceImpl.java @@ -14,7 +14,8 @@ import com.samsung.dsm.service.OAuth2AuthorizationService; @Service("loginAuthCodeService") public class LoginAuthCodeServiceImpl implements LoginAuthCodeService { - private final static Logger log = Logger.getLogger(LoginAuthCodeServiceImpl.class); + + private final static Logger LOG = Logger.getLogger(LoginAuthCodeServiceImpl.class); @Autowired private LoginAuthCodeServiceClientCredentials clientDetails; @@ -31,13 +32,13 @@ public class LoginAuthCodeServiceImpl implements LoginAuthCodeService { try { UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(login, password); Authentication authentication = authenticationManager.authenticate(authRequest); - log.trace("Successfully authenticated"); + LOG.trace("Successfully authenticated"); String name = clientDetails.getClientName(); String secret = clientDetails.getClientSecret(); String code = authCodeService.generateAuthCode(name, secret, authentication); - log.debug("Auth code generated " + code); + LOG.debug("Auth code generated " + code); return code; } catch (BadCredentialsException e) { return null; diff --git a/servers/dsm/src/test/java/com/samsung/dsm/EqualsHashCodeTest.java b/servers/dsm/src/test/java/com/samsung/dsm/EqualsHashCodeTest.java index 853e396..9c4a444 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/EqualsHashCodeTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/EqualsHashCodeTest.java @@ -1,4 +1,5 @@ package com.samsung.dsm; + import com.samsung.commons.domain.Agent; import com.samsung.commons.domain.Device; import com.samsung.commons.domain.Policy; @@ -39,25 +40,21 @@ public class EqualsHashCodeTest { @Parameterized.Parameters public static Collection data() { PolicyConfig.PolicyGroup.Policy[] policies = { - new PolicyConfig.PolicyGroup.Policy("name", 1, new String[]{"as"}) - }; + new PolicyConfig.PolicyGroup.Policy("name", 1, new String[] { "as" }) }; - Device device = new Device("uuid", "name", "type", "model", 1, new Policy(), - new User(), "parentUuid"); + Device device = new Device("uuid", "name", "type", "model", 1, new Policy(), new User(), "parentUuid"); device.setId(1L); ViewPolicyGroup viewPolicyGroup1 = new ViewPolicyGroup(new PolicyConfig.PolicyGroup("name", policies)); ViewPolicyGroup viewPolicyGroup2 = new ViewPolicyGroup(new PolicyConfig.PolicyGroup("name", policies)); - RestDevice restDevice1 = - new RestDevice("uuid", "name", "type", "model", 1, "parentId"); - RestDevice restDevice2 = - new RestDevice("uuid", "name", "type", "model", 1, "parentId"); + RestDevice restDevice1 = new RestDevice("uuid", "name", "type", "model", 1, "parentId"); + RestDevice restDevice2 = new RestDevice("uuid", "name", "type", "model", 1, "parentId"); - String[] items1 = {"item1", "item2"}; + String[] items1 = { "item1", "item2" }; PolicyConfig.PolicyGroup.Policy policy1 = new PolicyConfig.PolicyGroup.Policy("name", 1, items1); - String[] items2 = {"item1", "item2"}; + String[] items2 = { "item1", "item2" }; PolicyConfig.PolicyGroup.Policy policy2 = new PolicyConfig.PolicyGroup.Policy("name", 1, items2); ViewDevice viewDevice = new ViewDevice(device); @@ -73,7 +70,7 @@ public class EqualsHashCodeTest { ViewReport viewReport1 = new ViewReport(ReportType.Type.DAC, reports); reports = new ArrayList(); reports.add(report2); - ViewReport viewReport2 = new ViewReport(ReportType.Type.DAC,reports); + ViewReport viewReport2 = new ViewReport(ReportType.Type.DAC, reports); Agent agent = new Agent(); agent.setId(1L); @@ -84,27 +81,10 @@ public class EqualsHashCodeTest { ViewAgent viewAgent1 = new ViewAgent(agent, JSON); ViewAgent viewAgent2 = new ViewAgent(agent, JSON); - String policyText = "[" + - "{" + - "\"group\":\"no-display\"," + - "\"policies\":[]" + - "}," + - "{" + - "\"group\":\"tv-extension\"," + - "\"policies\":[" + - "{" + - "\"name\":\"usb\"," + - "\"state\":1," + - "\"items\":[]" + - "}," + - "{" + - "\"name\":\"policy2\"," + - "\"state\":0," + - "\"items\":[]" + - "}" + - "]" + - "}" + - "]"; + String policyText = "[" + "{" + "\"group\":\"no-display\"," + "\"policies\":[]" + "}," + "{" + + "\"group\":\"tv-extension\"," + "\"policies\":[" + "{" + "\"name\":\"usb\"," + "\"state\":1," + + "\"items\":[]" + "}," + "{" + "\"name\":\"policy2\"," + "\"state\":0," + "\"items\":[]" + "}" + "]" + + "}" + "]"; List agents = new ArrayList<>(); List types = new ArrayList<>(); types.add(ReportType.Type.SMACK); @@ -118,66 +98,44 @@ public class EqualsHashCodeTest { PolicyConfig.PolicyGroup policyGroup1 = new PolicyConfig.PolicyGroup("", policies); PolicyConfig.PolicyGroup policyGroup2 = new PolicyConfig.PolicyGroup("", policies); - Object[][] data = new Object[][]{ - {deviceStatusView, deviceStatusView, true}, - {new BaseView.DeviceStatusView(), new BaseView.DeviceStatusView(), true}, - {new BaseView.DeviceStatusView(), null, false}, - {new BaseView.DeviceStatusView(), "", false}, - - {overviewAgent, overviewAgent, true}, - {new DeviceOverview.OverviewAgent("name"), new DeviceOverview.OverviewAgent("name"), true}, - {new DeviceOverview.OverviewAgent("name"), null, false}, - {new DeviceOverview.OverviewAgent("name"), "", false}, - - {viewPolicyGroup1, viewPolicyGroup1, true}, - {viewPolicyGroup1, viewPolicyGroup2, true}, - {viewPolicyGroup1, null, false}, - {viewPolicyGroup1, "", false}, - - {viewReport1, viewReport1, true}, - {viewReport1, viewReport2, true}, - {viewReport1, null, false}, - {viewReport1, "", false}, - - {viewDevice, viewDevice, true}, - {new ViewDevice(device), new ViewDevice(device), true}, - {new ViewDevice(device), null, false}, - {new ViewDevice(device), "", false}, - - {new RestAgent("uuid", "name"), new RestAgent("uuid", "name"), true}, - {new RestAgent("uuid", "name"), null, false}, - {new RestAgent("uuid", "name"), "", false}, - - {restDevice1, restDevice1, true}, - {restDevice1, restDevice2, true}, - {restDevice1, null, false}, - {restDevice1, "", false}, - - {policy1, policy1, true}, - {policy1, policy2, true}, - {policy1, null, false}, - {policy1, "", false}, - - {viewAgent1, viewAgent1, true}, - {viewAgent1, viewAgent2, true}, - {viewAgent1, null, false}, - {viewAgent1, "", false}, - - {deviceOverview1, deviceOverview1, true}, - {deviceOverview1, deviceOverview2, true}, - {deviceOverview1, null, false}, - {deviceOverview1, "", false}, - - {overviewPolicy1, overviewPolicy1, true}, - {overviewPolicy1, overviewPolicy2, true}, - {overviewPolicy1, null, false}, - {overviewPolicy1, "", false}, - - {policyGroup1, policyGroup1, true}, - {policyGroup1, policyGroup2, true}, - {policyGroup1, null, false}, - {policyGroup1, "", false}, - }; + Object[][] data = new Object[][] { { deviceStatusView, deviceStatusView, true }, + { new BaseView.DeviceStatusView(), new BaseView.DeviceStatusView(), true }, + { new BaseView.DeviceStatusView(), null, false }, { new BaseView.DeviceStatusView(), "", false }, + + { overviewAgent, overviewAgent, true }, + { new DeviceOverview.OverviewAgent("name"), new DeviceOverview.OverviewAgent("name"), true }, + { new DeviceOverview.OverviewAgent("name"), null, false }, + { new DeviceOverview.OverviewAgent("name"), "", false }, + + { viewPolicyGroup1, viewPolicyGroup1, true }, { viewPolicyGroup1, viewPolicyGroup2, true }, + { viewPolicyGroup1, null, false }, { viewPolicyGroup1, "", false }, + + { viewReport1, viewReport1, true }, { viewReport1, viewReport2, true }, { viewReport1, null, false }, + { viewReport1, "", false }, + + { viewDevice, viewDevice, true }, { new ViewDevice(device), new ViewDevice(device), true }, + { new ViewDevice(device), null, false }, { new ViewDevice(device), "", false }, + + { new RestAgent("uuid", "name"), new RestAgent("uuid", "name"), true }, + { new RestAgent("uuid", "name"), null, false }, { new RestAgent("uuid", "name"), "", false }, + + { restDevice1, restDevice1, true }, { restDevice1, restDevice2, true }, { restDevice1, null, false }, + { restDevice1, "", false }, + + { policy1, policy1, true }, { policy1, policy2, true }, { policy1, null, false }, + { policy1, "", false }, + + { viewAgent1, viewAgent1, true }, { viewAgent1, viewAgent2, true }, { viewAgent1, null, false }, + { viewAgent1, "", false }, + + { deviceOverview1, deviceOverview1, true }, { deviceOverview1, deviceOverview2, true }, + { deviceOverview1, null, false }, { deviceOverview1, "", false }, + + { overviewPolicy1, overviewPolicy1, true }, { overviewPolicy1, overviewPolicy2, true }, + { overviewPolicy1, null, false }, { overviewPolicy1, "", false }, + + { policyGroup1, policyGroup1, true }, { policyGroup1, policyGroup2, true }, + { policyGroup1, null, false }, { policyGroup1, "", false }, }; return Arrays.asList(data); } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/IncreaseCoverageTest.java b/servers/dsm/src/test/java/com/samsung/dsm/IncreaseCoverageTest.java index 6bdf1e3..89946b6 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/IncreaseCoverageTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/IncreaseCoverageTest.java @@ -1,10 +1,11 @@ package com.samsung.dsm; + import static com.samsung.dsm.policy.parser.PolicyParserFactory.Type.JSON; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; @@ -121,27 +122,10 @@ public class IncreaseCoverageTest { Policy policy = new Policy(); agents.add(new Agent("uuid", "name", policy)); - String policyText = "[" + - "{" + - "\"group\":\"no-display\"," + - "\"policies\":[]" + - "}," + - "{" + - "\"group\":\"tv-extension\"," + - "\"policies\":[" + - "{" + - "\"name\":\"usb\"," + - "\"state\":1," + - "\"items\":[]" + - "}," + - "{" + - "\"name\":\"policy2\"," + - "\"state\":0," + - "\"items\":[]" + - "}" + - "]" + - "}" + - "]"; + String policyText = "[" + "{" + "\"group\":\"no-display\"," + "\"policies\":[]" + "}," + "{" + + "\"group\":\"tv-extension\"," + "\"policies\":[" + "{" + "\"name\":\"usb\"," + "\"state\":1," + + "\"items\":[]" + "}," + "{" + "\"name\":\"policy2\"," + "\"state\":0," + "\"items\":[]" + "}" + "]" + + "}" + "]"; List types = new ArrayList<>(); types.add(ReportType.Type.SMACK); @@ -189,7 +173,7 @@ public class IncreaseCoverageTest { list.add(device); assertTrue(device.getParentUuid().isEmpty()); viewDashboard.setDeviceType(devices); - + ViewDashboard.DeviceStatus deviceStatus = new ViewDashboard().new DeviceStatus(Device.Status.CONNECTED, 0); deviceStatus.getStatus(); deviceStatus.getStatusText(); @@ -214,16 +198,15 @@ public class IncreaseCoverageTest { assertNull(viewDevice.getOverview()); assertNotNull(viewDevice.getParentUuid()); } - @Test(expected = NullPointerException.class) - public void testPolicyParserFactorySwitch(){ + public void testPolicyParserFactorySwitch() { PolicyParserFactory factory = new PolicyParserFactory(); assertNull(factory.getParser(null)); } - + @Test - public void testViewPolicyGroupSetState(){ + public void testViewPolicyGroupSetState() { ViewPolicyGroup.ViewPolicy viewPolicy = new ViewPolicyGroup.ViewPolicy(new PolicyGroup.Policy("name", -1, new String[1])); assertFalse(viewPolicy.getIsToggle()); } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/ToStringTest.java b/servers/dsm/src/test/java/com/samsung/dsm/ToStringTest.java index 7f5b1a6..7052b8e 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/ToStringTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/ToStringTest.java @@ -1,4 +1,5 @@ package com.samsung.dsm; + import static com.samsung.dsm.policy.parser.PolicyParserFactory.Type.JSON; import static java.util.Collections.emptyList; import static org.hamcrest.core.Is.is; @@ -59,8 +60,7 @@ public class ToStringTest { device.setId(1L); PolicyConfig.PolicyGroup.Policy[] policies = { - new PolicyConfig.PolicyGroup.Policy("name", 1, new String[]{"name"}) - }; + new PolicyConfig.PolicyGroup.Policy("name", 1, new String[] { "name" }) }; ReportType type = new ReportType(); type.setType(ReportType.Type.DAC.toString()); @@ -74,37 +74,39 @@ public class ToStringTest { agent.setName("name"); agent.setPolicy(new Policy("[]")); - Object[][] data = new Object[][]{ - {new OAuthCode(), "OAuthCode [code=null, authentication=null]"}, - {new OAuthRefreshToken(), "OAuthRefreshToken [tokenId=null, token=null, authentication=null]"}, - {new OAuthClientToken(), "OAuthClientToken [tokenId=null, token=null, authenticationId=null, " + - "userName=null, clientId=null]"}, - {new OAuthClientDetails(), "OAuthClientDetails [clientId=null, resourceIds=null, secret=null, " + - "scope=null, authorizedGrantTypes=null, webServerRedirectUri=null, authorities=null, " + - "accessTokenValidity=null, refreshTokenValidity=null, additionalInformation=null, " + - "autoapprove=null]"}, - {new OAuthAccessToken(), "OAuthAccessToken [tokenId=null, token=null, authenticationId=null, " + - "userName=null, clientId=null, authentication=null, refreshToken=null]"}, - {deviceStatusView, "DeviceStatusView{status=status, statusText=status text}"}, - {new DeviceOverview(policy, JSON, emptyList(), emptyList()), - "DeviceOverview{policies=[OverviewPolicy{groupName=null}], reports=[], agents=[]}"}, - {new DeviceOverview.OverviewAgent("agent"), "OverviewAgent{name=agent}"}, - {new ViewDevice(device), "ViewDevice{id=1, uuid=uuid, name=name, type=, model=model, status=on, " + - "statusText=Connected, policies=null, agents=null, reports=[], overview=null}"}, - {new ViewPolicyGroup(new PolicyConfig.PolicyGroup("name", policies)), - "ViewPolicyGroup{name=name, displayName=name, policyList=[ViewPolicy{name=name, " + - "displayName=name, isToggle=true, state=1}], isDisplay=true}"}, - {new RestAgent("uuid", "name"), "RestAgent{uuid='uuid', name='name'}"}, - {new RestDevice("uuid", "name", "type", "model", 1, "parentUuid"), - "RestDevice [uuid=uuid, name=name, type=type, model=model, status=1, parentUuid=parentUuid]"}, - {new PolicyConfig.PolicyGroup.Policy("name", 1, new String[]{"item"}), - "Policy{name=name, state=1, items=skipped...}"}, - {new ReportConfig.Report("did", "date", "name", 1, "data"), - "Report [did=did, date=date, name=name, result=1, data=data]"}, - {viewReport, "ViewReport{reports=[], type=dac, name=DAC}"}, - {new ViewAgent(agent, JSON), "ViewAgent{id=1, uuid=uuid, name=name, policies=[]}"}, - {new PolicyConfig.PolicyGroup("", policies), "PolicyGroup{group=, policies=[skipped]}"} - }; + Object[][] data = new Object[][] { { new OAuthCode(), "OAuthCode [code=null, authentication=null]" }, + { new OAuthRefreshToken(), "OAuthRefreshToken [tokenId=null, token=null, authentication=null]" }, + { new OAuthClientToken(), + "OAuthClientToken [tokenId=null, token=null, authenticationId=null, " + + "userName=null, clientId=null]" }, + { new OAuthClientDetails(), + "OAuthClientDetails [clientId=null, resourceIds=null, secret=null, " + + "scope=null, authorizedGrantTypes=null, webServerRedirectUri=null, authorities=null, " + + "accessTokenValidity=null, refreshTokenValidity=null, additionalInformation=null, " + + "autoapprove=null]" }, + { new OAuthAccessToken(), + "OAuthAccessToken [tokenId=null, token=null, authenticationId=null, " + + "userName=null, clientId=null, authentication=null, refreshToken=null]" }, + { deviceStatusView, "DeviceStatusView{status=status, statusText=status text}" }, + { new DeviceOverview(policy, JSON, emptyList(), emptyList()), + "DeviceOverview{policies=[OverviewPolicy{groupName=null}], reports=[], agents=[]}" }, + { new DeviceOverview.OverviewAgent("agent"), "OverviewAgent{name=agent}" }, + { new ViewDevice(device), + "ViewDevice{id=1, uuid=uuid, name=name, type=, model=model, status=on, " + + "statusText=Connected, policies=null, agents=null, reports=[], overview=null}" }, + { new ViewPolicyGroup(new PolicyConfig.PolicyGroup("name", policies)), + "ViewPolicyGroup{name=name, displayName=name, policyList=[ViewPolicy{name=name, " + + "displayName=name, isToggle=true, state=1}], isDisplay=true}" }, + { new RestAgent("uuid", "name"), "RestAgent{uuid='uuid', name='name'}" }, + { new RestDevice("uuid", "name", "type", "model", 1, "parentUuid"), + "RestDevice [uuid=uuid, name=name, type=type, model=model, status=1, parentUuid=parentUuid]" }, + { new PolicyConfig.PolicyGroup.Policy("name", 1, new String[] { "item" }), + "Policy{name=name, state=1, items=skipped...}" }, + { new ReportConfig.Report("did", "date", "name", 1, "data"), + "Report [did=did, date=date, name=name, result=1, data=data]" }, + { viewReport, "ViewReport{reports=[], type=dac, name=DAC}" }, + { new ViewAgent(agent, JSON), "ViewAgent{id=1, uuid=uuid, name=name, policies=[]}" }, + { new PolicyConfig.PolicyGroup("", policies), "PolicyGroup{group=, policies=[skipped]}" } }; return Arrays.asList(data); } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/controller/AccountControllerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/controller/AccountControllerTest.java index a59f262..035461f 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/controller/AccountControllerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/controller/AccountControllerTest.java @@ -33,9 +33,10 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration public class AccountControllerTest { + private MockMvc mockMvc; @Autowired @@ -51,7 +52,6 @@ public class AccountControllerTest { private final String adminEmail = "admin@samsung.com"; - @Before public void setRole() { UserDetails useDetails = Mockito.mock(UserDetails.class); @@ -62,7 +62,7 @@ public class AccountControllerTest { Mockito.when(useDetails.getUsername()).thenReturn(adminEmail); SecurityContextHolder.setContext(securityContext); } - + @Before public void setUp() { userRole = roleService.getByName(Role.Type.USER.toString()); @@ -72,44 +72,34 @@ public class AccountControllerTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void loginTest() throws Exception { - mockMvc.perform(get("/login/")) - .andExpect(status().isOk()) - .andExpect(view().name("login")) - .andExpect(forwardedUrl("login")); + mockMvc.perform(get("/login/")).andExpect(status().isOk()).andExpect(view().name("login")) + .andExpect(forwardedUrl("login")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void registerTest() throws Exception { - mockMvc.perform(get("/register/")) - .andExpect(status().isOk()) - .andExpect(view().name("register")) - .andExpect(forwardedUrl("register")); + mockMvc.perform(get("/register/")).andExpect(status().isOk()).andExpect(view().name("register")) + .andExpect(forwardedUrl("register")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void passwordRecovery() throws Exception { - mockMvc.perform(get("/passrecovery")) - .andExpect(status().isOk()) - .andExpect(view().name("passRecovery")) - .andExpect(forwardedUrl("passRecovery")); + mockMvc.perform(get("/passrecovery")).andExpect(status().isOk()).andExpect(view().name("passRecovery")) + .andExpect(forwardedUrl("passRecovery")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void registerUserTest() throws Exception { String email = "test@mail"; - String response = mockMvc.perform(post("/register") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .param("name", "testName") - .param("email", email) - .param("roleId", userRole.getId().toString()) - .param("password", "123456") - .param("repeatPassword", "123456")) - .andExpect(status().isOk()) - .andExpect(forwardedUrl(null)) - .andReturn().getResponse().getContentAsString(); + String response = mockMvc + .perform(post("/register").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("name", "testName") + .param("email", email).param("roleId", userRole.getId().toString()).param("password", "123456") + .param("repeatPassword", "123456")) + .andExpect(status().isOk()).andExpect(forwardedUrl(null)).andReturn().getResponse() + .getContentAsString(); assertEquals("", response); User user = userService.getUserByEmail(email); @@ -120,8 +110,7 @@ public class AccountControllerTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void registerUserNegativeTest() throws Exception { - String response = mockMvc.perform(post("/register")) - .andReturn().getResponse().getContentAsString(); + String response = mockMvc.perform(post("/register")).andReturn().getResponse().getContentAsString(); assertNotEquals("", response); @@ -129,16 +118,12 @@ public class AccountControllerTest { User user = new User("user", email, false, new Date(), userRole); user = userService.save(user); - response = mockMvc.perform(post("/register") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .param("name", "testName") - .param("email", email) - .param("roleId", userRole.getId().toString()) - .param("password", "123456") - .param("repeatPassword", "123456")) - .andExpect(status().isOk()) - .andExpect(forwardedUrl(null)) - .andReturn().getResponse().getContentAsString(); + response = mockMvc + .perform(post("/register").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("name", "testName") + .param("email", email).param("roleId", userRole.getId().toString()).param("password", "123456") + .param("repeatPassword", "123456")) + .andExpect(status().isOk()).andExpect(forwardedUrl(null)).andReturn().getResponse() + .getContentAsString(); assertNotEquals("", response); diff --git a/servers/dsm/src/test/java/com/samsung/dsm/controller/AdminControllerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/controller/AdminControllerTest.java index c8be4d3..97b6aa2 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/controller/AdminControllerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/controller/AdminControllerTest.java @@ -306,9 +306,9 @@ public class AdminControllerTest { public void switchLockStatusTest() throws Exception { User user = new User(USER_NAME, USER_MAIL, false, new Date(), userRole); user = userService.save(user); - Boolean response = Boolean.parseBoolean( - mockMvc.perform(get("/admin/users/switch_status/{id}", user.getId())).andExpect(status().isOk()) - .andExpect(forwardedUrl(null)).andReturn().getResponse().getContentAsString()); + Boolean response = Boolean.parseBoolean(mockMvc.perform(get("/admin/users/switch_status/{id}", user.getId())) + .andExpect(status().isOk()).andExpect(forwardedUrl(null)).andReturn().getResponse() + .getContentAsString()); assertEquals(!user.getLocked(), response); userService.remove(user); diff --git a/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardControllerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardControllerTest.java index 41b2d75..17c89ab 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardControllerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardControllerTest.java @@ -26,7 +26,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) public class DashboardControllerTest { @@ -52,10 +52,8 @@ public class DashboardControllerTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void indexTest() throws Exception { - mockMvc.perform(get("/dashboard/").principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(view().name("dashboard")) - .andExpect(model().attribute("dashboard", is(notNullValue()))) + mockMvc.perform(get("/dashboard/").principal(principalMock)).andExpect(status().isOk()) + .andExpect(view().name("dashboard")).andExpect(model().attribute("dashboard", is(notNullValue()))) .andExpect(forwardedUrl("dashboard")); } @@ -65,10 +63,8 @@ public class DashboardControllerTest { public void indexRoleAdminTest() throws Exception { servletContext.declareRoles(Role.Type.ADMIN.type); - mockMvc.perform(get("/dashboard/").principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(view().name("dashboard")) - .andExpect(model().attribute("dashboard", is(notNullValue()))) + mockMvc.perform(get("/dashboard/").principal(principalMock)).andExpect(status().isOk()) + .andExpect(view().name("dashboard")).andExpect(model().attribute("dashboard", is(notNullValue()))) .andExpect(forwardedUrl("dashboard")); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardDevicesControllerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardDevicesControllerTest.java index f3fffe2..d8b91f5 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardDevicesControllerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/controller/DashboardDevicesControllerTest.java @@ -40,7 +40,8 @@ import com.samsung.dsm.model.view.DeviceOverview; import com.samsung.dsm.model.view.ViewDevice; /** - * @author Mail to: Artem Motchanyi, a.motchanyi@samsung.com + * @author Mail to: Artem Motchanyi, + * a.motchanyi@samsung.com * @version 1.0 * @file DashboardPolicyControllerTest.java * @brief Tests for DashboardPolicyController. @@ -50,19 +51,20 @@ import com.samsung.dsm.model.view.ViewDevice; * @par Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved. */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration @Transactional public class DashboardDevicesControllerTest { + private static final String DASHBOARD_DEVICES = "/dashboard/devices"; - private static final String DEVICE = "device"; + private static final String DEVICE = "device"; - private static final String DEVICES = "devices"; + private static final String DEVICES = "devices"; - private static final String ADMIN_EMAIL = "admin@samsung.com"; + private static final String ADMIN_EMAIL = "admin@samsung.com"; - private MockMvc mockMvc; + private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @@ -94,10 +96,8 @@ public class DashboardDevicesControllerTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDevicesNegative() throws Exception { - mockMvc.perform(get("/dashboard/devices/").principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(view().name(DEVICES)) - .andExpect(forwardedUrl(DEVICES)); + mockMvc.perform(get("/dashboard/devices/").principal(principalMock)).andExpect(status().isOk()) + .andExpect(view().name(DEVICES)).andExpect(forwardedUrl(DEVICES)); } @Test @@ -106,27 +106,21 @@ public class DashboardDevicesControllerTest { Device device = testUtils.createAndSaveDevice(); ViewDevice viewDevice = new ViewDevice(device); - viewDevice.setOverview(new DeviceOverview(device.getPolicy().getPolicy(), JSON, - reportService.getDeviceReportTypes(device.getId()), - agentService.findDeviceAgents(device.getUuid()))); - - mockMvc.perform(get("/dashboard/devices/overview/{id}", device.getId()) - .principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(model().attribute(DEVICE, viewDevice)) + viewDevice.setOverview(new DeviceOverview(device.getPolicy().getPolicy(), JSON, reportService + .getDeviceReportTypes(device.getId()), agentService.findDeviceAgents(device.getUuid()))); + + mockMvc.perform(get("/dashboard/devices/overview/{id}", device.getId()).principal(principalMock)) + .andExpect(status().isOk()).andExpect(model().attribute(DEVICE, viewDevice)) .andExpect(view().name("device-overview")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDevicesOverviewNegative() throws Exception { - mockMvc.perform(get("/dashboard/devices/overview/{id}", 42) - .principal(principalMock)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(DASHBOARD_DEVICES)); + mockMvc.perform(get("/dashboard/devices/overview/{id}", 42).principal(principalMock)) + .andExpect(status().isFound()).andExpect(redirectedUrl(DASHBOARD_DEVICES)); } - @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDeviceReports() throws Exception { @@ -136,20 +130,16 @@ public class DashboardDevicesControllerTest { ViewDevice viewDevice = new ViewDevice(device); viewDevice.addReports(ReportType.Type.getType(report.getType().getType()), singletonList(report)); - mockMvc.perform(get("/dashboard/devices/reports/{id}", device.getId()) - .principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(model().attribute(DEVICE, viewDevice)) + mockMvc.perform(get("/dashboard/devices/reports/{id}", device.getId()).principal(principalMock)) + .andExpect(status().isOk()).andExpect(model().attribute(DEVICE, viewDevice)) .andExpect(view().name("device-reports")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDevicesReportsNegative() throws Exception { - mockMvc.perform(get("/dashboard/devices/reports/{id}", 42) - .principal(principalMock)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(DASHBOARD_DEVICES)); + mockMvc.perform(get("/dashboard/devices/reports/{id}", 42).principal(principalMock)) + .andExpect(status().isFound()).andExpect(redirectedUrl(DASHBOARD_DEVICES)); } @Test @@ -161,20 +151,16 @@ public class DashboardDevicesControllerTest { ViewDevice viewDevice = new ViewDevice(device); viewDevice.setAgents(singletonList(agent), JSON); - mockMvc.perform(get("/dashboard/devices/agents/{id}", device.getId()) - .principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(model().attribute(DEVICE, viewDevice)) + mockMvc.perform(get("/dashboard/devices/agents/{id}", device.getId()).principal(principalMock)) + .andExpect(status().isOk()).andExpect(model().attribute(DEVICE, viewDevice)) .andExpect(view().name("device-agents")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDevicesAgentsNegative() throws Exception { - mockMvc.perform(get("/dashboard/devices/agents/{id}", 42) - .principal(principalMock)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(DASHBOARD_DEVICES)); + mockMvc.perform(get("/dashboard/devices/agents/{id}", 42).principal(principalMock)) + .andExpect(status().isFound()).andExpect(redirectedUrl(DASHBOARD_DEVICES)); } @Test @@ -184,29 +170,25 @@ public class DashboardDevicesControllerTest { ViewDevice viewDevice = new ViewDevice(device, JSON); - mockMvc.perform(get("/dashboard/devices/policies/{id}", device.getId()) - .principal(principalMock)) - .andExpect(status().isOk()) - .andExpect(model().attribute(DEVICE, viewDevice)) + mockMvc.perform(get("/dashboard/devices/policies/{id}", device.getId()).principal(principalMock)) + .andExpect(status().isOk()).andExpect(model().attribute(DEVICE, viewDevice)) .andExpect(view().name("device-policies")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDevicesPolicesNegative() throws Exception { - mockMvc.perform(get("/dashboard/devices/policies/{id}", 42) - .principal(principalMock)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(DASHBOARD_DEVICES)); + mockMvc.perform(get("/dashboard/devices/policies/{id}", 42).principal(principalMock)) + .andExpect(status().isFound()).andExpect(redirectedUrl(DASHBOARD_DEVICES)); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDeviceSetPolicy() throws Exception { Device device = testUtils.createAndSaveDevice(); - verifySetPolicies(device.getUuid(), - "[{\"group\":\"name\",\"policies\":[{\"name\":\"name\",\"state\":1,\"items\":[\"item\"]}]}]", - status().isOk()); + verifySetPolicies(device + .getUuid(), "[{\"group\":\"name\",\"policies\":[{\"name\":\"name\",\"state\":1,\"items\":[\"item\"]}]}]", status() + .isOk()); } @Test @@ -225,16 +207,13 @@ public class DashboardDevicesControllerTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void dashboardDeviceSetPolicyBadRequest() throws Exception { - mockMvc.perform(post("/dashboard/devices/policies/set", new ApplyPolicy()) - .principal(principalMock)).andExpect(status().isBadRequest()); + mockMvc.perform(post("/dashboard/devices/policies/set", new ApplyPolicy()).principal(principalMock)) + .andExpect(status().isBadRequest()); } @SuppressWarnings("PMD.SignatureDeclareThrowsException") private void verifySetPolicies(String uuid, String policies, ResultMatcher matcher) throws Exception { - mockMvc.perform(post("/dashboard/devices/policies/set") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .param("uuid", uuid) - .param("policies", policies)) - .andExpect(matcher); + mockMvc.perform(post("/dashboard/devices/policies/set").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .param("uuid", uuid).param("policies", policies)).andExpect(matcher); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/controller/HomeControllerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/controller/HomeControllerTest.java index 88387d2..11769fb 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/controller/HomeControllerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/controller/HomeControllerTest.java @@ -24,7 +24,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) public class HomeControllerTest { @@ -63,16 +63,12 @@ public class HomeControllerTest { @SuppressWarnings("PMD.SignatureDeclareThrowsException") private void mustReturnLoginViewForGuest() throws Exception { servletContext.declareRoles(GUEST.type); - mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andExpect(view().name("login")); + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("login")); } @SuppressWarnings("PMD.SignatureDeclareThrowsException") private void mustRedirectFor(Role.Type role, String url) throws Exception { servletContext.declareRoles(role.type); - mockMvc.perform(get("/")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(url)); + mockMvc.perform(get("/")).andExpect(status().isFound()).andExpect(redirectedUrl(url)); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/controller/UserControllerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/controller/UserControllerTest.java index 61438c7..8b9ce97 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/controller/UserControllerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/controller/UserControllerTest.java @@ -16,9 +16,10 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration public class UserControllerTest { + private MockMvc mockMvc; @Autowired @@ -32,8 +33,6 @@ public class UserControllerTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void userTest() throws Exception { - mockMvc.perform(get("/user")) - .andExpect(status().is(302)) - .andExpect(view().name("redirect:/dashboard")); + mockMvc.perform(get("/user")).andExpect(status().is(302)).andExpect(view().name("redirect:/dashboard")); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthAccessTokenTest.java b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthAccessTokenTest.java index 3266ac2..8df5c25 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthAccessTokenTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthAccessTokenTest.java @@ -128,8 +128,7 @@ public class OAuthAccessTokenTest { */ @Test public void testOAuthAccessTokenWithParameters() { - OAuthAccessToken oAuthAccessToken = new OAuthAccessToken(tokenId, token, authenticationId, userName, clientId, - authentication, refreshToken); + OAuthAccessToken oAuthAccessToken = new OAuthAccessToken(tokenId, token, authenticationId, userName, clientId, authentication, refreshToken); assertEquals(tokenId, oAuthAccessToken.getTokenId()); assertTrue(Arrays.equals(token, oAuthAccessToken.getToken())); @@ -174,7 +173,7 @@ public class OAuthAccessTokenTest { oAuthAccessToken.setToken(token); assertNotNull(oAuthAccessToken.getToken()); assertTrue(Arrays.equals(token, oAuthAccessToken.getToken())); - + } /** diff --git a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientDetailsTest.java b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientDetailsTest.java index 2280d1d..892cb6e 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientDetailsTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientDetailsTest.java @@ -29,12 +29,12 @@ import com.samsung.dsm.domain.oauth.OAuthClientDetails; */ @RunWith(Parameterized.class) public class OAuthClientDetailsTest { - + private static final String TRUE = "true"; - private static final String ADDITIONAL = "Additional"; - private static final String LOCALHOST = "http://localhost"; - private static final String READ_WRITE_TRUST = "Read, write, trust"; - private String clientId; + private static final String ADDITIONAL = "Additional"; + private static final String LOCALHOST = "http://localhost"; + private static final String READ_WRITE_TRUST = "Read, write, trust"; + private String clientId; private String resourceIds; private String secret; private String scope; @@ -45,16 +45,20 @@ public class OAuthClientDetailsTest { private Integer refreshTokenValidity; private String additionalInformation; private String autoapprove; - + @Parameters public static Collection data() { - Object[][] data = new Object[][] { - {"Client 1", "Resource 1", "Secret 1", READ_WRITE_TRUST, "Grand type 1", LOCALHOST, "Authorities 1", -1, -1, ADDITIONAL, TRUE }, - {"Client 2", "Resource 2", "Secret 2", READ_WRITE_TRUST, "Grand type 2", LOCALHOST, "Authorities 2", 1, 1, ADDITIONAL, TRUE }, - {"Client 3", "Resource 3", "Secret 3", READ_WRITE_TRUST, "Grand type 3", LOCALHOST, "Authorities 3", Integer.MIN_VALUE, Integer.MIN_VALUE, ADDITIONAL, TRUE }, - {"Client 4", "Resource 4", "Secret 4", READ_WRITE_TRUST, "Grand type 4", LOCALHOST, "Authorities 4", Integer.MAX_VALUE, Integer.MAX_VALUE, ADDITIONAL, TRUE }, - {"Client 5", "Resource 5", "Secret 5", READ_WRITE_TRUST, "Grand type 5", LOCALHOST, "Authorities 5", 0, 0, ADDITIONAL, TRUE } - }; + Object[][] data = new Object[][] { + { "Client 1", "Resource 1", "Secret 1", READ_WRITE_TRUST, "Grand type 1", LOCALHOST, "Authorities 1", + -1, -1, ADDITIONAL, TRUE }, + { "Client 2", "Resource 2", "Secret 2", READ_WRITE_TRUST, "Grand type 2", LOCALHOST, "Authorities 2", 1, + 1, ADDITIONAL, TRUE }, + { "Client 3", "Resource 3", "Secret 3", READ_WRITE_TRUST, "Grand type 3", LOCALHOST, "Authorities 3", + Integer.MIN_VALUE, Integer.MIN_VALUE, ADDITIONAL, TRUE }, + { "Client 4", "Resource 4", "Secret 4", READ_WRITE_TRUST, "Grand type 4", LOCALHOST, "Authorities 4", + Integer.MAX_VALUE, Integer.MAX_VALUE, ADDITIONAL, TRUE }, + { "Client 5", "Resource 5", "Secret 5", READ_WRITE_TRUST, "Grand type 5", LOCALHOST, "Authorities 5", 0, + 0, ADDITIONAL, TRUE } }; return Arrays.asList(data); } @@ -90,17 +94,17 @@ public class OAuthClientDetailsTest { this.additionalInformation = additionalInformation; this.autoapprove = autoapprove; } - + @Before public void initMocks() { MockitoAnnotations.initMocks(this); } - + /** * Checks default constructor */ @Test - public void testOAuthClientDetails(){ + public void testOAuthClientDetails() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); assertNull(oAuthClientDetails.getClientId()); assertNull(oAuthClientDetails.getResourceIds()); @@ -111,10 +115,10 @@ public class OAuthClientDetailsTest { assertNull(oAuthClientDetails.getAuthorities()); assertNull(oAuthClientDetails.getAccessTokenValidity()); assertNull(oAuthClientDetails.getRefreshTokenValidity()); - assertNull(oAuthClientDetails.getAdditionalInformation()); + assertNull(oAuthClientDetails.getAdditionalInformation()); assertNull(oAuthClientDetails.getAutoapprove()); } - + /** * Checks default constructor with parameters: * @@ -131,10 +135,8 @@ public class OAuthClientDetailsTest { * @param autoapprove - auto approve */ @Test - public void testOAuthClientDetailsWithParameters(){ - OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(clientId, resourceIds, secret, scope, - authorizedGrantTypes, webServerRedirectUri, authorities, accessTokenValidity, - refreshTokenValidity, additionalInformation, autoapprove); + public void testOAuthClientDetailsWithParameters() { + OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(clientId, resourceIds, secret, scope, authorizedGrantTypes, webServerRedirectUri, authorities, accessTokenValidity, refreshTokenValidity, additionalInformation, autoapprove); assertNotNull(oAuthClientDetails.getClientId()); assertNotNull(oAuthClientDetails.getResourceIds()); assertNotNull(oAuthClientDetails.getSecret()); @@ -144,9 +146,9 @@ public class OAuthClientDetailsTest { assertNotNull(oAuthClientDetails.getAuthorities()); assertNotNull(oAuthClientDetails.getAccessTokenValidity()); assertNotNull(oAuthClientDetails.getRefreshTokenValidity()); - assertNotNull(oAuthClientDetails.getAdditionalInformation()); + assertNotNull(oAuthClientDetails.getAdditionalInformation()); assertNotNull(oAuthClientDetails.getAutoapprove()); - + assertEquals(clientId, oAuthClientDetails.getClientId()); assertEquals(resourceIds, oAuthClientDetails.getResourceIds()); assertEquals(secret, oAuthClientDetails.getSecret()); @@ -156,33 +158,34 @@ public class OAuthClientDetailsTest { assertEquals(authorities, oAuthClientDetails.getAuthorities()); assertEquals(accessTokenValidity, oAuthClientDetails.getAccessTokenValidity()); assertEquals(refreshTokenValidity, oAuthClientDetails.getRefreshTokenValidity()); - assertEquals(additionalInformation, oAuthClientDetails.getAdditionalInformation()); + assertEquals(additionalInformation, oAuthClientDetails.getAdditionalInformation()); assertEquals(autoapprove, oAuthClientDetails.getAutoapprove()); } - + /** * Checks setting application client identifier. * * @param clientId - application client identifier. */ @Test - public void testSetClientId(){ + public void testSetClientId() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setClientId(clientId); assertNotNull(oAuthClientDetails.getClientId()); - assertEquals(clientId, oAuthClientDetails.getClientId()); + assertEquals(clientId, oAuthClientDetails.getClientId()); } - /** Checksd provides setting resource identifier. + /** + * Checksd provides setting resource identifier. * * @param resourceIds - resource identifiers. */ @Test - public void testSetResourceIds(){ + public void testSetResourceIds() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setResourceIds(resourceIds); assertNotNull(oAuthClientDetails.getResourceIds()); - assertEquals(resourceIds, oAuthClientDetails.getResourceIds()); + assertEquals(resourceIds, oAuthClientDetails.getResourceIds()); } /** @@ -191,11 +194,11 @@ public class OAuthClientDetailsTest { * @param secret - application client secret. */ @Test - public void testSetSecret(){ + public void testSetSecret() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setSecret(secret); assertNotNull(oAuthClientDetails.getSecret()); - assertEquals(secret, oAuthClientDetails.getSecret()); + assertEquals(secret, oAuthClientDetails.getSecret()); } /** @@ -204,11 +207,11 @@ public class OAuthClientDetailsTest { * @param scope - privilege. */ @Test - public void testSetScope(){ + public void testSetScope() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setScope(scope); assertNotNull(oAuthClientDetails.getScope()); - assertEquals(scope, oAuthClientDetails.getScope()); + assertEquals(scope, oAuthClientDetails.getScope()); } /** @@ -217,11 +220,11 @@ public class OAuthClientDetailsTest { * @param authorizedGrantTypes - authorized grant types. */ @Test - public void testSetAuthorizedGrantTypes(){ + public void testSetAuthorizedGrantTypes() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setAuthorizedGrantTypes(authorizedGrantTypes); - assertNotNull(oAuthClientDetails.getAuthorizedGrantTypes()); - assertEquals(authorizedGrantTypes, oAuthClientDetails.getAuthorizedGrantTypes()); + assertNotNull(oAuthClientDetails.getAuthorizedGrantTypes()); + assertEquals(authorizedGrantTypes, oAuthClientDetails.getAuthorizedGrantTypes()); } /** @@ -230,11 +233,11 @@ public class OAuthClientDetailsTest { * @param webServerRedirectUri - redirect URI. */ @Test - public void testSetWebServerRedirectUri(){ + public void testSetWebServerRedirectUri() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setWebServerRedirectUri(webServerRedirectUri); assertNotNull(oAuthClientDetails.getWebServerRedirectUri()); - assertEquals(webServerRedirectUri, oAuthClientDetails.getWebServerRedirectUri()); + assertEquals(webServerRedirectUri, oAuthClientDetails.getWebServerRedirectUri()); } /** @@ -243,11 +246,11 @@ public class OAuthClientDetailsTest { * @param authorities. */ @Test - public void testSetAuthorities(){ + public void testSetAuthorities() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setAuthorities(authorities); assertNotNull(oAuthClientDetails.getAuthorities()); - assertEquals(authorities, oAuthClientDetails.getAuthorities()); + assertEquals(authorities, oAuthClientDetails.getAuthorities()); } /** @@ -256,11 +259,11 @@ public class OAuthClientDetailsTest { * @param accessTokenValidity - access token validity time in seconds. */ @Test - public void testSetAccessTokenValidity(){ + public void testSetAccessTokenValidity() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setAccessTokenValidity(accessTokenValidity); assertNotNull(oAuthClientDetails.getAccessTokenValidity()); - assertEquals(accessTokenValidity, oAuthClientDetails.getAccessTokenValidity()); + assertEquals(accessTokenValidity, oAuthClientDetails.getAccessTokenValidity()); } /** @@ -269,11 +272,11 @@ public class OAuthClientDetailsTest { * @param refreshTokenValidity - refresh token validity time in seconds. */ @Test - public void testSetRefreshTokenValidity(){ + public void testSetRefreshTokenValidity() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setRefreshTokenValidity(refreshTokenValidity); assertNotNull(oAuthClientDetails.getRefreshTokenValidity()); - assertEquals(refreshTokenValidity, oAuthClientDetails.getRefreshTokenValidity()); + assertEquals(refreshTokenValidity, oAuthClientDetails.getRefreshTokenValidity()); } /** @@ -282,10 +285,10 @@ public class OAuthClientDetailsTest { * @param additionalInformation - additional information. */ @Test - public void testSetAdditionalInformation(){ + public void testSetAdditionalInformation() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setAdditionalInformation(additionalInformation); - assertNotNull(oAuthClientDetails.getAdditionalInformation()); + assertNotNull(oAuthClientDetails.getAdditionalInformation()); assertEquals(additionalInformation, oAuthClientDetails.getAdditionalInformation()); } @@ -295,11 +298,11 @@ public class OAuthClientDetailsTest { * @param autoapprove. */ @Test - public void testSetAutoapprove(){ + public void testSetAutoapprove() { OAuthClientDetails oAuthClientDetails = new OAuthClientDetails(); oAuthClientDetails.setAutoapprove(autoapprove); assertNotNull(oAuthClientDetails.getAutoapprove()); assertEquals(autoapprove, oAuthClientDetails.getAutoapprove()); } - + } \ No newline at end of file diff --git a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientTokenTest.java b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientTokenTest.java index 0ad3b10..e910ab5 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientTokenTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthClientTokenTest.java @@ -8,7 +8,6 @@ import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; -import org.hibernate.validator.cfg.defs.AssertTrueDef; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,8 +15,6 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mockito.MockitoAnnotations; -import com.samsung.dsm.domain.oauth.OAuthClientToken; - /** * @author Mail to: Yevhen Zozulia * @version 1.0 diff --git a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthCodeTest.java b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthCodeTest.java index 0559d41..39b648d 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthCodeTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthCodeTest.java @@ -43,7 +43,8 @@ public class OAuthCodeTest { } /** - * Public constructor for class OAuthCodeTest. Creates object OAuthCodeTest with + * Public constructor for class OAuthCodeTest. Creates object OAuthCodeTest + * with * parameters: * * @param code diff --git a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthRefreshTokenTest.java b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthRefreshTokenTest.java index 721ea8f..7052bd3 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthRefreshTokenTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/domain/oauth/OAuthRefreshTokenTest.java @@ -8,8 +8,6 @@ import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; -import javax.validation.constraints.AssertTrue; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -17,8 +15,6 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mockito.MockitoAnnotations; -import com.samsung.dsm.domain.oauth.OAuthRefreshToken; - /** * @author Mail to: Yevhen Zozulia * @version 1.0 @@ -32,23 +28,22 @@ import com.samsung.dsm.domain.oauth.OAuthRefreshToken; */ @RunWith(Parameterized.class) public class OAuthRefreshTokenTest { - + private String tokenId; private byte[] token; private byte[] authentication; @Parameters public static Collection data() { - Object[][] data = new Object[][] { - {"Token id = 1", "Refresh Token 1".getBytes(), "Authentication 1".getBytes()}, - {"Token id = 2", "Refresh Token 2".getBytes(), "Authentication 2".getBytes()}, - {"Token id = 3", "Refresh Token 3".getBytes(), "Authentication 3".getBytes()}, - {"Token id = 4", "Refresh Token 4".getBytes(), "Authentication 4".getBytes()}, - {"Token id = 5", "Refresh Token 5".getBytes(), "Authentication 5".getBytes()} - }; + Object[][] data = new Object[][] { + { "Token id = 1", "Refresh Token 1".getBytes(), "Authentication 1".getBytes() }, + { "Token id = 2", "Refresh Token 2".getBytes(), "Authentication 2".getBytes() }, + { "Token id = 3", "Refresh Token 3".getBytes(), "Authentication 3".getBytes() }, + { "Token id = 4", "Refresh Token 4".getBytes(), "Authentication 4".getBytes() }, + { "Token id = 5", "Refresh Token 5".getBytes(), "Authentication 5".getBytes() } }; return Arrays.asList(data); } - + /** * Public constructor for class OAuthRefreshTokenTest. Creates object * OAuthRefreshTokenTest with parameters: @@ -63,31 +58,31 @@ public class OAuthRefreshTokenTest { this.token = Arrays.copyOf(token, token.length); this.authentication = Arrays.copyOf(authentication, authentication.length); } - + @Before public void initMocks() { MockitoAnnotations.initMocks(this); } - + /** * Checks default constructor */ @Test - public void testOAuthRefreshToken(){ + public void testOAuthRefreshToken() { OAuthRefreshToken oAuthRefreshToken = new OAuthRefreshToken(); assertNull(oAuthRefreshToken.getTokenId()); assertNull(oAuthRefreshToken.getAuthentication()); assertNull(oAuthRefreshToken.getTokenId()); } - + /** - * - * Checks constructor with parameters: - * - * @param tokenId - token identifier - * @param token - refresh token - * @param authentication - authentication - */ + * + * Checks constructor with parameters: + * + * @param tokenId - token identifier + * @param token - refresh token + * @param authentication - authentication + */ @Test public void testOAuthRefreshTokenWithParameters() { OAuthRefreshToken oAuthRefreshToken = new OAuthRefreshToken(tokenId, token, authentication); @@ -98,7 +93,7 @@ public class OAuthRefreshTokenTest { assertNotNull(oAuthRefreshToken.getToken()); assertNotNull(oAuthRefreshToken.getAuthentication()); } - + /** * Checks setting token identifier. * @@ -137,5 +132,5 @@ public class OAuthRefreshTokenTest { assertNotNull(oAuthRefreshToken.getAuthentication()); assertTrue(Arrays.equals(authentication, oAuthRefreshToken.getAuthentication())); } - + } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/request/ApplyPolicyTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/request/ApplyPolicyTest.java index 01b1ebd..db8e37a 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/request/ApplyPolicyTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/request/ApplyPolicyTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; public class ApplyPolicyTest { + @Test public void setGetTest() { String uuid = "uuid"; diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/request/EditUserTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/request/EditUserTest.java index b4d9c9a..3c03bb2 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/request/EditUserTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/request/EditUserTest.java @@ -7,6 +7,7 @@ import org.junit.Test; import com.samsung.dsm.model.request.EditUser; public class EditUserTest { + @Test public void setIdTest() { Long expectedId = 1l; diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/request/NewUserTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/request/NewUserTest.java index 1f08ac3..69136ec 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/request/NewUserTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/request/NewUserTest.java @@ -7,6 +7,7 @@ import org.junit.Test; import com.samsung.dsm.model.request.NewUser; public class NewUserTest { + @Test public void setNameTest() { String name = "test"; diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/request/ResetPasswordTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/request/ResetPasswordTest.java index 801d7e4..f929d3a 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/request/ResetPasswordTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/request/ResetPasswordTest.java @@ -7,6 +7,7 @@ import org.junit.Test; import com.samsung.dsm.model.request.ResetPassword; public class ResetPasswordTest { + @Test public void setIdTest() { Long id = 1l; diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/view/BaseViewTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/view/BaseViewTest.java index cb20e05..988a4a6 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/view/BaseViewTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/view/BaseViewTest.java @@ -21,16 +21,19 @@ public class BaseViewTest { @Test public void getDeviceType() { @SuppressWarnings("serial") - Map map = new HashMap() {{ - put("tv", "tv"); - put("phone", "smartphone"); - put("light", "lamp"); - put("robotcleaner", "robotcleaner"); - put("airconditioner", "airconditioner"); - put("refrigerator", "refrigerator"); - put("smartplug", "smartplug"); - put("washer", "washer"); - }}; + Map map = new HashMap() { + + { + put("tv", "tv"); + put("phone", "smartphone"); + put("light", "lamp"); + put("robotcleaner", "robotcleaner"); + put("airconditioner", "airconditioner"); + put("refrigerator", "refrigerator"); + put("smartplug", "smartplug"); + put("washer", "washer"); + } + }; for (String key : map.keySet()) { assertThat(baseView.getDeviceType(key), is(map.get(key))); @@ -40,21 +43,24 @@ public class BaseViewTest { @Test public void getDeviceTypeToDisplay() { @SuppressWarnings("serial") - Map map = new HashMap() {{ - put("tv", "Smart TV"); - put("phone", "Smartphone"); - put("light", "Smart Lamp"); - put("robotcleaner", "Smart Robot Cleaner"); - put("airconditioner", "Smart Airconditioner"); - put("refrigerator", "Smart Refrigerator"); - put("smartplug", "Smart Plug"); - put("washer", "Smart Washer"); - }}; + Map map = new HashMap() { + + { + put("tv", "Smart TV"); + put("phone", "Smartphone"); + put("light", "Smart Lamp"); + put("robotcleaner", "Smart Robot Cleaner"); + put("airconditioner", "Smart Airconditioner"); + put("refrigerator", "Smart Refrigerator"); + put("smartplug", "Smart Plug"); + put("washer", "Smart Washer"); + } + }; for (String key : map.keySet()) { assertThat(baseView.getDeviceTypeToDisplay(key), is(map.get(key))); } - + assertThat(baseView.getDeviceTypeToDisplay(""), is("")); } @@ -74,14 +80,14 @@ public class BaseViewTest { public void getParseDeviceTypeNPE() { baseView.getDeviceTypeToDisplay(null); } - + @Test - public void testEmptyParseDeviceType(){ + public void testEmptyParseDeviceType() { assertNotNull(baseView.getDeviceTypeToDisplay("")); } @Test - public void testWrongParseDeviceType(){ + public void testWrongParseDeviceType() { assertNotNull(baseView.getDeviceTypeToDisplay("wrong")); } } \ No newline at end of file diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewPolicyGroupTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewPolicyGroupTest.java index de3a8ba..c325f24 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewPolicyGroupTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewPolicyGroupTest.java @@ -24,6 +24,7 @@ import com.samsung.dsm.policy.parser.JSONPolicyConfigParser; import com.samsung.dsm.policy.parser.PolicyConfigParser; public class ViewPolicyGroupTest { + public static String POLICY = "[" + "{" + "\"group\":\"no-display\"," + diff --git a/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewReportTest.java b/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewReportTest.java index a4669cf..f833182 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewReportTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/model/view/ViewReportTest.java @@ -25,27 +25,30 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; - @RunWith(Parameterized.class) public class ViewReportTest { - private static final String testInputDataBegin = "{" + "\"did\": \"1234\"," + "\"date\": \"12:25 PM; May 08, 2017\"," - + "\"name\": \"dac\"," + "\"result\": 0," + "\"data\": {log:\""; - private static final String testInputDataEnd = "\"}}"; + private static final String TEST_INPUT_DATA_BEGIN = "{" + "\"did\": \"1234\"," + + "\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"dac\"," + "\"result\": 0," + "\"data\": {log:\""; + + private static final String TEST_INPUT_DATA_END = "\"}}"; - private static final String dacReport = testInputDataBegin + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String DAC_REPORT = TEST_INPUT_DATA_BEGIN + + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; - - private static final String smackReport = testInputDataBegin + "audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; + + private static final String SMACK_REPORT = TEST_INPUT_DATA_BEGIN + + "audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; private List reports; private String type; @@ -68,17 +71,15 @@ public class ViewReportTest { @Parameters public static Collection data() { - Object[][] data = new Object[][] { - {ReportType.Type.DAC.toString(), "DAC", dacReport, "date", 0}, - {ReportType.Type.SMACK.toString(), "SMACK", smackReport, "date", 1} - }; + Object[][] data = new Object[][] { { ReportType.Type.DAC.toString(), "DAC", DAC_REPORT, "date", 0 }, + { ReportType.Type.SMACK.toString(), "SMACK", SMACK_REPORT, "date", 1 } }; return Arrays.asList(data); } @Test public void gettersTest() { - assertEquals(name , viewReport.getName()); + assertEquals(name, viewReport.getName()); assertEquals(type, viewReport.getType()); assertEquals(reports.size(), viewReport.getReports().size()); } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRequest.java b/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRequest.java index 5b3db7b..f5ac2ff 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRequest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRequest.java @@ -17,7 +17,9 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; public class PojoTestForModelRequest { - // Configured for expectation, so we know when a class gets added or removed. + + // Configured for expectation, so we know when a class gets added or + // removed. private static final int EXPECTED_CLASS_COUNT = 4; // The package to test @@ -25,29 +27,27 @@ public class PojoTestForModelRequest { @Test public void ensureExpectedPojoCount() { - List pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterClassName("^((?!Test).)*$")); + List pojoClasses = PojoClassFactory + .getPojoClasses(POJO_PACKAGE, new FilterClassName("^((?!Test).)*$")); - for(PojoClass pojoClass: pojoClasses){ - System.out.println(pojoClass); - } - Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); + for (PojoClass pojoClass : pojoClasses) { + System.out.println(pojoClass); + } + Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); } @Test public void testPojoStructureAndBehavior() { - Validator validator = ValidatorBuilder.create() - // Add Rules to validate structure for POJO_PACKAGE - // See com.openpojo.validation.rule.impl for more ... - .with(new GetterMustExistRule()) - .with(new SetterMustExistRule()) - .with(new TestClassMustBeProperlyNamedRule()) - // Add Testers to validate behaviour for POJO_PACKAGE - // See com.openpojo.validation.test.impl for more ... - .with(new SetterTester()) - .with(new GetterTester()) - .build(); - - validator.validate(POJO_PACKAGE, new FilterClassName("^((?![Test,Reset]).)*$")); + Validator validator = ValidatorBuilder.create() + // Add Rules to validate structure for POJO_PACKAGE + // See com.openpojo.validation.rule.impl for more ... + .with(new GetterMustExistRule()).with(new SetterMustExistRule()) + .with(new TestClassMustBeProperlyNamedRule()) + // Add Testers to validate behaviour for POJO_PACKAGE + // See com.openpojo.validation.test.impl for more ... + .with(new SetterTester()).with(new GetterTester()).build(); + + validator.validate(POJO_PACKAGE, new FilterClassName("^((?![Test,Reset]).)*$")); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRest.java b/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRest.java index f0f8d31..eee3933 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/pojo/PojoTestForModelRest.java @@ -15,7 +15,9 @@ import com.openpojo.validation.rule.impl.TestClassMustBeProperlyNamedRule; import com.openpojo.validation.test.impl.GetterTester; public class PojoTestForModelRest { - // Configured for expectation, so we know when a class gets added or removed. + + // Configured for expectation, so we know when a class gets added or + // removed. private static final int EXPECTED_CLASS_COUNT = 3; // The package to test @@ -23,26 +25,25 @@ public class PojoTestForModelRest { @Test public void ensureExpectedPojoCount() { - List pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterClassName("^((?!Test).)*$")); + List pojoClasses = PojoClassFactory + .getPojoClasses(POJO_PACKAGE, new FilterClassName("^((?!Test).)*$")); - for(PojoClass pojoClass: pojoClasses){ - System.out.println(pojoClass); - } - Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); + for (PojoClass pojoClass : pojoClasses) { + System.out.println(pojoClass); + } + Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); } @Test public void testPojoStructureAndBehavior() { - Validator validator = ValidatorBuilder.create() - // Add Rules to validate structure for POJO_PACKAGE - // See com.openpojo.validation.rule.impl for more ... - .with(new GetterMustExistRule()) - .with(new TestClassMustBeProperlyNamedRule()) - // Add Testers to validate behaviour for POJO_PACKAGE - // See com.openpojo.validation.test.impl for more ... - .with(new GetterTester()) - .build(); - - validator.validate(POJO_PACKAGE, new FilterClassName("^((?!Test).)*$")); + Validator validator = ValidatorBuilder.create() + // Add Rules to validate structure for POJO_PACKAGE + // See com.openpojo.validation.rule.impl for more ... + .with(new GetterMustExistRule()).with(new TestClassMustBeProperlyNamedRule()) + // Add Testers to validate behaviour for POJO_PACKAGE + // See com.openpojo.validation.test.impl for more ... + .with(new GetterTester()).build(); + + validator.validate(POJO_PACKAGE, new FilterClassName("^((?!Test).)*$")); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/policy/parser/JSONParserTest.java b/servers/dsm/src/test/java/com/samsung/dsm/policy/parser/JSONParserTest.java index 203d9e7..794f677 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/policy/parser/JSONParserTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/policy/parser/JSONParserTest.java @@ -75,20 +75,12 @@ public class JSONParserTest { @Test public void parserObjectToJsonTest() { - String expected = "[{" + - "\"group\":\"tv-extension\"," + - "\"policies\":[" + - "{" + - "\"name\":\"usb\"," + - "\"state\":0," + - "\"items\":[]" + - "}" + - "]" + - "}]"; + String expected = "[{" + "\"group\":\"tv-extension\"," + "\"policies\":[" + "{" + "\"name\":\"usb\"," + + "\"state\":0," + "\"items\":[]" + "}" + "]" + "}]"; PolicyConfigParser parser = new JSONPolicyConfigParser(); PolicyConfig.PolicyGroup.Policy policy = new PolicyConfig.PolicyGroup.Policy("usb", 0, new String[0]); - PolicyConfig.PolicyGroup policyGroup = new PolicyConfig.PolicyGroup("tv-extension", new Policy[]{policy}); - PolicyConfig config = new PolicyConfig(new PolicyGroup[]{policyGroup}); + PolicyConfig.PolicyGroup policyGroup = new PolicyConfig.PolicyGroup("tv-extension", new Policy[] { policy }); + PolicyConfig config = new PolicyConfig(new PolicyGroup[] { policyGroup }); assertEquals(expected, parser.toString(config)); } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactoryTest.java b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactoryTest.java index d530caf..36e0f05 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactoryTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerFactoryTest.java @@ -14,22 +14,24 @@ import com.samsung.commons.domain.ReportType; public class ReportAnalyzerFactoryTest { @Test - public void testGetAnalyzer(){ + public void testGetAnalyzer() { assertNotNull(ReportAnalyzerFactory.getAnalyzer(ReportType.Type.DAC.type)); assertNotNull(ReportAnalyzerFactory.getAnalyzer(ReportType.Type.SMACK.type)); assertNotNull(ReportAnalyzerFactory.getAnalyzer(ReportType.Type.SYSCALL.type)); } @Test - public void testGetAnalyzerWrongValues(){ + public void testGetAnalyzerWrongValues() { assertNull(ReportAnalyzerFactory.getAnalyzer("sim")); assertNull(ReportAnalyzerFactory.getAnalyzer("")); assertNull(ReportAnalyzerFactory.getAnalyzer(null)); } @Test() - public void testPrivateConstructors() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + public void testPrivateConstructors() + throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final Constructor[] constructors = ReportAnalyzerFactory.class.getDeclaredConstructors(); + for (Constructor constructor : constructors) { assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); @@ -37,5 +39,5 @@ public class ReportAnalyzerFactoryTest { assertNotNull(reportAnalyzerFactory); } } - + } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeysTest.java b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeysTest.java index a46828e..063ab7f 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeysTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/ReportAnalyzerKeysTest.java @@ -21,5 +21,5 @@ public class ReportAnalyzerKeysTest { assertNotNull(reportAnalyzerKeys); } } - + } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzerTest.java index f650e00..de52aae 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/DACReportAnalyzerTest.java @@ -19,39 +19,49 @@ import com.samsung.dsm.service.GrantedApplicationService; @ContextConfiguration(locations = { "classpath:root-context.xml" }) @SuppressWarnings("all") public class DACReportAnalyzerTest { - - private static final String testInputDataBegin = "{" + "\"did\": \"1234\"," + "\"date\": \"12:25 PM; May 08, 2017\"," - + "\"name\": \"dac\"," + "\"result\": 0," + "\"data\": {log:\""; - private static final String testInputDataEnd = "\"}}"; - - private static final String dacReport1 = testInputDataBegin + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String TEST_INPUT_DATA_BEGIN = "{" + "\"did\": \"1234\"," + + "\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"dac\"," + "\"result\": 0," + "\"data\": {log:\""; + + private static final String TEST_INPUT_DATA_END = "\"}}"; + + private static final String DAC_REPORT_1 = TEST_INPUT_DATA_BEGIN + + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; - - private static final String dacReport2 = testInputDataBegin + " \t\t\t\t\t\n\n\n\n [DAC] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; + + private static final String DAC_REPORT_2 = TEST_INPUT_DATA_BEGIN + + " \t\t\t\t\t\n\n\n\n [DAC] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; - - private static final String dacReport3 = testInputDataBegin + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; + + private static final String DAC_REPORT_3 = TEST_INPUT_DATA_BEGIN + + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/smack_test subj=User::Shell " + testInputDataEnd; - - private static final String dacReport4 = testInputDataBegin + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/smack_test subj=User::Shell " + + TEST_INPUT_DATA_END; + + private static final String DAC_REPORT_4 = TEST_INPUT_DATA_BEGIN + + "[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::smack_test " + testInputDataEnd; - - private static final String dacReport5 = testInputDataBegin + " \t\t\t\t\t\n\n\n\n [DAC] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::smack_test " + + TEST_INPUT_DATA_END; + + private static final String DAC_REPORT_5 = TEST_INPUT_DATA_BEGIN + + " \t\t\t\t\t\n\n\n\n [DAC] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=smack_test exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=smack_test exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; @Autowired GrantedApplicationService grantedApplicationService; @Test - public void testExtractReportDataDACReport(){ + public void testExtractReportDataDACReport() { DACReportAnalyzer analyzer = new DACReportAnalyzer(); - Map map = analyzer.extractReportData(dacReport1); + Map map = analyzer.extractReportData(DAC_REPORT_1); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -78,7 +88,7 @@ public class DACReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_COMM), "ls"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_EXE), "/usr/bin/ls"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SUBJ), "User::Shell"); - map = analyzer.extractReportData(dacReport2); + map = analyzer.extractReportData(DAC_REPORT_2); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -106,11 +116,11 @@ public class DACReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_EXE), "/usr/bin/ls"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SUBJ), "User::Shell"); } - + @Test - public void testCreateNotification(){ + public void testCreateNotification() { DACReportAnalyzer analyzer = new DACReportAnalyzer(); - Map map = analyzer.extractReportData(dacReport3); + Map map = analyzer.extractReportData(DAC_REPORT_3); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -146,7 +156,8 @@ public class DACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"Shell\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"Shell\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -154,7 +165,7 @@ public class DACReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(dacReport4); + map = analyzer.extractReportData(DAC_REPORT_4); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -190,7 +201,8 @@ public class DACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -198,7 +210,7 @@ public class DACReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(dacReport5); + map = analyzer.extractReportData(DAC_REPORT_5); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -234,7 +246,8 @@ public class DACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute \"/usr/bin/ls\", app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute \"/usr/bin/ls\", app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -243,5 +256,5 @@ public class DACReportAnalyzerTest { Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); } - + } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzerTest.java index eccce9f..9e046a0 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/MACReportAnalyzerTest.java @@ -4,7 +4,6 @@ package com.samsung.dsm.report.analyzer.impl; import java.util.Map; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -19,81 +18,89 @@ import com.samsung.dsm.service.GrantedApplicationService; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:root-context.xml" }) -@Ignore @SuppressWarnings("all") public class MACReportAnalyzerTest { - private static final String testInputDataBegin = "{" + "\"did\": \"1234\"," + "\"date\": \"12:25 PM; May 08, 2017\"," - + "\"name\": \"smack\"," + "\"result\": 0," + "\"data\": {log:\""; + private static final String TEST_INPUT_DATA_BEGIN = "{" + "\"did\": \"1234\"," + + "\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"smack\"," + "\"result\": 0," + "\"data\": {log:\""; - private static final String testInputDataEnd = "\"}}"; + private static final String TEST_INPUT_DATA_END = "\"}}"; - private static final String report1 = testInputDataBegin + "audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; + private static final String REPORT_1 = TEST_INPUT_DATA_BEGIN + + "audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; - private static final String report2 = testInputDataBegin + " audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=smack_test name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; - - private static final String report1audit = testInputDataBegin + " audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::ggggg object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=/smack_test/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; - - private static final String report2audit = testInputDataBegin + " audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::smack_test object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; + private static final String REPORT_2 = TEST_INPUT_DATA_BEGIN + + " audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=smack_test name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; - private static final String report3 = testInputDataBegin + "[MAC] audit(1500281615.877:724): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + testInputDataEnd; + private static final String REPORT_3 = TEST_INPUT_DATA_BEGIN + + " audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::ggggg object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=/smack_test/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; - private static final String report4OneString = testInputDataBegin + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]" + testInputDataEnd; + private static final String REPORT_4 = TEST_INPUT_DATA_BEGIN + + " audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::smack_test object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; - private static final String report5wrongFormatter = testInputDataBegin + "[MAC] audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]" + - "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; + private static final String REPORT_5 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281615.877:724): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + TEST_INPUT_DATA_END; - private static final String report6messageInManyRows = testInputDataBegin + "[MAC] audit(1500281615.877:724): lsm=SMACK fn=smack_inode_getattr action=denied \n" + private static final String REPORT_6 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]" + TEST_INPUT_DATA_END; + + private static final String REPORT_7 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281615.877:724): lsm=SMACK fn=smack_inode_getattr action=denied \n" + "mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash \n" - + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + testInputDataEnd; + + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + TEST_INPUT_DATA_END; - private static final String report7messageIncorrectMessage = testInputDataBegin + "\n\n\n\n\n\n \t\t\t\t\t[MAC] audit(1500281615.877:724): lsm=SMACK fn=smack_inode_getattr action=denied \n" + private static final String REPORT_8 = TEST_INPUT_DATA_BEGIN + + "\n\n\n\n\n\n \t\t\t\t\t[MAC] audit(1500281615.877:724): lsm=SMACK fn=smack_inode_getattr action=denied \n" + "mode=enforcing wait=no subject=User object=System=system requested=r d_inst=1 ppid=23926 ppid_comm=bash \n" - + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "\t\t\t[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + testInputDataEnd; + + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "\t\t\t[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + TEST_INPUT_DATA_END; + + private static final String REPORT_WRONG_FORMAT = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281615.877:723): lsm=SMACK fn=smack_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]" + + "[25055][#1 0x7f0674a4 in smack_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; @Autowired GrantedApplicationService grantedApplicationService; @Test - public void testNormalParseReport(){ + public void testNormalParseReport() { MACReportAnalyzer analyzer = new MACReportAnalyzer(); - Map map = analyzer.extractReportData(report1); + Map map = analyzer.extractReportData(REPORT_1); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -111,7 +118,7 @@ public class MACReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "smack_inode_getattr"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "SMACK"); - map = analyzer.extractReportData(report2); + map = analyzer.extractReportData(REPORT_2); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -129,7 +136,7 @@ public class MACReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "smack_inode_getxattr"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "SMACK"); - map = analyzer.extractReportData(report3); + map = analyzer.extractReportData(REPORT_5); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -150,9 +157,9 @@ public class MACReportAnalyzerTest { } @Test - public void testParseReportWhenMainMassegeWithTraceIsOneString(){ + public void testParseReportWhenMainMassegeWithTraceIsOneString() { MACReportAnalyzer analyzer = new MACReportAnalyzer(); - Map map = analyzer.extractReportData(report4OneString); + Map map = analyzer.extractReportData(REPORT_6); System.out.println(map); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); @@ -174,9 +181,9 @@ public class MACReportAnalyzerTest { } @Test - public void testParseReportWhenMainMassegeInManyRows(){ + public void testParseReportWhenMainMassegeInManyRows() { MACReportAnalyzer analyzer = new MACReportAnalyzer(); - Map map = analyzer.extractReportData(report6messageInManyRows); + Map map = analyzer.extractReportData(REPORT_7); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -197,9 +204,9 @@ public class MACReportAnalyzerTest { } @Test - public void testParseReportWhenMainMassegeHasIncorrectFormat(){ + public void testParseReportWhenMainMassegeHasIncorrectFormat() { MACReportAnalyzer analyzer = new MACReportAnalyzer(); - Map map = analyzer.extractReportData(report5wrongFormatter); + Map map = analyzer.extractReportData(REPORT_WRONG_FORMAT); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -217,7 +224,7 @@ public class MACReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "smack_inode_getxattr"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "SMACK"); - map = analyzer.extractReportData(report7messageIncorrectMessage); + map = analyzer.extractReportData(REPORT_8); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -238,64 +245,9 @@ public class MACReportAnalyzerTest { } @Test - public void testNormalParseReportWithAnalyze(){ - MACReportAnalyzer analyzer = new MACReportAnalyzer(); - Map map = analyzer.extractReportData(report1); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_DEV), "tmpfs"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PATH), "/tmp/wm_start"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_COMM), "bash"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PID), "23926"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM), "bash"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID), "22847"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_D_INST), "1"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_REQUESTED), "r"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_OBJECT), "System"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT), "User"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_WAIT), "no"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "smack_inode_getattr"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "SMACK"); - analyzer.analyze(map, grantedApplicationService); - Assert.assertNotNull(analyzer.getCode()); - Assert.assertEquals(analyzer.getCode(), "1"); - Assert.assertNotNull(analyzer.getTitle()); - Assert.assertEquals(analyzer.getTitle(), "Problem with permissions"); - Assert.assertNotNull(analyzer.getMessage()); - Assert.assertEquals(analyzer.getMessage(), "App \"bash\" try execute \"bash\", but hasn't permissions."); - map = analyzer.extractReportData(report2); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_DEV), "tmpfs"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PATH), "//wm_start"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_COMM), "smack_test"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PID), "25055"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM), "bash"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID), "23926"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_D_INST), "1"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_REQUESTED), "r"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_OBJECT), "System"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT), "User"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_WAIT), "no"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "smack_inode_getxattr"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "SMACK"); - analyzer.analyze(map, grantedApplicationService); - Assert.assertNotNull(analyzer.getCode()); - Assert.assertEquals(analyzer.getCode(), "2"); - Assert.assertNotNull(analyzer.getTitle()); - Assert.assertEquals(analyzer.getTitle(), "Application is not trusted"); - Assert.assertNotNull(analyzer.getMessage()); - Assert.assertEquals(analyzer.getMessage(), "App \"bash\" try execute \"smack_test\", app isn't trusted. Remove it?"); - } - - @Test - public void testNormalParseReportWithNotification(){ + public void testNormalParseReportWithNotification() { MACReportAnalyzer analyzer = new MACReportAnalyzer(); - Map map = analyzer.extractReportData(report1); + Map map = analyzer.extractReportData(REPORT_1); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -322,7 +274,7 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Problem with permissions"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"bash\" try execute \"bash\", but hasn't permissions."); + Assert.assertEquals(notification.getMessage(), "App \"\" try execute \"bash\", but hasn't permissions."); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -330,7 +282,7 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(report2); + map = analyzer.extractReportData(REPORT_2); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -357,7 +309,8 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"bash\" try execute \"smack_test\", app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"wm_start\" try execute \"smack_test\", app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -365,7 +318,7 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(report1audit); + map = analyzer.extractReportData(REPORT_3); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -392,7 +345,8 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"ggggg\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"ggggg\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -400,7 +354,7 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(report2audit); + map = analyzer.extractReportData(REPORT_4); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -427,7 +381,8 @@ public class MACReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); diff --git a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzerTest.java b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzerTest.java index c60bd01..ec16e1e 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzerTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/report/analyzer/impl/SYSCALLReportAnalyzerTest.java @@ -19,98 +19,118 @@ import com.samsung.dsm.service.GrantedApplicationService; @ContextConfiguration(locations = { "classpath:root-context.xml" }) @SuppressWarnings("all") public class SYSCALLReportAnalyzerTest { - private static final String testInputDataBegin = "{" + "\"did\": \"1234\"," + "\"date\": \"12:25 PM; May 08, 2017\"," - + "\"name\": \"syscall\"," + "\"result\": 0," + "\"data\": {log:\""; - private static final String testInputDataEnd = "\"}}"; + private static final String TEST_INPUT_DATA_BEGIN = "{" + "\"did\": \"1234\"," + + "\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"syscall\"," + "\"result\": 0," + + "\"data\": {log:\""; - private static final String report1 = testInputDataBegin + "audit(1500281614.841:722): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; + private static final String TEST_INPUT_DATA_END = "\"}}"; - private static final String report2 = testInputDataBegin + " audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=smack_test name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; - - private static final String report1audit = testInputDataBegin + " audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::ggggg object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=/smack_test/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; - - private static final String report2audit = testInputDataBegin + " audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::smack_test object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; + private static final String SYSCALL_REPORT_1 = TEST_INPUT_DATA_BEGIN + + "audit(1500281614.841:722): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; - private static final String report3 = testInputDataBegin + "[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + testInputDataEnd; + private static final String SYSCALL_REPORT_2 = TEST_INPUT_DATA_BEGIN + + " audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=smack_test name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; - private static final String report4OneString = testInputDataBegin + "[syscall] audit(1500281614.841:722): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]" + testInputDataEnd; + private static final String SYSCALL_REPORT_3 = TEST_INPUT_DATA_BEGIN + + " audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::ggggg object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=/smack_test/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; - private static final String report5wrongFormatter = testInputDataBegin + "[syscall] audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055" + - "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]" + - "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + - "[25055][#2 0xb673bac0 in ??]\n" + testInputDataEnd; + private static final String SYSCALL_REPORT_4 = TEST_INPUT_DATA_BEGIN + + " audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=pkg::smack_test object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=bash name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; - private static final String report6messageInManyRows = testInputDataBegin + "[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied \n" + private static final String SYSCALL_REPORT_5 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + TEST_INPUT_DATA_END; + + private static final String SYSCALL_REPORT_6 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1500281614.841:722): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]" + TEST_INPUT_DATA_END; + + private static final String SYSCALL_REPORT_7 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1500281615.877:723): lsm=syscall fn=syscall_inode_getxattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls name=wm_start path=//wm_start dev=tmpfs ino=18596 user_bt=25055" + + "[25055][#0 0xb667b70c in __GI_lgetxattr () from /usr/lib/libc-2.24.so]" + + "[25055][#1 0x7f0674a4 in syscall_of_file () from /usr/bin/ls]\n" + "[25055][#2 0xb673bac0 in ??]\n" + + TEST_INPUT_DATA_END; + + private static final String SYSCALL_REPORT_8 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied \n" + "mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash \n" - + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + testInputDataEnd; + + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + TEST_INPUT_DATA_END; - private static final String report7messageIncorrectMessage = testInputDataBegin + "\n\n\n\n\n\n \t\t\t\t\t[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied \n" + private static final String SYSCALL_REPORT_9 = TEST_INPUT_DATA_BEGIN + + "\n\n\n\n\n\n \t\t\t\t\t[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied \n" + "mode=enforcing wait=no subject=User object=System=system requested=r d_inst=1 ppid=23926 ppid_comm=bash \n" - + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "\t\t\t[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + testInputDataEnd; + + "pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "\t\t\t[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n" + TEST_INPUT_DATA_END; - private static final String dacReport1 = testInputDataBegin + "[syscall] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String SYSCALL_REPORT_10 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; - private static final String dacReport2 = testInputDataBegin + " \t\t\t\t\t\n\n\n\n [syscall] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String SYSCALL_REPORT_11 = TEST_INPUT_DATA_BEGIN + + " \t\t\t\t\t\n\n\n\n [syscall] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; - private static final String dacReport3 = testInputDataBegin + "[syscall] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String SYSCALL_REPORT_12 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/smack_test subj=User::Shell " + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/smack_test subj=User::Shell " + + TEST_INPUT_DATA_END; - private static final String dacReport4 = testInputDataBegin + "[syscall] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String SYSCALL_REPORT_13 = TEST_INPUT_DATA_BEGIN + + "[syscall] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::smack_test " + testInputDataEnd; + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::smack_test " + + TEST_INPUT_DATA_END; - private static final String dacReport5 = testInputDataBegin + " \t\t\t\t\t\n\n\n\n [syscall] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + private static final String SYSCALL_REPORT_14 = TEST_INPUT_DATA_BEGIN + + " \t\t\t\t\t\n\n\n\n [syscall] \n\n\n\naudit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " - + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=smack_test exe=/usr/bin/ls subj=User::Shell " + testInputDataEnd; - + + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=smack_test exe=/usr/bin/ls subj=User::Shell " + + TEST_INPUT_DATA_END; @Autowired GrantedApplicationService grantedApplicationService; @Test - public void testNormalParseReport(){ + public void testNormalParseReport() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(report1); + Map map = analyzer.extractReportData(SYSCALL_REPORT_1); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -128,7 +148,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "syscall_inode_getattr"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "syscall"); - map = analyzer.extractReportData(report2); + map = analyzer.extractReportData(SYSCALL_REPORT_2); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -146,7 +166,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "syscall_inode_getxattr"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "syscall"); - map = analyzer.extractReportData(report3); + map = analyzer.extractReportData(SYSCALL_REPORT_5); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -167,9 +187,9 @@ public class SYSCALLReportAnalyzerTest { } @Test - public void testParseReportWhenMainMassegeWithTraceIsOneString(){ + public void testParseReportWhenMainMassegeWithTraceIsOneString() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(report4OneString); + Map map = analyzer.extractReportData(SYSCALL_REPORT_6); System.out.println(map); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); @@ -191,9 +211,9 @@ public class SYSCALLReportAnalyzerTest { } @Test - public void testParseReportWhenMainMassegeInManyRows(){ + public void testParseReportWhenMainMassegeInManyRows() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(report6messageInManyRows); + Map map = analyzer.extractReportData(SYSCALL_REPORT_8); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -214,9 +234,9 @@ public class SYSCALLReportAnalyzerTest { } @Test - public void testParseReportWhenMainMassegeHasIncorrectFormat(){ + public void testParseReportWhenMainMassegeHasIncorrectFormat() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(report5wrongFormatter); + Map map = analyzer.extractReportData(SYSCALL_REPORT_7); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -234,7 +254,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "syscall_inode_getxattr"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "syscall"); - map = analyzer.extractReportData(report7messageIncorrectMessage); + map = analyzer.extractReportData(SYSCALL_REPORT_9); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -255,64 +275,9 @@ public class SYSCALLReportAnalyzerTest { } @Test - public void testNormalParseReportWithAnalyze(){ - SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(report1); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_DEV), "tmpfs"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PATH), "/tmp/wm_start"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_COMM), "bash"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PID), "23926"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM), "bash"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID), "22847"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_D_INST), "1"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_REQUESTED), "r"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_OBJECT), "System"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT), "User"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_WAIT), "no"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "syscall_inode_getattr"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "syscall"); - analyzer.analyze(map, grantedApplicationService); - Assert.assertNotNull(analyzer.getCode()); - Assert.assertEquals(analyzer.getCode(), "1"); - Assert.assertNotNull(analyzer.getTitle()); - Assert.assertEquals(analyzer.getTitle(), "Problem with permissions"); - Assert.assertNotNull(analyzer.getMessage()); - Assert.assertEquals(analyzer.getMessage(), "App \"bash\" try execute \"bash\", but hasn't permissions."); - map = analyzer.extractReportData(report2); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_DEV), "tmpfs"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PATH), "//wm_start"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_COMM), "smack_test"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PID), "25055"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID_COMM), "bash"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_PPID), "23926"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_D_INST), "1"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_REQUESTED), "r"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_OBJECT), "System"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_SUBJECT), "User"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_WAIT), "no"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_MODE), "enforcing"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_FN), "syscall_inode_getxattr"); - Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_LSM), "syscall"); - analyzer.analyze(map, grantedApplicationService); - Assert.assertNotNull(analyzer.getCode()); - Assert.assertEquals(analyzer.getCode(), "2"); - Assert.assertNotNull(analyzer.getTitle()); - Assert.assertEquals(analyzer.getTitle(), "Application is not trusted"); - Assert.assertNotNull(analyzer.getMessage()); - Assert.assertEquals(analyzer.getMessage(), "App \"bash\" try execute \"smack_test\", app isn't trusted. Remove it?"); - } - - @Test - public void testNormalParseReportWithNotification(){ + public void testNormalParseReportWithNotification() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(report1); + Map map = analyzer.extractReportData(SYSCALL_REPORT_1); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "23926"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -347,7 +312,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(report2); + map = analyzer.extractReportData(SYSCALL_REPORT_2); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -374,7 +339,8 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute \"smack_test\", app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute \"smack_test\", app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -382,7 +348,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(report1audit); + map = analyzer.extractReportData(SYSCALL_REPORT_3); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -409,7 +375,8 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"ggggg\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"ggggg\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -417,7 +384,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(report2audit); + map = analyzer.extractReportData(SYSCALL_REPORT_4); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_ACTION), "denied"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_USER_BT), "25055"); Assert.assertEquals(map.get(ReportAnalyzerKeys.MAC_REPORT_INO), "18596"); @@ -444,7 +411,8 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -453,11 +421,11 @@ public class SYSCALLReportAnalyzerTest { Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); } - + @Test - public void testExtractReportDataDACReport(){ + public void testExtractReportDataDACReport() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(dacReport1); + Map map = analyzer.extractReportData(SYSCALL_REPORT_10); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -484,7 +452,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_COMM), "ls"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_EXE), "/usr/bin/ls"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SUBJ), "User::Shell"); - map = analyzer.extractReportData(dacReport2); + map = analyzer.extractReportData(SYSCALL_REPORT_11); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -512,11 +480,11 @@ public class SYSCALLReportAnalyzerTest { Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_EXE), "/usr/bin/ls"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SUBJ), "User::Shell"); } - + @Test - public void testCreateNotification(){ + public void testCreateNotification() { SYSCALLReportAnalyzer analyzer = new SYSCALLReportAnalyzer(); - Map map = analyzer.extractReportData(dacReport3); + Map map = analyzer.extractReportData(SYSCALL_REPORT_12); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -552,7 +520,8 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"Shell\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"Shell\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -560,7 +529,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(dacReport4); + map = analyzer.extractReportData(SYSCALL_REPORT_13); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -596,7 +565,8 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute command, app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); @@ -604,7 +574,7 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getPolicy()); Assert.assertEquals(notification.getPolicy(), "defaultPolicy"); Assert.assertNotNull(notification.getCurrentTime()); - map = analyzer.extractReportData(dacReport5); + map = analyzer.extractReportData(SYSCALL_REPORT_14); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_ARCH), "40000028"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_SYSCALL), "5"); Assert.assertEquals(map.get(ReportAnalyzerKeys.DAC_REPORT_PER), "800000"); @@ -640,7 +610,8 @@ public class SYSCALLReportAnalyzerTest { Assert.assertNotNull(notification.getTitle()); Assert.assertEquals(notification.getTitle(), "Application is not trusted"); Assert.assertNotNull(notification.getMessage()); - Assert.assertEquals(notification.getMessage(), "App \"smack_test\" try execute \"/usr/bin/ls\", app isn't trusted. Remove it?"); + Assert.assertEquals(notification + .getMessage(), "App \"smack_test\" try execute \"/usr/bin/ls\", app isn't trusted. Remove it?"); Assert.assertNotNull(notification.getCloudUserId()); Assert.assertEquals(notification.getCloudUserId(), "cloudUserId"); Assert.assertNotNull(notification.getDeviceId()); diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/DeviceApiTest.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/DeviceApiTest.java index aa9b892..3fe6f56 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/DeviceApiTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/DeviceApiTest.java @@ -34,11 +34,9 @@ import com.samsung.commons.service.RoleService; import com.samsung.commons.service.UserService; import com.samsung.dsm.utils.JsonUtils; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration - public class DeviceApiTest { private static final String PARENT_UUID = "parentUuid"; @@ -73,7 +71,8 @@ public class DeviceApiTest { User user = userService.getUserByEmail("admin@samsung.com"); // Device with agent - Device device = new Device("1234", "s8", "phone", "samsung s8 edge", 1, policyService.initPolicy(), user, PARENT_UUID); + Device device = new Device("1234", "s8", "phone", "samsung s8 edge", 1, policyService + .initPolicy(), user, PARENT_UUID); List agents = new ArrayList<>(); Agent agent = new Agent("5678", "name1", policyService.initPolicy()); @@ -83,9 +82,14 @@ public class DeviceApiTest { device.setUser(user); devices.add(deviceService.save(device)); - devices.add(deviceService.save(new Device("1235", "s4", "phone", "samsung s7 edge", 1, policyService.initPolicy(), user, PARENT_UUID))); - devices.add(deviceService.save(new Device("1236", "airconditioner samsung", "airconditioner", "AR12JSFSRWK", 1, policyService.initPolicy(), user, false, PARENT_UUID))); - devices.add(deviceService.save(new Device("1237", "vacuum cleaner samsung", "vacuum cleaner", "FY128192JJJ", 1, policyService.initPolicy(), user, true, PARENT_UUID))); + devices.add(deviceService.save(new Device("1235", "s4", "phone", "samsung s7 edge", 1, policyService + .initPolicy(), user, PARENT_UUID))); + devices.add(deviceService + .save(new Device("1236", "airconditioner samsung", "airconditioner", "AR12JSFSRWK", 1, policyService + .initPolicy(), user, false, PARENT_UUID))); + devices.add(deviceService + .save(new Device("1237", "vacuum cleaner samsung", "vacuum cleaner", "FY128192JJJ", 1, policyService + .initPolicy(), user, true, PARENT_UUID))); // User without devices userService.save(new User("another", "another@samsung.com", false, new Date(), roleService.findById(1L))); @@ -106,7 +110,8 @@ public class DeviceApiTest { public void deviceByUUIDOk() throws Exception { ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1234")).andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); - assertTrue(JsonUtils.equalJson(content, "{\"uuid\":\"1234\",\"name\":\"s8\",\"type\":\"phone\",\"model\":\"samsung s8 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}")); + assertTrue(JsonUtils + .equalJson(content, "{\"uuid\":\"1234\",\"name\":\"s8\",\"type\":\"phone\",\"model\":\"samsung s8 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}")); } @Test @@ -118,25 +123,26 @@ public class DeviceApiTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void findByCloudUserUuidOk() throws Exception { - ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1234/byCloudUserUuid")).andExpect(status().isOk()); + ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1234/byCloudUserUuid")) + .andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); - assertTrue(JsonUtils.equalJsonArrays(content, - "[{\"uuid\":\"1234\",\"name\":\"s8\",\"type\":\"phone\",\"model\":\"samsung s8 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}," + - "{\"uuid\":\"1235\",\"name\":\"s4\",\"type\":\"phone\",\"model\":\"samsung s7 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}," + - "{\"uuid\":\"1236\",\"name\":\"airconditioner samsung\",\"type\":\"airconditioner\",\"model\":\"AR12JSFSRWK\",\"status\":1,\"parentUuid\":\"parentUuid\"}]")); + assertTrue(JsonUtils + .equalJsonArrays(content, "[{\"uuid\":\"1234\",\"name\":\"s8\",\"type\":\"phone\",\"model\":\"samsung s8 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}," + + "{\"uuid\":\"1235\",\"name\":\"s4\",\"type\":\"phone\",\"model\":\"samsung s7 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}," + + "{\"uuid\":\"1236\",\"name\":\"airconditioner samsung\",\"type\":\"airconditioner\",\"model\":\"AR12JSFSRWK\",\"status\":1,\"parentUuid\":\"parentUuid\"}]")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") - public void findByCloudUserNotFound() throws Exception{ - mockMvc.perform(get(ROOT_URL + "/device/5678/byCloudUserUuid")) - .andExpect(status().isNotFound()); + public void findByCloudUserNotFound() throws Exception { + mockMvc.perform(get(ROOT_URL + "/device/5678/byCloudUserUuid")).andExpect(status().isNotFound()); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void findByCloudUserUuidEmptyDeviceList() throws Exception { - ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1235/byCloudUserUuid")).andExpect(status().isOk()); + ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1235/byCloudUserUuid")) + .andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); assertEquals("[]", content); } @@ -165,7 +171,7 @@ public class DeviceApiTest { ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1234/policy")).andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); - assertEquals("[{\"group\": \"tv-extension\",\"policies\": [{\"name\": \"sound\",\"state\": 1,\"items\": []},{\"name\": \"bluetooth\",\"state\": 1,\"items\": []},{\"name\": \"wifi\",\"state\": 1,\"items\": []},{\"name\": \"usb\",\"state\": 1,\"items\": []},{\"name\": \"dtv-tunner\",\"state\": 1,\"items\": []},{\"name\": \"iptables\",\"state\": 1,\"items\": [\"*:www.naver.com:*\",\"*:www.google.com:*\"]}]}]",content); + assertEquals("[{\"group\": \"tv-extension\",\"policies\": [{\"name\": \"sound\",\"state\": 1,\"items\": []},{\"name\": \"bluetooth\",\"state\": 1,\"items\": []},{\"name\": \"wifi\",\"state\": 1,\"items\": []},{\"name\": \"usb\",\"state\": 1,\"items\": []},{\"name\": \"dtv-tunner\",\"state\": 1,\"items\": []},{\"name\": \"iptables\",\"state\": 1,\"items\": [\"*:www.naver.com:*\",\"*:www.google.com:*\"]}]}]", content); } @Test @@ -174,7 +180,7 @@ public class DeviceApiTest { ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1237/policy")).andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); - assertEquals("[{\"group\": \"tv-extension\",\"policies\": [{\"name\": \"sound\",\"state\": 1,\"items\": []},{\"name\": \"bluetooth\",\"state\": 1,\"items\": []},{\"name\": \"wifi\",\"state\": 1,\"items\": []},{\"name\": \"usb\",\"state\": 1,\"items\": []},{\"name\": \"dtv-tunner\",\"state\": 1,\"items\": []},{\"name\": \"iptables\",\"state\": 1,\"items\": [\"*:www.naver.com:*\",\"*:www.google.com:*\"]}]}]",content); + assertEquals("[{\"group\": \"tv-extension\",\"policies\": [{\"name\": \"sound\",\"state\": 1,\"items\": []},{\"name\": \"bluetooth\",\"state\": 1,\"items\": []},{\"name\": \"wifi\",\"state\": 1,\"items\": []},{\"name\": \"usb\",\"state\": 1,\"items\": []},{\"name\": \"dtv-tunner\",\"state\": 1,\"items\": []},{\"name\": \"iptables\",\"state\": 1,\"items\": [\"*:www.naver.com:*\",\"*:www.google.com:*\"]}]}]", content); } @Test diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/IotCloudApiTest.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/IotCloudApiTest.java index 2ddfbd8..15be70f 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/IotCloudApiTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/IotCloudApiTest.java @@ -20,11 +20,9 @@ import org.springframework.web.context.WebApplicationContext; import com.samsung.commons.service.IotCloudService; import com.samsung.dsm.rest.iotcloud.IotCloudApi; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration - public class IotCloudApiTest { private final String ROOT_URL = "/restapi"; @@ -58,17 +56,15 @@ public class IotCloudApiTest { public void createAndSaveIotCloudUserConflict() throws Exception { normalUser(); - mockMvc.perform(get(ROOT_URL + "/iotcloud/createUser") - .param("email", "admin@samsung.com") - .param("uuid", "1234567890")) - .andExpect(status().isConflict()); + mockMvc.perform(get(ROOT_URL + "/iotcloud/createUser").param("email", "admin@samsung.com") + .param("uuid", "1234567890")).andExpect(status().isConflict()); } @Test public void createAndSaveIotCloudUserAndRemove() { IotCloudService iotCloudService = Mockito.mock(IotCloudService.class); IotCloudApi iotCloudApi = new IotCloudApi(); - iotCloudApi.deleteUser("1111");//Check for exception + iotCloudApi.deleteUser("1111");// Check for exception iotCloudApi.setIotCloudService(iotCloudService); iotCloudApi.deleteUser("1111"); } @@ -78,18 +74,14 @@ public class IotCloudApiTest { public void createAndSaveIotCloudUserNotFound() throws Exception { @SuppressWarnings("unused") ResultActions result = mockMvc.perform(get(ROOT_URL + "/iotcloud/createUser") - .param("email", "some-email@example.com") - .param("uuid", "1234567890")) - .andExpect(status().isNotFound()); + .param("email", "some-email@example.com").param("uuid", "1234567890")).andExpect(status().isNotFound()); } @SuppressWarnings("PMD.SignatureDeclareThrowsException") private void normalUser() throws Exception { @SuppressWarnings("unused") ResultActions result = mockMvc.perform(get(ROOT_URL + "/iotcloud/createUser") - .param("email", "admin@samsung.com") - .param("uuid", "1234567890")) - .andExpect(status().isOk()); + .param("email", "admin@samsung.com").param("uuid", "1234567890")).andExpect(status().isOk()); } } \ No newline at end of file diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/PolicyApiTest.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/PolicyApiTest.java index c3bf86e..1da8fc4 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/PolicyApiTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/PolicyApiTest.java @@ -34,11 +34,9 @@ import com.samsung.commons.service.PolicyService; import com.samsung.commons.service.UserService; import com.samsung.dsm.utils.JsonUtils; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration - public class PolicyApiTest { private final String ROOT_URL = "/restapi"; @@ -92,24 +90,22 @@ public class PolicyApiTest { ResultActions result = mockMvc.perform(get(ROOT_URL + "/device/1234")).andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); - assertTrue(JsonUtils.equalJson(content, "{\"uuid\":\"1234\",\"name\":\"s8\",\"type\":\"phone\",\"model\":\"samsung s8 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}")); + assertTrue(JsonUtils + .equalJson(content, "{\"uuid\":\"1234\",\"name\":\"s8\",\"type\":\"phone\",\"model\":\"samsung s8 edge\",\"status\":1,\"parentUuid\":\"parentUuid\"}")); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void findByUUIDNotFound() throws Exception { - mockMvc.perform(get(ROOT_URL + "/policy/device/dev-unexistent-uuid/agent/agent-unexistent-uuid")).andExpect(status().isNotFound()); + mockMvc.perform(get(ROOT_URL + "/policy/device/dev-unexistent-uuid/agent/agent-unexistent-uuid")) + .andExpect(status().isNotFound()); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void findByUUID() throws Exception { - String content = mockMvc.perform( - get(ROOT_URL + format("/policy/device/%s/agent/%s", "1234", "5678"))) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + String content = mockMvc.perform(get(ROOT_URL + format("/policy/device/%s/agent/%s", "1234", "5678"))) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); assertThat(content, is("[{\"group\": \"tv-extension\",\"policies\": [{\"name\": \"sound\",\"state\": 1,\"items\": []}," + "{\"name\": \"bluetooth\",\"state\": 1,\"items\": []},{\"name\": \"wifi\",\"state\": 1,\"items\": []},{\"name\": \"usb\",\"state\": 1,\"items\": []}," @@ -119,22 +115,14 @@ public class PolicyApiTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void requestPolicy() throws Exception { - mockMvc.perform( - get(ROOT_URL + format("/policy/request/%s/device/%s", policy.getId(), "1234"))) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + mockMvc.perform(get(ROOT_URL + format("/policy/request/%s/device/%s", policy.getId(), "1234"))) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void requestAgentPolicy() throws Exception { - mockMvc.perform( - get(ROOT_URL + format("/policy/request/%s/agent/%s", policy.getId(), agent.getUuid()))) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(); + mockMvc.perform(get(ROOT_URL + format("/policy/request/%s/agent/%s", policy.getId(), agent.getUuid()))) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); } } \ No newline at end of file diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/ReportApiTest.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/ReportApiTest.java index b6764cf..4e26296 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/ReportApiTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/ReportApiTest.java @@ -29,90 +29,94 @@ import com.samsung.commons.service.PolicyService; import com.samsung.commons.service.ReportService; import com.samsung.commons.service.UserService; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration @SuppressWarnings("all") public class ReportApiTest { - private static final String testInputData = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\",\"name\": \"sim\",\"result\": 0,\"data\": {}}"; + private static final String TEST_REPORT = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\",\"name\": \"sim\",\"result\": 0,\"data\": {}}"; - private static final String testInputDataBegin = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + private static final String TEST_INPUT_DATA_BEGIN = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"smack\",\"result\": 0,\"data\": {log=\""; - private static final String testInputDataEnd = "\"}}"; - - private static final String report = testInputDataBegin + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; - - private static final String reportAuditTrailSmack1 = testInputDataBegin + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=smack_test pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; - - private static final String reportAuditTrailSmack2 = testInputDataBegin + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=smack_test path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; - - private static final String reportAuditTrailSmack3 = testInputDataBegin + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=pkg:com::smack_test object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; - - private static final String reportAuditTrailSmack4 = testInputDataBegin + "[MAC] audit(1500281614.841:722): lsm=SMACK fn= action= mode= wait=no subject=pkg:com::smack_test object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + - "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + - "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + - "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + - "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + - "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + - "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + - "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + - "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + testInputDataEnd; - - private static final String dacReport1 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + private static final String TEST_INPUT_DATA_END = "\"}}"; + + private static final String REPORT_1 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; + + private static final String REPORT_2 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=smack_test pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; + + private static final String REPORT_3 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=smack_test path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; + + private static final String REPORT_4 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281614.841:722): lsm=SMACK fn=smack_inode_getattr action=denied mode=enforcing wait=no subject=pkg:com::smack_test object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; + + private static final String REPORT_5 = TEST_INPUT_DATA_BEGIN + + "[MAC] audit(1500281614.841:722): lsm=SMACK fn= action= mode= wait=no subject=pkg:com::smack_test object=System requested=r d_inst=1 ppid=22847 ppid_comm=bash pid=23926 comm=bash path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=23926\n" + + "[23926][#0 0x429b5e3c in ___xstat64 () from /usr/lib/libc-2.24.so]\n" + + "[23926][#1 0x0006b439 in append_to_match () from /usr/bin/bash]\n" + + "[23926][#2 0x0006cda9 in rl_complete_internal () from /usr/bin/bash]\n" + + "[23926][#3 0x00067385 in _rl_dispatch_subseq () from /usr/bin/bash]\n" + + "[23926][#4 0x00067543 in readline_internal_char () from /usr/bin/bash]\n" + + "[23926][#5 0x000679f7 in readline () from /usr/bin/bash]\n" + + "[23926][#6 0x00026e1b in yy_readline_get () from /usr/bin/bash]\n" + + "[23926][#7 0x0002860d in shell_getc () from /usr/bin/bash]\n" + TEST_INPUT_DATA_END; + + private static final String REPORT_6 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"dac\",\"result\": 0,\"data\": {log=\"[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell \"}}"; - - private static final String dacReport2 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + + private static final String REPORT_7 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"dac\",\"result\": 0,\"data\": {log=\"[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell \"}}"; - - private static final String dacReport3 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + + private static final String REPORT_8 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + "\"name\": \"dac\",\"result\": 0,\"data\": {log=\"[DAC] audit(1505216628.914:62): arch=40000028 syscall=5 per=800000 success=no exit=-13 " + "a0=b7e3c6a0 a1=a4800 a2=b6ef84d0 a3=2f items=1 ppid=1001 pid=1005 auid=4294967295 uid=5001 gid=100 euid=5001 suid=5001 " + "fsuid=5001 egid=100 sgid=100 fsgid=100 ses=4294967295 tty=pts1 comm=ls exe=/usr/bin/ls subj=User::Shell \"}}"; - - private static final String syscallReport = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," - + "\"name\": \"syscall\",\"result\": 0,\"data\": {log=\"[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + - "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + - "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + - "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n\"}}"; + + private static final String REPORT_9 = "{\"did\": \"1234\",\"date\": \"12:25 PM; May 08, 2017\"," + + "\"name\": \"syscall\",\"result\": 0,\"data\": {log=\"[syscall] audit(1500281615.877:724): lsm=syscall fn=syscall_inode_getattr action=denied mode=enforcing wait=no subject=User object=System requested=r d_inst=1 ppid=23926 ppid_comm=bash pid=25055 comm=ls path=/tmp/wm_start dev=tmpfs ino=18596 user_bt=25055\n" + + "[25055][#0 0xb666aecc in ___lxstat64 () from /usr/lib/libc-2.24.so]\n" + + "[25055][#1 0x7f06c52c in gobble_file () from /usr/bin/ls]\n" + + "[25055][#2 0x7f0685a8 in main () from /usr/bin/ls]\n\"}}"; private MockMvc mockMvc; private long reportId1; @@ -121,8 +125,6 @@ public class ReportApiTest { private long reportAuditTrailSmack2Id; private long reportAuditTrailSmack3Id; private long reportAuditTrailSmack4Id; - - @Autowired private WebApplicationContext webApplicationContext; @@ -150,23 +152,30 @@ public class ReportApiTest { iotCloudService.createAndSaveUser("admin@samsung.com", "1234"); User user = userService.findByUsername("admin"); - Device device = new Device("1234", "s4", "phone", "samsung s7 edge", 1, policyService.initPolicy(), user, "parentUuid"); + Device device = new Device("1234", "s4", "phone", "samsung s7 edge", 1, policyService + .initPolicy(), user, "parentUuid"); deviceService.save(device); - - Device deviceForAudit = new Device("4321", "s4", "phone", "samsung s7 edge", 1, policyService.initPolicy(), user, "parentUuid"); + + Device deviceForAudit = new Device("4321", "s4", "phone", "samsung s7 edge", 1, policyService + .initPolicy(), user, "parentUuid"); deviceService.save(deviceForAudit); ReportType reportType = reportTypeRepository.findByType(ReportType.Type.DAC.type); reportService.save(new Report(reportType, "report1", "12/11/2016", 1, device)); reportService.save(new Report(reportType, "report2", "13/12/2017", 2, device)); - reportId1 = reportService.save(new Report(reportType, testInputData, "13/12/2017", 2, device)).getId(); - reportId2 = reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), report, "13/12/2017", 2, device)).getId(); - - reportAuditTrailSmack1Id = reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack1, "13/12/2017", 2, deviceForAudit)).getId(); - reportAuditTrailSmack2Id = reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack2, "13/12/2017", 2, deviceForAudit)).getId(); - reportAuditTrailSmack3Id = reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack3, "13/12/2017", 2, deviceForAudit)).getId(); - reportAuditTrailSmack4Id = reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack4, "13/12/2017", 2, deviceForAudit)).getId(); + reportId1 = reportService.save(new Report(reportType, TEST_REPORT, "13/12/2017", 2, device)).getId(); + reportId2 = reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_1, "13/12/2017", 2, device)).getId(); + + reportAuditTrailSmack1Id = reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_2, "13/12/2017", 2, deviceForAudit)).getId(); + reportAuditTrailSmack2Id = reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_3, "13/12/2017", 2, deviceForAudit)).getId(); + reportAuditTrailSmack3Id = reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_4, "13/12/2017", 2, deviceForAudit)).getId(); + reportAuditTrailSmack4Id = reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_5, "13/12/2017", 2, deviceForAudit)).getId(); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @@ -190,7 +199,7 @@ public class ReportApiTest { + "\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"}]}"), content); } - private String strip(String str){ + private String strip(String str) { System.out.println(str.replace("\n", "").replace("\b", "").replace("\t", "").replace("\r", "")); return str.replace("\n", "").replace("\b", "").replace("\t", "").replace("\r", ""); } @@ -207,7 +216,7 @@ public class ReportApiTest { public void newReportNotificationWrongReport() throws Exception { mockMvc.perform(get("/restapi/report/newreport/" + reportId1)).andExpect(status().isOk()); } - + @Test public void newReportNotification() throws Exception { mockMvc.perform(get("/restapi/report/newreport/" + reportId2)).andExpect(status().isOk()); @@ -224,116 +233,153 @@ public class ReportApiTest { @Test public void reportByDeviceUUIDOkForAuditTrail() throws Exception { User user = userService.findByUsername("admin"); - Device deviceForAuditTrail = new Device("111111111", "s4", "phone", "samsung s7 edge", 1, policyService.initPolicy(), user, "parentUuid"); + Device deviceForAuditTrail = new Device("111111111", "s4", "phone", "samsung s7 edge", 1, policyService + .initPolicy(), user, "parentUuid"); deviceService.save(deviceForAuditTrail); - //SMACK - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack3, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack4, "13/12/2017", 2, deviceForAuditTrail)); - - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack3, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack4, "13/12/2017", 2, deviceForAuditTrail)); - - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack3, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SMACK.type), reportAuditTrailSmack4, "13/12/2017", 2, deviceForAuditTrail)); - - //DAC - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport3, "13/12/2017", 2, deviceForAuditTrail)); - - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport3, "13/12/2017", 2, deviceForAuditTrail)); - - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport3, "13/12/2017", 2, deviceForAuditTrail)); - - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport1, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport2, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.DAC.type), dacReport3, "13/12/2017", 2, deviceForAuditTrail)); - - //SYSCALL - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); - reportService.save(new Report(reportTypeRepository.findByType(ReportType.Type.SYSCALL.type), syscallReport, "13/12/2017", 2, deviceForAuditTrail)); + // SMACK + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_2, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_3, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_4, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_5, "13/12/2017", 2, deviceForAuditTrail)); + + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_2, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_3, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_4, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_5, "13/12/2017", 2, deviceForAuditTrail)); + + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_2, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_3, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_4, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SMACK.type), REPORT_5, "13/12/2017", 2, deviceForAuditTrail)); + + // DAC + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_6, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_7, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_8, "13/12/2017", 2, deviceForAuditTrail)); + + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_6, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_7, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_8, "13/12/2017", 2, deviceForAuditTrail)); + + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_6, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_7, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_8, "13/12/2017", 2, deviceForAuditTrail)); + + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_6, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_7, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.DAC.type), REPORT_8, "13/12/2017", 2, deviceForAuditTrail)); + + // SYSCALL + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); + reportService.save(new Report(reportTypeRepository + .findByType(ReportType.Type.SYSCALL.type), REPORT_9, "13/12/2017", 2, deviceForAuditTrail)); ResultActions result = mockMvc.perform(get("/restapi/report/111111111")).andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); - System.out.println("-------------------------------------------------------------------------------------------------"); + System.out + .println("-------------------------------------------------------------------------------------------------"); System.out.println(content); - System.out.println("-------------------------------------------------------------------------------------------------"); + System.out + .println("-------------------------------------------------------------------------------------------------"); System.out.println(); - assertEquals(strip("{" - + "\"syscall\":[" - + "{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\"," - + "\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\"," - + "\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," - + "\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\"," - + "\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\"," - + "\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\"," - + "\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"}," - + "{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\"," - + "\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\"," - + "\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\"," - + "\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\"," - + "\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\"," - + "\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\"," - + "\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\"," - + "\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\"," - + "\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\"," - + "\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\"," - + "\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"}]," - + "\"dac\":[{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\"," - + "\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\"," - + "\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\"," - + "\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\"," - + "\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\"," - + "\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\"," - + "\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\"," - + "\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\"," - + "\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"}," - + "{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\"," - + "\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\"," - + "\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\"," - + "\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\"," - + "\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\"," - + "\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\"," - + "\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\"," - + "\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\"," - + "\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\"," - + "\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\"," - + "\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\"," - + "\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\"," - + "\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"}]," - + "\"smack\":[{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," - + "\"dev\":\"tmpfs\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\"," - + "\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\"," - + "\"wait\":\"no\",\"comm\":\"smack_test\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\"," - + "\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"smack_test\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\"," - + "\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"}," - + "{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," - + "\"dev\":\"tmpfs\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\"," - + "\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\"," - + "\"comm\":\"smack_test\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," - + "\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"smack_test\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\"," - + "\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\"," - + "\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\"," - + "\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\"," - + "\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"}]}"), content); + assertEquals(strip("{" + "\"syscall\":[" + + "{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\"," + + "\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\"," + + "\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," + + "\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\"," + + "\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\"," + + "\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\"," + + "\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"}," + + "{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\"," + + "\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\"," + + "\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\"," + + "\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\"," + + "\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\"," + + "\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\"," + + "\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\"," + + "\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\",\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\"," + + "\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"ls\",\"subject\":\"User\"," + + "\"lsm\":\"syscall\",\"fn\":\"syscall_inode_getattr\",\"pid\":\"25055\",\"ino\":\"18596\",\"ppid\":\"23926\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\"," + + "\"action\":\"denied\",\"user_bt\":\"25055\",\"object\":\"System\"}]," + + "\"dac\":[{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\"," + + "\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\"," + + "\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\"," + + "\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\"," + + "\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\"," + + "\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\"," + + "\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\"," + + "\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\"," + + "\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"}," + + "{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\"," + + "\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\"," + + "\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\"," + + "\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\"," + + "\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\"," + + "\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\"," + + "\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\",\"exe\":\"/usr/bin/ls\"," + + "\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\"," + + "\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\",\"egid\":\"100\"," + + "\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\",\"a1\":\"a4800\",\"fsuid\":\"5001\"," + + "\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"},{\"date\":\"13/12/2017\",\"syscall\":\"5\",\"gid\":\"100\",\"fsgid\":\"100\",\"pid\":\"1005\",\"suid\":\"5001\",\"uid\":\"5001\"," + + "\"egid\":\"100\",\"exe\":\"/usr/bin/ls\",\"sgid\":\"100\",\"per\":\"800000\",\"subj\":\"User::Shell\",\"ses\":\"4294967295\",\"auid\":\"4294967295\",\"comm\":\"ls\",\"euid\":\"5001\",\"a0\":\"b7e3c6a0\",\"ppid\":\"1001\"," + + "\"a1\":\"a4800\",\"fsuid\":\"5001\",\"exit\":\"-13\",\"a2\":\"b6ef84d0\",\"a3\":\"2f\",\"success\":\"no\",\"tty\":\"pts1\",\"arch\":\"40000028\",\"items\":\"1\"}]," + + "\"smack\":[{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," + + "\"dev\":\"tmpfs\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\"," + + "\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\"," + + "\"wait\":\"no\",\"comm\":\"smack_test\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\"," + + "\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"smack_test\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\"," + + "\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"}," + + "{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," + + "\"dev\":\"tmpfs\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\"," + + "\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\"," + + "\"comm\":\"smack_test\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\"," + + "\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"smack_test\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"User\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\"," + + "\"ino\":\"18596\",\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\"," + + "\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"pid\":\"23926\",\"ino\":\"18596\",\"ppid\":\"22847\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\"," + + "\"user_bt\":\"23926\",\"object\":\"System\"},{\"ppid_comm\":\"bash\",\"date\":\"13/12/2017\",\"wait\":\"no\",\"comm\":\"bash\",\"subject\":\"pkg:com::smack_test\",\"lsm\":\"SMACK\",\"fn\":\"smack_inode_getattr\",\"pid\":\"23926\",\"ino\":\"18596\"," + + "\"ppid\":\"22847\",\"mode\":\"enforcing\",\"d_inst\":\"1\",\"path\":\"/tmp/wm_start\",\"requested\":\"r\",\"dev\":\"tmpfs\",\"action\":\"denied\",\"user_bt\":\"23926\",\"object\":\"System\"}]}"), content); } } \ No newline at end of file diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/accesstoken/AccessTokenApiTest.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/accesstoken/AccessTokenApiTest.java index cb88fb8..cbccce2 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/accesstoken/AccessTokenApiTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/accesstoken/AccessTokenApiTest.java @@ -37,9 +37,8 @@ import com.samsung.commons.domain.User; import com.samsung.commons.service.UserService; import com.samsung.dsm.service.AccessTokenService; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @WebAppConfiguration public class AccessTokenApiTest { @@ -81,7 +80,7 @@ public class AccessTokenApiTest { } @Test - public void getUserDetailsByAccessTokenNoUser() { + public void getUserDetailsByAccessTokenNoUser() { AccessTokenApi accessTokenApi = setupAccessTokenApi(() -> { Authentication auth = mock(Authentication.class); when(auth.getName()).thenReturn("admin"); @@ -97,11 +96,9 @@ public class AccessTokenApiTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void loginOk() throws Exception { - ResultActions result = - mockMvc.perform(get(ROOT_URL + "/login") - .param("login", "admin@samsung.com") - .param("password", "111111")) - .andExpect(status().isOk()); + ResultActions result = mockMvc + .perform(get(ROOT_URL + "/login").param("login", "admin@samsung.com").param("password", "111111")) + .andExpect(status().isOk()); String content = result.andReturn().getResponse().getContentAsString(); assertThat(content, not(isEmptyString())); @@ -110,25 +107,22 @@ public class AccessTokenApiTest { @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void accessTokenFailed() throws Exception { - mockMvc.perform(get(ROOT_URL + "/access_token") - .param("access_token", "bad-token")) + mockMvc.perform(get(ROOT_URL + "/access_token").param("access_token", "bad-token")) .andExpect(status().isUnauthorized()); } @Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void loginFailed() throws Exception { - ResultActions result = - mockMvc.perform(get(ROOT_URL + "/login") - .param("login", "non-existent-client-id") - .param("password", "non-existent-secret")) - .andExpect(status().isUnauthorized()); + ResultActions result = mockMvc.perform(get(ROOT_URL + "/login").param("login", "non-existent-client-id") + .param("password", "non-existent-secret")).andExpect(status().isUnauthorized()); String content = result.andReturn().getResponse().getContentAsString(); assertThat(content, isEmptyString()); } - private static AccessTokenApi setupAccessTokenApi(Supplier supplierAuth, Supplier supplierUser) { + private static AccessTokenApi setupAccessTokenApi(Supplier supplierAuth, + Supplier supplierUser) { AccessTokenService accessTokenService = mock(AccessTokenService.class); UserService userService = mock(UserService.class); @@ -143,9 +137,9 @@ public class AccessTokenApiTest { return accessTokenApi; } - + @Test - public void testException(){ + public void testException() { AccessTokenApi accessTokenApi = new AccessTokenApi(); ResponseEntity response = accessTokenApi.getUserDetailsByAccessToken("access_token"); assertTrue(response.getStatusCode().equals(UNAUTHORIZED)); diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderImplMock.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderImplMock.java index 5b94d8f..3ff6698 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderImplMock.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderImplMock.java @@ -4,24 +4,26 @@ import com.samsung.commons.model.MQPolicy; import com.samsung.commons.model.Notification; public class MQSenderImplMock extends MQSenderImpl { - - MQSenderImplMock(String host){ + + MQSenderImplMock(String host) { super(host); } @Override public boolean sendNotification(Notification notification) { - try{ + try { super.sendNotification(notification); - }catch(Exception e){} + } catch (Exception e) { + } return true; } @Override public boolean sendPolicy(MQPolicy policy) { - try{ + try { super.sendPolicy(policy); - }catch(Exception e){} + } catch (Exception e) { + } return true; } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderTest.java b/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderTest.java index 8ef24af..1919133 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/rest/mq/MQSenderTest.java @@ -63,8 +63,8 @@ public class MQSenderTest { private MQSender setupSender(HttpStatus status, String host) { MQSenderImpl mqSender = new MQSenderImpl(host); RestTemplate restTemplate = mock(RestTemplate.class); - when(restTemplate.exchange(any(), any(), any(), Mockito.eq(ResponseEntity.class))).thenReturn( - new ResponseEntity<>(status)); + when(restTemplate.exchange(any(), any(), any(), Mockito.eq(ResponseEntity.class))) + .thenReturn(new ResponseEntity<>(status)); Whitebox.setInternalState(mqSender, "restTemplate", restTemplate); return mqSender; diff --git a/servers/dsm/src/test/java/com/samsung/dsm/service/AccessTokenServiceTest.java b/servers/dsm/src/test/java/com/samsung/dsm/service/AccessTokenServiceTest.java index 1b77f08..c5ed083 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/service/AccessTokenServiceTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/service/AccessTokenServiceTest.java @@ -36,7 +36,7 @@ import com.samsung.dsm.service.impl.AccessTokenServiceImpl; */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) public class AccessTokenServiceTest { private static final String accessToken = "Access token"; @@ -88,13 +88,8 @@ public class AccessTokenServiceTest { } private OAuthAccessToken createToken() { - return new OAuthAccessToken( - "Token identifier 1", - accessToken.getBytes(), - "Authentication Id 1", - "User name 1", - "Client 1", - "Client 1".getBytes(), - "refresh token 1"); + return new OAuthAccessToken("Token identifier 1", accessToken + .getBytes(), "Authentication Id 1", "User name 1", "Client 1", "Client 1" + .getBytes(), "refresh token 1"); } } diff --git a/servers/dsm/src/test/java/com/samsung/dsm/service/impl/GrantedApplicationServiceTest.java b/servers/dsm/src/test/java/com/samsung/dsm/service/impl/GrantedApplicationServiceTest.java index 6e4d2ad..f7decd5 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/service/impl/GrantedApplicationServiceTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/service/impl/GrantedApplicationServiceTest.java @@ -16,7 +16,7 @@ import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(locations = {"classpath:root-context.xml"}) +@ContextConfiguration(locations = { "classpath:root-context.xml" }) @Transactional public class GrantedApplicationServiceTest { diff --git a/servers/dsm/src/test/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceTest.java b/servers/dsm/src/test/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceTest.java index 2595bea..00ded18 100644 --- a/servers/dsm/src/test/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceTest.java +++ b/servers/dsm/src/test/java/com/samsung/dsm/service/impl/OAuth2AuthorizationServiceTest.java @@ -56,8 +56,7 @@ public class OAuth2AuthorizationServiceTest { public void before() { initMocks(this); - service = new OAuth2AuthorizationServiceImpl( - authenticationManager, clientDetailsService, oauth2RequestFactory, authCodeServices); + service = new OAuth2AuthorizationServiceImpl(authenticationManager, clientDetailsService, oauth2RequestFactory, authCodeServices); } @SuppressWarnings("unchecked") -- 2.7.4