diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml index 77b350f807..c7411ff8b0 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml @@ -22,13 +22,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.annotations - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - API Management Annotations WSO2 Carbon - API Management Custom Annotation Module diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml index c1e8e0fb50..f75231d8d5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -21,12 +21,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT org.wso2.carbon.apimgt.application.extension.api war WSO2 Carbon - API Application Management API diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml index 45835dd02a..1f1bfd05c9 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml @@ -22,12 +22,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT org.wso2.carbon.apimgt.application.extension bundle WSO2 Carbon - API Application Management diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml index 526508155b..15e6a11f22 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml @@ -21,13 +21,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.handlers - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - API Security Handler Component WSO2 Carbon - API Management Security Handler Module diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml index 00ad78ac2c..b29c2947c5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml @@ -13,13 +13,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.client - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - API Management Integration Client WSO2 Carbon - API Management Integration Client diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml index 2788aa93cc..072a0495c1 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml @@ -13,13 +13,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.generated.client - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - API Management Integration Generated Client WSO2 Carbon - API Management Integration Client diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index f5e3dc3e69..70a93b8e21 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -22,13 +22,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - API Management Webapp Publisher WSO2 Carbon - API Management Webapp Publisher diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index a3f8608de4..e1f2195282 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -276,7 +276,7 @@ public class APIPublisherUtil { if(null != resourcesList) { for (ApiUriTemplate template : templates) { String fullPaath = ""; - if( template.getUriTemplate() != AnnotationProcessor.WILD_CARD ) { + if (!template.getUriTemplate().equals(AnnotationProcessor.WILD_CARD)) { fullPaath = apiConfig.getContext() + template.getUriTemplate(); } else{ diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/InvalidConfigurationStateException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/InvalidConfigurationStateException.java index d3022f11d1..7604fe88a6 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/InvalidConfigurationStateException.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/InvalidConfigurationStateException.java @@ -23,53 +23,7 @@ public class InvalidConfigurationStateException extends RuntimeException { private static final long serialVersionUID = -3151279311329070397L; - private String errorMessage; - private int errorCode; - - public InvalidConfigurationStateException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public InvalidConfigurationStateException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - public InvalidConfigurationStateException(String msg) { super(msg); - setErrorMessage(msg); } - - public InvalidConfigurationStateException() { - super(); - } - - public InvalidConfigurationStateException(Throwable cause) { - super(cause); - } - } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherConfigurationFailedException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherConfigurationFailedException.java index e5b3252f8e..cc73f0baa3 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherConfigurationFailedException.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherConfigurationFailedException.java @@ -25,20 +25,4 @@ public class WebappPublisherConfigurationFailedException extends Exception { public WebappPublisherConfigurationFailedException(String msg, Exception nestedEx) { super(msg, nestedEx); } - - public WebappPublisherConfigurationFailedException(String message, Throwable cause) { - super(message, cause); - } - - public WebappPublisherConfigurationFailedException(String msg) { - super(msg); - } - - public WebappPublisherConfigurationFailedException() { - super(); - } - - public WebappPublisherConfigurationFailedException(Throwable cause) { - super(cause); - } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java index 1007c50026..b8fe08cfcb 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java @@ -1,38 +1,10 @@ package org.wso2.carbon.apimgt.webapp.publisher.config; -public class APIResourceManagementException extends Exception{ - private static final long serialVersionUID = -3151279311929070297L; +public class APIResourceManagementException extends Exception { + private static final long serialVersionUID = -3151279311929070297L; - private String errorMessage; - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public APIResourceManagementException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public APIResourceManagementException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public APIResourceManagementException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public APIResourceManagementException() { - super(); - } - - public APIResourceManagementException(Throwable cause) { - super(cause); - } + public APIResourceManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/exception/APIManagerPublisherException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/exception/APIManagerPublisherException.java index b98aef3c9a..aaa24b1fa7 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/exception/APIManagerPublisherException.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/exception/APIManagerPublisherException.java @@ -25,24 +25,7 @@ public class APIManagerPublisherException extends Exception { private static final long serialVersionUID = -8933142342423122660L; - public APIManagerPublisherException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public APIManagerPublisherException(String message, Throwable cause) { - super(message, cause); - } - - public APIManagerPublisherException(String msg) { - super(msg); - } - - public APIManagerPublisherException() { - super(); - } - public APIManagerPublisherException(Throwable cause) { super(cause); } - } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java index 2a5b533eaf..87d27c5e52 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java @@ -33,10 +33,10 @@ import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIIn import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIList; import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig; import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope; -import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; -import org.wso2.carbon.apimgt.webapp.publisher.utils.Api; +import org.wso2.carbon.apimgt.webapp.publisher.utils.MockApi; +import org.wso2.carbon.apimgt.webapp.publisher.utils.TestUtils; import java.lang.reflect.Field; import java.util.*; @@ -46,8 +46,7 @@ import static org.mockito.Mockito.doReturn; /** * This is the test class for {@link APIPublisherServiceImpl} */ -public class -APIPublisherServiceTest extends BaseAPIPublisherTest { +public class APIPublisherServiceTest extends BaseAPIPublisherTest { private static final Log log = LogFactory.getLog(APIPublisherServiceTest.class); private APIPublisherServiceImpl apiPublisherService = new APIPublisherServiceImpl(); @@ -78,7 +77,7 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService(). getPublisherClient(); doReturn(publisherClient).when(integrationClientService).getPublisherClient(); - APIsApi apIsApi = Mockito.mock(Api.class, Mockito.CALLS_REAL_METHODS); + APIsApi apIsApi = Mockito.mock(MockApi.class, Mockito.CALLS_REAL_METHODS); doReturn(apIsApi).when(publisherClient).getApi(); API api = Mockito.mock(API.class, Mockito.CALLS_REAL_METHODS); api.setStatus("CREATED"); @@ -87,7 +86,7 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { } @Test(description = "createAPIListWithNoApi | will fail if there are any exceptions") - private void publishWithNoAPIListCreated() throws APIManagerPublisherException { + public void publishWithNoAPIListCreated() throws APIManagerPublisherException { APIConfig apiConfig = new APIConfig(); setApiConfigs(apiConfig, "testAPI-2"); APIPublisherDataHolder apiPublisherDataHolder = Mockito.mock(APIPublisherDataHolder.getInstance(). @@ -98,7 +97,7 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService(). getPublisherClient(); doReturn(publisherClient).when(integrationClientService).getPublisherClient(); - APIsApi apIsApi = Mockito.mock(Api.class, Mockito.CALLS_REAL_METHODS); + APIsApi apIsApi = Mockito.mock(MockApi.class, Mockito.CALLS_REAL_METHODS); doReturn(apIsApi).when(publisherClient).getApi(); API api = Mockito.mock(API.class, Mockito.CALLS_REAL_METHODS); api.setStatus("CREATED"); @@ -116,7 +115,7 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { } @Test(description = "createAPIList | will fail if there are any exceptions") - private void publishWithAPIListCreated() throws APIManagerPublisherException { + public void publishWithAPIListCreated() throws APIManagerPublisherException { APIConfig apiConfig = new APIConfig(); setApiConfigs(apiConfig, "testAPI-3"); APIPublisherDataHolder apiPublisherDataHolder = Mockito.mock(APIPublisherDataHolder.getInstance(). @@ -127,7 +126,7 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService(). getPublisherClient(); doReturn(publisherClient).when(integrationClientService).getPublisherClient(); - APIsApi apIsApi = Mockito.mock(Api.class, Mockito.CALLS_REAL_METHODS); + APIsApi apIsApi = Mockito.mock(MockApi.class, Mockito.CALLS_REAL_METHODS); doReturn(apIsApi).when(publisherClient).getApi(); API api = Mockito.mock(API.class, Mockito.CALLS_REAL_METHODS); api.setStatus("CREATED"); @@ -149,7 +148,7 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { } @Test(description = "publish API with scope added | will fail if there are any exceptions") - private void publishWithAPIScope() throws APIManagerPublisherException { + public void publishWithAPIScope() throws APIManagerPublisherException { APIConfig apiConfig = new APIConfig(); setApiConfigs(apiConfig, "testAPI-4"); Set scopes = new HashSet<>(); @@ -175,24 +174,8 @@ APIPublisherServiceTest extends BaseAPIPublisherTest { Map apiScopes = new HashMap<>(); Set scopes = new HashSet<>(apiScopes.values()); apiConfig.setScopes(scopes); - setAPIURITemplates(apiConfig); - } - - private void setAPIURITemplates(APIConfig apiConfig) { - Set uriTemplates = new LinkedHashSet<>(); - ApiUriTemplate template = new ApiUriTemplate(); - template.setAuthType("Application & Application User"); - template.setHttpVerb("POST"); - template.setResourceURI("https://localhost:9443/api/device-mgt/windows/v1.0/admin/devices/reboot"); - template.setUriTemplate("/reboot"); - ApiScope scope = new ApiScope(); - scope.setKey("perm:windows:reboot"); - scope.setName("Reboot"); - scope.setRoles("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot"); - scope.setDescription("Lock reset on Windows devices"); - template.setScope(scope); - uriTemplates.add(template); - apiConfig.setUriTemplates(uriTemplates); + TestUtils util = new TestUtils(); + util.setAPIURITemplates(apiConfig, "/reboot"); } private void initializeOAuthApplication() throws NoSuchFieldException, IllegalAccessException { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtilTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtilTest.java index ca1bc1fba4..45b8d71257 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtilTest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtilTest.java @@ -18,35 +18,40 @@ package org.wso2.carbon.apimgt.webapp.publisher; import org.testng.Assert; -import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration; import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig; import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope; +import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; import org.wso2.carbon.apimgt.webapp.publisher.utils.MockServletContext; +import org.wso2.carbon.apimgt.webapp.publisher.utils.TestUtils; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.servlet.ServletContext; import java.util.ArrayList; import java.util.List; +import java.util.Set; import static org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil.buildApiConfig; +import static org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil.getApiEndpointUrl; +import static org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil.setResourceAuthTypes; /** * This is the test class for {@link APIPublisherUtil} */ public class APIPublisherUtilTest extends BaseAPIPublisherTest { + private static final String AUTH_TYPE_NON_SECURED = "None"; + @BeforeTest public void initialConfigs() throws WebappPublisherConfigurationFailedException, org.wso2.carbon.user.core.UserStoreException, RegistryException { @@ -55,7 +60,7 @@ public class APIPublisherUtilTest extends BaseAPIPublisherTest { } @Test(description = "test buildAPIConfig method and ensures an APIConfig is created") - private void buildApiConfigTest() throws UserStoreException, RegistryException { + public void buildApiConfigTest() throws UserStoreException, RegistryException { try { startTenantFlowAsTestTenant(); ServletContext servletContext = new MockServletContext(); @@ -71,7 +76,7 @@ public class APIPublisherUtilTest extends BaseAPIPublisherTest { @Test(description = "test buildAPIConfig method as SuperTenant and ensures" + " an APIConfig is created") - private void buildApiConfigAsSuperTenat() throws UserStoreException { + public void buildApiConfigAsSuperTenant() throws UserStoreException { ServletContext servletContext = new MockServletContext(); APIResourceConfiguration apiDef = new APIResourceConfiguration(); List resources = new ArrayList<>(); @@ -82,7 +87,7 @@ public class APIPublisherUtilTest extends BaseAPIPublisherTest { @Test(description = "test buildAPIConfig with API tags specified and ensures " + "an APIConfig is created") - private void buildApiConfigTestWithTags() throws UserStoreException { + public void buildApiConfigTestWithTags() throws UserStoreException { ServletContext servletContext = new MockServletContext(); APIResourceConfiguration apiDef = new APIResourceConfiguration(); List resources = new ArrayList<>(); @@ -96,7 +101,7 @@ public class APIPublisherUtilTest extends BaseAPIPublisherTest { @Test(description = "test buildAPIConfig method with API scopes specified and " + "ensures an APIConfig is created") - private void buildApiConfigTestWithScope() throws UserStoreException, APIManagerPublisherException { + public void buildApiConfigTestWithScope() throws UserStoreException, APIManagerPublisherException { ServletContext servletContext = new MockServletContext(); APIResourceConfiguration apiDef = new APIResourceConfiguration(); List resources = new ArrayList<>(); @@ -111,6 +116,38 @@ public class APIPublisherUtilTest extends BaseAPIPublisherTest { Assert.assertNotNull(apiConfig, "API configuration is null."); } + @Test(description = "test method for setResourceAuthTypes") + public void testSetResourceAuthTypes() throws UserStoreException { + ServletContext servletContext = new MockServletContext(); + APIResourceConfiguration apiDef = new APIResourceConfiguration(); + List resources = new ArrayList<>(); + apiDef.setResources(resources); + APIConfig apiConfig = buildApiConfig(servletContext, apiDef); + apiConfig.setContext("/*"); + TestUtils util = new TestUtils(); + util.setAPIURITemplates(apiConfig, "/*"); + Assert.assertNotNull(apiConfig, "API configuration is null."); + setResourceAuthTypes(servletContext, apiConfig); + Set templates = apiConfig.getUriTemplates(); + Assert.assertEquals(templates.iterator().next().getAuthType(), AUTH_TYPE_NON_SECURED, "Resource " + + "auth type is not properly set"); + } + + @Test(description = "test the method getApiEndpointUrl") + public void testGetApiEndpointUrl() { + String context = "/reboot"; + String url = getApiEndpointUrl(context); + Assert.assertEquals(url, "https://localhost:9445/reboot", "Expected url " + + "is not same as actual url"); + } + + @Test(expectedExceptions = WebappPublisherConfigurationFailedException.class, description = + "this tests the method convertToDocument with a undefined file name and ensures an " + + "exception occurs ") + public void testConvertToDocumentForException() throws WebappPublisherConfigurationFailedException { + WebappPublisherUtil.convertToDocument(null); + } + private void setUserRealm() throws RegistryException, org.wso2.carbon.user.core.UserStoreException { RealmConfiguration configuration = new RealmConfiguration(); UserRealm userRealm = new InMemoryRealmService().getUserRealm(configuration); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/BaseAPIPublisherTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/BaseAPIPublisherTest.java index e935b98e2a..229d11a970 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/BaseAPIPublisherTest.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/BaseAPIPublisherTest.java @@ -28,7 +28,7 @@ import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.apimgt.integration.generated.client.publisher.api.APIsApi; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; -import org.wso2.carbon.apimgt.webapp.publisher.utils.Api; +import org.wso2.carbon.apimgt.webapp.publisher.utils.MockApi; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.internal.OSGiDataHolder; @@ -87,7 +87,7 @@ public abstract class BaseAPIPublisherTest { PublisherClient publisherClient = Mockito.mock(PublisherClient.class, Mockito.CALLS_REAL_METHODS); doReturn(publisherClient).when(integrationClientService).getPublisherClient(); - APIsApi api = new Api(); + APIsApi api = new MockApi(); Field field = PublisherClient.class.getDeclaredField("api"); field.setAccessible(true); field.set(publisherClient, api); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/Api.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockApi.java similarity index 96% rename from components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/Api.java rename to components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockApi.java index 820da060a9..f9e22de3e8 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/Api.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockApi.java @@ -25,9 +25,9 @@ import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.FileI import java.io.File; /** - * Class to create Api for testing. + * Class to create MockApi for testing. */ -public class Api implements APIsApi { +public class MockApi implements APIsApi { @Override public void apisApiIdDelete(String apiId, String ifMatch, String ifUnmodifiedSince) { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockServletContext.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockServletContext.java index d88dac206a..c85d274a41 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockServletContext.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockServletContext.java @@ -130,7 +130,7 @@ public class MockServletContext implements ServletContext { @Override public String getInitParameter(String s) { - return "true"; + return "/*"; } @Override diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/TestUtils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/TestUtils.java new file mode 100644 index 0000000000..0f925940a8 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/TestUtils.java @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.apimgt.webapp.publisher.utils; + +import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; +import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope; +import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * Contains util methods for webAppPublisher tests. + */ +public class TestUtils { + + public void setAPIURITemplates(APIConfig apiConfig, String uriTemplate) { + Set uriTemplates = new LinkedHashSet<>(); + ApiUriTemplate template = new ApiUriTemplate(); + template.setAuthType("Application & Application User"); + template.setHttpVerb("POST"); + template.setResourceURI("https://localhost:9443/api/device-mgt/windows/v1.0/admin/devices/reboot"); + template.setUriTemplate(uriTemplate); + ApiScope scope = new ApiScope(); + scope.setKey("perm:windows:reboot"); + scope.setName("Reboot"); + scope.setRoles("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot"); + scope.setDescription("Lock reset on Windows devices"); + template.setScope(scope); + uriTemplates.add(template); + apiConfig.setUriTemplates(uriTemplates); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/etc/webapp-publisher-config.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/etc/webapp-publisher-config.xml index 6e03eb73bd..9e0fe964b8 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/etc/webapp-publisher-config.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/etc/webapp-publisher-config.xml @@ -24,7 +24,7 @@ - https://${iot.core.host}:${iot.core.https.port} + https://localhost:9445 true diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index d7115ee25a..8eb460962c 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,13 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 apimgt-extensions - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - API Management Extensions Component http://wso2.org diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml index caf08e5cdd..85d4c9c48e 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index 1bbeb0ad64..37f23afc97 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml index 4db036d18d..aea01487e9 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml @@ -21,13 +21,13 @@ org.wso2.carbon.devicemgt certificate-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.core - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Certificate Management Core WSO2 Carbon - Certificate Management Core @@ -60,7 +60,7 @@ org.apache.commons.logging, javax.security.auth.x500, javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", org.bouncycastle.asn1, org.bouncycastle.asn1.x500, @@ -94,7 +94,8 @@ io.swagger.annotations.*;resolution:=optional, org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.registry.indexing.*, - javax.cache.* + javax.cache.*, + javax.naming.ldap @@ -105,36 +106,40 @@ - org.apache.maven.plugins maven-surefire-plugin 2.18 - - file:src/test/resources/log4j.properties - src/test/resources/testng.xml + + ${basedir}/target/coverage-reports/jacoco-unit.exec + file:src/test/resources/log4j.properties + org.jacoco jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - + ${jacoco.maven.plugin.version} - jacoco-initialize + default-instrument + + instrument + + + + default-restore-instrumented-classes - prepare-agent + restore-instrumented-classes jacoco-site - test + prepare-package report @@ -143,13 +148,24 @@ ${basedir}/target/coverage-reports/site + + default-report-integration + + report-integration + + - + + org.jacoco + org.jacoco.agent + ${jacoco.maven.plugin.version} + runtime + org.eclipse.osgi org.eclipse.osgi diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index f81539018b..877d606af8 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -61,6 +61,9 @@ import org.wso2.carbon.certificate.mgt.core.util.CommonUtil; import org.wso2.carbon.certificate.mgt.core.util.Serializer; import org.wso2.carbon.context.PrivilegedCarbonContext; +import javax.naming.InvalidNameException; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; import javax.security.auth.x500.X500Principal; import javax.xml.bind.DatatypeConverter; import java.io.ByteArrayInputStream; @@ -112,7 +115,7 @@ public class CertificateGenerator { } } } catch (ClassNotFoundException | IOException e) { - String errorMsg = "Error while deserializing the certificate."; + String errorMsg = "Error while during deserialization of the certificate."; throw new CertificateManagementDAOException(errorMsg, e); } @@ -320,10 +323,20 @@ public class CertificateGenerator { CertificateResponse lookUpCertificate = null; KeyStoreReader keyStoreReader = new KeyStoreReader(); if (distinguishedName != null && !distinguishedName.isEmpty()) { - String[] dnSplits = distinguishedName.split("/CN="); - if (dnSplits != null) { - String commonNameExtracted = dnSplits[dnSplits.length - 1]; - lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted); + LdapName ldapName; + try { + ldapName = new LdapName(distinguishedName); + } catch (InvalidNameException e) { + throw new KeystoreException( + "Invalid name exception while trying to create a LDAP name using the distinguished name ", e); + } + for (Rdn relativeDistinuguishedNames : ldapName.getRdns()) { + if (relativeDistinuguishedNames.getType().equalsIgnoreCase("CN")) { + System.err.println("CN is: " + relativeDistinuguishedNames.getValue()); + lookUpCertificate = keyStoreReader + .getCertificateBySerial(String.valueOf(relativeDistinuguishedNames.getValue())); + break; + } } } return lookUpCertificate; @@ -409,21 +422,8 @@ public class CertificateGenerator { Date validityEndDate = commonUtil.getValidityEndDate(); X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL); - //X500Name certSubject = request.getSubject(); - Attribute attributes[] = request.getAttributes(); -// if (certSubject == null) { -// certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL); -// } else { -// org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs(); -// -// if (rdn == null || rdn.length == 0) { -// certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL); -// } -// } - - RDN[] certUniqueIdRDN; BigInteger certUniqueIdentifier; diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java new file mode 100644 index 0000000000..8eb45f394e --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateCacheManagerImplTests.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.certificate.mgt.core.impl; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.wso2.carbon.certificate.mgt.core.cache.CertificateCacheManager; +import org.wso2.carbon.certificate.mgt.core.common.BaseDeviceManagementCertificateTest; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; + +/** + * This class tests CertificateCache manager methods + */ +public class CertificateCacheManagerImplTests extends BaseDeviceManagementCertificateTest { + + private CertificateCacheManager manager; + + @BeforeClass + @Override + public void init() throws Exception { + initDataSource(); + CertificateManagementDAOFactory.init(this.getDataSource()); + manager = org.wso2.carbon.certificate.mgt.core.cache.impl.CertificateCacheManagerImpl.getInstance(); + Assert.assertNotNull(manager); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java new file mode 100644 index 0000000000..8fe7aee6ba --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorNegativeTests.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.certificate.mgt.core.impl; +import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.cert.CertIOException; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.pkcs.PKCS10CertificationRequest; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.util.CSRGenerator; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import javax.sql.DataSource; +import java.io.File; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.NoSuchProviderException; +import java.security.NoSuchAlgorithmException; +import java.security.SignatureException; +import java.security.InvalidKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.sql.SQLException; + +/** + * This class has the negative tests for CertificateGenerator class + */ +@PowerMockIgnore({"java.net.ssl", "javax.security.auth.x500.X500Principal"}) +@PrepareForTest({CertificateGenerator.class}) +public class CertificateGeneratorNegativeTests extends PowerMockTestCase { + + @Test(description = "This test case tests behaviour when a certificate IO error occurs", + expectedExceptions = KeystoreException.class) + public void negativeTestGenerateCertificateFromCSR() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //Prepare mock objects + X509v3CertificateBuilder mock = Mockito.mock(X509v3CertificateBuilder.class); + Mockito.when(mock.addExtension(Matchers.any(ASN1ObjectIdentifier.class), Matchers.anyBoolean(), + Matchers.any(ASN1Encodable.class))).thenThrow(new CertIOException("CERTIO")); + PowerMockito.whenNew(X509v3CertificateBuilder.class).withAnyArguments().thenReturn(mock); + //prepare input parameters + CSRGenerator csrGeneration = new CSRGenerator(); + KeyStoreReader keyStoreReader = new KeyStoreReader(); + KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024); + byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair); + PKCS10CertificationRequest certificationRequest; + PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey(); + X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate(); + certificationRequest = new PKCS10CertificationRequest(csrData); + generator.generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName()); + + } + + @Test(description = "This test case tests behaviour when Certificate Operator creation error occurs", + expectedExceptions = KeystoreException.class) + public void negativeTestGenerateCertificateFromCSR2() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //Prepare mock objects + JcaContentSignerBuilder mock = Mockito.mock(JcaContentSignerBuilder.class); + Mockito.when(mock.setProvider(Matchers.eq(CertificateManagementConstants.PROVIDER))).thenReturn(mock); + Mockito.when(mock.build(Matchers.any(PrivateKey.class))).thenThrow(new OperatorCreationException("OPERATOR")); + PowerMockito.whenNew(JcaContentSignerBuilder.class).withAnyArguments().thenReturn(mock); + //prepare input parameters + CSRGenerator csrGeneration = new CSRGenerator(); + KeyStoreReader keyStoreReader = new KeyStoreReader(); + KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024); + byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair); + PKCS10CertificationRequest certificationRequest; + PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey(); + X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate(); + certificationRequest = new PKCS10CertificationRequest(csrData); + generator.generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName()); + } + + @Test(description = "This test case tests the behaviour when certificate exception occurs when verifying" + , expectedExceptions = KeystoreException.class) + public void negativeTestGenerateCertificateFromCSR3() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //Prepare mock objects + JcaX509CertificateConverter mock = Mockito.mock(JcaX509CertificateConverter.class); + Mockito.when(mock.setProvider(Matchers.eq(CertificateManagementConstants.PROVIDER))).thenReturn(mock); + Mockito.when(mock.getCertificate(Matchers.any(X509CertificateHolder.class))).thenThrow(new CertificateException()); + PowerMockito.whenNew(JcaX509CertificateConverter.class).withAnyArguments().thenReturn(mock); + //prepare input parameters + CSRGenerator csrGeneration = new CSRGenerator(); + KeyStoreReader keyStoreReader = new KeyStoreReader(); + KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024); + byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair); + PKCS10CertificationRequest certificationRequest; + PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey(); + X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate(); + certificationRequest = new PKCS10CertificationRequest(csrData); + generator.generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName()); + + } + + @Test(description = "This test case tests behaviour when the Certificate provider does not exist" + , expectedExceptions = KeystoreException.class) + public void negativeTestGenerateX509Certificate1() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //prepare mock objects + X509Certificate mock = Mockito.mock(X509Certificate.class); + PowerMockito.doThrow(new NoSuchProviderException()).when(mock).verify(Matchers.any()); + JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class); + Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv); + Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock); + PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv); + generator.generateX509Certificate(); + } + + @Test(description = "This test case tests behaviour when the Certificate Algorithm does not exist" + , expectedExceptions = KeystoreException.class) + public void negativeTestGenerateX509Certificate2() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //prepare mock objects + X509Certificate mock = Mockito.mock(X509Certificate.class); + PowerMockito.doThrow(new NoSuchAlgorithmException()).when(mock).verify(Matchers.any()); + JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class); + Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv); + Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock); + PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv); + generator.generateX509Certificate(); + } + + @Test(description = "This test case tests behaviour when the Signature validation fails" + , expectedExceptions = KeystoreException.class) + public void negativeTestGenerateX509Certificate3() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //prepare mock objects + X509Certificate mock = Mockito.mock(X509Certificate.class); + PowerMockito.doThrow(new SignatureException()).when(mock).verify(Matchers.any()); + JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class); + Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv); + Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock); + PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv); + generator.generateX509Certificate(); + } + + @Test(description = "This test case tests behaviour when the Certificate exception occurs" + , expectedExceptions = KeystoreException.class) + public void negativeTestGenerateX509Certificate4() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //prepare mock objects + X509Certificate mock = Mockito.mock(X509Certificate.class); + PowerMockito.doThrow(new CertificateException()).when(mock).verify(Matchers.any()); + JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class); + Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv); + Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock); + PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv); + generator.generateX509Certificate(); + } + + @Test(description = "This test case tests behaviour when the Certificate key is invalid" + , expectedExceptions = KeystoreException.class) + public void negativeTestGenerateX509Certificate5() throws Exception { + CertificateGenerator generator = new CertificateGenerator(); + //prepare mock objects + X509Certificate mock = Mockito.mock(X509Certificate.class); + PowerMockito.doThrow(new InvalidKeyException()).when(mock).verify(Matchers.any()); + JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class); + Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv); + Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock); + PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv); + generator.generateX509Certificate(); + } + + @Test(description = "This test case tests behavior when the CA certificate is null" + , expectedExceptions = KeystoreException.class) + public void negativeTestGetRootCertificates1() throws KeystoreException { + CertificateGenerator generator = new CertificateGenerator(); + generator.getRootCertificates(null, new byte[10]); + } + + @Test(description = "This test case tests behavior when the CA certificate is null", + expectedExceptions = KeystoreException.class) + public void negativeTestGetRootCertificates2() throws KeystoreException { + CertificateGenerator generator = new CertificateGenerator(); + generator.getRootCertificates(new byte[10], null); + } + + + @BeforeClass + public void init() throws SQLException { + if (System.getProperty("carbon.home") == null) { + File file = new File("src/test/resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + file = new File("../resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + file = new File("../../resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + file = new File("../../../resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + } + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants + .SUPER_TENANT_DOMAIN_NAME); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); + + DataSource normalDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS); + DataSource daoExceptionDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS); + Mockito.when(normalDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn("H2"); + + CertificateManagementDAOFactory.init(normalDatasource); + Mockito.when(daoExceptionDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn("H2"); + Mockito.when(daoExceptionDatasource.getConnection().prepareStatement(Mockito.anyString())).thenThrow(new SQLException()); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java new file mode 100644 index 0000000000..f0c0e765f3 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.certificate.mgt.core.impl; + +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockTestCase; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; +import org.wso2.carbon.certificate.mgt.core.exception.TransactionManagementException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import javax.sql.DataSource; +import java.io.File; +import java.sql.SQLException; + +/** + * This class covers the negative tests for CertificateManagementServiceImpl class + */ +@PowerMockIgnore({"java.net.ssl", "javax.security.auth.x500.X500Principal"}) +@PrepareForTest({CertificateManagementServiceImpl.class, JcaX509CertificateConverter.class, CertificateGenerator.class, + CertificateManagementDAOFactory.class}) +public class CertificateManagementServiceImplNegativeTests extends PowerMockTestCase { + + private CertificateManagementServiceImpl instance; + private DataSource daoExceptionDatasource; + private static final String MOCK_SERIAL = "1234"; + private static final String MOCK_DATASOURCE = "H2"; + + @BeforeClass + public void init() throws SQLException { + if (System.getProperty("carbon.home") == null) { + File file = new File("src/test/resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + file = new File("../resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + file = new File("../../resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + file = new File("../../../resources/carbon-home"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + } + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants + .SUPER_TENANT_DOMAIN_NAME); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); + DataSource normalDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS); + Mockito.when(normalDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn(MOCK_DATASOURCE); + CertificateManagementDAOFactory.init(normalDatasource); + + //configure datasource to throw dao exception + daoExceptionDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS); + Mockito.when(daoExceptionDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn(MOCK_DATASOURCE); + Mockito.when(daoExceptionDatasource.getConnection().prepareStatement(Mockito.anyString())).thenThrow(new SQLException()); + + //save as class variable + instance = CertificateManagementServiceImpl.getInstance(); + } + + + @Test(description = "This test case tests behaviour when an error occurs when opening the data source" + , expectedExceptions = CertificateManagementException.class) + public void negativeTestRetrieveCertificate2() throws Exception { + PowerMockito.mockStatic(CertificateManagementDAOFactory.class); + PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); + instance.retrieveCertificate(MOCK_SERIAL); + } + + @Test(description = "This test case tests behaviour when an error occurs when looking for a certificate with " + + "a serial number", expectedExceptions = CertificateManagementException.class) + public void negativeTestRetrieveCertificate() throws Exception { + CertificateManagementDAOFactory.init(daoExceptionDatasource); + CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); + instance1.retrieveCertificate(MOCK_SERIAL); + } + + @Test(description = "This test case tests behaviour when an error occurs when opening the data source", + expectedExceptions = CertificateManagementException.class) + public void negativeTestGetAllCertificates() throws Exception { + PowerMockito.mockStatic(CertificateManagementDAOFactory.class); + PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); + instance.getAllCertificates(1, 2); + } + + @Test(description = "This test case tests behaviour when an error occurs getting the list of certificates from repository" + , expectedExceptions = CertificateManagementException.class) + public void negativeTestGetAllCertificates2() throws Exception { + CertificateManagementDAOFactory.init(daoExceptionDatasource); + CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); + instance1.getAllCertificates(1, 2); + } + + @Test(description = "This test case tests behaviour when data source transaction error occurs when removing the certificate" + , expectedExceptions = CertificateManagementException.class) + public void negativeTestRemoveCertificate() throws Exception { + PowerMockito.mockStatic(CertificateManagementDAOFactory.class); + PowerMockito.doThrow(new TransactionManagementException()).when(CertificateManagementDAOFactory.class, "beginTransaction"); + instance.removeCertificate(MOCK_SERIAL); + } + + @Test(description = "This test case tests behaviour when an error occurs while removing the certificate from the certificate " + + "repository", expectedExceptions = CertificateManagementException.class) + public void negativeTestRemoveCertificate2() throws Exception { + CertificateManagementDAOFactory.init(daoExceptionDatasource); + CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); + instance1.removeCertificate(MOCK_SERIAL); + } + + @Test(description = "This test case tests behaviour when an error occurs when opening the data source", + expectedExceptions = CertificateManagementException.class) + public void negativeTestGetCertificates() throws Exception { + PowerMockito.mockStatic(CertificateManagementDAOFactory.class); + PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); + instance.getCertificates(); + } + + @Test(description = "This test case tests behaviour when an error occurs while looking up for the list of certificates" + , expectedExceptions = CertificateManagementException.class) + public void negativeTestGetCertificates2() throws CertificateManagementException { + CertificateManagementDAOFactory.init(daoExceptionDatasource); + CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); + instance1.getCertificates(); + } + + @Test(description = "This test case tests behaviour when an error occurs when opening the data source", + expectedExceptions = CertificateManagementException.class) + public void negativeTestSearchCertificates() throws Exception { + PowerMockito.mockStatic(CertificateManagementDAOFactory.class); + PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); + instance.searchCertificates(MOCK_SERIAL); + } + + @Test(description = "This test case tests behaviour when an error occurs while searching for the certificate by the serial" + , expectedExceptions = CertificateManagementException.class) + public void negativeTestSearchCertificates2() throws CertificateManagementException { + CertificateManagementDAOFactory.init(daoExceptionDatasource); + CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); + instance1.searchCertificates(MOCK_SERIAL); + } + + //Powermockito requirement + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateTests.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateTests.java new file mode 100644 index 0000000000..3c47eea758 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateTests.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.certificate.mgt.core.impl; + +import org.testng.Assert; +import org.testng.annotations.Test; +import org.wso2.carbon.certificate.mgt.core.bean.Certificate; +import org.wso2.carbon.certificate.mgt.core.util.DummyCertificate; + +/** + * This class tests the DTO for certificates + */ +public class CertificateTests { + + private static String SERIAL = "1234"; + private static String TENANT_DOMAIN = "tenant_domain"; + private static int TENANT_ID = 1234; + + @Test(description = "This test case tests the Certificate object getters and setters") + public void certificateCreationTest() { + + Certificate certificate = new Certificate(); + certificate.setSerial(SERIAL); + certificate.setCertificate(new DummyCertificate()); + certificate.setTenantDomain(TENANT_DOMAIN); + certificate.setTenantId(TENANT_ID); + + Assert.assertEquals(certificate.getCertificate(), new DummyCertificate()); + Assert.assertEquals(certificate.getSerial(), SERIAL); + Assert.assertEquals(certificate.getTenantDomain(), TENANT_DOMAIN); + Assert.assertEquals(certificate.getTenantId(), TENANT_ID); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml index b76295f108..13b5914320 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/testng.xml @@ -27,6 +27,10 @@ + + + + diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index f0628cde9e..84d524477a 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt certificate-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Certificate Management Component http://wso2.org diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml index e18fe0fd7d..6915053c59 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml index 719c6c9d3c..33d7c4d2f5 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml index 67c391291c..119c3193cd 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml index 04a0b54820..217fe3c61a 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index 17cd30e93c..9fc79c8a98 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index 432eb436b3..5e511281fe 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 57d43d97bc..92d3b17a77 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml index 6035f978df..493d85c381 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index 5661da9cf7..f132b3697d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml @@ -75,6 +75,18 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + @@ -148,11 +160,6 @@ cxf-rt-transports-http provided - - junit - junit - test - commons-httpclient.wso2 commons-httpclient @@ -212,6 +219,14 @@ org.apache.axis2.wso2 axis2-client + + org.mockito + mockito-core + + + javassist + javassist + @@ -223,6 +238,14 @@ org.apache.axis2.wso2 axis2-client + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + + + org.mockito + mockito-core + @@ -249,6 +272,12 @@ org.wso2.carbon.devicemgt org.wso2.carbon.certificate.mgt.core provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + + io.swagger @@ -378,6 +407,15 @@ org.wso2.carbon.apimgt.integration.client provided + + org.powermock + powermock-module-testng + test + + + org.powermock + powermock-api-mockito + test + - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java index 3cc9401449..57c0b7cde6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceTypeManagementAdminServiceImpl.java @@ -23,7 +23,6 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.InvalidConfigurationException; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; -import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService; @@ -89,8 +88,6 @@ public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagemen String msg = "Error occurred at server side while adding a device type."; log.error(msg, e); return Response.serverError().entity(msg).build(); - } catch (InvalidConfigurationException e) { - return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } } else { return Response.status(Response.Status.BAD_REQUEST).build(); @@ -114,8 +111,6 @@ public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagemen String msg = "Error occurred at server side while updating the device type."; log.error(msg, e); return Response.serverError().entity(msg).build(); - } catch (InvalidConfigurationException e) { - return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } } else { return Response.status(Response.Status.BAD_REQUEST).build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index 254ad9a95e..cbbfaf32ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -101,7 +101,6 @@ import java.util.List; */ public class DeviceMgtAPIUtils { - public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE; private static final String NOTIFIER_FREQUENCY = "notifierFrequency"; private static final String STREAM_DEFINITION_PREFIX = "iot.per.device.stream."; private static final String DEFAULT_HTTP_PROTOCOL = "https"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java new file mode 100644 index 0000000000..6c222e8311 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java @@ -0,0 +1,655 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.caching.impl.CacheImpl; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceAgentService; +import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; +import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; +import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.cache.CacheManager; +import javax.ws.rs.core.Response; +import java.rmi.RemoteException; +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This class holds the unit tests for the class {@link DeviceAgentServiceImpl} + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.CarbonContext", "org.wso2.carbon.context.internal.CarbonContextDataHolder"}) +@PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class, + DeviceAccessAuthorizationService.class, EventStreamAdminServiceStub.class, PrivilegedCarbonContext.class, + CarbonContext.class, CarbonUtils.class}) +public class DeviceAgentServiceTest { + + private static final Log log = LogFactory.getLog(DeviceTypeManagementAdminService.class); + private DeviceManagementProviderService deviceManagementProviderService; + private DeviceAgentService deviceAgentService; + private EventStreamAdminServiceStub eventStreamAdminServiceStub; + private PrivilegedCarbonContext privilegedCarbonContext; + private CarbonContext carbonContext; + private CacheManager cacheManager; + private DeviceAccessAuthorizationService deviceAccessAuthorizationService; + private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; + private static final String TEST_DEVICE_IDENTIFIER = "11222334455"; + private static final String AUTHENTICATED_USER = "admin"; + private static final String TENANT_DOMAIN = "carbon.super"; + private static Device demoDevice; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() { + log.info("Initializing DeviceAgent tests"); + initMocks(this); + this.deviceManagementProviderService = Mockito + .mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS); + this.deviceAgentService = new DeviceAgentServiceImpl(); + this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class, + Mockito.RETURNS_MOCKS); + this.privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class, Mockito.RETURNS_MOCKS); + this.carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + this.eventStreamAdminServiceStub = Mockito.mock(EventStreamAdminServiceStub.class, Mockito.RETURNS_MOCKS); + demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + this.cacheManager = Mockito.mock(CacheManager.class, Mockito.RETURNS_MOCKS); + } + + @Test(description = "Test device Enrollment when the device is null") + public void testEnrollDeviceWithDeviceIsNULL() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceAgentService.enrollDevice(null); + + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test device enrollment when device type is null.") + public void testEnrollDeviceWithDeviceTypeNull() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Device device = DeviceMgtAPITestHelper.generateDummyDevice(null, TEST_DEVICE_IDENTIFIER); + Response response = this.deviceAgentService.enrollDevice(device); + + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test device enrollment of a device with null device identifier.") + public void testEnrollNewDeviceWithDeviceIdentifierIsNull() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, null); + Response response = this.deviceAgentService.enrollDevice(device); + + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test an already enrolled device") + public void testEnrollExistingDevice() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice); + Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device); + Response response = this.deviceAgentService.enrollDevice(device); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test the device enrollment success scenario.") + public void testEnrollDeviceSuccess() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")) + .toReturn(AUTHENTICATED_USER); + + EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); + enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); + demoDevice.setEnrolmentInfo(enrolmentInfo); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice); + + Response response = this.deviceAgentService.enrollDevice(demoDevice); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test the device enrollment with device management exception.") + public void testEnrollDeviceWithException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")) + .toReturn(AUTHENTICATED_USER); + + Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); + enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any())) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceAgentService.enrollDevice(device); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test dis-enrolling the device success scenario.") + public void testDisEnrollDeviceSuccess() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any())).thenReturn(true); + Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test dis-enrolling non existing device.") + public void testDisEnrollNonExistingDevice() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(), + "The response status should be 204"); + } + + @Test(description = "Test dis-enrolling device error") + public void testDisEnrollingDeviceError() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any())).thenThrow(new + DeviceManagementException()); + Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test device update scenario with device management exception.") + public void testUpdateDeviceDMException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new + DeviceManagementException()); + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test update device scenario when the device is null.") + public void testUpdateDeviceWithNoDevice() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, null); + + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test the update device scenario when there is no enrolled device.") + public void testUpdatingNonExistingDevice() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(null); + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "The response status should be 404"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test update device with device access authorization exception.") + public void testEnrollDeviceWithDeviceAccessAuthException() throws DeviceManagementException, + DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new DeviceAccessAuthorizationException()); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(this.deviceManagementProviderService); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Test update device when user does not have device access permission.") + public void testUpdateDeviceWithNoDeviceAccessPermission() throws DeviceManagementException, + DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(false); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(), + "The response status should be 401"); + Mockito.reset(this.deviceManagementProviderService); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Test update device when device modification is unsuccessful.") + public void testUpdateDeviceNOTModify() throws DeviceManagementException, DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); + + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode(), + "The response status should be 304"); + Mockito.reset(this.deviceManagementProviderService); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Test updating device when modify enrollment throws exception") + public void testUpdateDeviceWithModifyEnrollmentFailure() throws DeviceManagementException, DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); + + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenThrow(new DeviceManagementException()); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(this.deviceManagementProviderService); + Mockito.reset(this.deviceAccessAuthorizationService); + } + @Test(description = "Test updating device success scenario.") + public void testUpdateDeviceSuccess() throws DeviceManagementException, DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); + + Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); + Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode(), + "The response status should be 202"); + Mockito.reset(this.deviceManagementProviderService); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Test publish events with null payload.") + public void testPublishEventsWithNullPayload() { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN); + + Map payload = null; + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test publish events with no device access authorization.") + public void testPublishEventsWithOutAuthorization() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(false); + Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN); + Map payload = new HashMap<>(); + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(), + "The response status should be 401"); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test + public void testPublishEventsWithDeviceAccessAuthException() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new DeviceAccessAuthorizationException()); + Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN); + Map payload = new HashMap<>(); + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Test event publishing when the event stream dao is null.") + public void testEventPublishWithNullEventAttributesAndNullEventStreamDefDAO() throws DeviceAccessAuthorizationException, RemoteException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toReturn(this.eventStreamAdminServiceStub); + Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString())).thenReturn(null); + + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + Mockito.reset(eventStreamAdminServiceStub); + } + + @Test(description ="Test the error scenario of Publishing Events with null event attributes.") + public void testEventPublishWithEventAttributesNULLAndPublishEventsFailure() throws + DeviceAccessAuthorizationException, RemoteException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toReturn(this.eventStreamAdminServiceStub); + EventStreamAttributeDto eventStreamAttributeDto = Mockito.mock(EventStreamAttributeDto.class, + Mockito.RETURNS_MOCKS); + EventStreamDefinitionDto eventStreamDefinitionDto = Mockito.mock(EventStreamDefinitionDto.class, + Mockito.RETURNS_MOCKS); + Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString())) + .thenReturn(eventStreamDefinitionDto); + Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{}); + EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class, + Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")).toReturn + (eventPublisherService); + + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test Event publishing success scenario.") + public void testEventPublishWithEventAttributesNULLAndPublishEventsSuccess() + throws DeviceAccessAuthorizationException, RemoteException, DataPublisherConfigurationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toReturn(this.eventStreamAdminServiceStub); + EventStreamAttributeDto eventStreamAttributeDto = Mockito.mock(EventStreamAttributeDto.class, + Mockito.RETURNS_MOCKS); + EventStreamDefinitionDto eventStreamDefinitionDto = Mockito.mock(EventStreamDefinitionDto.class, + Mockito.RETURNS_MOCKS); + Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString())) + .thenReturn(eventStreamDefinitionDto); + Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{}); + EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class, + Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")).toReturn + (eventPublisherService); + Mockito.when(eventPublisherService.publishEvent(Mockito.anyString(), Mockito.anyString(), Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn(true); + + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200"); + } + + @Test(description = "Test event publishing when PublishEvents throws DataPublisherConfigurationException.") + public void testPublishEventsDataPublisherConfig() throws DeviceAccessAuthorizationException, RemoteException, DataPublisherConfigurationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toReturn(this.eventStreamAdminServiceStub); + EventStreamAttributeDto eventStreamAttributeDto = Mockito.mock(EventStreamAttributeDto.class, + Mockito.RETURNS_MOCKS); + EventStreamDefinitionDto eventStreamDefinitionDto = Mockito.mock(EventStreamDefinitionDto.class, + Mockito.RETURNS_MOCKS); + Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString())) + .thenReturn(eventStreamDefinitionDto); + Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{}); + EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class, + Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")) + .toReturn(eventPublisherService); + Mockito.when(eventPublisherService.publishEvent(Mockito.anyString(), Mockito.anyString(), Mockito.any(), + Mockito.any(), Mockito.any())).thenThrow( + new DataPublisherConfigurationException("meta data[0] should have the device Id field")); + + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test Publish events with Axis Fault.") + public void testPublishEventsWithAxisFault() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toThrow(new AxisFault("")); + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test Publishing events when EventStreamAdminService throws Remote exception.") + public void testPublishEventsWithRemoteException() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toThrow(new RemoteException()); + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test Publishing events when EventStreamAdminService throws JWT exception.") + public void testPublishEventsWithJWTException() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toThrow(new JWTClientException()); + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test Publishing events when EventStreamAdminService throws User Store exception.") + public void testPublishEventsWithUserStoreException() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(this.privilegedCarbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) + .toThrow(new UserStoreException()); + Map payload = new HashMap<>(); + CacheImpl cache = Mockito.mock(CacheImpl.class); + + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache")) + .toReturn(cache); + + Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java new file mode 100644 index 0000000000..c17270ab11 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -0,0 +1,556 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; +import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; +import javax.ws.rs.core.Response; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This class includes unit tests for testing the functionality of {@link DeviceManagementServiceImpl} + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.CarbonContext"}) +@PrepareForTest({DeviceMgtAPIUtils.class, MultitenantUtils.class, CarbonContext.class}) +public class DeviceManagementServiceImplTest { + + private static final Log log = LogFactory.getLog(DeviceManagementServiceImplTest.class); + private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; + private static final String TEST_DEVICE_NAME = "TEST-DEVICE"; + private static final String DEFAULT_USERNAME = "admin"; + private static final String TENANT_AWARE_USERNAME = "admin@carbon.super"; + private static final String DEFAULT_ROLE = "admin"; + private static final String DEFAULT_OWNERSHIP = "BYOD"; + private static final String DEFAULT_STATUS = "ACTIVE"; + private static final String DEFAULT_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; + private DeviceManagementService deviceManagementService; + private DeviceAccessAuthorizationService deviceAccessAuthorizationService; + private DeviceManagementProviderService deviceManagementProviderService; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() { + log.info("Initializing DeviceManagementServiceImpl tests"); + initMocks(this); + this.deviceManagementProviderService = Mockito + .mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS); + this.deviceManagementService = new DeviceManagementServiceImpl(); + this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class); + } + + @Test(description = "Testing if the device is enrolled when the device is enrolled.") + public void testIsEnrolledWhenDeviceIsEnrolled() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.isEnrolled(Mockito.any(DeviceIdentifier.class))) + .thenReturn(true); + Response response = this.deviceManagementService.isEnrolled(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing if the device is enrolled when the device is not enrolled.", + dependsOnMethods = "testIsEnrolledWhenDeviceIsEnrolled") + public void testIsEnrolledWhenDeviceIsNotEnrolled() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.isEnrolled(Mockito.any(DeviceIdentifier.class))) + .thenReturn(false); + Response response = this.deviceManagementService.isEnrolled(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing if the device enrolled api when exception occurred.", + dependsOnMethods = "testIsEnrolledWhenDeviceIsNotEnrolled") + public void testIsEnrolledError() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.isEnrolled(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new DeviceManagementException()); + Response response = this.deviceManagementService.isEnrolled(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing get devices when request exists both name and role.") + public void testGetDevicesWhenBothNameAndRoleAvailable() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + Response response = this.deviceManagementService + .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); + } + + @Test(description = "Testing get devices with correct request.") + public void testGetDevices() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername")) + .toReturn(TENANT_AWARE_USERNAME); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, true, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing get devices when DeviceAccessAuthorizationService is not available") + public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(null); + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test(description = "Testing get devices when user is the device admin") + public void testGetDevicesWhenUserIsAdmin() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername")) + .toReturn(TENANT_AWARE_USERNAME); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing get devices when user is unauthorized.") + public void testGetDevicesWhenUserIsUnauthorized() throws Exception { + PowerMockito.spy(MultitenantUtils.class); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + PowerMockito.doReturn(TENANT_AWARE_USERNAME) + .when(MultitenantUtils.class, "getTenantAwareUsername", DEFAULT_USERNAME); + PowerMockito.doReturn("newuser@carbon.super").when(MultitenantUtils.class, "getTenantAwareUsername", "newuser"); + Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(false); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS, 1, + null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Testing get devices with IF-Modified-Since") + public void testGetDevicesWithModifiedSince() { + String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername")) + .toReturn(TENANT_AWARE_USERNAME); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, ifModifiedSince, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); + response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, ifModifiedSince, true, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); + response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, "ErrorModifiedSince", false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); + } + + @Test(description = "Testing get devices with Since") + public void testGetDevicesWithSince() { + String since = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername")) + .toReturn(TENANT_AWARE_USERNAME); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, since, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, since, null, true, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, "ErrorSince", null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); + } + + @Test(description = "Testing get devices when unable to retrieve devices") + public void testGetDeviceServerErrorWhenGettingDeviceList() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername")) + .toReturn(TENANT_AWARE_USERNAME); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + Mockito.when(this.deviceManagementProviderService + .getAllDevices(Mockito.any(PaginationRequest.class), Mockito.anyBoolean())) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing get devices when unable to check if the user is the admin user") + public void testGetDevicesServerErrorWhenCheckingAdminUser() throws DeviceAccessAuthorizationException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) + .toReturn(this.deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername")) + .toReturn(TENANT_AWARE_USERNAME); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser()) + .thenThrow(new DeviceAccessAuthorizationException()); + + Response response = this.deviceManagementService + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS, 1, null, null, false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + Mockito.reset(this.deviceAccessAuthorizationService); + } + + @Test(description = "Testing get devices with correct request") + public void testGetDeviceTypesByUser() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + + Response response = this.deviceManagementService.getDeviceByUser(true, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService.getDeviceByUser(false, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing get devices with correct request when unable to get devices.") + public void testGetDeviceTypesByUserException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS)); + Mockito.when(this.deviceManagementProviderService.getDevicesOfUser(Mockito.any(PaginationRequest.class))) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceManagementService.getDeviceByUser(true, 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test(description = "Testing delete device with correct request.") + public void testDeleteDevice() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing delete unavailable device.") + public void testDeleteUnavailableDevice() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean())).thenReturn(null); + Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing delete device when unable to delete device.") + public void testDeleteDeviceException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new DeviceManagementException()); + Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString()); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing getting device location") + public void testGetDeviceLocation() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")). + toReturn(Mockito.mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS)); + Response response = this.deviceManagementService + .getDeviceLocation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing getting device location when unable to retrieve location") + public void testGetDeviceLocationException() throws DeviceDetailsMgtException { + DeviceInformationManager deviceInformationManager = Mockito + .mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")). + toReturn(deviceInformationManager); + Mockito.when(deviceInformationManager.getDeviceLocation(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new DeviceDetailsMgtException()); + Response response = this.deviceManagementService + .getDeviceLocation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test(description = "Testing getting device information") + public void testGetDeviceInformation() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")). + toReturn(Mockito.mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS)); + Response response = this.deviceManagementService + .getDeviceInformation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing getting device information when unable to retrieve information") + public void testGetDeviceInformationException() throws DeviceDetailsMgtException { + DeviceInformationManager deviceInformationManager = Mockito + .mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")). + toReturn(deviceInformationManager); + Mockito.when(deviceInformationManager.getDeviceInfo(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new DeviceDetailsMgtException()); + Response response = this.deviceManagementService + .getDeviceInformation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test(description = "Testing getting device features") + public void testGetFeaturesOfDevice() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceManagementService + .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test(description = "Testing getting device features when feature manager is not registered for the device type") + public void testGetFeaturesOfDeviceWhenFeatureManagerIsNotRegistered() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn(null); + Response response = this.deviceManagementService + .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing getting device features when unable to get the feature manager") + public void testGetFeaturesException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())) + .thenThrow(new DeviceManagementException()); + Response response = this.deviceManagementService + .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Testing search devices") + public void testSearchDevices() { + SearchManagerService searchManagerService = Mockito.mock(SearchManagerServiceImpl.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getSearchManagerService")) + .toReturn(searchManagerService); + Response response = this.deviceManagementService + .searchDevices(10, 5, new SearchContext()); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Expects to return HTTP 200 when the search is successful"); + } + + @Test(description = "Testing search devices when unable to search devices") + public void testSearchDevicesException() throws SearchMgtException { + SearchManagerService searchManagerService = Mockito.mock(SearchManagerServiceImpl.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getSearchManagerService")) + .toReturn(searchManagerService); + Mockito.when(searchManagerService.search(Mockito.any(SearchContext.class))).thenThrow(new SearchMgtException()); + Response response = this.deviceManagementService + .searchDevices(10, 5, new SearchContext()); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Expects HTTP 500 when an exception occurred while searching the device"); + } + + @Test(description = "Testing getting installed applications of a device") + public void testGetInstalledApplications() { + ApplicationManagementProviderService applicationManagementProviderService = Mockito + .mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService")) + .toReturn(applicationManagementProviderService); + Response response = this.deviceManagementService + .getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Expects to return HTTP 200 when the application list is retrieved successfully."); + } + + @Test(description = "Testing getting installed applications of a device when unable to fetch applications") + public void testGetInstalledApplicationsException() throws ApplicationManagementException { + ApplicationManagementProviderService applicationManagementProviderService = Mockito + .mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService")) + .toReturn(applicationManagementProviderService); + Mockito.when( + applicationManagementProviderService.getApplicationListForDevice(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new ApplicationManagementException()); + Response response = this.deviceManagementService + .getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Expects HTTP 500 when an exception occurred while retrieving application list of the device"); + } + + @Test(description = "Testing getting operation list of a device") + public void testGetDeviceOperations() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceManagementService + .getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Expects to return HTTP 200 when the operation is retrieved successfully."); + } + + @Test(description = "Testing getting operation list of a device when unable to retrieve operations") + public void testGetDeviceOperationsException() throws OperationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getOperations(Mockito.any(DeviceIdentifier.class), + Mockito.any(PaginationRequest.class))).thenThrow(new OperationManagementException()); + Response response = this.deviceManagementService + .getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Expects to return HTTP 500 when an exception occurred while retrieving operation list of the device"); + } + + @Test(description = "Testing getting effective policy of a device") + public void testGetEffectivePolicyOfDevice() throws PolicyManagementException { + PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) + .toReturn(policyManagerService); + Response response = this.deviceManagementService + .getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Expects to return HTTP 200 when retrieving effective policy is successful"); + } + + @Test(description = "Testing getting effective policy of a device when unable to retrieve effective policy") + public void testGetEffectivePolicyOfDeviceException() throws PolicyManagementException { + PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) + .toReturn(policyManagerService); + Mockito.when(policyManagerService.getAppliedPolicyToDevice(Mockito.any(DeviceIdentifier.class))) + .thenThrow(new PolicyManagementException()); + Response response = this.deviceManagementService + .getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Expects to return HTTP 500 when an exception occurred while getting effective policy of the device"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java new file mode 100644 index 0000000000..5b438a0574 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementAdminServiceTest.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceTypeManagementAdminServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; + +import javax.ws.rs.core.Response; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This class holds the unit tests for the class {@link DeviceTypeManagementAdminService} + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils"}) +@PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class}) +public class DeviceTypeManagementAdminServiceTest { + + private static final Log log = LogFactory.getLog(DeviceTypeManagementAdminService.class); + private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; + private static final String TEST_DEVICE_TYPE_1 = "DUMMY-DEVICE-TYPE-1"; + private static final String TEST_DEVICE_TYPE_2 = "DUMMY DEVICE TYPE"; + private static final int TEST_DEVICE_TYPE_ID = 12345; + private static final int TEST_DEVICE_TYPE_ID_1 = 123452; + private static final int TEST_DEVICE_TYPE_ID_2 = 121233452; + private DeviceTypeManagementAdminService deviceTypeManagementAdminService; + private DeviceManagementProviderService deviceManagementProviderService; + private DeviceTypeGeneratorService deviceTypeGeneratorService; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() throws DeviceManagementException { + log.info("Initializing DeviceTypeManagementAdmin tests"); + initMocks(this); + this.deviceManagementProviderService = Mockito + .mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS); + this.deviceTypeGeneratorService = Mockito.mock(DeviceTypeGeneratorServiceImpl.class, Mockito.RETURNS_MOCKS); + this.deviceTypeManagementAdminService = new DeviceTypeManagementAdminServiceImpl(); + } + + @Test(description = "Test get all the device types.") + public void testGetDeviceTypes() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + Response response = this.deviceTypeManagementAdminService.getDeviceTypes(); + + log.info(response.getEntity()); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The Response status code " + + "should be 200."); + } + + @Test(description = "Test the error scenario of getting all the device types.") + public void testGetDeviceTypesError() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + Mockito.when(deviceManagementProviderService.getDeviceTypes()).thenThrow(new DeviceManagementException()); + Response response = this.deviceTypeManagementAdminService.getDeviceTypes(); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The expected status code is 500."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test the new device type creation scenario.") + public void testAddDeviceTypeWithExistingName() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE_1, TEST_DEVICE_TYPE_ID_1); + Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType); + + log.info(response.getEntity()); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(), + "The Response Status code should be 409."); + } + + @Test(description = "Test the new device type creation scenario when device type name is unqualified.") + public void testAddDeviceTypeWithUnqualifiedName() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE_2, TEST_DEVICE_TYPE_ID_2); + Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType); + + log.info(response.getEntity()); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The Response Status code should be 400."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test creating a new device type success scenario.") + public void testAddDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService")) + .toReturn(this.deviceTypeGeneratorService); + + Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); + Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The Response Status code should be 200."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test the create device type scenario when the device type is null.") + public void testAddDeviceTypeWithNoDeviceType() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + Response response = this.deviceTypeManagementAdminService.addDeviceType(null); + + log.info(response.getEntity()); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The Response Status code should be 409."); + } + + @Test(description = "Test the device type creation scenario with Device Management exception.") + public void testAddDeviceTypeWithException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenThrow(new + DeviceManagementException()); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); + Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The Response Status code should be 500."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test the update device type scenario.") + public void testUpdateDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService")) + .toReturn(this.deviceTypeGeneratorService); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); + Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The Response Status code should be 200."); + } + + @Test(description = "Test the update device type scenario.") + public void testUpdateNonExistingDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService")) + .toReturn(this.deviceTypeGeneratorService); + Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); + Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The Response Status code should be 400."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test update device Type when device type is null") + public void testUpdateDeviceTypeWithNullDeviceType() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + Response response = this.deviceTypeManagementAdminService.updateDeviceType(null); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The Response Status code should be 400."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test update device Type with DeviceManagementException") + public void testUpdateDeviceTypeWithException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())) + .thenThrow(new DeviceManagementException()); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); + Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType); + + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The Response Status code should be 500."); + Mockito.reset(deviceManagementProviderService); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceTest.java new file mode 100644 index 0000000000..2062f7dc44 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceTest.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceTypeManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; + +import javax.ws.rs.core.Response; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This class holds the unit tests for the class {@link DeviceTypeManagementService} + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils"}) +@PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class}) +public class DeviceTypeManagementServiceTest { + + private static final Log log = LogFactory.getLog(DeviceManagementServiceImplTest.class); + private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; + private static final int TEST_DEVICE_TYPE_ID = 12345; + private static final String MODIFIED_SINCE = "1234503934242"; + private DeviceTypeManagementService deviceTypeManagementService; + private DeviceManagementProviderService deviceManagementProviderService; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() throws DeviceManagementException { + log.info("Initializing DeviceTypeManagement tests"); + initMocks(this); + this.deviceManagementProviderService = Mockito + .mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS); + this.deviceTypeManagementService = new DeviceTypeManagementServiceImpl(); + } + + @Test(description = "Testing for existing device types.") + public void testExistingDeviceType() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceTypeManagementService.getDeviceTypes(""); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response states should be 200."); + } + + @Test(description = "Testing get existing device types error") + public void testExistingDeviceTypesError() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDeviceTypes()).thenThrow(new DeviceManagementException()); + + Response response = this.deviceTypeManagementService.getDeviceTypes(); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Testing get existing device types error") + public void testExistingDeviceTypesModifiedError() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenThrow(new + DeviceManagementException()); + + Response response = this.deviceTypeManagementService.getDeviceTypes(MODIFIED_SINCE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test case to retrieve the Features of specified device type.") + public void testGetDeviceTypeFeatures() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, MODIFIED_SINCE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200."); + } + + @Test(description = "Test case to test the error scenario when retrieving the Features of specified device type.") + public void testGetDeviceTypeFeaturesError() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + FeatureManager featureManager = Mockito.mock(FeatureManager.class); + Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn + (featureManager); + Mockito.when((featureManager).getFeatures()).thenThrow(new DeviceManagementException()); + Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, MODIFIED_SINCE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500."); + Mockito.reset(deviceManagementProviderService); + Mockito.reset(featureManager); + } + + @Test(description = "Test getting device type features when feature manager is null.") + public void testGetDeviceTypeFeaturesWithNoFeatureManager() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn(null); + Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, MODIFIED_SINCE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "The response status should be 404."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test to get all the device types.") + public void testGetDeviceTypes() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceTypeManagementService.getDeviceTypes(); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200."); + } + + @Test(description = "Test to get all the device types.") + public void testGetDeviceTypesWithDeviceTypes() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + List deviceTypes = DeviceMgtAPITestHelper.getDummyDeviceTypeList(5); + Mockito.when(this.deviceManagementProviderService.getDeviceTypes()).thenReturn(deviceTypes); + + Response response = this.deviceTypeManagementService.getDeviceTypes(); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response state should be 200"); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test to get all the device types for the given name") + public void testGetDeviceTypeByName() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200."); + } + + @Test(description = "Test the scenario when there are no device types for the given name.") + public void testGetDeviceTypeByNameError() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null); + + Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(), + "The response status should be 204."); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test the scenario when there are no device types for the given name.") + public void testGetDeviceTypeByNameException() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + Mockito.reset(deviceManagementProviderService); + } + + @Test(description = "Test to get all the device types when given name is null") + public void testGetDeviceTypeByNameBadRequest() throws Exception { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Response response = this.deviceTypeManagementService.getDeviceTypeByName(null); + Assert.assertNotNull(response, "The response object is null."); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test to clear the sensitive metadata information of device type") + public void testClearMetaEntryInfo() throws NoSuchMethodException, InvocationTargetException, + IllegalAccessException { + Method clearMetaEntryInfo = DeviceTypeManagementServiceImpl.class.getDeclaredMethod("clearMetaEntryInfo", + DeviceType.class); + clearMetaEntryInfo.setAccessible(true); + + DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID); + DeviceType returned = (DeviceType) clearMetaEntryInfo.invoke(this.deviceTypeManagementService, deviceType); + + Assert.assertNotNull(returned.getDeviceTypeMetaDefinition(), "The response object is null."); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java new file mode 100644 index 0000000000..5fa279b6a0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Helper class for Device Management API test cases. + */ +public class DeviceMgtAPITestHelper { + + private static final String DEVICE_TYPE_DESCRIPTION = "Dummy Description"; + public static final String DEVICE_TYPE = "TEST_DEVICE_TYPE"; + public static final String DEVICE_NAME = "TEST_DEVICE"; + public static final String DEVICE_IDENTIFIER = "12345"; + public final static String OWNER = "admin"; + + /** + * Creates a Device Type with given name and given id. + * If the name is null, the TEST_DEVICE_TYPE will be used as the name. + * + * @param name : Name of the device type. + * @param deviceTypeId : The Id of the device type. + * @return DeviceType + */ + public static DeviceType getDummyDeviceType(String name, int deviceTypeId) { + DeviceType deviceType = new DeviceType(); + deviceType.setId(deviceTypeId); + deviceType.setName(name != null ? name : DEVICE_TYPE); + + DeviceTypeMetaDefinition deviceTypeMetaDefinition = new DeviceTypeMetaDefinition(); + deviceTypeMetaDefinition.setClaimable(true); + deviceTypeMetaDefinition.setDescription(DEVICE_TYPE_DESCRIPTION); + + PushNotificationConfig pushNotificationConfig = + new PushNotificationConfig(name, true, null); + deviceTypeMetaDefinition.setPushNotificationConfig(pushNotificationConfig); + + deviceType.setDeviceTypeMetaDefinition(deviceTypeMetaDefinition); + return deviceType; + } + + /** + * Generates a list of device types. + * + * @param count: The number of device types that is needed. + * @return List : A list of device types. + */ + public static List getDummyDeviceTypeList(int count) { + List deviceTypes = new ArrayList<>(); + + for (int i = 0; i < count; i++) { + DeviceType deviceType = getDummyDeviceType(DEVICE_TYPE + count, count); + deviceTypes.add(deviceType); + } + + return deviceTypes; + } + + public static Device generateDummyDevice(String deviceType, String identifier) { + Device device = new Device(); + device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo + .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE)); + device.setDescription("Test Description"); + device.setDeviceIdentifier(identifier); + device.setType(deviceType); + device.setDeviceInfo(generateDeviceInfo()); + device.setName(DEVICE_NAME); + device.setFeatures(new ArrayList<>()); + device.setProperties(new ArrayList<>()); + return device; + } + + public static EnrolmentInfo generateEnrollmentInfo(long dateOfEnrollment, long dateOfLastUpdate, + String owner, EnrolmentInfo.OwnerShip ownership, + EnrolmentInfo.Status status) { + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(dateOfEnrollment); + enrolmentInfo.setDateOfLastUpdate(dateOfLastUpdate); + enrolmentInfo.setOwner(owner); + enrolmentInfo.setOwnership(ownership); + enrolmentInfo.setStatus(status); + return enrolmentInfo; + } + + public static DeviceInfo generateDeviceInfo() { + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setIMEI("IMEI-12345"); + deviceInfo.setIMSI("IMSI-12344"); + deviceInfo.setDeviceModel("DUMMY_MODEL"); + deviceInfo.setVendor("WSO2"); + deviceInfo.setOsVersion("OREO"); + deviceInfo.setOsBuildDate("24-05-2017"); + deviceInfo.setBatteryLevel(25.0); + deviceInfo.setInternalTotalMemory(1.5); + deviceInfo.setInternalAvailableMemory(2.5); + deviceInfo.setExternalTotalMemory(16.76); + deviceInfo.setExternalAvailableMemory(4.56); + deviceInfo.setConnectionType("CON_TYPE"); + deviceInfo.setSsid("SSID"); + deviceInfo.setCpuUsage(23.5); + deviceInfo.setTotalRAMMemory(1.5); + deviceInfo.setAvailableRAMMemory(2.33); + deviceInfo.setPluggedIn(true); + return deviceInfo; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/log4j.properties b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/log4j.properties new file mode 100644 index 0000000000..e415fd607d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/log4j.properties @@ -0,0 +1,34 @@ +# +# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +# +# WSO2 Inc. licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +# +# This is the log4j configuration file used by WSO2 Carbon +# +# IMPORTANT : Please do not remove or change the names of any +# of the Appender defined here. The layout pattern & log file +# can be changed using the WSO2 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=DEBUG, STD_OUT + +# Redirect log messages to console +log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender +log4j.appender.STD_OUT.Target=System.out +log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout +log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml new file mode 100644 index 0000000000..aa09de781f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml index a8100ff934..97ca36a215 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml @@ -21,7 +21,7 @@ device-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 415716e556..184c6f6a9b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 1dc588f0e1..e083572b1a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -1062,9 +1062,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { conn = this.getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "e.DATE_OF_ENROLMENT, e.ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e" + + ".OWNERSHIP, e.STATUS, e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS " + + "ENROLMENT_ID FROM DM_ENROLMENT e WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 7bfe0dd31e..da64cb2a84 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -147,7 +147,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public FeatureManager getFeatureManager(String deviceType) { + public FeatureManager getFeatureManager(String deviceType) throws DeviceManagementException { DeviceManager deviceManager = this.getDeviceManager(deviceType); if (deviceManager == null) { if (log.isDebugEnabled()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 69efaa107d..2b6a7b0bb4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -445,11 +445,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } private int getGroupCount(GroupPaginationRequest request) throws GroupManagementException { - if (request == null) { - String msg = "Received empty request for getGroupCount"; - log.error(msg); - throw new GroupManagementException(msg); - } if (log.isDebugEnabled()) { log.debug("Get groups count, pagination request " + request.toString()); } @@ -522,7 +517,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( tenantId).getUserStoreManager(); - List currentUserRoles = getRoles(groupId); + } catch (UserStoreException e) { + String msg = "User store error in updating sharing roles."; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } + List currentUserRoles = getRoles(groupId); + try { + GroupManagementDAOFactory.beginTransaction(); if (newRoles != null) { for (String role : newRoles) { @@ -546,10 +548,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid GroupManagementDAOFactory.rollbackTransaction(); log.error(e); throw new GroupManagementException(e); - } catch (UserStoreException e) { - String msg = "User store error in updating sharing roles."; - log.error(msg, e); - throw new GroupManagementException(msg, e); } catch (TransactionManagementException e) { log.error(e); throw new GroupManagementException(e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java index e30edc3f48..b67a0ceb27 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java @@ -95,7 +95,7 @@ public class TestDeviceManager implements DeviceManager { @Override public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { - return false; + return true; } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheManagerImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheManagerImplTest.java new file mode 100644 index 0000000000..4d6fa89375 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/cache/DeviceCacheManagerImplTest.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.cache; + +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; +import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; +import org.wso2.carbon.device.mgt.core.common.TestDataHolder; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; +import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/* + Unit tests for DeviceCacheManagerImpl + */ +public class DeviceCacheManagerImplTest extends BaseDeviceManagementTest { + private static final int NO_OF_DEVICES = 5; + private static final String UPDATE_NAME = "updatedName"; + private static final String DEVICE_TYPE = "TEST_TYPE"; + private static final String DEVICE_ID_PREFIX = "TEST-DEVICE-ID-"; + private DeviceCacheManagerImpl deviceCacheManager; + private List deviceIds = new ArrayList<>(); + private List devices = new ArrayList<>(); + private List deviceCacheKeyList = new ArrayList<>(); + + @BeforeClass + public void init() throws DeviceManagementException, IOException { + DeviceConfigurationManager.getInstance().initConfig(); + for (int i = 0; i < NO_OF_DEVICES; i++) { + deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE)); + } + devices = TestDataHolder.generateDummyDeviceData(this.deviceIds); + deviceCacheManager = Mockito.mock(DeviceCacheManagerImpl.class, Mockito.CALLS_REAL_METHODS); + DeviceCacheConfiguration configuration = new DeviceCacheConfiguration(); + configuration.setEnabled(true); + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + config.setDeviceCacheConfiguration(configuration); + initializeCarbonContext(); + } + + private void initializeCarbonContext() throws IOException { + if (System.getProperty("carbon.home") == null) { + File file = new File("src/test/resources"); + if (file.exists()) { + System.setProperty("carbon.home", file.getAbsolutePath()); + } + } + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( + org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID); + } + + @Test(description = "Adding all test devices to the cache") + public void testAddDeviceToCache() throws DeviceManagementException { + for (int i = 0; i < NO_OF_DEVICES; i++) { + deviceCacheManager.addDeviceToCache(deviceIds.get(i), devices.get(i), MultitenantConstants.SUPER_TENANT_ID); + } + } + + @Test(description = "Adding existing device again", dependsOnMethods = {"testAddDeviceToCache"}) + public void testAddExistingDeviceToCache() throws DeviceManagementException { + deviceCacheManager.addDeviceToCache(deviceIds.get(0), devices.get(0), MultitenantConstants.SUPER_TENANT_ID); + } + + @Test(description = "test updating and getting a device in Cache", + dependsOnMethods = {"testAddExistingDeviceToCache"}) + public void testUpdateDeviceInCache() { + devices.get(0).setName(UPDATE_NAME); + deviceCacheManager.updateDeviceInCache(deviceIds.get(0), devices.get(0), MultitenantConstants.SUPER_TENANT_ID); + Device tempDevice = deviceCacheManager.getDeviceFromCache(deviceIds.get(0), MultitenantConstants + .SUPER_TENANT_ID); + Assert.assertEquals(tempDevice.getName(), UPDATE_NAME,"Device name not updated in the cache"); + } + + @Test(description = "test getting a device from cache", dependsOnMethods = {"testAddDeviceToCache"}) + public void testGetDeviceFromCache() throws DeviceManagementException { + Device tempDevice = deviceCacheManager.getDeviceFromCache(deviceIds.get(1), MultitenantConstants + .SUPER_TENANT_ID); + Assert.assertEquals(tempDevice, devices.get(1),"Received device from cache is not matching " + + "with the saved device"); + } + + @Test(description = "test removing a device from cache", dependsOnMethods = {"testUpdateDeviceInCache"}) + public void testRemoveDeviceFromCache() throws DeviceManagementException { + deviceCacheManager.removeDeviceFromCache(deviceIds.get(0), MultitenantConstants.SUPER_TENANT_ID); + } + + @Test(description = "test removing list of devices from cache", dependsOnMethods = {"testRemoveDeviceFromCache"}) + public void testRemoveDevicesFromCache() { + //starting from index 1 since 0 is already deleted + for (int i = 1; i < NO_OF_DEVICES; i++) { + DeviceCacheKey deviceCacheKey = new DeviceCacheKey(); + deviceCacheKey.setDeviceId(devices.get(i).getDeviceIdentifier()); + deviceCacheKey.setDeviceType(devices.get(i).getType()); + deviceCacheKey.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + deviceCacheKeyList.add(deviceCacheKey); + } + deviceCacheManager.removeDevicesFromCache(deviceCacheKeyList); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java index 0c72394baf..a1cb8cd21e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java @@ -497,6 +497,17 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes return resultSet; } + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testUpdateDeviceInfo() throws DeviceManagementException, + TransactionManagementException, DeviceDetailsMgtDAOException { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); + + boolean status = deviceMgtService.updateDeviceInfo(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE), device); + Assert.assertTrue(status); + } + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) public void testDeviceByDateWithNonExistentDevice() throws DeviceManagementException, TransactionManagementException, DeviceDetailsMgtDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java new file mode 100644 index 0000000000..c8ebdd37d2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceNegativeTest.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.service; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceNotFoundException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException; +import org.wso2.carbon.device.mgt.core.TestUtils; +import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + +/** + * This test class is used for for testing negative scenarios of {@link GroupManagementProviderService} + */ +public class GroupManagementProviderServiceNegativeTest extends BaseDeviceManagementTest { + private GroupManagementProviderService groupManagementProviderService; + + @BeforeClass + @Override + public void init() throws Exception { + DataSource datasource = this.getDataSource(this. + readDataSourceConfig("src/test/resources/config/datasource/no-table-data-source-config.xml")); + GroupManagementDAOFactory.init(datasource); + groupManagementProviderService = new GroupManagementProviderServiceImpl(); + } + + @Test(description = "This method tests the addDevices method under negative scenarios", + expectedExceptions = {GroupManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while adding device to group.*") + public void testAddDevicesScenario1() throws GroupManagementException, DeviceNotFoundException { + List list = TestUtils.getDeviceIdentifiersList(); + groupManagementProviderService.addDevices(1, list); + } + + @Test(description = "This method tests the addDevices method under negative circumstances", expectedExceptions = + {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred in addDevices for.*") + public void testAddDevicesScenario2() throws GroupManagementException, DeviceNotFoundException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier("test", "test"); + List list = new ArrayList<>(); + list.add(deviceIdentifier); + groupManagementProviderService.addDevices(1, list); + } + + @Test(description = "This method tests the getGroup method of the GroupManagementProviderService under " + + "negative conditions", expectedExceptions = {GroupManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while obtaining group.*") + public void testGetGroup() throws GroupManagementException { + groupManagementProviderService.getGroup(1); + } + + @Test(description = "This method tests the getGroup method of the GroupManagementProviderService under " + + "negative conditions", expectedExceptions = {GroupManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while obtaining group with name.*") + public void testGetGroupWithName() throws GroupManagementException { + groupManagementProviderService.getGroup("1"); + } + + @Test(description = "This method tests the getGroups method of the GroupManagementProviderService under negative " + + "conditions", expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = + "Error occurred while retrieving all groups in tenant.*") + public void testGetGroups() throws GroupManagementException { + groupManagementProviderService.getGroups(); + } + + @Test(description = "This method tests the getGroups method of the GroupManagementProviderService under negative " + + "conditions", expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = + "Error occurred while retrieving all groups accessible to user.*") + public void testGetGroupsWithUserName() throws GroupManagementException { + groupManagementProviderService.getGroups("test"); + } + + @Test(description = "This method tests the getGroupCount method under negative circumstances", expectedExceptions + = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred while retrieving all " + + "groups in tenant") + public void testGetGroupCount() throws GroupManagementException { + groupManagementProviderService.getGroupCount(); + } + + @Test(description = "This method tests the getGroupCount method with username under negative circumstances", + expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred " + + "while retrieving group count of user.*") + public void testGetGroupCountWithUserName() throws GroupManagementException { + groupManagementProviderService.getGroupCount("test"); + + } + + @Test(description = "This method tests the getGroups method with pagination request under negative " + + "circumstances", expectedExceptions = {GroupManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while retrieving all groups in tenant") + public void testGetGroupsWithPaginationRequest() throws GroupManagementException { + groupManagementProviderService.getGroups(TestUtils.createPaginationRequest()); + } + + @Test(description = "This method tests the getGroups method with pagination request and username under negative " + + "circumstances", expectedExceptions = {GroupManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while retrieving all groups accessible to user.") + public void testGetGroupsWithPaginationRequestAndUserName() throws GroupManagementException { + groupManagementProviderService.getGroups("test", TestUtils.createPaginationRequest()); + } + + @Test(description = "This method tests the get roles method under negative circumstances", + expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred " + + "while retrieving all groups in tenant.*") + public void testManageGroupSharing() throws GroupManagementException, RoleDoesNotExistException { + groupManagementProviderService.getRoles(1); + } + + @Test(description = "This method tests the getDeviceCount under negative circumstances.", expectedExceptions = + {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred while retrieving all " + + "groups in tenant.*") + public void testGetDeviceCount() throws GroupManagementException { + groupManagementProviderService.getDeviceCount(1); + } + + @Test(description = "This method tests the getDevices method under negative circumstances", expectedExceptions = + {GroupManagementException.class}) + public void testGetDevicesWithPagination() throws GroupManagementException { + groupManagementProviderService.getDevices(1, 0, 10); + } + + @Test(description = "This method tests the getGroupCount with username when the user name is given as null", + expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Received empty " + + "user name for getGroupCount.*") + public void testGetGroupCountWithUserName2() throws GroupManagementException { + groupManagementProviderService.getGroupCount(null); + } + + @Test(description = "This method tests getGroups method under negative circumstances", + expectedExceptionsMessageRegExp = "Received empty device identifier for getGroups", + expectedExceptions = {GroupManagementException.class}) + public void testGetGroupsWithDeviceIdentifier() throws GroupManagementException { + groupManagementProviderService.getGroups((DeviceIdentifier) null); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml index c7dd69b8e0..c0fd2360d2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml @@ -56,6 +56,8 @@ + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 677bc14153..ac36cda059 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml index 560e9a724b..a246d15e92 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml index ff5f175e42..3bed399d20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml @@ -23,7 +23,7 @@ device-mgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index d9a947580d..b87524208b 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml b/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml index cf3cdd156a..4a2b9e2840 100644 --- a/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml +++ b/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt email-sender - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/components/email-sender/pom.xml b/components/email-sender/pom.xml index 394e889e8b..2e59bb12dd 100644 --- a/components/email-sender/pom.xml +++ b/components/email-sender/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml index 5ff9a37937..324ce2714e 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml @@ -22,13 +22,13 @@ org.wso2.carbon.devicemgt identity-extensions - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.oauth.extensions - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - OAuth Extensions http://wso2.org diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml index 92fcdd602d..cfd32a0fc3 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml @@ -21,7 +21,7 @@ identity-extensions org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT 4.0.0 diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml index 065f757aa4..9b9084d3ee 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt identity-extensions - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml @@ -94,6 +94,10 @@ org.opensaml xmltooling + + jboss + javassist + @@ -146,6 +150,16 @@ h2-database-engine test + + org.powermock + powermock-module-testng + test + + + org.powermock + powermock-api-mockito + test + diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientTest.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientTest.java index 33311c953d..a9c759e29e 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientTest.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientTest.java @@ -19,18 +19,39 @@ package org.wso2.carbon.identity.jwt.client.extension.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.testng.Assert; +import org.testng.IObjectFactory; import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; +import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.Properties; +@PrepareForTest(JWTClientUtil.class) public class JWTClientTest { - private static final Log log = LogFactory.getLog(JWTClientManagerServiceTest.class); + private static final Log log = LogFactory.getLog(JWTClientTest.class); + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } private JWTClient jwtClient; @@ -38,25 +59,158 @@ public class JWTClientTest { public void init() { Properties prop = new Properties(); prop.put("default-jwt-client", "true"); + prop.put("TokenEndpoint", "http://example.com"); jwtClient = new JWTClient(new JWTConfig(prop)); } @Test(description = "Test get JWT token.") public void testGetJwtToken() throws JWTClientException { - jwtClient.getJwtToken("admin"); + String mockToken = "123456789"; + PowerMockito.mockStatic(JWTClientUtil.class); + PowerMockito.when(JWTClientUtil.generateSignedJWTAssertion(Mockito.anyString(), Mockito.any(JWTConfig.class), + Mockito.anyBoolean())).thenReturn(mockToken); + String token = jwtClient.getJwtToken("admin"); + Assert.assertEquals(token, mockToken); } @Test(description = "Test get JWT token by claims.") public void testGetJwtTokenByClaims() throws JWTClientException { Map claims = new HashMap<>(); claims.put("name", "admin"); - jwtClient.getJwtToken("admin", claims); + String mockToken = "123456789"; + PowerMockito.mockStatic(JWTClientUtil.class); + PowerMockito.when(JWTClientUtil.generateSignedJWTAssertion(Mockito.anyString(), Mockito.any(JWTConfig.class), + Mockito.anyBoolean(), Mockito.any())).thenReturn(mockToken); + String token = jwtClient.getJwtToken("admin", claims); + Assert.assertEquals(token, mockToken); + } + + @Test(description = "Test get JWT token by tenant sign true.") + public void testGetJwtTokenByTenantSignTrue() throws JWTClientException { + Map claims = new HashMap<>(); + claims.put("name", "admin"); + String mockToken = "123456789"; + PowerMockito.mockStatic(JWTClientUtil.class); + PowerMockito.when(JWTClientUtil.generateSignedJWTAssertion(Mockito.anyString(), Mockito.any(JWTConfig.class), + Mockito.anyBoolean(), Mockito.any())).thenReturn(mockToken); + String token = jwtClient.getJwtToken("admin", claims, true); + Assert.assertEquals(token, mockToken); } - @Test(description = "Test get JWT token by tenant sign.") - public void testGetJwtTokenByTenantSign() throws JWTClientException { + @Test(description = "Test get JWT token by tenant sign false.") + public void testGetJwtTokenByTenantSignFalse() throws JWTClientException { Map claims = new HashMap<>(); claims.put("name", "admin"); - jwtClient.getJwtToken("admin", claims, true); + String mockToken = "123456789"; + PowerMockito.mockStatic(JWTClientUtil.class); + PowerMockito.when(JWTClientUtil.generateSignedJWTAssertion(Mockito.anyString(), Mockito.any(JWTConfig.class), + Mockito.anyBoolean(), Mockito.any())).thenReturn(mockToken); + String token = jwtClient.getJwtToken("admin", claims, false); + Assert.assertEquals(token, mockToken); + } + + @Test(description = "Test get token info.") + public void testGetTokenInfo() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, + IOException, JWTClientException { + mockJWTClientUtil(); + AccessTokenInfo tokenInfo = jwtClient.getAccessToken("key", "secret", "admin", "default"); + Assert.assertEquals(tokenInfo.getAccessToken(), "b7882d23f1f8257f4bc6cf4a20633ab1"); + } + + @Test(description = "Test get token info assertion null.") + public void testGetTokenInfoAssertionNull() throws KeyManagementException, NoSuchAlgorithmException, + KeyStoreException, + IOException { + HttpClient httpClient = Mockito.mock(HttpClient.class); + HttpResponse httpResponse = Mockito.mock(HttpResponse.class); + Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse); + + PowerMockito.mockStatic(JWTClientUtil.class); + try { + PowerMockito.when(JWTClientUtil.generateSignedJWTAssertion(Mockito.anyString(), Mockito.any(JWTConfig + .class), + + Mockito.anyBoolean())).thenReturn(null); + PowerMockito.when(JWTClientUtil.getHttpClient(Mockito.anyString())).thenReturn(httpClient); + PowerMockito.when(JWTClientUtil.getResponseString(Mockito.any(HttpResponse.class))).thenReturn + ("\n" + + "{\n" + + " \"scope\":\"default\",\n" + + " \"token_type\":\"Bearer\",\n" + + " \"expires_in\":3600,\n" + + " \"refresh_token\":\"7ed6bae2b1d36c041787e8c8e2d6cbf8\",\n" + + " \"access_token\":\"b7882d23f1f8257f4bc6cf4a20633ab1\"\n" + + "}"); + jwtClient.getAccessToken("key", "secret", "admin", "default"); + Assert.fail(); + } catch (JWTClientException e) { + Assert.assertNotNull(e); + } + } + + @Test(description = "Test get token info with encoded app credentials.") + public void testGetTokenInfoWithEncodeCredentials() throws KeyManagementException, NoSuchAlgorithmException, + KeyStoreException, + IOException, JWTClientException { + mockJWTClientUtil(); + AccessTokenInfo tokenInfo = jwtClient.getAccessToken("a2V5OnNlY3JldA==", "admin", "default"); + Assert.assertEquals(tokenInfo.getAccessToken(), "b7882d23f1f8257f4bc6cf4a20633ab1"); + } + + @Test(description = "Test get token info with invalid encoded app credentials.") + public void testGetTokenInfoWithInvalidEncodeCredentials() throws KeyManagementException, + NoSuchAlgorithmException, KeyStoreException, + IOException { + try { + mockJWTClientUtil(); + jwtClient.getAccessToken("8s7d6fgh4j3", "admin", "default"); + Assert.fail(); + } catch (JWTClientException e) { + Assert.assertNotNull(e); + } + } + + @Test(description = "Test get token info with name value pair.") + public void testGetTokenInfoWithNameValue() throws KeyManagementException, NoSuchAlgorithmException, + KeyStoreException, + IOException, JWTClientException { + mockJWTClientUtil(); + Map map = new HashMap(); + map.put("admin", "admin"); + AccessTokenInfo tokenInfo = jwtClient.getAccessToken("key", "secret", "admin", "default", map); + Assert.assertEquals(tokenInfo.getAccessToken(), "b7882d23f1f8257f4bc6cf4a20633ab1"); + } + + @Test(description = "Test get token from refresh token.") + public void testGetAccessTokenFromRefreshToken() throws KeyManagementException, NoSuchAlgorithmException, + KeyStoreException, + IOException, JWTClientException { + mockJWTClientUtil(); + Map map = new HashMap(); + map.put("admin", "admin"); + AccessTokenInfo tokenInfo = jwtClient.getAccessTokenFromRefreshToken("7ed6bae2b1d36c041787e8c8e2d6cbf8", + "admin", "default", "key", "secret"); + Assert.assertEquals(tokenInfo.getAccessToken(), "b7882d23f1f8257f4bc6cf4a20633ab1"); + } + + private void mockJWTClientUtil() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, + IOException, JWTClientException { + HttpClient httpClient = Mockito.mock(HttpClient.class); + HttpResponse httpResponse = Mockito.mock(HttpResponse.class); + Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse); + + PowerMockito.mockStatic(JWTClientUtil.class); + PowerMockito.when(JWTClientUtil.generateSignedJWTAssertion(Mockito.anyString(), Mockito.any(JWTConfig.class), + Mockito.anyBoolean())).thenReturn("b7882d23f1f8257f4bc6cf4a20633ab1"); + PowerMockito.when(JWTClientUtil.getHttpClient(Mockito.anyString())).thenReturn(httpClient); + PowerMockito.when(JWTClientUtil.getResponseString(Mockito.any(HttpResponse.class))).thenReturn + ("\n" + + "{\n" + + " \"scope\":\"default\",\n" + + " \"token_type\":\"Bearer\",\n" + + " \"expires_in\":3600,\n" + + " \"refresh_token\":\"7ed6bae2b1d36c041787e8c8e2d6cbf8\",\n" + + " \"access_token\":\"b7882d23f1f8257f4bc6cf4a20633ab1\"\n" + + "}"); } } diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/resources/log4j.properties b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/resources/log4j.properties index 90c5d0edce..7e18cfdc75 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/resources/log4j.properties +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/test/resources/log4j.properties @@ -25,7 +25,7 @@ # settings will override the settings in this file. # -log4j.rootLogger=DEBUG, STD_OUT +log4j.rootLogger=INFO, STD_OUT # Redirect log messages to console log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 5cd4de1336..141f5139ef 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml index ddc111c6dd..a4bdeaf103 100644 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt policy-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.complex.policy.decision.point - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Policy Decision Point WSO2 Carbon - Policy Decision Point diff --git a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml index 31e23434ee..8ff32fcdc0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml @@ -3,14 +3,14 @@ org.wso2.carbon.devicemgt policy-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.decision.point - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Policy Decision Point WSO2 Carbon - Policy Decision Point diff --git a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml index 9593e9caf9..7178c06f5e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml @@ -3,7 +3,7 @@ org.wso2.carbon.devicemgt policy-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.information.point - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Policy Information Point WSO2 Carbon - Policy Information Point diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml index b87008bf7b..e922d2a15b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt policy-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.mgt.common - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Policy Management Common WSO2 Carbon - Policy Management Common diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java index 91e1eff05c..eab6f6214f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java @@ -154,11 +154,5 @@ public interface PolicyAdministratorPoint { List getProfiles() throws PolicyManagementException; -// Feature addFeature(Feature feature) throws FeatureManagementException; -// -// Feature updateFeature(Feature feature) throws FeatureManagementException; - - boolean deleteFeature(int featureId) throws FeatureManagementException; - int getPolicyCount() throws PolicyManagementException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml index f91853b45c..bae78282cd 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt policy-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.mgt.core - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Policy Management Core WSO2 Carbon - Policy Management Core @@ -223,9 +223,14 @@ - org.mockito - mockito-core - 2.10.0 + org.powermock + powermock-api-mockito + test + + + org.powermock + powermock-module-testng + test diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java index e64b8214df..00d7280a9d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/FeatureDAO.java @@ -96,15 +96,6 @@ public interface FeatureDAO { */ List getFeaturesForProfile(int profileId) throws FeatureManagerDAOException; - /** - * This method is used remove a feature. - * - * @param featureId id of the removing feature. - * @return returns true if success. - * @throws FeatureManagerDAOException - */ - boolean deleteFeature(int featureId) throws FeatureManagerDAOException; - /** * This method is used to remove set of features of given profile. * @@ -123,6 +114,13 @@ public interface FeatureDAO { */ boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException; + /** + * This method is used to remove a profile feature of given feature id. + * + * @param featureId id of the feature. + * @return returns true if success. + * @throws FeatureManagerDAOException + */ boolean deleteProfileFeatures(int featureId) throws FeatureManagerDAOException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java index 32e00c03c4..1483e6ebc7 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java @@ -180,7 +180,7 @@ public class ProfileDAOImpl implements ProfileDAO { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; - Profile profile = new Profile(); + Profile profile = null; try { conn = this.getConnection(); String query = "SELECT * FROM DM_PROFILE WHERE ID = ?"; @@ -189,7 +189,7 @@ public class ProfileDAOImpl implements ProfileDAO { resultSet = stmt.executeQuery(); while (resultSet.next()) { - + profile = new Profile(); profile.setProfileId(profileId); profile.setProfileName(resultSet.getString("PROFILE_NAME")); profile.setTenantId(resultSet.getInt("TENANT_ID")); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java index 2c3da0e30c..8d04fdec5b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/feature/AbstractFeatureDAO.java @@ -30,6 +30,7 @@ import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; +import javax.naming.OperationNotSupportedException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; @@ -49,13 +50,13 @@ public abstract class AbstractFeatureDAO implements FeatureDAO { @Override public ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException { - return null; + throw new UnsupportedOperationException(); } @Override public ProfileFeature updateProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagerDAOException { - return null; + throw new UnsupportedOperationException(); } @Override @@ -311,30 +312,6 @@ public abstract class AbstractFeatureDAO implements FeatureDAO { return featureList; } - @Override - public boolean deleteFeature(int featureId) throws FeatureManagerDAOException { - Connection conn; - PreparedStatement stmt = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - - try { - conn = this.getConnection(); - String query = "DELETE FROM DM_FEATURES WHERE ID = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(query); - stmt.setInt(1, featureId); - stmt.setInt(2, tenantId); - if(stmt.executeUpdate() > 0) { - return true; - } - return false; - } catch (SQLException e) { - throw new FeatureManagerDAOException("Unable to delete the feature " + featureId + " (Feature ID) " + - "from database.", e); - } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, null); - } - } - private Connection getConnection() throws FeatureManagerDAOException { return PolicyManagementDAOFactory.getConnection(); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index 50d58c3bf4..d595a3c4eb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -338,22 +338,6 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { } } - /* @Override - public Feature addFeature(Feature feature) throws FeatureManagementException { - return featureManager.addFeature(feature); - } - - @Override - public Feature updateFeature(Feature feature) throws FeatureManagementException { - return featureManager.updateFeature(feature); - - }*/ - - @Override - public boolean deleteFeature(int featureId) throws FeatureManagementException { - return featureManager.deleteFeature(featureId); - } - @Override public int getPolicyCount() throws PolicyManagementException { return PolicyCacheManagerImpl.getInstance().getAllPolicies().size(); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/FeatureManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/FeatureManager.java index 9c4673a84a..e0c6f3fdbe 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/FeatureManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/FeatureManager.java @@ -21,36 +21,27 @@ package org.wso2.carbon.policy.mgt.core.mgt; import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; +import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import java.util.List; public interface FeatureManager { - /*Feature addFeature(Feature feature) throws FeatureManagementException; - - public List addFeatures(List features) throws FeatureManagementException; - - Feature updateFeature(Feature feature) throws FeatureManagementException;*/ - - boolean deleteFeature(Feature feature) throws FeatureManagementException; - ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagementException; ProfileFeature updateProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagementException; - List addProfileFeatures(List features, int profileId) throws FeatureManagementException; - - List updateProfileFeatures(List features, int profileId) throws FeatureManagementException; + List addProfileFeatures(List features, int profileId) + throws FeatureManagementException; + List updateProfileFeatures(List features, int profileId) + throws FeatureManagementException; List getAllFeatures(String deviceType) throws FeatureManagementException; List getFeaturesForProfile(int profileId) throws FeatureManagementException; - boolean deleteFeature(int featureId) throws FeatureManagementException; - boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagementException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImpl.java index edaceae3f8..dff12ac54f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImpl.java @@ -21,13 +21,15 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; +import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO; import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO; +import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import java.sql.SQLException; @@ -36,130 +38,28 @@ import java.util.List; public class FeatureManagerImpl implements FeatureManager { private FeatureDAO featureDAO; + private ProfileDAO profileDAO; private static Log log = LogFactory.getLog(FeatureManagerImpl.class); public FeatureManagerImpl() { featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); - } - - /*@Override - public Feature addFeature(Feature feature) throws FeatureManagementException { - try { - PolicyManagementDAOFactory.beginTransaction(); - feature = featureDAO.addFeature(feature); - PolicyManagementDAOFactory.commitTransaction(); - - } catch (PolicyManagerDAOException e) { - try { - PolicyManagementDAOFactory.rollbackTransaction(); - } catch (PolicyManagerDAOException e1) { - log.warn("Unable to roll back the transaction"); - } - String msg = "Error occurred while adding feature (" + feature.getName() + ")"; - log.error(msg, e); - throw new FeatureManagementException(msg, e); - } catch (FeatureManagerDAOException e) { - try { - PolicyManagementDAOFactory.rollbackTransaction(); - } catch (PolicyManagerDAOException e1) { - log.warn("Unable to roll back the transaction"); - } - String msg = "Error occurred while adding feature (" + feature.getName() + ")"; - log.error(msg, e); - throw new FeatureManagementException(msg, e); - } - return feature; - }*/ - - /*@Override - public List addFeatures(List features) throws FeatureManagementException { - try { - PolicyManagementDAOFactory.beginTransaction(); - features = featureDAO.addFeatures(features); - PolicyManagementDAOFactory.commitTransaction(); - - } catch (PolicyManagerDAOException e) { - try { - PolicyManagementDAOFactory.rollbackTransaction(); - } catch (PolicyManagerDAOException e1) { - log.warn("Unable to roll back the transaction"); - } - String msg = "Error occurred while adding feature (" + features.size()+ ")"; - log.error(msg, e); - throw new FeatureManagementException(msg, e); - } catch (FeatureManagerDAOException e) { - try { - PolicyManagementDAOFactory.rollbackTransaction(); - } catch (PolicyManagerDAOException e1) { - log.warn("Unable to roll back the transaction"); - } - String msg = "Error occurred while adding feature (" + features.size() + ")"; - log.error(msg, e); - throw new FeatureManagementException(msg, e); - } - - return features; - }*/ - - /* @Override - public Feature updateFeature(Feature feature) throws FeatureManagementException { - try { - PolicyManagementDAOFactory.beginTransaction(); - feature = featureDAO.updateFeature(feature); - PolicyManagementDAOFactory.commitTransaction(); - - } catch (PolicyManagerDAOException e) { - try { - PolicyManagementDAOFactory.rollbackTransaction(); - } catch (PolicyManagerDAOException e1) { - log.warn("Unable to roll back the transaction"); - } - String msg = "Error occurred while updating feature (" + feature.getName() + ")"; - log.error(msg, e); - throw new FeatureManagementException(msg, e); - } catch (FeatureManagerDAOException e) { - try { - PolicyManagementDAOFactory.rollbackTransaction(); - } catch (PolicyManagerDAOException e1) { - log.warn("Unable to roll back the transaction"); - } - String msg = "Error occurred while updating feature (" + feature.getName() + ")"; - log.error(msg, e); - throw new FeatureManagementException(msg, e); - } - return feature; - }*/ - - @Override - public boolean deleteFeature(Feature feature) throws FeatureManagementException { - boolean bool; - try { - PolicyManagementDAOFactory.beginTransaction(); - bool = featureDAO.deleteFeature(feature.getId()); - PolicyManagementDAOFactory.commitTransaction(); - } catch (FeatureManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new FeatureManagementException("Error occurred while deleting the feature (" + feature.getName() + - ")", e); - } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new FeatureManagementException("Error occurred while deleting the feature (" + feature.getName() + - ") from database", e); - } finally { - PolicyManagementDAOFactory.closeConnection(); - } - return bool; + profileDAO = PolicyManagementDAOFactory.getProfileDAO(); } @Override public ProfileFeature addProfileFeature(ProfileFeature feature, int profileId) throws FeatureManagementException { try { PolicyManagementDAOFactory.beginTransaction(); + Profile profile = profileDAO.getProfile(profileId); + if (profile == null) { + throw new FeatureManagementException( + "Could not find a profile with the profile id: " + profileId); + } feature = featureDAO.addProfileFeature(feature, profileId); PolicyManagementDAOFactory.commitTransaction(); - } catch (PolicyManagerDAOException | FeatureManagerDAOException e) { + } catch (ProfileManagerDAOException | PolicyManagerDAOException | FeatureManagerDAOException e) { throw new FeatureManagementException("Error occurred while adding profile feature (" + - feature.getFeatureCode() + " - " + profileId + ")", e); + feature.getFeatureCode() + " - " + profileId + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -168,16 +68,22 @@ public class FeatureManagerImpl implements FeatureManager { @Override public ProfileFeature updateProfileFeature(ProfileFeature feature, int profileId) throws - FeatureManagementException { + FeatureManagementException { try { PolicyManagementDAOFactory.beginTransaction(); + Profile profile = profileDAO.getProfile(profileId); + if (profile == null) { + throw new FeatureManagementException( + "Could not find a profile with the profile id: " + profileId); + } feature = featureDAO.updateProfileFeature(feature, profileId); PolicyManagementDAOFactory.commitTransaction(); - } catch (FeatureManagerDAOException | PolicyManagerDAOException e) { + } catch (ProfileManagerDAOException | FeatureManagerDAOException | PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while updating feature (" + - feature.getFeatureCode() + " - " + profileId + ") in database.", e); + feature.getFeatureCode() + " - " + profileId + + ") in database.", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -186,19 +92,23 @@ public class FeatureManagerImpl implements FeatureManager { @Override public List addProfileFeatures(List features, int profileId) throws - FeatureManagementException { + FeatureManagementException { try { PolicyManagementDAOFactory.beginTransaction(); + Profile profile = profileDAO.getProfile(profileId); + if (profile == null) { + throw new FeatureManagementException( + "Could not find a profile with the profile id: " + profileId); + } features = featureDAO.addProfileFeatures(features, profileId); PolicyManagementDAOFactory.commitTransaction(); - } catch (FeatureManagerDAOException e) { + } catch (ProfileManagerDAOException | FeatureManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while adding the features to profile id (" + - profileId + ")", e); + profileId + ")", e); } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while adding the features to profile id (" + - profileId + ") to the database", e); + profileId + ") to the database", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -207,25 +117,28 @@ public class FeatureManagerImpl implements FeatureManager { @Override public List updateProfileFeatures(List features, int profileId) throws - FeatureManagementException { + FeatureManagementException { try { PolicyManagementDAOFactory.beginTransaction(); + Profile profile = profileDAO.getProfile(profileId); + if (profile == null) { + throw new FeatureManagementException( + "Could not find a profile with the profile id: " + profileId); + } features = featureDAO.updateProfileFeatures(features, profileId); PolicyManagementDAOFactory.commitTransaction(); - } catch (FeatureManagerDAOException e) { + } catch (ProfileManagerDAOException | FeatureManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while updating the features to profile id (" + - profileId + ")", e); + profileId + ")", e); } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while updating the features to profile id (" + - profileId + ") to the database", e); + profileId + ") to the database", e); } finally { PolicyManagementDAOFactory.closeConnection(); } return features; } - @Override public List getAllFeatures(String deviceType) throws FeatureManagementException { @@ -245,8 +158,13 @@ public class FeatureManagerImpl implements FeatureManager { public List getFeaturesForProfile(int profileId) throws FeatureManagementException { try { PolicyManagementDAOFactory.openConnection(); + Profile profile = profileDAO.getProfile(profileId); + if (profile == null) { + throw new FeatureManagementException( + "Could not find a profile with the profile id: " + profileId); + } return featureDAO.getFeaturesForProfile(profileId); - } catch (FeatureManagerDAOException e) { + } catch (ProfileManagerDAOException | FeatureManagerDAOException e) { throw new FeatureManagementException("Error occurred while getting the features", e); } catch (SQLException e) { throw new FeatureManagementException("Error occurred while opening a connection to the data source", e); @@ -255,27 +173,6 @@ public class FeatureManagerImpl implements FeatureManager { } } - @Override - public boolean deleteFeature(int featureId) throws FeatureManagementException { - boolean bool; - try { - PolicyManagementDAOFactory.beginTransaction(); - bool = featureDAO.deleteFeature(featureId); - PolicyManagementDAOFactory.commitTransaction(); - } catch (FeatureManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new FeatureManagementException("Error occurred while deleting the feature - id (" + - featureId + ")", e); - } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new FeatureManagementException("Error occurred while deleting the feature - id (" + featureId + - ") from database.", e); - } finally { - PolicyManagementDAOFactory.closeConnection(); - } - return bool; - } - @Override public boolean deleteFeaturesOfProfile(Profile profile) throws FeatureManagementException { boolean bool; @@ -286,11 +183,10 @@ public class FeatureManagerImpl implements FeatureManager { } catch (FeatureManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while deleting the feature of - profile (" + - profile.getProfileName() + ")", e); + profile.getProfileName() + ")", e); } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new FeatureManagementException("Error occurred while deleting the feature of - profile (" + - profile.getProfileName() + ") from database", e); + profile.getProfileName() + ") from database", e); } finally { PolicyManagementDAOFactory.closeConnection(); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index ada8b58763..160d512ee5 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -20,12 +20,17 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.policy.mgt.common.ProfileManagementException; -import org.wso2.carbon.policy.mgt.core.dao.*; +import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO; +import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO; +import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException; import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; import java.sql.SQLException; @@ -70,7 +75,6 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while adding the profile features (" + profile.getProfileName() + ")", e); } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new ProfileManagementException("Error occurred while adding the profile (" + profile.getProfileName() + ") to the database", e); } finally { @@ -100,7 +104,6 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while updating the profile features (" + profile.getProfileName() + ")", e); } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new ProfileManagementException("Error occurred while updating the profile (" + profile.getProfileName() + ") to the database", e); } finally { @@ -127,7 +130,6 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while deleting the features from profile (" + profile.getProfileName() + ")", e); } catch (PolicyManagerDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new ProfileManagementException("Error occurred while deleting the profile (" + profile.getProfileName() + ") from database", e); } finally { @@ -143,6 +145,9 @@ public class ProfileManagerImpl implements ProfileManager { try { PolicyManagementDAOFactory.openConnection(); profile = profileDAO.getProfile(profileId); + if (profile == null) { + throw new ProfileManagementException("Profile is not available with profile id (" + profileId + ")"); + } featureList = featureDAO.getFeaturesForProfile(profileId); profile.setProfileFeaturesList(featureList); } catch (ProfileManagerDAOException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java index 9e86417fd0..230291206b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java @@ -21,45 +21,104 @@ package org.wso2.carbon.policy.mgt.core; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.testng.annotations.BeforeClass; +import org.testng.Assert; import org.testng.annotations.BeforeSuite; +import org.testng.internal.collections.Pair; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.DeviceNotFoundException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; +import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; -import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; +import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.common.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; +import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; +import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; +import org.wso2.carbon.registry.core.config.RegistryContext; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.internal.RegistryDataHolder; +import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.user.core.service.RealmService; import javax.sql.DataSource; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; +import java.io.InputStream; +import java.lang.reflect.Field; import java.sql.Connection; +import java.sql.DatabaseMetaData; import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public abstract class BasePolicyManagementDAOTest { private DataSource dataSource; private static final Log log = LogFactory.getLog(BasePolicyManagementDAOTest.class); + protected DeviceManagementProviderService deviceMgtService; + protected GroupManagementProviderService groupMgtService; + protected ProfileManager profileManager; + + private static final String ADMIN_USER = "admin"; + @BeforeSuite public void setupDataSource() throws Exception { this.initDatSource(); this.initSQLScript(); - this.initialize(); this.initiatePrivilegedCaronContext(); DeviceConfigurationManager.getInstance().initConfig(); } - public void initialize() throws TaskException { + protected void initializeServices() throws Exception { + initDatSource(); + initSQLScript(); + + DeviceConfigurationManager.getInstance().initConfig(); + + deviceMgtService = new DeviceManagementProviderServiceImpl(); + groupMgtService = new GroupManagementProviderServiceImpl(); + + DeviceManagementServiceComponent.notifyStartupListeners(); + DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService); + DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService()); + DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService( + new DeviceAccessAuthorizationServiceImpl()); + DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupMgtService); + DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); + + PolicyEvaluationPoint policyEvaluationPoint = new SimplePolicyEvaluationTest(); + PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint("Simple", policyEvaluationPoint); + PolicyManagementDataHolder.getInstance().setDeviceManagementService(deviceMgtService); + profileManager = new ProfileManagerImpl(); } public void initDatSource() throws Exception { @@ -93,14 +152,11 @@ public abstract class BasePolicyManagementDAOTest { } PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants - .SUPER_TENANT_DOMAIN_NAME); + .SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); } - @BeforeClass - public abstract void init() throws Exception; - private DataSource getDataSource(DataSourceConfig config) { PoolProperties properties = new PoolProperties(); properties.setUrl(config.getUrl()); @@ -138,4 +194,103 @@ public abstract class BasePolicyManagementDAOTest { return dataSource; } + + protected Object changeFieldValue(Object targetObj, String fieldName, Object valueObj) + throws IllegalAccessException, NoSuchFieldException { + Field field = targetObj.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + Object oldVal = field.get(targetObj); + field.set(targetObj, valueObj); + return oldVal; + } + + protected RegistryService getRegistryService() throws RegistryException { + RealmService realmService = new InMemoryRealmService(); + RegistryDataHolder.getInstance().setRealmService(realmService); + DeviceManagementDataHolder.getInstance().setRealmService(realmService); + InputStream is = this.getClass().getClassLoader().getResourceAsStream( + "carbon-home/repository/conf/registry.xml"); + RegistryContext context = RegistryContext.getBaseInstance(is, realmService); + context.setSetup(true); + return context.getEmbeddedRegistryService(); + } + + protected boolean enrollDevice(String deviceName, String deviceType) { + boolean success = false; + EnrolmentInfo enrolmentInfo = new EnrolmentInfo( + ADMIN_USER, EnrolmentInfo.OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE); + Device device1 = new Device(deviceName, deviceType, deviceName, deviceName, enrolmentInfo, null, null); + try { + success = deviceMgtService.enrollDevice(device1); + } catch (DeviceManagementException e) { + String msg = "Failed to enroll a device."; + log.error(msg, e); + Assert.fail(); + } + return success; + } + + protected void createDeviceGroup(String groupName) { + DeviceGroup deviceGroup = new DeviceGroup(groupName); + deviceGroup.setDescription(groupName); + deviceGroup.setOwner(ADMIN_USER); + try { + groupMgtService.createGroup(deviceGroup, null, null); + } catch (GroupAlreadyExistException | GroupManagementException e) { + String msg = "Failed to create group: " + groupName; + log.error(msg, e); + Assert.fail(msg); + } + } + + protected void addDeviceToGroup(DeviceIdentifier deviceIdentifier, String groupName) { + List groupDevices = new ArrayList<>(); + groupDevices.add(deviceIdentifier); + try { + DeviceGroup group = groupMgtService.getGroup(groupName); + groupMgtService.addDevices(group.getGroupId(), groupDevices); + } catch (DeviceNotFoundException | GroupManagementException e) { + String msg = "Failed to add device " + deviceIdentifier.getId() + " to group " + groupName; + log.error(msg, e); + Assert.fail(msg); + } + } + + public interface Command { + void call(Object paramObj) throws Exception; + } + + protected void testThrowingException(Object targetObj, Object paramObj, Command command, String fieldName, + Object mockObj, + Class exceptionClass) throws Exception { + Object oldObj = changeFieldValue(targetObj, fieldName, mockObj); + try { + command.call(paramObj); + } catch (Exception e) { + if (!(e.getCause().getClass().getName().equals(exceptionClass.getName()))) { + throw e; + } + } finally { + changeFieldValue(targetObj, fieldName, oldObj); + } + } + + protected Pair> mockConnection() throws Exception { + //Throwing PolicyManagerDAOException while adding profile + DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class); + when(databaseMetaData.getDatabaseProductName()).thenReturn("H2"); + + Connection conn = mock(Connection.class); + when(conn.getMetaData()).thenReturn(databaseMetaData); + + DataSource dataSource = mock(DataSource.class); + when(dataSource.getConnection()).thenReturn(conn); + + Field dataSourceField = PolicyManagementDAOFactory.class.getDeclaredField("dataSource"); + dataSourceField.setAccessible(true); + DataSource oldDataSource = (DataSource) dataSourceField.get(null); + PolicyManagementDAOFactory.init(dataSource); + + return new Pair<>(conn, new Pair<>(oldDataSource, dataSource)); + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java index a2d8d4b725..e78f58ef8f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java @@ -52,12 +52,6 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { private DeviceIdentifier identifier = new DeviceIdentifier(); - @BeforeClass - @Override - public void init() throws Exception { - - } - @Test public void testMonitorDao() { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index d056f8a1ff..032acdb878 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -52,14 +52,12 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { private static final Log log = LogFactory.getLog(PolicyDAOTestCase.class); @BeforeClass - @Override public void init() throws Exception { initDatSource(); // System.setProperty("GetTenantIDForTest", "Super"); initiatePrivilegedCaronContext(); } - @Test public void addDeviceType() throws DeviceManagementDAOException { try { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java index 03eb400364..2c47b72b21 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java @@ -45,7 +45,6 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { @BeforeClass - @Override public void init() throws Exception { PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest(); PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint.getName(), evaluationPoint); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java index e21fa59f4b..a218429863 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java @@ -19,7 +19,6 @@ package org.wso2.carbon.policy.mgt.core; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.mockito.Spy; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -59,7 +58,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; -import org.wso2.carbon.policy.mgt.core.mock.TypeADeviceManagementService; +import org.wso2.carbon.policy.mgt.core.mock.TypeXDeviceManagementService; import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; import org.wso2.carbon.policy.mgt.core.task.MonitoringTask; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; @@ -90,8 +89,6 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest { public static final String DEVICE_2 = "device2"; public static final String DEVICE_TYPE_B = "deviceTypeB"; - private DeviceManagementProviderService deviceMgtService; - private GroupManagementProviderService groupMgtService; private OperationManager operationManager; private PolicyManagerService policyManagerService; private Profile profile; @@ -100,75 +97,8 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest { @BeforeClass public void init() throws Exception { - super.initSQLScript(); - - DeviceConfigurationManager.getInstance().initConfig(); log.info("Initializing policy tests"); - - deviceMgtService = new DeviceManagementProviderServiceImpl(); - groupMgtService = new GroupManagementProviderServiceImpl(); - - DeviceManagementServiceComponent.notifyStartupListeners(); - DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService); - DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService()); - DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl()); - DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupMgtService); - DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); - - PolicyEvaluationPoint policyEvaluationPoint = new SimplePolicyEvaluationTest(); - PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint("Simple", policyEvaluationPoint); - PolicyManagementDataHolder.getInstance().setDeviceManagementService(deviceMgtService); - } - - private RegistryService getRegistryService() throws RegistryException { - RealmService realmService = new InMemoryRealmService(); - RegistryDataHolder.getInstance().setRealmService(realmService); - DeviceManagementDataHolder.getInstance().setRealmService(realmService); - InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml"); - RegistryContext context = RegistryContext.getBaseInstance(is, realmService); - context.setSetup(true); - return context.getEmbeddedRegistryService(); - } - - private boolean enrollDevice(String deviceName, String deviceType) { - boolean success = false; - EnrolmentInfo enrolmentInfo = new EnrolmentInfo( - ADMIN_USER, EnrolmentInfo.OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE); - Device device1 = new Device(deviceName, deviceType, deviceName, deviceName, enrolmentInfo, null, null); - try { - success = deviceMgtService.enrollDevice(device1); - } catch (DeviceManagementException e) { - String msg = "Failed to enroll a device."; - log.error(msg, e); - Assert.fail(); - } - return success; - } - - private void createDeviceGroup(String groupName) { - DeviceGroup deviceGroup = new DeviceGroup(groupName); - deviceGroup.setDescription(groupName); - deviceGroup.setOwner(ADMIN_USER); - try { - groupMgtService.createGroup(deviceGroup, null, null); - } catch (GroupAlreadyExistException | GroupManagementException e) { - String msg = "Failed to create group: " + groupName; - log.error(msg, e); - Assert.fail(msg); - } - } - - private void addDeviceToGroup(DeviceIdentifier deviceIdentifier, String groupName) { - List groupDevices = new ArrayList<>(); - groupDevices.add(deviceIdentifier); - try { - DeviceGroup group = groupMgtService.getGroup(groupName); - groupMgtService.addDevices(group.getGroupId(), groupDevices); - } catch (DeviceNotFoundException | GroupManagementException e) { - String msg = "Failed to add device " + deviceIdentifier.getId() + " to group " + groupName; - log.error(msg, e); - Assert.fail(msg); - } + super.initializeServices(); } @Test @@ -176,7 +106,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); policyManagerService = new PolicyManagerServiceImpl(); - deviceMgtService.registerDeviceType(new TypeADeviceManagementService()); + deviceMgtService.registerDeviceType(new TypeXDeviceManagementService(DEVICE_TYPE_A)); operationManager = new OperationManagerImpl(DEVICE_TYPE_A); enrollDevice(DEVICE1, DEVICE_TYPE_A); createDeviceGroup(GROUP1); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java new file mode 100644 index 0000000000..7a0a756faf --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mgt/impl/FeatureManagerImplTest.java @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.policy.mgt.core.mgt.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.powermock.api.mockito.PowerMockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.testng.internal.collections.Pair; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; +import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; +import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; +import org.wso2.carbon.policy.mgt.common.FeatureManagementException; +import org.wso2.carbon.policy.mgt.core.BasePolicyManagementDAOTest; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; +import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO; +import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO; +import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException; +import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; +import org.wso2.carbon.policy.mgt.core.mock.TypeXDeviceManagementService; +import org.wso2.carbon.policy.mgt.core.util.FeatureCreator; +import org.wso2.carbon.policy.mgt.core.util.ProfileCreator; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.List; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class FeatureManagerImplTest extends BasePolicyManagementDAOTest { + + private static final Log log = LogFactory.getLog(PolicyManagerServiceImpl.class); + + private static final String DEVICE4 = "device4"; + private static final String GROUP4 = "group4"; + private static final String POLICY4 = "policy4"; + private static final String DEVICE_TYPE_D = "deviceTypeD"; + + private OperationManager operationManager; + private FeatureManager featureManager; + private Profile profile1; + private List profileFeaturesList1; + + @BeforeClass + public void initialize() throws Exception { + log.info("Initializing feature manager tests"); + super.initializeServices(); + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + deviceMgtService.registerDeviceType(new TypeXDeviceManagementService(DEVICE_TYPE_D)); + operationManager = new OperationManagerImpl(DEVICE_TYPE_D); + featureManager = new FeatureManagerImpl(); + + enrollDevice(DEVICE4, DEVICE_TYPE_D); + createDeviceGroup(GROUP4); + DeviceGroup group4 = groupMgtService.getGroup(GROUP4); + addDeviceToGroup(new DeviceIdentifier(DEVICE4, DEVICE_TYPE_D), GROUP4); + + Profile profile = new Profile(); + profile.setTenantId(tenantId); + profile.setCreatedDate(new Timestamp(System.currentTimeMillis())); + profile.setDeviceType(DEVICE_TYPE_D); + } + + @Test(description = "This test case tests handling UnsupportedOperationException when adding new profile feature", + expectedExceptions = {UnsupportedOperationException.class}) + public void testAddProfileFeature() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + featureManager.addProfileFeature(profileFeature, profile1.getProfileId()); + } + + + @Test(description = "This test case tests adding new profile feature to a non existent profile", + dependsOnMethods = "testAddProfileFeature", + expectedExceptions = {FeatureManagementException.class}) + public void testAddProfileFeatureThrowingFeatureManagementException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + int nonExistentProfileId = 9999; + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + //Adding profile + featureManager.addProfileFeature(profileFeature, nonExistentProfileId); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature", + dependsOnMethods = "testAddProfileFeature") + public void testAddProfileFeatureThrowingProfileManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + ProfileDAO profileDAO = mock(ProfileDAO.class); + when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException()); + + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + testThrowingException(featureManager, + profileFeature, + p -> featureManager.addProfileFeature((ProfileFeature) p, profile1.getProfileId()), + "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature", + dependsOnMethods = "testAddProfileFeatureThrowingProfileManagerDAOException") + public void testAddProfileFeatureThrowingFeatureManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + testThrowingException(featureManager, + profileFeature, + p -> featureManager.addProfileFeature((ProfileFeature) p, profile1.getProfileId()), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when adding new profile feature", + dependsOnMethods = "testAddProfileFeatureThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testAddProfileThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean()); + try { + featureManager.addProfileFeature(profileFeature, profile.getProfileId()); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests adding new profile features", + dependsOnMethods = "testAddProfileThrowingIllegalTransactionStateException") + public void testAddProfileFeatures() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + //Adding profile + profile1 = profileManager.addProfile(profile); + profileFeaturesList1 = featureManager.addProfileFeatures(profile.getProfileFeaturesList(), + profile1.getProfileId()); + Assert.assertEquals(profileFeaturesList1.size(), profile.getProfileFeaturesList().size()); + } + + @Test(description = "This test case tests adding new profile features to a non existent profile", + dependsOnMethods = "testAddProfileFeatures", + expectedExceptions = {FeatureManagementException.class}) + public void testAddProfileFeaturesThrowingFeatureManagementException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + int nonExistentProfileId = 9999; + //Adding profile + featureManager.addProfileFeatures(profile.getProfileFeaturesList(), nonExistentProfileId); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature", + dependsOnMethods = "testAddProfileFeatures") + public void testAddProfileFeaturesThrowingProfileManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + ProfileDAO profileDAO = mock(ProfileDAO.class); + when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException()); + + List profileFeaturesList = profile.getProfileFeaturesList(); + testThrowingException(featureManager, + profileFeaturesList, + p -> featureManager.addProfileFeatures((List) p, profile1.getProfileId()), + "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature", + dependsOnMethods = "testAddProfileFeaturesThrowingProfileManagerDAOException") + public void testAddProfileFeaturesThrowingFeatureManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + + List profileFeaturesList = profile.getProfileFeaturesList(); + testThrowingException(featureManager, + profileFeaturesList, + p -> featureManager.addProfileFeatures((List) p, profile1.getProfileId()), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when adding new profile feature", + dependsOnMethods = "testAddProfileFeaturesThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testAddProfileFeaturesThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + List profileFeaturesList = profile.getProfileFeaturesList(); + + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean()); + try { + featureManager.addProfileFeatures(profileFeaturesList, profile.getProfileId()); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests handling UnsupportedOperationException when updating a profile feature", + expectedExceptions = {UnsupportedOperationException.class}) + public void testUpdateProfileFeature() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + featureManager.updateProfileFeature(profileFeature, profile1.getProfileId()); + } + + @Test(description = "This test case tests updating a non existent profile feature", + expectedExceptions = {FeatureManagementException.class}, + dependsOnMethods = "testUpdateProfileFeature") + public void testUpdateProfileFeatureThrowingFeatureManagementException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + int nonExistentProfileId = 9999; + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + featureManager.updateProfileFeature(profileFeature, nonExistentProfileId); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature", + dependsOnMethods = "testAddProfileFeature") + public void testUpdateProfileFeatureThrowingProfileManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + ProfileDAO profileDAO = mock(ProfileDAO.class); + when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException()); + + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + testThrowingException(featureManager, + profileFeature, + p -> featureManager.updateProfileFeature((ProfileFeature) p, profile1.getProfileId()), + "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature", + dependsOnMethods = "testUpdateProfileFeatureThrowingProfileManagerDAOException") + public void testUpdateProfileFeatureThrowingFeatureManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.updateProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + + ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0); + testThrowingException(featureManager, + profileFeature, + p -> featureManager.updateProfileFeature((ProfileFeature) p, profile1.getProfileId()), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests updating profile features", + dependsOnMethods = "testAddProfileFeatures") + public void testUpdateProfileFeatures() throws Exception { + String newFeatureCode = "C002"; + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + int createdProfileId = profileManager.addProfile(profile).getProfileId(); + profileFeaturesList1.get(0).setFeatureCode(newFeatureCode); + List updatedProfileFeatures = featureManager.updateProfileFeatures(profileFeaturesList1, + createdProfileId); + Assert.assertEquals(updatedProfileFeatures.get(0).getFeatureCode(), newFeatureCode); + } + + @Test(description = "This test case tests handling FeatureManagementException when updating profile features", + dependsOnMethods = "testUpdateProfileFeatures", + expectedExceptions = {FeatureManagementException.class}) + public void testUpdateProfileFeaturesThrowingFeatureManagementException() throws Exception { + String newFeatureCode = "C002"; + int nonExistentProfileId = 9999; + profileFeaturesList1.get(0).setFeatureCode(newFeatureCode); + List updatedProfileFeatures = featureManager.updateProfileFeatures(profileFeaturesList1, + nonExistentProfileId); + Assert.assertEquals(updatedProfileFeatures.get(0).getFeatureCode(), newFeatureCode); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature", + dependsOnMethods = "testUpdateProfileFeaturesThrowingFeatureManagementException") + public void testUpdateProfileFeaturesThrowingProfileManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + ProfileDAO profileDAO = mock(ProfileDAO.class); + when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException()); + + List profileFeaturesList = profile.getProfileFeaturesList(); + testThrowingException(featureManager, + profileFeaturesList, + p -> featureManager + .updateProfileFeatures((List) p, profile1.getProfileId()), + "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature", + dependsOnMethods = "testUpdateProfileFeaturesThrowingProfileManagerDAOException") + public void testUpdateProfileFeaturesThrowingFeatureManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + + List profileFeaturesList = profile.getProfileFeaturesList(); + testThrowingException(featureManager, + profileFeaturesList, + p -> featureManager + .updateProfileFeatures((List) p, profile1.getProfileId()), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when adding new profile feature", + dependsOnMethods = "testUpdateProfileFeaturesThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testUpdateProfileFeaturesThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + List profileFeaturesList = profile.getProfileFeaturesList(); + + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean()); + try { + featureManager.updateProfileFeatures(profileFeaturesList, profile.getProfileId()); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests retrieving all features of a device type", + dependsOnMethods = "testUpdateProfileFeaturesThrowingIllegalTransactionStateException", + expectedExceptions = FeatureManagementException.class) + public void testGetAllFeatures() throws Exception { + featureManager.getAllFeatures(DEVICE_TYPE_D); + } + + @Test(description = "This test case tests handling SQLException when all features of a device type", + dependsOnMethods = "testGetAllFeatures", + expectedExceptions = {IllegalTransactionStateException.class, FeatureManagementException.class}) + public void testGetAllFeaturesThrowingIllegalTransactionStateException() throws Exception { + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + try { + featureManager.getAllFeatures(DEVICE_TYPE_D); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests retrieving features of a profile", + dependsOnMethods = "testGetAllFeaturesThrowingIllegalTransactionStateException") + public void testGetFeaturesForProfile() throws Exception { + featureManager.getFeaturesForProfile(profile1.getProfileId()); + } + + @Test(description = "This test case tests retrieving features to a non existent profile", + dependsOnMethods = "testGetFeaturesForProfile", + expectedExceptions = {FeatureManagementException.class}) + public void testGetFeaturesForProfileThrowingFeatureManagementException() throws Exception { + int nonExistentProfileId = 9999; + featureManager.getFeaturesForProfile(nonExistentProfileId); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when retrieving features of a " + + "profile", + dependsOnMethods = "testGetFeaturesForProfile") + public void testGetFeaturesForProfileThrowingProfileManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + ProfileDAO profileDAO = mock(ProfileDAO.class); + when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException()); + + testThrowingException(featureManager, + null, + p -> featureManager.getFeaturesForProfile(profile1.getProfileId()), + "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when retrieving features of a " + + "profile", + dependsOnMethods = "testGetFeaturesForProfileThrowingProfileManagerDAOException") + public void testGetFeaturesForProfileThrowingFeatureManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + + testThrowingException(featureManager, + null, + p -> featureManager.getFeaturesForProfile(profile1.getProfileId()), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when retrieving features of a profile", + dependsOnMethods = "testGetFeaturesForProfileThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testGetFeaturesForProfileThrowingIllegalTransactionStateException() throws Exception { + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + try { + featureManager.getFeaturesForProfile(profile1.getProfileId()); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when deleting features of a profile", + dependsOnMethods = "testGetFeaturesForProfile") + public void testDeleteFeaturesOfProfileThrowingFeatureManagerDAOException() throws Exception { + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D); + profile1 = profileManager.addProfile(profile); + + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.deleteFeaturesOfProfile(any(Profile.class))).thenThrow(new FeatureManagerDAOException()); + + testThrowingException(featureManager, + profile1, + p -> featureManager.deleteFeaturesOfProfile(profile), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when deleting features of a profile", + dependsOnMethods = "testDeleteFeaturesOfProfileThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testDeleteFeaturesOfProfileThrowingIllegalTransactionStateException() throws Exception { + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + try { + featureManager.deleteFeaturesOfProfile(profile1); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests deleting features of a profile", + dependsOnMethods = "testDeleteFeaturesOfProfileThrowingIllegalTransactionStateException") + public void testDeleteFeaturesOfProfile() throws Exception { + featureManager.deleteFeaturesOfProfile(profile1); + } +} \ No newline at end of file diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java new file mode 100644 index 0000000000..622a3e0414 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImplTest.java @@ -0,0 +1,369 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.policy.mgt.core.mgt.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.powermock.api.mockito.PowerMockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.testng.internal.collections.Pair; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; +import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; +import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; +import org.wso2.carbon.policy.mgt.common.ProfileManagementException; +import org.wso2.carbon.policy.mgt.core.BasePolicyManagementDAOTest; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; +import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO; +import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO; +import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.impl.ProfileDAOImpl; +import org.wso2.carbon.policy.mgt.core.mock.TypeXDeviceManagementService; +import org.wso2.carbon.policy.mgt.core.util.FeatureCreator; +import org.wso2.carbon.policy.mgt.core.util.ProfileCreator; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyListOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ProfileManagerImplTest extends BasePolicyManagementDAOTest { + private static final Log log = LogFactory.getLog(PolicyManagerServiceImpl.class); + + private static final String DEVICE3 = "device3"; + private static final String GROUP3 = "group3"; + private static final String POLICY3 = "policy3"; + private static final String DEVICE_TYPE_C = "deviceTypeC"; + + private Profile profile1; + private OperationManager operationManager; + + @BeforeClass + public void initialize() throws Exception { + log.info("Initializing policy manager tests"); + super.initializeServices(); + deviceMgtService.registerDeviceType(new TypeXDeviceManagementService(DEVICE_TYPE_C)); + operationManager = new OperationManagerImpl(DEVICE_TYPE_C); + enrollDevice(DEVICE3, DEVICE_TYPE_C); + createDeviceGroup(GROUP3); + DeviceGroup group1 = groupMgtService.getGroup(GROUP3); + addDeviceToGroup(new DeviceIdentifier(DEVICE3, DEVICE_TYPE_C), GROUP3); + } + + @Test(description = "This test case tests adding new profile") + public void testAddProfile() throws Exception { + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C); + //Adding profile + profile1 = profileManager.addProfile(profile); + Assert.assertEquals(profile1.getProfileName(), profile.getProfileName()); + Assert.assertEquals(profile1.getTenantId(), profile.getTenantId()); + Assert.assertEquals(profile1.getDeviceType(), profile.getDeviceType()); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile", + dependsOnMethods = "testAddProfile") + public void testAddProfileThrowingProfileManagerDAOException() throws Exception { + ProfileDAO profileDAO = mock(ProfileDAOImpl.class); + when(profileDAO.addProfile(any(Profile.class))).thenThrow(new ProfileManagerDAOException()); + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C); + testThrowingException(profileManager, profile, p -> profileManager.addProfile((Profile) p), "profileDAO", + profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile", + dependsOnMethods = "testAddProfileThrowingProfileManagerDAOException") + public void testAddProfileThrowingFeatureManagerDAOException() throws Exception { + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.addProfileFeatures(anyListOf(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C); + testThrowingException(profileManager, profile, p -> profileManager.addProfile((Profile) p), "featureDAO", + featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when adding new profile", + dependsOnMethods = "testAddProfileThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testAddProfileThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C); + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean()); + try { + profileManager.addProfile(profile); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests updating profile", + dependsOnMethods = "testAddProfile") + public void testUpdateProfile() throws Exception { + String newProfileName = "Updated Test Profile"; + Profile savedProfile = profileManager.getProfile(profile1.getProfileId()); + savedProfile.setProfileName(newProfileName); + Profile updateProfile = profileManager.updateProfile(savedProfile); + Assert.assertEquals(updateProfile.getProfileName(), newProfileName); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when updating profile", + dependsOnMethods = "testUpdateProfile") + public void testUpdateProfileThrowingProfileManagerDAOException() throws Exception { + ProfileDAO profileDAO = mock(ProfileDAOImpl.class); + when(profileDAO.updateProfile(any(Profile.class))).thenThrow(new ProfileManagerDAOException()); + + String newProfileName = "Updated Test Profile"; + Profile savedProfile = profileManager.getProfile(profile1.getProfileId()); + savedProfile.setProfileName(newProfileName); + testThrowingException(profileManager, savedProfile, p -> profileManager.updateProfile((Profile) p), + "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when updating profile", + dependsOnMethods = "testUpdateProfileThrowingProfileManagerDAOException") + public void testUpdateProfileThrowingFeatureManagerDAOException() throws Exception { + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.updateProfileFeatures(anyListOf(ProfileFeature.class), anyInt())).thenThrow( + new FeatureManagerDAOException()); + + String newProfileName = "Updated Test Profile"; + Profile savedProfile = profileManager.getProfile(profile1.getProfileId()); + savedProfile.setProfileName(newProfileName); + testThrowingException(profileManager, savedProfile, p -> profileManager.updateProfile((Profile) p), + "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when updating profile", + dependsOnMethods = {"testUpdateProfileThrowingFeatureManagerDAOException"}, + expectedExceptions = IllegalTransactionStateException.class) + public void testUpdateProfileThrowingIllegalTransactionStateException() throws Exception { + //Retrieving profile object + Profile savedProfile = profileManager.getProfile(profile1.getProfileId()); + + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean()); + + String newProfileName = "Updated Test Profile"; + savedProfile.setProfileName(newProfileName); + try { + profileManager.updateProfile(savedProfile); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests retrieving profile", dependsOnMethods = "testAddProfile") + public void testGetProfile() throws Exception { + Profile savedProfile = profileManager.getProfile(profile1.getProfileId()); + Assert.assertEquals(profile1.getProfileName(), savedProfile.getProfileName()); + Assert.assertEquals(profile1.getTenantId(), savedProfile.getTenantId()); + Assert.assertEquals(profile1.getDeviceType(), savedProfile.getDeviceType()); + } + + @Test(description = "This test case tests retrieving non existent profile", dependsOnMethods = "testGetProfile", + expectedExceptions = ProfileManagementException.class) + public void testGetProfileThrowingProfileManagementException() throws Exception { + int nonExistentProfileId = 9999; + profileManager.getProfile(nonExistentProfileId); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when retrieving profile", + dependsOnMethods = "testGetProfile") + public void testGetProfileThrowingProfileManagerDAOException() throws Exception { + ProfileDAO profileDAO = mock(ProfileDAOImpl.class); + when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.getProfile(((Profile) p).getProfileId()), + "profileDAO", + profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when retrieving profile", + dependsOnMethods = "testGetProfileThrowingProfileManagerDAOException") + public void testGetProfileThrowingFeatureManagerDAOException() throws Exception { + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.getFeaturesForProfile(anyInt())).thenThrow(new FeatureManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.getProfile(((Profile) p).getProfileId()), + "featureDAO", + featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when retrieving profile", + dependsOnMethods = "testGetProfileThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testGetProfileThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + + try { + profileManager.getProfile(profile1.getProfileId()); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests retrieving all profiles", + dependsOnMethods = "testAddProfile") + public void testGetAllProfiles() throws Exception { + profileManager.getAllProfiles(); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when retrieving all profiles", + dependsOnMethods = "testGetAllProfiles") + public void testGetAllProfilesThrowingProfileManagerDAOException() throws Exception { + ProfileDAO profileDAO = mock(ProfileDAOImpl.class); + when(profileDAO.getAllProfiles()).thenThrow(new ProfileManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.getAllProfiles(), "profileDAO", profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when retrieving all profiles", + dependsOnMethods = "testGetAllProfilesThrowingProfileManagerDAOException") + public void testGetAllProfilesThrowingFeatureManagerDAOException() throws Exception { + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.getAllProfileFeatures()).thenThrow(new FeatureManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.getAllProfiles(), "featureDAO", featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when retrieving all profiles", + dependsOnMethods = "testGetAllProfilesThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testGetAllProfilesThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + + try { + profileManager.getAllProfiles(); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests retrieving profiles of a device type", + dependsOnMethods = "testAddProfile") + public void testGetProfilesOfDeviceType() throws Exception { + profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C); + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when retrieving all profiles of a " + + "device type", + dependsOnMethods = "testGetProfilesOfDeviceType") + public void testGetProfilesOfDeviceTypeThrowingProfileManagerDAOException() throws Exception { + ProfileDAO profileDAO = mock(ProfileDAOImpl.class); + when(profileDAO.getProfilesOfDeviceType(anyString())).thenThrow(new ProfileManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C), + "profileDAO", + profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when retrieving all profiles of a " + + "device type", + dependsOnMethods = "testGetProfilesOfDeviceTypeThrowingProfileManagerDAOException") + public void testGetProfilesOfDeviceTypeThrowingFeatureManagerDAOException() throws Exception { + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.getAllProfileFeatures()).thenThrow(new FeatureManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C), + "featureDAO", + featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when retrieving all profiles of a device type", + dependsOnMethods = "testGetProfilesOfDeviceTypeThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testGetProfilesOfDeviceTypeThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + + try { + profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests handling ProfileManagerDAOException when deleting a profile", + dependsOnMethods = "testGetProfilesOfDeviceTypeThrowingIllegalTransactionStateException") + public void testDeleteProfileThrowingProfileManagerDAOException() throws Exception { + ProfileDAO profileDAO = mock(ProfileDAOImpl.class); + when(profileDAO.deleteProfile(any(Profile.class))).thenThrow(new ProfileManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.deleteProfile(profile1), "profileDAO", + profileDAO, + ProfileManagerDAOException.class); + } + + @Test(description = "This test case tests handling FeatureManagerDAOException when deleting a profile", + dependsOnMethods = "testDeleteProfileThrowingProfileManagerDAOException") + public void testDeleteProfileThrowingFeatureManagerDAOException() throws Exception { + FeatureDAO featureDAO = mock(FeatureDAO.class); + when(featureDAO.deleteFeaturesOfProfile(any(Profile.class))).thenThrow(new FeatureManagerDAOException()); + testThrowingException(profileManager, profile1, p -> profileManager.deleteProfile(profile1), "featureDAO", + featureDAO, + FeatureManagerDAOException.class); + } + + @Test(description = "This test case tests handling SQLException when deleting a profile", + dependsOnMethods = "testDeleteProfileThrowingFeatureManagerDAOException", + expectedExceptions = IllegalTransactionStateException.class) + public void testDeleteProfileThrowingIllegalTransactionStateException() throws Exception { + //Creating profile object + Pair> pair = mockConnection(); + PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection(); + + try { + profileManager.deleteProfile(profile1); + } finally { + PolicyManagementDAOFactory.init(pair.second().first()); + } + } + + @Test(description = "This test case tests deleting a profile", + dependsOnMethods = "testDeleteProfileThrowingIllegalTransactionStateException", + expectedExceptions = {ProfileManagementException.class}) + public void testDeleteProfile() throws Exception { + profileManager.deleteProfile(profile1); + Profile savedProfile = profileManager.getProfile(profile1.getProfileId()); + } +} \ No newline at end of file diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeADeviceManagementService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManagementService.java similarity index 93% rename from components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeADeviceManagementService.java rename to components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManagementService.java index df070ab3c2..93fa5c6207 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeADeviceManagementService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManagementService.java @@ -32,12 +32,12 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import java.util.ArrayList; -public class TypeADeviceManagementService implements DeviceManagementService { +public class TypeXDeviceManagementService implements DeviceManagementService { - public static String DEVICE_TYPE = "deviceTypeA"; + private String deviceType; - public TypeADeviceManagementService() { - super(); + public TypeXDeviceManagementService(String deviceType) { + this.deviceType = deviceType; } @Override @@ -47,7 +47,7 @@ public class TypeADeviceManagementService implements DeviceManagementService { @Override public String getType() { - return DEVICE_TYPE; + return deviceType; } @Override diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java index b1d05d969f..21a49c4e9a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java @@ -27,11 +27,15 @@ import java.util.List; public class ProfileCreator { public static Profile getProfile(List features) { + return getProfile(features, "android"); + } + + public static Profile getProfile(List features, String deviceType) { Profile profile = new Profile(); profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); profile.setProfileName("Test Profile"); profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); - profile.setDeviceType("android"); + profile.setDeviceType(deviceType); return profile; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml index 5daa8c13ed..7cb72faa84 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml @@ -32,9 +32,11 @@ - + + + diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index b3f6bfd697..28ed8e6cf8 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -23,13 +23,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 policy-mgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Policy Management Component http://wso2.org diff --git a/components/test-coverage/pom.xml b/components/test-coverage/pom.xml index a89b44a4ab..27ba841d98 100644 --- a/components/test-coverage/pom.xml +++ b/components/test-coverage/pom.xml @@ -21,7 +21,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 @@ -195,6 +195,10 @@ + + + + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 4190b35bf7..1f46b733e2 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -21,14 +21,14 @@ org.wso2.carbon.devicemgt webapp-authenticator-framework - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.webapp.authenticator.framework - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT bundle WSO2 Carbon - Web Application Authenticator Framework Bundle WSO2 Carbon - Web Application Authenticator Framework Bundle @@ -167,21 +167,19 @@ org.wso2.tomcat tomcat-servlet-api - - org.wso2.carbon - org.wso2.carbon.logging - org.wso2.carbon org.wso2.carbon.tomcat.ext - org.wso2.carbon.identity.framework org.wso2.carbon.identity.base + + + org.opensaml + xmltooling + + org.wso2.carbon.identity.framework @@ -253,6 +251,21 @@ powermock-api-mockito test + + org.wso2.carbon.devicemgt + org.wso2.carbon.identity.jwt.client.extension + test + + + org.slf4j + slf4j-nop + test + + + org.apache.sling + org.apache.sling.testing.osgi-mock + test + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java index dba70afda4..d4d50f7bf1 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java @@ -22,53 +22,12 @@ public class AuthenticationException extends Exception { private static final long serialVersionUID = -3151279311929070297L; - private String errorMessage; - private int errorCode; - - public AuthenticationException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public AuthenticationException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public AuthenticationException(String msg, Exception nestedEx) { super(msg, nestedEx); - setErrorMessage(msg); - } - - public AuthenticationException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); } public AuthenticationException(String msg) { super(msg); - setErrorMessage(msg); - } - - public AuthenticationException() { - super(); } - public AuthenticationException(Throwable cause) { - super(cause); - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java index 3d768ecff4..73e809fdd3 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java @@ -21,10 +21,8 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.owasp.encoder.Encode; import org.w3c.dom.Document; -import javax.servlet.http.HttpServletResponse; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -35,14 +33,7 @@ public class AuthenticationFrameworkUtil { private static final Log log = LogFactory.getLog(AuthenticationFrameworkUtil.class); - public static void handleNoMatchAuthScheme(Request request, Response response, String httpVerb, String version, - String context) { - String msg = "Resource is not matched for HTTP Verb: '" + httpVerb + "', API context: '" + context + - "', Version: '" + version + "' and RequestURI: '" + Encode.forHtml(request.getRequestURI()) + "'"; - handleResponse(request, response, HttpServletResponse.SC_FORBIDDEN, msg); - } - - public static void handleResponse(Request request, Response response, int statusCode, String payload) { + static void handleResponse(Request request, Response response, int statusCode, String payload) { response.setStatus(statusCode); String targetResponseContentType = request.getHeader(Constants.HTTPHeaders.HEADER_HTTP_ACCEPT); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java index 61d08dc1db..a62fe4d4e7 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java @@ -22,53 +22,8 @@ public class AuthenticatorFrameworkException extends Exception { private static final long serialVersionUID = -3151279311229070297L; - private String errorMessage; - private int errorCode; - - public AuthenticatorFrameworkException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public AuthenticatorFrameworkException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public AuthenticatorFrameworkException(String msg, Exception nestedEx) { super(msg, nestedEx); - setErrorMessage(msg); - } - - public AuthenticatorFrameworkException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public AuthenticatorFrameworkException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public AuthenticatorFrameworkException() { - super(); - } - - public AuthenticatorFrameworkException(Throwable cause) { - super(cause); } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index 5a357a3ab5..c1cf0897dc 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.webapp.authenticator.framework; +import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; @@ -85,7 +86,8 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { } private boolean isContextSkipped(Request request) { - String ctx = request.getContext().getPath(); + Context context = request.getContext(); + String ctx = context == null ? null :context.getPath(); if (ctx == null || "".equals(ctx)) { ctx = request.getContextPath(); if (ctx == null || "".equals(ctx)) { @@ -105,7 +107,10 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { private boolean isNonSecuredEndPoint(Request request) { String uri = request.getRequestURI(); - if(!uri.endsWith("/")) { + if (uri == null) { + uri = ""; + } + if (!uri.endsWith("/")) { uri = uri + "/"; } String contextPath = request.getContextPath(); @@ -120,7 +125,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { while (tokenizer.hasMoreTokens()) { skippedEndPoint = tokenizer.nextToken(); skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim(); - if(!skippedEndPoint.endsWith("/")) { + if (!skippedEndPoint.endsWith("/")) { skippedEndPoint = skippedEndPoint + "/"; } nonSecuredEndpoints.put(skippedEndPoint, "true"); @@ -133,22 +138,21 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { private void processRequest(Request request, Response response, CompositeValve compositeValve, AuthenticationInfo authenticationInfo) { switch (authenticationInfo.getStatus()) { - case SUCCESS: - case CONTINUE: - this.getNext().invoke(request, response, compositeValve); - break; - case FAILURE: - String msg = "Failed to authorize incoming request"; - if (authenticationInfo.getMessage() != null && !authenticationInfo.getMessage().isEmpty()) { - msg = authenticationInfo.getMessage(); - response.setHeader("WWW-Authenticate", msg); - } - if (log.isDebugEnabled()) { - log.debug(msg + " , API : " + Encode.forUriComponent(request.getRequestURI())); - } - AuthenticationFrameworkUtil. - handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); - break; + case SUCCESS: + case CONTINUE: + this.getNext().invoke(request, response, compositeValve); + break; + case FAILURE: + String msg = "Failed to authorize incoming request"; + if (authenticationInfo.getMessage() != null && !authenticationInfo.getMessage().isEmpty()) { + msg = authenticationInfo.getMessage(); + response.setHeader("WWW-Authenticate", msg); + } + if (log.isDebugEnabled()) { + log.debug(msg + " , API : " + Encode.forUriComponent(request.getRequestURI())); + } + AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); + break; } } } \ No newline at end of file diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java index 4222b1a629..46e0e77b31 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java @@ -24,14 +24,9 @@ import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFram import java.util.Map; -public class WebappAuthenticatorFactory { +class WebappAuthenticatorFactory { - public static WebappAuthenticator getAuthenticator(String authScheme) { - return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository(). - getAuthenticator(authScheme); - } - - public static WebappAuthenticator getAuthenticator(Request request) { + static WebappAuthenticator getAuthenticator(Request request) { Map authenticators = AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators(); for (WebappAuthenticator authenticator : authenticators.values()) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index 1a3ac9d18d..5a40a3a951 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -1,3 +1,22 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + package org.wso2.carbon.webapp.authenticator.framework.authenticator; import org.apache.catalina.connector.Request; @@ -39,11 +58,8 @@ public class CertificateAuthenticator implements WebappAuthenticator { @Override public boolean canHandle(Request request) { - if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null || request.getHeader(MUTUAL_AUTH_HEADER) != null - || request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) { - return true; - } - return false; + return request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null + || request.getHeader(MUTUAL_AUTH_HEADER) != null || request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null; } @Override @@ -64,8 +80,12 @@ public class CertificateAuthenticator implements WebappAuthenticator { authenticationInfo = checkCertificateResponse(certificateResponse); } else if (request.getHeader(MUTUAL_AUTH_HEADER) != null) { - X509Certificate[] clientCertificate = (X509Certificate[]) request. - getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); + Object object = request.getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); + X509Certificate[] clientCertificate = null; + if (object instanceof X509Certificate[]) { + clientCertificate = (X509Certificate[]) request. + getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); + } if (clientCertificate != null && clientCertificate[0] != null) { CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). getCertificateManagementService().verifyPEMSignature(clientCertificate[0]); @@ -76,7 +96,6 @@ public class CertificateAuthenticator implements WebappAuthenticator { authenticationInfo.setMessage("No client certificate is present"); } } else if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null) { - String certHeader = request.getHeader(CERTIFICATE_VERIFICATION_HEADER); if (certHeader != null && AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService(). @@ -105,7 +124,6 @@ public class CertificateAuthenticator implements WebappAuthenticator { EnrolmentInfo enrolmentInfo = tenantedDeviceWrapper.getDevice().getEnrolmentInfo(); authenticationInfo.setUsername(enrolmentInfo.getOwner()); } - authenticationInfo.setStatus(Status.CONTINUE); } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 99fd36d534..87ef877351 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -86,6 +86,12 @@ public class JWTAuthenticator implements WebappAuthenticator { @Override public AuthenticationInfo authenticate(Request request, Response response) { String requestUri = request.getRequestURI(); + SignedJWT jwsObject; + String username; + String tenantDomain; + int tenantId; + String issuer; + AuthenticationInfo authenticationInfo = new AuthenticationInfo(); if (requestUri == null || "".equals(requestUri)) { authenticationInfo.setStatus(Status.CONTINUE); @@ -94,19 +100,25 @@ public class JWTAuthenticator implements WebappAuthenticator { requestUri = ""; } StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); - String context = tokenizer.nextToken(); + String context = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; if (context == null || "".equals(context)) { authenticationInfo.setStatus(Status.CONTINUE); } try { String authorizationHeader = request.getHeader(JWT_ASSERTION_HEADER); + jwsObject = SignedJWT.parse(authorizationHeader); + username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); + tenantDomain = MultitenantUtils.getTenantDomain(username); + tenantId = Integer.parseInt(jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_TENANT_ID)); + issuer = jwsObject.getJWTClaimsSet().getIssuer(); + } catch (ParseException e) { + log.error("Error occurred while parsing JWT header.", e); + authenticationInfo.setMessage("Error occurred while parsing JWT header"); + return authenticationInfo; + } + try { - SignedJWT jwsObject = SignedJWT.parse(authorizationHeader); - String username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); - String tenantDomain = MultitenantUtils.getTenantDomain(username); - int tenantId = Integer.parseInt(jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_TENANT_ID)); - String issuer = jwsObject.getJWTClaimsSet().getIssuer(); PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId); @@ -116,7 +128,7 @@ public class JWTAuthenticator implements WebappAuthenticator { loadTenantRegistry(tenantId); KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { - String alias = properties.getProperty(issuer); + String alias = properties == null ? null : properties.getProperty(issuer); if (alias != null && !alias.isEmpty()) { ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); @@ -124,7 +136,8 @@ public class JWTAuthenticator implements WebappAuthenticator { String trustStorePassword = serverConfig.getFirstProperty( DEFAULT_TRUST_STORE_PASSWORD); keyStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray()); - publicKey = keyStore.getCertificate(alias).getPublicKey(); + java.security.cert.Certificate certificate = keyStore.getCertificate(alias); + publicKey = certificate == null ? null : certificate.getPublicKey(); } else { authenticationInfo.setStatus(Status.FAILURE); return authenticationInfo; @@ -139,33 +152,32 @@ public class JWTAuthenticator implements WebappAuthenticator { publicKeyHolder.put(issuerAlias, publicKey); } } - //Get the filesystem keystore default primary certificate - JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) publicKey); - if (jwsObject.verify(verifier)) { + JWSVerifier verifier = null; + if (publicKey != null) { + verifier = new RSASSAVerifier((RSAPublicKey) publicKey); + } + if (verifier != null && jwsObject.verify(verifier)) { username = MultitenantUtils.getTenantAwareUsername(username); - if (tenantId == -1) { - log.error("tenantDomain is not valid. username : " + username + ", tenantDomain " + - ": " + tenantDomain); + UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService(). + getTenantUserRealm(tenantId).getUserStoreManager(); + if (userStore.isExistingUser(username)) { + authenticationInfo.setTenantId(tenantId); + authenticationInfo.setUsername(username); + authenticationInfo.setTenantDomain(tenantDomain); + authenticationInfo.setStatus(Status.CONTINUE); } else { - UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService(). - getTenantUserRealm(tenantId).getUserStoreManager(); - if (userStore.isExistingUser(username)) { - authenticationInfo.setTenantId(tenantId); - authenticationInfo.setUsername(username); - authenticationInfo.setTenantDomain(tenantDomain); - authenticationInfo.setStatus(Status.CONTINUE); - } + authenticationInfo.setStatus(Status.FAILURE); } } else { authenticationInfo.setStatus(Status.FAILURE); } } catch (UserStoreException e) { log.error("Error occurred while obtaining the user.", e); - } catch (ParseException e) { - log.error("Error occurred while parsing the JWT header.", e); - } catch (Exception e) { + authenticationInfo.setStatus(Status.FAILURE); + } catch (Exception e) { log.error("Error occurred while verifying the JWT header.", e); + authenticationInfo.setStatus(Status.FAILURE); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java index 42dbfe417c..96de132910 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java @@ -29,19 +29,4 @@ public class OAuthTokenValidationException extends Exception { super(msg, nestedEx); } - public OAuthTokenValidationException(String message, Throwable cause) { - super(message, cause); - } - - public OAuthTokenValidationException(String msg) { - super(msg); - } - - public OAuthTokenValidationException() { - super(); - } - - public OAuthTokenValidationException(Throwable cause) { - super(cause); - } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java deleted file mode 100644 index c8abdab444..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.webapp.authenticator.framework.authorizer; - -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; -import org.wso2.carbon.tomcat.ext.valves.CompositeValve; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; - -import javax.servlet.http.HttpServletResponse; - -public class PermissionAuthorizationValve extends CarbonTomcatValve { - - private static final Log log = LogFactory.getLog(PermissionAuthorizationValve.class); - private static final String AUTHORIZATION_ENABLED = "authorization-enabled"; - - - @Override - public void invoke(Request request, Response response, CompositeValve compositeValve) { - - String permissionStatus = request.getContext().findParameter(AUTHORIZATION_ENABLED); - if (permissionStatus == null || permissionStatus.isEmpty()) { - this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); - return; - } - // check whether the permission checking function is enabled in web.xml - boolean isEnabled = Boolean.valueOf(permissionStatus); - if (!isEnabled) { - this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); - return; - } - - if (log.isDebugEnabled()) { - log.debug("Checking permission of request: " + request.getRequestURI()); - } - PermissionAuthorizer permissionAuthorizer = new PermissionAuthorizer(); - WebappAuthenticator.Status status = permissionAuthorizer.authorize(request, response); - this.processResponse(request, response, compositeValve, status); - } - - private void processResponse(Request request, Response response, CompositeValve compositeValve, - WebappAuthenticator.Status status) { - switch (status) { - case SUCCESS: - case CONTINUE: - this.getNext().invoke(request, response, compositeValve); - break; - case FAILURE: - String msg = "Failed to authorize incoming request"; - log.error(msg); - AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); - break; - } - } -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java deleted file mode 100644 index c17d6fcc6a..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.webapp.authenticator.framework.authorizer; - -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.owasp.encoder.Encode; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; -import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; -import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.webapp.authenticator.framework.Constants; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; - -import java.util.Properties; - -/** - * This class represents the methods that are used to authorize requests. - */ -public class PermissionAuthorizer { - - private static final Log log = LogFactory.getLog(PermissionAuthorizer.class); - - public WebappAuthenticator.Status authorize(Request request, Response response) { - - return WebappAuthenticator.Status.SUCCESS; - } - -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java index 26d8ff995d..1b6aef18ae 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java @@ -43,10 +43,10 @@ public class WebappTenantAuthorizer { } private static boolean isProviderTenant(Request request, String requestTenantDomain) { - Object tenantDoamin = request.getServletContext().getAttribute(PROVIDER_TENANT_DOMAIN_PARAM_NAME); + Object tenantDomain = request.getServletContext().getAttribute(PROVIDER_TENANT_DOMAIN_PARAM_NAME); String param = null; - if (tenantDoamin != null) { - param = (String)request.getServletContext().getAttribute(PROVIDER_TENANT_DOMAIN_PARAM_NAME); + if (tenantDomain != null) { + param = (String)tenantDomain; } return (param == null || requestTenantDomain.equals(param)); } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java index 007eef108d..67ab3ef49a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java @@ -88,15 +88,4 @@ public class WebappAuthenticatorConfig { } } - private static Schema getSchema() throws AuthenticatorFrameworkException { - try { - File deviceManagementSchemaConfig = new File(WebappAuthenticatorConfig.AUTHENTICATOR_CONFIG_SCHEMA_PATH); - SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - return factory.newSchema(deviceManagementSchemaConfig); - } catch (SAXException e) { - throw new AuthenticatorFrameworkException("Error occurred while initializing the schema of " + - "webapp-authenticator-config.xml", e); - } - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java index 702a5cbc9e..0cc7017557 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java @@ -34,7 +34,7 @@ public class AuthenticatorConfigServiceImpl implements AuthenticatorConfigServic public AuthenticatorConfig getAuthenticatorConfig(String authenticatorName) throws InvalidConfigurationStateException { List configs = WebappAuthenticatorConfig.getInstance().getAuthenticators(); - int index = 0; + int index; if (authenticatorName == null || authenticatorName.isEmpty()) { return null; } @@ -42,9 +42,9 @@ public class AuthenticatorConfigServiceImpl implements AuthenticatorConfigServic AuthenticatorConfig authenticatorConfig = configs.get(i); if (authenticatorName.equals(authenticatorConfig.getName())) { index = i; - break; + return configs.get(index); } } - return configs.get(index); + return null; } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java index d4bcaf2e20..fc437004a0 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/BaseWebAppAuthenticatorFrameworkTest.java @@ -21,18 +21,25 @@ package org.wso2.carbon.webapp.authenticator.framework; import org.testng.annotations.BeforeSuite; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.internal.CarbonCoreDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils; +import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.internal.RegistryDataHolder; import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; +import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.wso2.carbon.webapp.authenticator.framework.util.TestTenantIndexingLoader; +import org.wso2.carbon.webapp.authenticator.framework.util.TestTenantRegistryLoader; import java.io.File; +import java.io.InputStream; import java.net.URL; import static org.wso2.carbon.security.SecurityConstants.ADMIN_USER; @@ -56,6 +63,17 @@ public class BaseWebAppAuthenticatorFrameworkTest { .setTenantDomain(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantId(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID); + CarbonCoreDataHolder.getInstance().setRegistryService(getRegistryService()); + AuthenticatorFrameworkDataHolder.getInstance().setTenantRegistryLoader(new TestTenantRegistryLoader()); + AuthenticatorFrameworkDataHolder.getInstance().setTenantIndexingLoader(new TestTenantIndexingLoader()); + } + + /** + * To get the registry service. + * @return RegistryService + * @throws RegistryException Registry Exception + */ + private RegistryService getRegistryService() throws RegistryException, UserStoreException { RealmService realmService = new InMemoryRealmService(); AuthenticatorFrameworkDataHolder.getInstance().setRealmService(realmService); UserStoreManager userStoreManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService() @@ -63,5 +81,12 @@ public class BaseWebAppAuthenticatorFrameworkTest { Permission adminPermission = new Permission(PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH, CarbonConstants.UI_PERMISSION_ACTION); userStoreManager.addRole(ADMIN_ROLE + "t", new String[] { ADMIN_USER }, new Permission[] { adminPermission }); + RegistryDataHolder.getInstance().setRealmService(realmService); + DeviceManagementDataHolder.getInstance().setRealmService(realmService); + InputStream is = BaseWebAppAuthenticatorFrameworkTest.class.getClassLoader() + .getResourceAsStream("carbon-home/repository/conf/registry.xml"); + RegistryContext context = RegistryContext.getBaseInstance(is, realmService); + context.setSetup(true); + return context.getEmbeddedRegistryService(); } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java new file mode 100644 index 0000000000..69cbac221a --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.wso2.carbon.webapp.authenticator.framework; + +import org.apache.catalina.Context; +import org.apache.catalina.connector.Connector; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.catalina.core.StandardContext; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.tomcat.ext.valves.CompositeValve; +import org.wso2.carbon.webapp.authenticator.framework.util.TestRequest; + +import javax.servlet.http.HttpServletResponse; +import java.lang.reflect.Field; +import java.util.Base64; + +import static org.wso2.carbon.security.SecurityConstants.ADMIN_USER; + +/** + * This is a test class for {@link WebappAuthenticationValve}. + */ +public class WebappAuthenticationValveTest { + private WebappAuthenticationValve webappAuthenticationValve; + private CompositeValve compositeValve; + + @BeforeClass() + public void setup() { + webappAuthenticationValve = new WebappAuthenticationValve(); + compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + } + + @Test(description = "This method tests the invoke method of the WebAppAuthenticationValve with the context path " + + "starting with carbon") + public void testInvokeWithContextSkippedScenario1() { + Request request = new Request(); + Context context = new StandardContext(); + context.setPath("carbon"); + CompositeValve compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + request.setContext(context); + webappAuthenticationValve.invoke(request, null, compositeValve); + request = new TestRequest("", "test"); + context = new StandardContext(); + compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + request.setContext(context); + webappAuthenticationValve.invoke(request, null, compositeValve); + } + + @Test(description = "This method tests the behaviour of the invoke method of WebAuthenticationValve when " + + "un-secured endpoints are invoked.") + public void testInvokeUnSecuredEndpoints() { + Request request = new TestRequest("", "test"); + Context context = new StandardContext(); + context.setPath("carbon1"); + context.addParameter("doAuthentication", String.valueOf(true)); + context.addParameter("nonSecuredEndPoints", "test, test1"); + CompositeValve compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + request.setContext(context); + webappAuthenticationValve.invoke(request, null, compositeValve); + } + + @Test(description = "This method tests the behaviour of the invoke method of WebAuthenticationValve when " + + "secured endpoints are invoked.") + public void testInvokeSecuredEndpoints() throws NoSuchFieldException, IllegalAccessException { + String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes())); + Request request = createRequest("basic " + encodedString); + webappAuthenticationValve.invoke(request, null, compositeValve); + encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER + "test").getBytes())); + request = createRequest("basic " + encodedString); + Response response = new Response(); + org.apache.coyote.Response coyoteResponse = new org.apache.coyote.Response(); + Connector connector = new Connector(); + response.setConnector(connector); + response.setCoyoteResponse(coyoteResponse); + webappAuthenticationValve.invoke(request, response, compositeValve); + Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED, + "Response of un-authorized request is not updated"); + } + + @Test(description = "This method tests the behaviour of invoke method when the request does not satisfy any " + + "authenticator requirements") + public void testInvokeWithoutProperAuthenticator() throws NoSuchFieldException, IllegalAccessException { + Request request = createRequest("basic"); + Response response = new Response(); + org.apache.coyote.Response coyoteResponse = new org.apache.coyote.Response(); + Connector connector = new Connector(); + response.setConnector(connector); + response.setCoyoteResponse(coyoteResponse); + webappAuthenticationValve.invoke(request, response, compositeValve); + Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED, + "Response of un-authorized request is not updated"); + } + + /** + * To create a request with the given authorization header + * + * @param authorizationHeader Authorization header + * @return the relevant request. + * @throws IllegalAccessException Illegal Access Exception. + * @throws NoSuchFieldException No Such Field Exception. + */ + private Request createRequest(String authorizationHeader) throws IllegalAccessException, NoSuchFieldException { + Request request = new TestRequest("", ""); + Context context = new StandardContext(); + context.addParameter("basicAuth", "true"); + context.addParameter("managed-api-enabled", "true"); + context.setPath("carbon1"); + context.addParameter("doAuthentication", String.valueOf(true)); + request.setContext(context); + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER); + bytes.setString(authorizationHeader); + Field headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); + headersField.setAccessible(true); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + headersField.set(coyoteRequest, mimeHeaders); + request.setCoyoteRequest(coyoteRequest); + return request; + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java index 637a46598a..57cb61101c 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java @@ -18,16 +18,15 @@ */ package org.wso2.carbon.webapp.authenticator.framework; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.utils.ServerConstants; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkException; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; +import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfigService; import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig; +import org.wso2.carbon.webapp.authenticator.framework.config.impl.AuthenticatorConfigServiceImpl; import java.util.List; @@ -42,10 +41,8 @@ public class WebappAuthenticatorConfigTest { public void testConfigInitialization() { try { WebappAuthenticatorConfig.init(); - WebappAuthenticatorConfig config = WebappAuthenticatorConfig.getInstance(); Assert.assertNotNull(config); - List authConfigs = config.getAuthenticators(); Assert.assertNotNull(authConfigs); } catch (AuthenticatorFrameworkException e) { @@ -56,6 +53,27 @@ public class WebappAuthenticatorConfigTest { } } + + @Test(description = "This method tests getAuthenticatorConfig method of AuthenticatorConfigService", + dependsOnMethods = {"testConfigInitialization"}) + public void getAuthenticatorConfigTest() { + AuthenticatorConfigService authenticatorConfigService = new AuthenticatorConfigServiceImpl(); + AuthenticatorConfig authenticatorConfig = authenticatorConfigService.getAuthenticatorConfig("BasicAuth"); + Assert.assertNotNull(authenticatorConfig, + "Added authenticator config for the BasicAuth authenticator cannot be retrieved successfully"); + Assert.assertEquals(authenticatorConfig.getClassName(), + "org.wso2.carbon.webapp.authenticator.framework" + ".authenticator.BasicAuthAuthenticator", + "Class name related with Basic Auth does not match with " + + "the class name specified in the configuration"); + authenticatorConfig = authenticatorConfigService.getAuthenticatorConfig(null); + Assert.assertNull(authenticatorConfig, + "Authenticator is retrieved even when the authenticator name is given as null"); + authenticatorConfig = authenticatorConfigService.getAuthenticatorConfig("non-existing"); + Assert.assertNull(authenticatorConfig, + "Authenticator is retrieved for a non-existing authenticator"); + + } + @AfterClass public void cleanup() { System.setProperty(ServerConstants.CARBON_CONFIG_DIR_PATH, ""); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java new file mode 100644 index 0000000000..05d8bf1eb0 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticatorTest.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.wso2.carbon.webapp.authenticator.framework.authenticator; + +import org.apache.catalina.Context; +import org.apache.catalina.connector.Request; +import org.apache.catalina.core.StandardContext; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; +import org.bouncycastle.cert.jcajce.JcaCertStore; +import org.bouncycastle.cms.CMSAbsentContent; +import org.bouncycastle.cms.CMSException; +import org.bouncycastle.cms.CMSSignedData; +import org.bouncycastle.cms.CMSSignedDataGenerator; +import org.h2.jdbcx.JdbcDataSource; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader; +import org.wso2.carbon.certificate.mgt.core.scep.SCEPException; +import org.wso2.carbon.certificate.mgt.core.scep.SCEPManager; +import org.wso2.carbon.certificate.mgt.core.scep.SCEPManagerImpl; +import org.wso2.carbon.certificate.mgt.core.scep.TenantedDeviceWrapper; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.wso2.carbon.webapp.authenticator.framework.util.TestCertificateGenerator; + +import javax.sql.DataSource; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URL; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +/** + * This is a test case for {@link CertificateAuthenticator}. + */ +public class CertificateAuthenticatorTest { + private CertificateAuthenticator certificateAuthenticator; + private Request certificationVerificationRequest; + private Request mutalAuthHeaderRequest; + private Request proxyMutalAuthHeaderRequest; + private Field headersField; + private static final String MUTUAL_AUTH_HEADER = "mutual-auth-header"; + private static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header"; + private static final String CERTIFICATE_VERIFICATION_HEADER = "Mdm-Signature"; + private static final String CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate"; + private X509Certificate X509certificate; + + @BeforeClass + public void setup() throws KeystoreException, NoSuchFieldException, IllegalAccessException, SQLException, + DeviceManagementException, CertificateEncodingException, CMSException, IOException, SCEPException { + certificateAuthenticator = new CertificateAuthenticator(); + CertificateManagementService certificateManagementService = Mockito + .mock(CertificateManagementServiceImpl.class, Mockito.CALLS_REAL_METHODS); + headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); + headersField.setAccessible(true); + + Field certificateManagementServiceImpl = CertificateManagementServiceImpl.class.getDeclaredField + ("certificateManagementServiceImpl"); + certificateManagementServiceImpl.setAccessible(true); + Field keyStoreReaderField = CertificateManagementServiceImpl.class.getDeclaredField("keyStoreReader"); + keyStoreReaderField.setAccessible(true); + Field certificateGeneratorField = CertificateManagementServiceImpl.class.getDeclaredField + ("certificateGenerator"); + certificateGeneratorField.setAccessible(true); + certificateManagementServiceImpl.set(null, certificateManagementService); + + // Create KeyStore Reader + Field dataSource = CertificateManagementDAOFactory.class.getDeclaredField("dataSource"); + dataSource.setAccessible(true); + dataSource.set(null, createDatabase()); + Field databaseEngine = CertificateManagementDAOFactory.class.getDeclaredField("databaseEngine"); + databaseEngine.setAccessible(true); + databaseEngine.set(null, "H2"); + KeyStoreReader keyStoreReader = new KeyStoreReader(); + keyStoreReaderField.set(null, keyStoreReader); + + CertificateGenerator certificateGenerator = new TestCertificateGenerator(); + certificateGeneratorField.set(null, certificateGenerator); + + AuthenticatorFrameworkDataHolder.getInstance(). + setCertificateManagementService(certificateManagementService); + X509certificate = certificateManagementService.generateX509Certificate(); + + proxyMutalAuthHeaderRequest = createRequest(PROXY_MUTUAL_AUTH_HEADER, String.valueOf(X509certificate)); + System.setProperty("carbon.config.dir.path", + System.getProperty("carbon.home") + File.separator + "repository" + File.separator + "conf"); + DeviceConfigurationManager.getInstance().initConfig(); + certificationVerificationRequest = createRequest(CERTIFICATE_VERIFICATION_HEADER, + createEncodedSignature(X509certificate)); + + mutalAuthHeaderRequest = createRequest(MUTUAL_AUTH_HEADER, "test"); + + SCEPManager scepManager = Mockito.mock(SCEPManagerImpl.class, Mockito.CALLS_REAL_METHODS); + TenantedDeviceWrapper tenantedDeviceWrapper = new TenantedDeviceWrapper(); + tenantedDeviceWrapper.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + tenantedDeviceWrapper.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + Device device = new Device(); + device.setEnrolmentInfo(new EnrolmentInfo("admin", null, null)); + tenantedDeviceWrapper.setDevice(device); + Mockito.doReturn(tenantedDeviceWrapper).when(scepManager).getValidatedDevice(Mockito.any()); + AuthenticatorFrameworkDataHolder.getInstance().setScepManager(scepManager); + } + + @Test(description = "This test case tests the behaviour of the CertificateAuthenticator for Proxy mutal Auth " + + "Header requests") + public void testRequestsWithProxyMutalAuthHeader() + throws KeystoreException, NoSuchFieldException, IllegalAccessException { + Assert.assertTrue(certificateAuthenticator.canHandle(proxyMutalAuthHeaderRequest), "canHandle method " + + "returned false for a request with all the required header"); + AuthenticationInfo authenticationInfo = certificateAuthenticator + .authenticate(proxyMutalAuthHeaderRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertNull(authenticationInfo.getTenantDomain(), + "Authentication got succeeded without proper certificate"); + + proxyMutalAuthHeaderRequest = createRequest(PROXY_MUTUAL_AUTH_HEADER, + String.valueOf(X509certificate.getIssuerDN())); + authenticationInfo = certificateAuthenticator.authenticate(proxyMutalAuthHeaderRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertNotNull(authenticationInfo.getTenantDomain(), + "Authentication got failed for a proper certificate"); + + CertificateGenerator tempCertificateGenerator = new CertificateGenerator(); + X509Certificate certificateWithOutCN = tempCertificateGenerator.generateX509Certificate(); + proxyMutalAuthHeaderRequest = createRequest(PROXY_MUTUAL_AUTH_HEADER, + String.valueOf(certificateWithOutCN.getIssuerDN())); + authenticationInfo = certificateAuthenticator.authenticate(proxyMutalAuthHeaderRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE, + "Authentication got passed with a certificate without CN"); + + + } + + @Test(description = "This test case tests the behaviour of the CertificateAuthenticator for Certification " + + "Verification Header requests") + public void testRequestCertificateVerificationHeader() + throws CertificateEncodingException, IOException, CMSException, NoSuchFieldException, + IllegalAccessException { + Assert.assertTrue(certificateAuthenticator.canHandle(certificationVerificationRequest), + "canHandle method returned false for a request with all the required header"); + AuthenticationInfo authenticationInfo = certificateAuthenticator + .authenticate(certificationVerificationRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertNull(authenticationInfo.getTenantDomain(), "Authentication got passed without proper certificate"); + authenticationInfo = certificateAuthenticator.authenticate(certificationVerificationRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertEquals(authenticationInfo.getTenantDomain(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, + "Authentication failed for a valid request with " + CERTIFICATE_VERIFICATION_HEADER + " header"); + } + + @Test(description = "This test case tests the behaviour of the Certificate Authenticator for the requests with " + + "Mutal Auth Header") + public void testMutalAuthHeaderRequest() { + Assert.assertTrue(certificateAuthenticator.canHandle(mutalAuthHeaderRequest), + "canHandle method returned false for a request with all the required header"); + + AuthenticationInfo authenticationInfo = certificateAuthenticator.authenticate(mutalAuthHeaderRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertEquals(authenticationInfo.getMessage(), "No client certificate is present", + "Authentication got passed without proper certificate"); + + X509Certificate[] x509Certificates = new X509Certificate[1]; + x509Certificates[0] = X509certificate; + mutalAuthHeaderRequest.setAttribute(CLIENT_CERTIFICATE_ATTRIBUTE, x509Certificates); + authenticationInfo = certificateAuthenticator.authenticate(mutalAuthHeaderRequest, null); + Assert.assertNotNull(authenticationInfo, "Authentication Info from Certificate Authenticator is null"); + Assert.assertEquals(authenticationInfo.getTenantDomain(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, + "Authentication failed even with proper certificate"); + } + /** + * To create a request that can be understandable by Certificate Authenticator. + * + * @param headerName Name of the header + * @param value Value for the header + * @return Request that is created. + * @throws IllegalAccessException Illegal Access Exception. + * @throws NoSuchFieldException No Such Field Exception. + */ + private Request createRequest(String headerName, String value) throws IllegalAccessException, NoSuchFieldException { + Request request = new Request(); + Context context = new StandardContext(); + request.setContext(context); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue(headerName); + bytes.setString(value); + headersField.set(coyoteRequest, mimeHeaders); + + request.setCoyoteRequest(coyoteRequest); + return request; + } + + /** + * To create certificate management database. + * + * @return Datasource. + * @throws SQLException SQL Exception. + */ + private DataSource createDatabase() throws SQLException { + URL resourceURL = ClassLoader.getSystemResource("sql-scripts" + File.separator + "h2.sql"); + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL("jdbc:h2:mem:cert;DB_CLOSE_DELAY=-1"); + dataSource.setUser("sa"); + dataSource.setPassword("sa"); + final String LOAD_DATA_QUERY = "RUNSCRIPT FROM '" + resourceURL.getPath() + "'"; + Connection conn = null; + Statement statement = null; + try { + conn = dataSource.getConnection(); + statement = conn.createStatement(); + statement.execute(LOAD_DATA_QUERY); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) {} + } + if (statement != null) { + statement.close(); + } + } + return dataSource; + } + + /** + * To create a encoded signature from certificate. + * + * @param x509Certificate Certificate that need to be encoded. + * @return Encoded signature. + * @throws CertificateEncodingException Certificate Encoding Exception. + * @throws CMSException CMS Exception. + * @throws IOException IO Exception. + */ + private String createEncodedSignature(X509Certificate x509Certificate) throws CertificateEncodingException, + CMSException, IOException { + CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); + List list = new ArrayList<>(); + list.add(x509Certificate); + JcaCertStore store = new JcaCertStore(list); + generator.addCertificates(store); + AtomicReference degenerateSd = new AtomicReference<>(generator.generate(new CMSAbsentContent())); + byte[] signature = degenerateSd.get().getEncoded(); + return Base64.getEncoder().encodeToString(signature); + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java new file mode 100644 index 0000000000..3a82156b6b --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticatorTest.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.webapp.authenticator.framework.authenticator; + +import org.apache.catalina.connector.Request; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * This is a test class for {@link JWTAuthenticator}. + */ +public class JWTAuthenticatorTest { + private JWTAuthenticator jwtAuthenticator; + private Field headersField; + private final String JWT_HEADER = "X-JWT-Assertion"; + private String jwtToken; + private String wrongJwtToken; + private String jwtTokenWithWrongUser; + private static final String SIGNED_JWT_AUTH_USERNAME = "http://wso2.org/claims/enduser"; + private static final String SIGNED_JWT_AUTH_TENANT_ID = "http://wso2.org/claims/enduserTenantId"; + private Properties properties; + private final String ISSUER = "wso2.org/products/iot"; + private final String ALIAS = "wso2carbon"; + + @BeforeClass + public void setup() throws NoSuchFieldException, IOException, JWTClientException { + jwtAuthenticator = new JWTAuthenticator(); + headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); + headersField.setAccessible(true); + ClassLoader classLoader = getClass().getClassLoader(); + URL resourceUrl = classLoader.getResource("jwt.properties"); + File jwtPropertyFile; + JWTConfig jwtConfig = null; + if (resourceUrl != null) { + jwtPropertyFile = new File(resourceUrl.getFile()); + Properties jwtConfigProperties = new Properties(); + jwtConfigProperties.load(new FileInputStream(jwtPropertyFile)); + jwtConfig = new JWTConfig(jwtConfigProperties); + } + Map customClaims = new HashMap<>(); + customClaims.put(SIGNED_JWT_AUTH_USERNAME, "admin"); + customClaims.put(SIGNED_JWT_AUTH_TENANT_ID, String.valueOf(MultitenantConstants.SUPER_TENANT_ID)); + jwtToken = JWTClientUtil.generateSignedJWTAssertion("admin", jwtConfig, false, customClaims); + customClaims = new HashMap<>(); + customClaims.put(SIGNED_JWT_AUTH_USERNAME, "admin"); + customClaims.put(SIGNED_JWT_AUTH_TENANT_ID, "-1"); + wrongJwtToken = JWTClientUtil.generateSignedJWTAssertion("admin", jwtConfig, false, customClaims); + customClaims = new HashMap<>(); + customClaims.put(SIGNED_JWT_AUTH_USERNAME, "notexisting"); + customClaims.put(SIGNED_JWT_AUTH_TENANT_ID, String.valueOf(MultitenantConstants.SUPER_TENANT_ID)); + jwtTokenWithWrongUser = JWTClientUtil.generateSignedJWTAssertion("notexisting", jwtConfig, false, customClaims); + } + + @Test(description = "This method tests the get methods in the JWTAuthenticator", + dependsOnMethods = "testAuthenticate") + public void testGetMethods() { + Assert.assertEquals(jwtAuthenticator.getName(), "JWT", "GetName method returns wrong value"); + Assert.assertNotNull(jwtAuthenticator.getProperties(), "Properties are not properly added to JWT " + + "Authenticator"); + Assert.assertEquals(jwtAuthenticator.getProperties().size(), properties.size(), + "Added properties do not match with retrieved properties"); + Assert.assertNull(jwtAuthenticator.getProperty("test"), "Retrieved a propety that was never added"); + Assert.assertNotNull(jwtAuthenticator.getProperty(ISSUER), ALIAS); + } + + @Test(description = "This method tests the canHandle method under different conditions of request") + public void testHandle() throws IllegalAccessException, NoSuchFieldException { + Request request = new Request(); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + request.setCoyoteRequest(coyoteRequest); + Assert.assertFalse(jwtAuthenticator.canHandle(request)); + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue(JWT_HEADER); + bytes.setString("test"); + headersField.set(coyoteRequest, mimeHeaders); + request.setCoyoteRequest(coyoteRequest); + Assert.assertTrue(jwtAuthenticator.canHandle(request)); + } + + @Test(description = "This method tests authenticate method under the successful condition", dependsOnMethods = + { "testAuthenticateFailureScenarios" }) + public void testAuthenticate() throws IllegalAccessException, NoSuchFieldException { + Request request = createJWTRequest(jwtToken, "test"); + AuthenticationInfo authenticationInfo = jwtAuthenticator.authenticate(request, null); + Assert.assertNotNull(authenticationInfo.getUsername(), "Proper authentication request is not properly " + + "authenticated by the JWTAuthenticator"); + } + + @Test(description = "This method tests the authenticate method under failure conditions") + public void testAuthenticateFailureScenarios() throws NoSuchFieldException, IllegalAccessException { + Request request = createJWTRequest("test", ""); + AuthenticationInfo authenticationInfo = jwtAuthenticator.authenticate(request, null); + Assert.assertNotNull(authenticationInfo, "Returned authentication info was null"); + Assert.assertNull(authenticationInfo.getUsername(), "Un-authenticated request contain username"); + request = createJWTRequest(jwtToken, ""); + authenticationInfo = jwtAuthenticator.authenticate(request, null); + Assert.assertNotNull(authenticationInfo, "Returned authentication info was null"); + Assert.assertNull(authenticationInfo.getUsername(), "Un-authenticated request contain username"); + properties = new Properties(); + properties.setProperty(ISSUER, "test"); + jwtAuthenticator.setProperties(properties); + request = createJWTRequest(jwtToken, ""); + authenticationInfo = jwtAuthenticator.authenticate(request, null); + Assert.assertNotNull(authenticationInfo, "Returned authentication info was null"); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE, + "Un authenticated request does not contain status as failure"); + properties = new Properties(); + properties.setProperty(ISSUER, ALIAS); + jwtAuthenticator.setProperties(properties); + request = createJWTRequest(wrongJwtToken, ""); + authenticationInfo = jwtAuthenticator.authenticate(request, null); + Assert.assertNotNull(authenticationInfo, "Returned authentication info was null"); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE, + "Un authenticated request does not contain status as failure"); + request = createJWTRequest(jwtTokenWithWrongUser, ""); + authenticationInfo = jwtAuthenticator.authenticate(request, null); + Assert.assertNotNull(authenticationInfo, "Returned authentication info was null"); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE, + "Un authenticated request does not contain status as failure"); + } + + + /** + * To create a JWT request with the given jwt header. + * @param jwtToken JWT token to be added to the header + * @param requestUri Request URI to be added to the request. + */ + private Request createJWTRequest(String jwtToken, String requestUri) + throws IllegalAccessException, NoSuchFieldException { + Request request = new Request(); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue(JWT_HEADER); + bytes.setString(jwtToken); + headersField.set(coyoteRequest, mimeHeaders); + Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB"); + uriMB.setAccessible(true); + bytes = MessageBytes.newInstance(); + bytes.setString(requestUri); + uriMB.set(coyoteRequest, bytes); + request.setCoyoteRequest(coyoteRequest); + return request; + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponentTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponentTest.java new file mode 100644 index 0000000000..a3a06039ec --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponentTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.webapp.authenticator.framework.internal; + +import org.apache.sling.testing.mock.osgi.MockOsgi; +import org.testng.annotations.Test; + +/** + * This is a test class for {@link WebappAuthenticatorFrameworkServiceComponent} + */ +public class WebappAuthenticatorFrameworkServiceComponentTest { + + @Test(description = "This method tests whether the bundle activator does not throw any exceptions, even under " + + "possible exception scenarios") + public void testActivateWithException() { + WebappAuthenticatorFrameworkServiceComponent webappAuthenticatorFrameworkServiceComponent = new + WebappAuthenticatorFrameworkServiceComponent(); + webappAuthenticatorFrameworkServiceComponent.activate(null); + } + + @Test(description = "This method tests whether bundle activation succeed with the proper confitions.") + public void testActivateWithoutExceptions() { + WebappAuthenticatorFrameworkServiceComponent webappAuthenticatorFrameworkServiceComponent = new + WebappAuthenticatorFrameworkServiceComponent(); + webappAuthenticatorFrameworkServiceComponent.activate(MockOsgi.newComponentContext()); + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestCertificateGenerator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestCertificateGenerator.java new file mode 100644 index 0000000000..5f8f96923d --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestCertificateGenerator.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.wso2.carbon.webapp.authenticator.framework.util; + +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.wso2.carbon.certificate.mgt.core.bean.Certificate; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; +import org.wso2.carbon.certificate.mgt.core.util.CommonUtil; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import javax.security.auth.x500.X500Principal; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.security.Security; +import java.security.SignatureException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * This is a mock implementation of {@link CertificateGenerator}. + */ +public class TestCertificateGenerator extends CertificateGenerator { + private int count = 0; + + public X509Certificate generateX509Certificate() throws KeystoreException { + BigInteger serialNumber = CommonUtil.generateSerialNumber(); + String defaultPrinciple = "CN=" + serialNumber + ",O=WSO2,OU=Mobile,C=LK"; + CommonUtil commonUtil = new CommonUtil(); + Date validityBeginDate = commonUtil.getValidityStartDate(); + Date validityEndDate = commonUtil.getValidityEndDate(); + Security.addProvider(new BouncyCastleProvider()); + + try { + KeyPairGenerator keyPairGenerator = KeyPairGenerator + .getInstance(CertificateManagementConstants.RSA, CertificateManagementConstants.PROVIDER); + keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom()); + KeyPair pair = keyPairGenerator.generateKeyPair(); + X500Principal principal = new X500Principal(defaultPrinciple); + X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(principal, serialNumber, + validityBeginDate, validityEndDate, principal, pair.getPublic()); + ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA) + .setProvider(CertificateManagementConstants.PROVIDER).build(pair.getPrivate()); + X509Certificate certificate = new JcaX509CertificateConverter() + .setProvider(CertificateManagementConstants.PROVIDER) + .getCertificate(certificateBuilder.build(contentSigner)); + certificate.verify(certificate.getPublicKey()); + List certificates = new ArrayList<>(); + org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = + new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); + certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + certificateToStore.setCertificate(certificate); + certificates.add(certificateToStore); + saveCertInKeyStore(certificates); + return certificate; + } catch (NoSuchAlgorithmException e) { + String errorMsg = "No such algorithm found when generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (NoSuchProviderException e) { + String errorMsg = "No such provider found when generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (OperatorCreationException e) { + String errorMsg = "Issue in operator creation when generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (CertificateExpiredException e) { + String errorMsg = "Certificate expired after generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (CertificateNotYetValidException e) { + String errorMsg = "Certificate not yet valid when generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (CertificateException e) { + String errorMsg = "Certificate issue occurred when generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (InvalidKeyException e) { + String errorMsg = "Invalid key used when generating certificate"; + throw new KeystoreException(errorMsg, e); + } catch (SignatureException e) { + String errorMsg = "Signature related issue occurred when generating certificate"; + throw new KeystoreException(errorMsg, e); + } + } + + public String extractChallengeToken(X509Certificate certificate) { + if (count != 0) { + return "WSO2 (Challenge)"; + } else { + count++; + return null; + } + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java new file mode 100644 index 0000000000..6b5b8cb85b --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.webapp.authenticator.framework.util; + +import org.apache.catalina.connector.Request; + +/** + * This is a test class implementation of {@link Request} + */ +public class TestRequest extends Request { + private String contextPath; + private String requestURI; + + public TestRequest(String contextPath, String requestURI) { + this.contextPath = contextPath; + this.requestURI = requestURI; + } + + @Override + public String getContextPath() { + return contextPath; + } + + @Override + public String getRequestURI() { + return requestURI; + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestTenantIndexingLoader.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestTenantIndexingLoader.java new file mode 100644 index 0000000000..3f8b84dacf --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestTenantIndexingLoader.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.wso2.carbon.webapp.authenticator.framework.util; + +import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; + +/** + * This is a mock implementation of {@link TenantIndexingLoader} + */ +public class TestTenantIndexingLoader implements TenantIndexingLoader { + @Override + public void loadTenantIndex(int i) { } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestTenantRegistryLoader.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestTenantRegistryLoader.java new file mode 100644 index 0000000000..42d6f04f76 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestTenantRegistryLoader.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.webapp.authenticator.framework.util; + +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.service.TenantRegistryLoader; + +/** + * This is a mock implementation of {@link TenantRegistryLoader} for the test cases. + */ +public class TestTenantRegistryLoader implements TenantRegistryLoader { + @Override + public void loadTenantRegistry(int i) throws RegistryException { } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/conf/cdm-config.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/conf/cdm-config.xml new file mode 100644 index 0000000000..70ff0a6f41 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/conf/cdm-config.xml @@ -0,0 +1,96 @@ + + + + + + + + jdbc/DM_DS + + + + + 1000 + 60000 + 60000 + true + + org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider + + org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider + org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider + org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider + + + + false + + + https://localhost:9443 + admin + admin + + + org.wso2.carbon.policy.mgt + true + 60000 + 5 + 8 + 20 + + + + Simple + + + + 20 + 20 + 20 + 20 + 20 + 20 + + + + true + + + + true + 600 + + 10000 + + + false + 86400 + + + false + false + + BYOD,COPE + + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/resources/security/client-truststore.jks b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/resources/security/client-truststore.jks new file mode 100644 index 0000000000..3b9fdfb9e8 Binary files /dev/null and b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/resources/security/client-truststore.jks differ diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/resources/security/wso2carbon.jks b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/resources/security/wso2carbon.jks new file mode 100644 index 0000000000..b4b6220bae Binary files /dev/null and b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/carbon-home/repository/resources/security/wso2carbon.jks differ diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/jwt.properties b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/jwt.properties new file mode 100644 index 0000000000..839769e4c3 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/jwt.properties @@ -0,0 +1,57 @@ +# +# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +# +# WSO2 Inc. licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +#issuer of the JWT +iss=wso2.org/products/iot + +TokenEndpoint=https://${iot.gateway.host}:${iot.gateway.https.port}/token?tenantDomain=carbon.super + +#audience of JWT claim +#comma seperated values +aud=devicemgt + +#expiration time of JWT (number of minutes from the current time) +exp=1000 + +#issued at time of JWT (number of minutes from the current time) +iat=0 + +#nbf time of JWT (number of minutes from current time) +nbf=0 + +#skew between IDP and issuer(seconds) +skew=0 + +# JWT Id +#jti=token123 + +#KeyStore to cryptographic credentials +KeyStore=target/test-classes/carbon-home/repository/resources/security/wso2carbon.jks + +#Password of the KeyStore +KeyStorePassword=wso2carbon + +#Alias of the SP's private key +PrivateKeyAlias=wso2carbon + +#Private key password to retrieve the private key used to sign +#AuthnRequest and LogoutRequest messages +PrivateKeyPassword=wso2carbon + +#this will be used as the default IDP config if there isn't any config available for tenants. +default-jwt-client=false diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/sql-scripts/h2.sql b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/sql-scripts/h2.sql new file mode 100644 index 0000000000..7cf6882829 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/sql-scripts/h2.sql @@ -0,0 +1,25 @@ +-- +-- Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +-- +-- WSO2 Inc. licenses this file to you under the Apache License, +-- Version 2.0 (the "License"); you may not use this file except +-- in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, +-- software distributed under the License is distributed on an +-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +-- KIND, either express or implied. See the License for the +-- specific language governing permissions and limitations +-- under the License. + +CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( + ID INTEGER auto_increment NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL, + PRIMARY KEY (ID) +); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml index d166d4b15e..bb43e50bdc 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml @@ -22,7 +22,7 @@ - + @@ -31,6 +31,10 @@ + + + + diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index 8a039c09cd..ae64501dac 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt webapp-authenticator-framework - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Webapp Authenticator Framework http://wso2.org diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml index aee0053b20..a92757d8ea 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml @@ -21,14 +21,14 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.application.extension.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - API Management Application Extension Feature http://wso2.org This feature contains an implementation of a api application registration, which takes care of subscription diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml index 21cd8e3d74..746ab58f40 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.handler.server.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Management - APIM handler Server Feature http://wso2.org This feature contains the handler for the api authentications diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml index 8bc00561d1..3d3ebc7ac2 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml @@ -21,13 +21,13 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.client.feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - APIM Integration Client Feature http://wso2.org diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml index d6aaea623a..9f5123adaf 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml @@ -21,14 +21,14 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - API Management Webapp Publisher Feature http://wso2.org This feature contains an implementation of a Tomcat lifecycle listener, which takes care of publishing diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 6553a3d1a1..31cfebbf6f 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt apimgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - API Management Extensions Feature http://wso2.org diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml index fcbce9d773..67f8e6eb47 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index 4ecaf97f03..c39be61e9d 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml index 6bbe7752d5..f71bc7f2b8 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.server.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Certificate Management Server Feature http://wso2.org This feature contains the core bundles required for back-end Certificate Management functionality diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index a785c751f4..7cbb914602 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt certificate-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Certificate Management Feature http://wso2.org diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml index 5802e02903..c0389a2cef 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Type Deployer Feature http://wso2.org WSO2 Carbon - Device Type Deployer Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index 51fbc838cb..741a0540a2 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - FCM Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - MQTT Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index 929fc52057..9a27238701 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - MQTT Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - MQTT Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index e390d6c8f7..4f0b0d510b 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - MQTT Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - MQTT Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index 11e4e7bc36..31839c556f 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - XMPP Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - XMPP Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index d607c28460..c1e34d9e99 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/pom.xml index 2e15777494..65725eacfd 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.analytics.data.publisher.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Management Server Feature http://wso2.org This feature contains bundles related to device analytics data publisher diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml index 1186d6d60a..60a8b57b78 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml index 4fec0a99b9..8e2f2410b0 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml @@ -4,14 +4,14 @@ org.wso2.carbon.devicemgt device-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Management Extensions Feature http://wso2.org This feature contains common extensions used by key device management functionalities diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml index ae3efcbd6b..2947a41886 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml index 9a0fd82651..576891b838 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt device-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.server.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Management Server Feature http://wso2.org This feature contains the core bundles required for Back-end Device Management functionality diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml index 3395a77803..41800e95a3 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 3b195c6400..e1ffdcd0a8 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml diff --git a/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml b/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml index 95d3011678..3a5ae83370 100644 --- a/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml +++ b/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt email-sender-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.email.sender.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Email Sender Feature http://wso2.org This feature contains the core bundles required for email sender related functionality diff --git a/features/email-sender/pom.xml b/features/email-sender/pom.xml index 574a06bb20..370e3e62a0 100644 --- a/features/email-sender/pom.xml +++ b/features/email-sender/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt email-sender-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Email Sender Feature http://wso2.org diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml index c7d209ebbe..4c573b7d90 100644 --- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml @@ -23,14 +23,14 @@ org.wso2.carbon.devicemgt jwt-client-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.identity.jwt.client.extension.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - JWT Client Feature http://wso2.org This feature contains jwt client implementation from which we can get a access token using the jwt diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index 4b4bccf0c1..abea0b8bf8 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -23,13 +23,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 jwt-client-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - JWT Client Extension Feature http://wso2.org diff --git a/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml b/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml index 477fef5cc7..46a0e35d33 100644 --- a/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml +++ b/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml @@ -23,14 +23,14 @@ org.wso2.carbon.devicemgt oauth-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.oauth.extensions.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Mgt OAuth Extensions Feature http://wso2.org This feature contains devicemgt related OAuth extensions diff --git a/features/oauth-extensions/pom.xml b/features/oauth-extensions/pom.xml index 8b25b81a53..b2b611a2fe 100644 --- a/features/oauth-extensions/pom.xml +++ b/features/oauth-extensions/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt oauth-extensions-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Device Management OAuth Extensions Feature http://wso2.org diff --git a/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml b/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml index b535ac8f55..5852cdcf84 100644 --- a/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml @@ -23,14 +23,14 @@ org.wso2.carbon.devicemgt policy-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.policy.mgt.server.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Policy Management Server Feature http://wso2.org This feature contains the core bundles required for Back-end Device Management functionality diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index 92d4820562..0a23900933 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -23,14 +23,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt policy-mgt-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Policy Management Feature http://wso2.org diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml index 46f2ed3adc..8a76e1199a 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt webapp-authenticator-framework-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.webapp.authenticator.framework.server.feature pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Webapp Authenticator Framework Server Feature http://wso2.org This feature contains the core bundles required for Back-end Device Management functionality diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index e9557fcc6e..7b0ff3bf0d 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt webapp-authenticator-framework-feature - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT pom WSO2 Carbon - Webapp Authenticator Framework Feature http://wso2.org diff --git a/pom.xml b/pom.xml index 5e2e6c6686..bb7679bd99 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt pom - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT WSO2 Carbon - Device Management - Parent http://wso2.org WSO2 Connected Device Manager Components @@ -1568,6 +1568,12 @@ + + org.slf4j + slf4j-nop + test + ${slf4j.nop.version} + @@ -1863,7 +1869,7 @@ 1.2.11.wso2v10 - 3.0.148-SNAPSHOT + 3.0.162-SNAPSHOT 4.4.8 @@ -1890,7 +1896,7 @@ [4.4.8, 5.0.0) - 2.7.16 + 3.2.0 2.5.11 1.1.wso2v1 1.9.0 @@ -2005,6 +2011,7 @@ 1.0b3 1.7.0 1.4.0.wso2v1 + 1.7.25