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 3e7496e796..351b57cc89 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.annotations - 3.0.136-SNAPSHOT + 3.0.170-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 2491289e4e..9002ca59b2 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 - 3.0.136-SNAPSHOT + 3.0.170-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 6c08f55444..350cdb6368 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 - 3.0.136-SNAPSHOT + 3.0.170-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 23a01c76ff..6bf9da9f7a 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.handlers - 3.0.136-SNAPSHOT + 3.0.170-SNAPSHOT bundle WSO2 Carbon - API Security Handler Component WSO2 Carbon - API Management Security Handler Module @@ -55,6 +55,11 @@ org.json.wso2 json + + org.slf4j + slf4j-simple + test + @@ -97,6 +102,15 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + src/test/resources/testng.xml + + + org.jacoco jacoco-maven-plugin diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java index 7c7b317537..89e7c38eb7 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/APIMCertificateMGTException.java @@ -26,37 +26,8 @@ public class APIMCertificateMGTException extends Exception{ private static final long serialVersionUID = -37676242646464497L; - private String errorMessage; - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public APIMCertificateMGTException(String msg, Exception nestedEx) { super(msg, nestedEx); - setErrorMessage(msg); - } - - public APIMCertificateMGTException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public APIMCertificateMGTException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public APIMCertificateMGTException() { - super(); - } - - public APIMCertificateMGTException(Throwable cause) { - super(cause); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java index 2891e06179..b851ee4f8c 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandler.java @@ -19,7 +19,6 @@ package org.wso2.carbon.apimgt.handlers; import com.google.gson.Gson; import org.apache.axis2.context.MessageContext; -import org.apache.axis2.description.HandlerDescription; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.core.axis2.Axis2MessageContext; @@ -51,11 +50,9 @@ import java.util.StringTokenizer; */ public class AuthenticationHandler extends AbstractHandler { private static final Log log = LogFactory.getLog(AuthenticationHandler.class); - private static HandlerDescription EMPTY_HANDLER_METADATA = new HandlerDescription("API Security Handler"); - private HandlerDescription handlerDesc; private RESTInvoker restInvoker; - private static final String X_JWT_ASSERTION = "X-JWT-Assertion"; + private static final String X_JWT_ASSERTION = "X-JWT-Assertion"; private static final String JWTTOKEN = "JWTToken"; private static final String AUTHORIZATION = "Authorization"; private static final String BEARER = "Bearer "; @@ -69,15 +66,14 @@ public class AuthenticationHandler extends AbstractHandler { public AuthenticationHandler() { log.info("Engaging API Security Handler.........."); restInvoker = new RESTInvoker(); - this.handlerDesc = EMPTY_HANDLER_METADATA; this.iotServerConfiguration = Utils.initConfig(); } /** * Handling the message and checking the security. * - * @param messageContext - * @return + * @param messageContext Request message context. + * @return Boolean value of the result of the processing the request. */ @Override public boolean handleRequest(org.apache.synapse.MessageContext messageContext) { @@ -91,16 +87,19 @@ public class AuthenticationHandler extends AbstractHandler { Map headers = (Map) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS); try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - RESTResponse response; + RESTResponse response = null; if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) { - String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE).toString(); + String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE); if (log.isDebugEnabled()) { log.debug("Verify Cert:\n" + mdmSignature); } String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); + if (deviceType == null) { + return false; + } URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(); + Map certVerifyHeaders = this.setHeaders(this.restInvoker); Certificate certificate = new Certificate(); certificate.setPem(mdmSignature); @@ -109,8 +108,7 @@ public class AuthenticationHandler extends AbstractHandler { Gson gson = new Gson(); String certVerifyContent = gson.toJson(certificate); - response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, - null, certVerifyContent); + response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent); String str = response.getContent(); if (log.isDebugEnabled()) { @@ -125,7 +123,7 @@ public class AuthenticationHandler extends AbstractHandler { } } else if (headers.containsKey(AuthConstants.PROXY_MUTUAL_AUTH_HEADER)) { - String subjectDN = headers.get(AuthConstants.PROXY_MUTUAL_AUTH_HEADER).toString(); + String subjectDN = headers.get(AuthConstants.PROXY_MUTUAL_AUTH_HEADER); if (log.isDebugEnabled()) { log.debug("Verify subject DN: " + subjectDN); @@ -133,7 +131,7 @@ public class AuthenticationHandler extends AbstractHandler { String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(); + Map certVerifyHeaders = this.setHeaders(this.restInvoker); Certificate certificate = new Certificate(); certificate.setPem(subjectDN); certificate.setTenantId(tenantId); @@ -141,8 +139,7 @@ public class AuthenticationHandler extends AbstractHandler { Gson gson = new Gson(); String certVerifyContent = gson.toJson(certificate); - response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, - null, certVerifyContent); + response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent); if (log.isDebugEnabled()) { log.debug("Verify response:" + response.getContent()); } @@ -152,23 +149,19 @@ public class AuthenticationHandler extends AbstractHandler { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bais = new ByteArrayInputStream(certs[0].getEncoded()); X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais); - if (bais != null) { - bais.close(); - } + bais.close(); if (x509 != null) { headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509)); return true; - } else { - response = null; } } else if (headers.containsKey(AuthConstants.ENCODED_PEM)) { - String encodedPem = headers.get(AuthConstants.ENCODED_PEM).toString(); + String encodedPem = headers.get(AuthConstants.ENCODED_PEM); if (log.isDebugEnabled()) { log.debug("Verify Cert:\n" + encodedPem); } String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); - Map certVerifyHeaders = this.setHeaders(); + Map certVerifyHeaders = this.setHeaders(this.restInvoker); Certificate certificate = new Certificate(); certificate.setPem(encodedPem); @@ -176,8 +169,7 @@ public class AuthenticationHandler extends AbstractHandler { certificate.setSerial(""); Gson gson = new Gson(); String certVerifyContent = gson.toJson(certificate); - response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, - null, certVerifyContent); + response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent); if (log.isDebugEnabled()) { log.debug("Verify response:" + response.getContent()); } @@ -224,9 +216,9 @@ public class AuthenticationHandler extends AbstractHandler { return null; } - private Map setHeaders() throws APIMCertificateMGTException { + private Map setHeaders(RESTInvoker restInvoker) throws APIMCertificateMGTException { Map map = new HashMap<>(); - String accessToken = Utils.getAccessToken(iotServerConfiguration); + String accessToken = Utils.getAccessToken(iotServerConfiguration, restInvoker); map.put(AUTHORIZATION, BEARER + accessToken); map.put(CONTENT_TYPE, "application/json"); return map; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java index 107d754ff4..bd59e03dc1 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTInvoker.java @@ -17,11 +17,9 @@ */ package org.wso2.carbon.apimgt.handlers.invoker; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.Header; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; @@ -32,42 +30,37 @@ import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; -import java.nio.charset.StandardCharsets; import java.util.Map; +import java.util.Set; public class RESTInvoker { private static final Log log = LogFactory.getLog(RESTInvoker.class); - private int maxTotalConnections = 100; - private int maxTotalConnectionsPerRoute = 100; - private int connectionTimeout = 120000; - private int socketTimeout = 120000; - private CloseableHttpClient client = null; - private PoolingHttpClientConnectionManager connectionManager = null; public RESTInvoker() { configureHttpClient(); } private void configureHttpClient() { - + int connectionTimeout = 120000; + int socketTimeout = 120000; + int maxTotalConnectionsPerRoute = 100; + int maxTotalConnections = 100; RequestConfig defaultRequestConfig = RequestConfig.custom() .setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout) .setSocketTimeout(socketTimeout) .build(); - - connectionManager = new PoolingHttpClientConnectionManager(); + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute); connectionManager.setMaxTotal(maxTotalConnections); client = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(defaultRequestConfig) .build(); - - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("REST client initialized with " + "maxTotalConnection = " + maxTotalConnections + "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute + @@ -76,81 +69,24 @@ public class RESTInvoker { } - public void closeHttpClient() { - IOUtils.closeQuietly(client); - IOUtils.closeQuietly(connectionManager); - } - - /** - * Invokes the http GET method - * - * @param uri endpoint/service url - * @param requestHeaders header list - * @param username username for authentication - * @param password password for authentication - * @return RESTResponse of the GET request (can be the response body or the response status code) - * @throws Exception - */ - public RESTResponse invokeGET(URI uri, Map requestHeaders, String username, String password) throws IOException { - - HttpGet httpGet = null; - CloseableHttpResponse response = null; - Header[] headers; - int httpStatus; - String contentType; - String output; - try { - httpGet = new HttpGet(uri); - if (requestHeaders != null && !requestHeaders.isEmpty()) { - Object keys[] = requestHeaders.keySet().toArray(); - for (Object header : keys) { - httpGet.setHeader(header.toString(), requestHeaders.get(header).toString()); - } - } - response = sendReceiveRequest(httpGet, username, password); - output = IOUtils.toString(response.getEntity().getContent()); - headers = response.getAllHeaders(); - httpStatus = response.getStatusLine().getStatusCode(); - contentType = response.getEntity().getContentType().getValue(); - if (log.isDebugEnabled()) { - log.debug("Invoked GET " + uri.toString() + " - Response message: " + output); - } - EntityUtils.consume(response.getEntity()); - } finally { - if (response != null) { - IOUtils.closeQuietly(response); - } - if (httpGet != null) { - httpGet.releaseConnection(); - } - } - return new RESTResponse(contentType, output, headers, httpStatus); - } - - - public RESTResponse invokePOST(URI uri, Map requestHeaders, String username, - String password, String payload) throws IOException { + public RESTResponse invokePOST(URI uri, Map requestHeaders, String payload) throws IOException { HttpPost httpPost = null; CloseableHttpResponse response = null; - Header[] headers; int httpStatus; - String contentType; String output; try { httpPost = new HttpPost(uri); httpPost.setEntity(new StringEntity(payload)); if (requestHeaders != null && !requestHeaders.isEmpty()) { - Object keys[] = requestHeaders.keySet().toArray(); - for (Object header : keys) { - httpPost.setHeader(header.toString(), requestHeaders.get(header).toString()); + Set keys = requestHeaders.keySet(); + for (String header : keys) { + httpPost.setHeader(header, requestHeaders.get(header)); } } - response = sendReceiveRequest(httpPost, username, password); + response = sendReceiveRequest(httpPost); output = IOUtils.toString(response.getEntity().getContent()); - headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); - contentType = response.getEntity().getContentType().getValue(); if (log.isDebugEnabled()) { log.debug("Invoked POST " + uri.toString() + " - Input payload: " + payload + " - Response message: " + output); @@ -164,116 +100,11 @@ public class RESTInvoker { httpPost.releaseConnection(); } } - return new RESTResponse(contentType, output, headers, httpStatus); - } - - /** - * Invokes the http PUT method - * - * @param uri endpoint/service url - * @param requestHeaders header list - * @param username username for authentication - * @param password password for authentication - * @param payload payload body passed - * @return RESTResponse of the PUT request (can be the response body or the response status code) - * @throws Exception - */ - public RESTResponse invokePUT(URI uri, Map requestHeaders, String username, String password, - String payload) throws IOException { - - HttpPut httpPut = null; - CloseableHttpResponse response = null; - Header[] headers; - int httpStatus; - String contentType; - String output; - try { - httpPut = new HttpPut(uri); - httpPut.setEntity(new StringEntity(payload)); - if (requestHeaders != null && !requestHeaders.isEmpty()) { - Object keys[] = requestHeaders.keySet().toArray(); - for (Object header : keys) { - httpPut.setHeader(header.toString(), requestHeaders.get(header).toString()); - } - } - response = sendReceiveRequest(httpPut, username, password); - output = IOUtils.toString(response.getEntity().getContent()); - headers = response.getAllHeaders(); - httpStatus = response.getStatusLine().getStatusCode(); - contentType = response.getEntity().getContentType().getValue(); - if (log.isDebugEnabled()) { - log.debug("Invoked PUT " + uri.toString() + " - Response message: " + output); - } - EntityUtils.consume(response.getEntity()); - } finally { - if (response != null) { - IOUtils.closeQuietly(response); - } - if (httpPut != null) { - httpPut.releaseConnection(); - } - } - return new RESTResponse(contentType, output, headers, httpStatus); - } - - /** - * Invokes the http DELETE method - * - * @param uri endpoint/service url - * @param requestHeaders header list - * @param username username for authentication - * @param password password for authentication - * @return RESTResponse of the DELETE (can be the response status code or the response body) - * @throws Exception - */ - public RESTResponse invokeDELETE(URI uri, Map requestHeaders, String username, String password) throws IOException { - - HttpDelete httpDelete = null; - CloseableHttpResponse response = null; - Header[] headers; - int httpStatus; - String contentType; - String output; - try { - httpDelete = new HttpDelete(uri); - if (requestHeaders != null && !requestHeaders.isEmpty()) { - Object keys[] = requestHeaders.keySet().toArray(); - for (Object header : keys) { - httpDelete.setHeader(header.toString(), requestHeaders.get(header).toString()); - } - } - response = sendReceiveRequest(httpDelete, username, password); - output = IOUtils.toString(response.getEntity().getContent()); - headers = response.getAllHeaders(); - httpStatus = response.getStatusLine().getStatusCode(); - contentType = response.getEntity().getContentType().getValue(); - if (log.isDebugEnabled()) { - log.debug("Invoked DELETE " + uri.toString() + " - Response message: " + output); - } - EntityUtils.consume(response.getEntity()); - } finally { - if (response != null) { - IOUtils.closeQuietly(response); - } - if (httpDelete != null) { - httpDelete.releaseConnection(); - } - } - return new RESTResponse(contentType, output, headers, httpStatus); + return new RESTResponse(output, httpStatus); } - private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase, String username, String password) + private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase) throws IOException { - CloseableHttpResponse response; - if (username != null && !username.equals("") && password != null) { - String combinedCredentials = username + ":" + password; - byte[] encodedCredentials = Base64.encodeBase64(combinedCredentials.getBytes(StandardCharsets.UTF_8)); - requestBase.addHeader("Authorization", "Basic " + new String(encodedCredentials)); - - response = client.execute(requestBase); - } else { - response = client.execute(requestBase); - } - return response; + return client.execute(requestBase); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java index 7ce0389baa..205130b30e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/invoker/RESTResponse.java @@ -17,40 +17,25 @@ */ package org.wso2.carbon.apimgt.handlers.invoker; -import org.apache.http.Header; /** * RESTResponse class holds the data retrieved from the HTTP invoke response. */ public class RESTResponse { - private String contentType; private String content; - private Header[] headers; private int httpStatus; /** * Constructor * - * @param contentType from the REST invoke response * @param content from the REST invoke response - * @param headers from the REST invoke response * @param httpStatus from the REST invoke response */ - public RESTResponse(String contentType, String content, Header[] headers, int httpStatus) { - this.contentType = contentType; + RESTResponse(String content, int httpStatus) { this.content = content; - this.headers = headers; this.httpStatus = httpStatus; } - /** - * Get the content type of the EST invoke response - * - * @return String content type of the response - */ - public String getContentType() { - return contentType; - } /** * Get contents of the REST invoke response @@ -61,15 +46,6 @@ public class RESTResponse { return content; } - /** - * Get headers of the REST invoke response - * - * @return headers of the REST invoke response - */ - public Header[] getHeaders() { - return headers; - } - /** * Get the HTTP Status code from REST invoke response * diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java index 74870c131f..f2a9f7a42b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/AuthConstants.java @@ -21,18 +21,6 @@ package org.wso2.carbon.apimgt.handlers.utils; * This initializes the constance. */ public class AuthConstants { -// public static final String SEC_FAULT = "SECURITY_VALIDATION_FAILURE"; -// public static final String HTTPS = "https"; -// public static final String WSSE = "wsse"; -// public static final String AUTH_CONFIGURATION_FILE_NAME = "api-filter-config.xml"; -// public static final String API_FILTER_CONFIG_ELEMENT = "apiFilterConfig"; -// public static final String API_LIST_PROPERTY = "apiList"; -// public static final String HOST = "host"; -// public static final String HTTPS_PORT = "httpsPort"; -// public static final String USERNAME = "username"; -// public static final String PASSWORD = "password"; -// public static final String IOS_VERIFY_ENDPOINT = "ios-verify-endpoint"; -// public static final String ANDROID_VERIFY_ENDPOINT = "android-verify-endpoint"; public static final String MDM_SIGNATURE = "mdm-signature"; public static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header"; public static final String MUTUAL_AUTH_HEADER = "mutual-auth-header"; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java index e7d239a1ee..a36dc0f647 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/main/java/org/wso2/carbon/apimgt/handlers/utils/Utils.java @@ -59,14 +59,22 @@ public class Utils { /** * This method initializes the iot-api-config.xml file. - * @return + * + * @return IoTServerConfiguration Object based on the configuration file. */ public static IOTServerConfiguration initConfig() { - try { + return initConfig(CarbonUtils.getCarbonConfigDirPath() + File.separator + IOT_APIS_CONFIG_FILE); + } - String IOTServerAPIConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separator - + IOT_APIS_CONFIG_FILE; - File file = new File(IOTServerAPIConfigurationPath); + /** + * This methods initialized the iot-api-config.xml from provided path. + * + * @param path The actual file path of iot-api-config.xml + * @return The instance of the IOTServerConfiguration based on the configuration. + */ + public static IOTServerConfiguration initConfig(String path) { + try { + File file = new File(path); Document doc = Utils.convertToDocument(file); JAXBContext fileContext = JAXBContext.newInstance(IOTServerConfiguration.class); @@ -91,7 +99,7 @@ public class Utils { /** * This method gets the values from system variables and sets to xml. */ - public static String replaceProperties(String text) { + private static String replaceProperties(String text) { String regex = "\\$\\{(.*?)\\}"; Pattern pattern = Pattern.compile(regex); Matcher matchPattern = pattern.matcher(text); @@ -107,11 +115,12 @@ public class Utils { /** * This class build the iot-api-config.xml file. - * @param file - * @return + * + * @param file The file object of iot-api-config.xml. + * @return Document instance of the file * @throws APIMCertificateMGTException */ - public static Document convertToDocument(File file) throws APIMCertificateMGTException { + private static Document convertToDocument(File file) throws APIMCertificateMGTException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { @@ -126,48 +135,46 @@ public class Utils { /** * This class get the access token from the key manager. - * @param iotServerConfiguration - * @return + * + * @param iotServerConfiguration Instance of the IoTsererConfiguration. + * @return Access token will be returned. * @throws APIMCertificateMGTException */ - public static String getAccessToken(IOTServerConfiguration iotServerConfiguration) + public static String getAccessToken(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker) throws APIMCertificateMGTException { try { if (clientId == null || clientSecret == null) { - getClientSecretes(iotServerConfiguration); + getClientSecretes(iotServerConfiguration, restInvoker); } URI tokenUrl = new URI(iotServerConfiguration.getOauthTokenEndpoint()); - String tokenContent = "grant_type=password&username=" + iotServerConfiguration.getUsername()+ "&password=" + + String tokenContent = "grant_type=password&username=" + iotServerConfiguration.getUsername() + "&password=" + iotServerConfiguration.getPassword() + "&scope=activity-view"; String tokenBasicAuth = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes()); - Map tokenHeaders = new HashMap(); + Map tokenHeaders = new HashMap<>(); tokenHeaders.put("Authorization", tokenBasicAuth); tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded"); - RESTInvoker restInvoker = new RESTInvoker(); - RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, null, null, tokenContent); - if(log.isDebugEnabled()) { + RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, tokenContent); + if (log.isDebugEnabled()) { log.debug("Token response:" + response.getContent()); } JSONObject jsonResponse = new JSONObject(response.getContent()); - String accessToken = jsonResponse.getString("access_token"); - return accessToken; + return jsonResponse.getString("access_token"); - } catch (URISyntaxException e) { + } catch (URISyntaxException | IOException e) { throw new APIMCertificateMGTException("Error occurred while trying to call oauth token endpoint", e); } catch (JSONException e) { throw new APIMCertificateMGTException("Error occurred while converting the json to object", e); - } catch (IOException e) { - throw new APIMCertificateMGTException("Error occurred while trying to call oauth token endpoint", e); } } /** * This method register an application to get the client key and secret. - * @param iotServerConfiguration + * + * @param iotServerConfiguration Instance of the IoTServerConfiguration. * @throws APIMCertificateMGTException */ - private static void getClientSecretes(IOTServerConfiguration iotServerConfiguration) + private static void getClientSecretes(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker) throws APIMCertificateMGTException { try { String username = iotServerConfiguration.getUsername(); @@ -180,13 +187,12 @@ public class Utils { dcr.setCallbackUrl(AuthConstants.CALLBACK_URL); dcr.setIsSaasApp(true); String dcrContent = dcr.toJSON(); - Map dcrHeaders = new HashMap(); + Map dcrHeaders = new HashMap<>(); String basicAuth = Base64.encode((username + ":" + password).getBytes()); dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE); dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth); URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint()); - RESTInvoker restInvoker = new RESTInvoker(); - RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, null, null, dcrContent); + RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, dcrContent); if (log.isDebugEnabled()) { log.debug("DCR response :" + response.getContent()); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java new file mode 100644 index 0000000000..f42505409a --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/AuthenticationHandlerTest.java @@ -0,0 +1,316 @@ +/* +* 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.handlers; + +import com.google.gson.Gson; +import junit.framework.Assert; +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMDocument; +import org.apache.axiom.soap.SOAPEnvelope; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.engine.AxisConfiguration; +import org.apache.http.ProtocolVersion; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.entity.BasicHttpEntity; +import org.apache.http.message.BasicStatusLine; +import org.apache.synapse.MessageContext; +import org.apache.synapse.config.SynapseConfigUtils; +import org.apache.synapse.config.SynapseConfiguration; +import org.apache.synapse.core.SynapseEnvironment; +import org.apache.synapse.core.axis2.Axis2MessageContext; +import org.apache.synapse.core.axis2.Axis2SynapseEnvironment; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.apimgt.handlers.beans.ValidationResponce; +import org.wso2.carbon.apimgt.handlers.invoker.RESTInvoker; +import org.wso2.carbon.apimgt.handlers.mock.MockClient; +import org.wso2.carbon.apimgt.handlers.mock.MockHttpResponse; +import org.wso2.carbon.apimgt.handlers.utils.AuthConstants; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import javax.security.cert.X509Certificate; + +/** + * This testcase will focus on covering the methods of {@link AuthenticationHandler} + */ +public class AuthenticationHandlerTest extends BaseAPIHandlerTest { + + private AuthenticationHandler handler; + private SynapseConfiguration synapseConfiguration; + private MockClient mockClient; + + @BeforeClass + public void initTest() { + TestUtils.setSystemProperties(); + this.handler = new AuthenticationHandler(); + this.synapseConfiguration = new SynapseConfiguration(); + } + + @Test(description = "Handle request with empty transport headers") + public void testHandleRequestWithEmptyTransportHeader() throws Exception { + boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, + new HashMap<>(), "https://test.com/testservice")); + Assert.assertFalse(response); + } + + @Test(description = "Handle request with without device type", + dependsOnMethods = "testHandleRequestWithEmptyTransportHeader") + public void testHandleRequestWithoutDeviceType() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); + boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice")); + Assert.assertFalse(response); + } + + @Test(description = "Handle request with device type URI with MDM ceritificate", + dependsOnMethods = "testHandleRequestWithoutDeviceType") + public void testHandleSuccessfulRequestMDMCertificate() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); + setMockClient(); + this.mockClient.setResponse(getDCRResponse()); + this.mockClient.setResponse(getAccessTokenReponse()); + this.mockClient.setResponse(getValidationResponse()); + boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice")); + Assert.assertTrue(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with device type URI with Proxy Mutual Auth Header", + dependsOnMethods = "testHandleSuccessfulRequestMDMCertificate") + public void testHandleSuccessRequestProxyMutualAuthHeader() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, "Test Header"); + setMockClient(); + this.mockClient.setResponse(getAccessTokenReponse()); + this.mockClient.setResponse(getValidationResponse()); + boolean response = this.handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice")); + Assert.assertTrue(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with device type URI with Mutual Auth Header", + dependsOnMethods = "testHandleSuccessRequestProxyMutualAuthHeader") + public void testHandleSuccessRequestMutualAuthHeader() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header"); + setMockClient(); + this.mockClient.setResponse(getAccessTokenReponse()); + this.mockClient.setResponse(getValidationResponse()); + MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice"); + org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); + String certStr = getContent(TestUtils.getAbsolutePathOfConfig("ra_cert.pem")); + X509Certificate cert = X509Certificate.getInstance(new ByteArrayInputStream(certStr. + getBytes(StandardCharsets.UTF_8.name()))); + axisMC.setProperty(AuthConstants.CLIENT_CERTIFICATE, new X509Certificate[]{cert}); + boolean response = this.handler.handleRequest(messageContext); + Assert.assertTrue(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with device type URI with Encoded Pem", + dependsOnMethods = "testHandleSuccessRequestMutualAuthHeader") + public void testHandleSuccessRequestEncodedPem() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); + setMockClient(); + this.mockClient.setResponse(getAccessTokenReponse()); + this.mockClient.setResponse(getValidationResponse()); + MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice"); + boolean response = this.handler.handleRequest(messageContext); + Assert.assertTrue(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with device type URI with Encoded Pem with invalid response", + dependsOnMethods = "testHandleSuccessRequestEncodedPem") + public void testHandleSuccessRequestEncodedPemInvalidResponse() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); + setMockClient(); + this.mockClient.setResponse(getAccessTokenReponse()); + this.mockClient.setResponse(getInvalidResponse()); + MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice"); + boolean response = this.handler.handleRequest(messageContext); + Assert.assertFalse(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with cert management exception ", + dependsOnMethods = "testHandleSuccessRequestEncodedPem") + public void testHandleRequestWithCertMgmtException() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); + setMockClient(); + this.mockClient.setResponse(null); + MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice"); + boolean response = this.handler.handleRequest(messageContext); + Assert.assertFalse(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with IO exception", + dependsOnMethods = "testHandleRequestWithCertMgmtException") + public void testHandleRequestWithIOException() throws Exception { + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem"); + setMockClient(); + this.mockClient.setResponse(getAccessTokenReponse()); + this.mockClient.setResponse(null); + MessageContext messageContext = createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice"); + boolean response = this.handler.handleRequest(messageContext); + Assert.assertFalse(response); + this.mockClient.reset(); + } + + @Test(description = "Handle request with URI exception", + dependsOnMethods = "testHandleRequestWithIOException") + public void testHandleRequestWithURIException() throws Exception { + TestUtils.resetSystemProperties(); + HashMap transportHeaders = new HashMap<>(); + transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); + AuthenticationHandler handler = new AuthenticationHandler(); + boolean response = handler.handleRequest(createSynapseMessageContext("", this.synapseConfiguration, + transportHeaders, "https://test.com/testservice/api/testdevice")); + Assert.assertFalse(response); + TestUtils.setSystemProperties(); + } + + @Test(description = "Handle response") + public void testHandleResponse() throws Exception { + boolean response = this.handler.handleResponse(null); + Assert.assertTrue(response); + } + + + private static MessageContext createSynapseMessageContext( + String payload, SynapseConfiguration config, HashMap transportHeaders, + String address) throws Exception { + org.apache.axis2.context.MessageContext mc = + new org.apache.axis2.context.MessageContext(); + AxisConfiguration axisConfig = config.getAxisConfiguration(); + if (axisConfig == null) { + axisConfig = new AxisConfiguration(); + config.setAxisConfiguration(axisConfig); + } + ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig); + SynapseEnvironment env = new Axis2SynapseEnvironment(cfgCtx, config); + MessageContext synMc = new Axis2MessageContext(mc, config, env); + SOAPEnvelope envelope = + OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope(); + OMDocument omDoc = + OMAbstractFactory.getSOAP11Factory().createOMDocument(); + omDoc.addChild(envelope); + envelope.getBody().addChild(SynapseConfigUtils.stringToOM(payload)); + synMc.setEnvelope(envelope); + synMc.setTo(new EndpointReference(address)); + org.apache.axis2.context.MessageContext axis2MessageContext = + ((Axis2MessageContext) synMc).getAxis2MessageContext(); + axis2MessageContext.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, transportHeaders); + return synMc; + } + + private void setMockClient() throws NoSuchFieldException, IllegalAccessException { + Field restInvokerField = this.handler.getClass().getDeclaredField("restInvoker"); + restInvokerField.setAccessible(true); + RESTInvoker restInvoker = (RESTInvoker) restInvokerField.get(this.handler); + Field clientField = restInvoker.getClass().getDeclaredField("client"); + clientField.setAccessible(true); + this.mockClient = new MockClient(); + clientField.set(restInvoker, this.mockClient); + } + + private CloseableHttpResponse getDCRResponse() throws IOException { + CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); + String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("dcr-response.json"); + BasicHttpEntity responseEntity = new BasicHttpEntity(); + responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile). + getBytes(StandardCharsets.UTF_8.name()))); + responseEntity.setContentType(TestUtils.CONTENT_TYPE); + mockDCRResponse.setEntity(responseEntity); + mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); + return mockDCRResponse; + } + + private CloseableHttpResponse getAccessTokenReponse() throws IOException { + CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); + String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("accesstoken-response.json"); + BasicHttpEntity responseEntity = new BasicHttpEntity(); + responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile). + getBytes(StandardCharsets.UTF_8.name()))); + responseEntity.setContentType(TestUtils.CONTENT_TYPE); + mockDCRResponse.setEntity(responseEntity); + mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); + return mockDCRResponse; + } + + private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException { + ValidationResponce response = new ValidationResponce(); + response.setDeviceId("1234"); + response.setDeviceType("testdevice"); + response.setJWTToken("1234567788888888"); + response.setTenantId(-1234); + Gson gson = new Gson(); + String jsonReponse = gson.toJson(response); + CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); + BasicHttpEntity responseEntity = new BasicHttpEntity(); + responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name()))); + responseEntity.setContentType(TestUtils.CONTENT_TYPE); + mockDCRResponse.setEntity(responseEntity); + mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); + return mockDCRResponse; + } + + private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException { + CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); + BasicHttpEntity responseEntity = new BasicHttpEntity(); + responseEntity.setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name()))); + responseEntity.setContentType(TestUtils.CONTENT_TYPE); + mockDCRResponse.setEntity(responseEntity); + mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request")); + return mockDCRResponse; + } + + private String getContent(String filePath) throws IOException { + FileReader fileReader = new FileReader(filePath); + BufferedReader bufferedReader = new BufferedReader(fileReader); + String content = ""; + String line; + while ((line = bufferedReader.readLine()) != null) { + content += line + "\n"; + } + bufferedReader.close(); + return content; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/BaseAPIHandlerTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/BaseAPIHandlerTest.java new file mode 100644 index 0000000000..57a293e2eb --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/BaseAPIHandlerTest.java @@ -0,0 +1,60 @@ +/* +* 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.handlers; + +import org.testng.annotations.BeforeSuite; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.io.File; + +/** + * This is the base test case for API Handler tests. + */ +public class BaseAPIHandlerTest { + + @BeforeSuite + public void init() { + setUpCarbonHome(); + } + + private void setUpCarbonHome() { + 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("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); + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/IOTServerConfigurationTest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/IOTServerConfigurationTest.java new file mode 100644 index 0000000000..84ebc86365 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/IOTServerConfigurationTest.java @@ -0,0 +1,97 @@ +/* +* 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.handlers; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.apimgt.handlers.config.IOTServerConfiguration; +import org.wso2.carbon.apimgt.handlers.utils.Utils; + +import java.io.File; + +/** + * This class validates the behaviour of {@link IOTServerConfiguration} + */ +public class IOTServerConfigurationTest extends BaseAPIHandlerTest { + private static final String CONFIG_DIR = "carbon-home" + File.separator + "repository" + File.separator + + "conf" + File.separator; + + @BeforeClass + public void initTest(){ + TestUtils.resetSystemProperties(); + } + + @Test(description = "Validating the IoT Server configuration initialization without system properties") + public void initConfigWithoutSystemProps() { + IOTServerConfiguration serverConfiguration = Utils.initConfig(); + Assert.assertTrue(serverConfiguration != null); + Assert.assertEquals(serverConfiguration.getHostname(), "https://${iot.core.host}:${iot.core.https.port}/"); + Assert.assertEquals(serverConfiguration.getVerificationEndpoint(), + "https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/"); + Assert.assertEquals(serverConfiguration.getUsername(), "testuser"); + Assert.assertEquals(serverConfiguration.getPassword(), "testuserpwd"); + Assert.assertEquals(serverConfiguration.getDynamicClientRegistrationEndpoint(), + "https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register"); + Assert.assertEquals(serverConfiguration.getOauthTokenEndpoint(), + "https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token"); + Assert.assertEquals(serverConfiguration.getApis().size(), 1); + Assert.assertEquals(serverConfiguration.getApis().get(0).getContextPath(), "/services"); + } + + @Test(description = "Initializing IoT server config with invalid configuration", + dependsOnMethods = "initConfigWithoutSystemProps") + public void initConfigWithInvalidConfig() { + IOTServerConfiguration serverConfig = Utils.initConfig(TestUtils.getAbsolutePathOfConfig(CONFIG_DIR + + "iot-api-config-invalid.xml")); + Assert.assertEquals(serverConfig, null); + } + + @Test(description = "Initializing IoT server config with invalid xml", + dependsOnMethods = "initConfigWithInvalidConfig") + public void initConfigWithInvalidXMLConfig() { + IOTServerConfiguration serverConfig = Utils.initConfig(TestUtils.getAbsolutePathOfConfig(CONFIG_DIR + + "iot-api-config-invalid-xml.xml")); + Assert.assertEquals(serverConfig, null); + } + + @Test(description = "Initializing IoT server config with system configs", + dependsOnMethods = "initConfigWithInvalidXMLConfig") + public void initConfigWithSystemProps() { + TestUtils.setSystemProperties(); + IOTServerConfiguration serverConfiguration = Utils.initConfig(); + Assert.assertTrue(serverConfiguration != null); + Assert.assertEquals(serverConfiguration.getHostname(), "https://" + TestUtils.IOT_CORE_HOST + ":" + + TestUtils.IOT_CORE_HTTPS_PORT + + "/"); + Assert.assertEquals(serverConfiguration.getVerificationEndpoint(), + "https://" + TestUtils.IOT_CORE_HOST + ":" + TestUtils.IOT_CORE_HTTPS_PORT + + "/api/certificate-mgt/v1.0/admin/certificates/" + + "verify/"); + Assert.assertEquals(serverConfiguration.getUsername(), "testuser"); + Assert.assertEquals(serverConfiguration.getPassword(), "testuserpwd"); + Assert.assertEquals(serverConfiguration.getDynamicClientRegistrationEndpoint(), + "https://" + TestUtils.IOT_KEYMANAGER_HOST + ":" + TestUtils.IOT_KEYMANAGER_PORT + + "/client-registration/v0.11/register"); + Assert.assertEquals(serverConfiguration.getOauthTokenEndpoint(), + "https://" + TestUtils.IOT_KEYMANAGER_HOST + ":" + TestUtils.IOT_KEYMANAGER_PORT + + "/oauth2/token"); + Assert.assertEquals(serverConfiguration.getApis().size(), 1); + Assert.assertEquals(serverConfiguration.getApis().get(0).getContextPath(), "/services"); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/TestUtils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/TestUtils.java new file mode 100644 index 0000000000..5b22e1c5d9 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/TestUtils.java @@ -0,0 +1,61 @@ +/* +* 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.handlers; + +import org.testng.Assert; + +import java.io.File; +import java.net.URL; + +/** + * Utils class which provides utility methods for other testcases. + */ +public class TestUtils { + static final String IOT_CORE_HOST = "iot.core.wso2.com"; + static final String IOT_CORE_HTTPS_PORT = "9443"; + static final String IOT_KEYMANAGER_HOST = "iot.keymanager.wso2.com"; + static final String IOT_KEYMANAGER_PORT = "9443"; + static final String CONTENT_TYPE = "application/json"; + + private static final String IOT_HOST_PROPERTY = "iot.core.host"; + private static final String IOT_PORT_PROPERTY = "iot.core.https.port"; + private static final String IOT_KEY_MANAGER_HOST_PROPERTY = "iot.keymanager.host"; + private static final String IOT_KEY_MANAGER_PORT_PROPERTY = "iot.keymanager.https.port"; + + static String getAbsolutePathOfConfig(String configFilePath) { + ClassLoader classLoader = TestUtils.class.getClassLoader(); + URL invalidConfig = classLoader.getResource(configFilePath); + Assert.assertTrue(invalidConfig != null); + File file = new File(invalidConfig.getFile()); + return file.getAbsolutePath(); + } + + static void setSystemProperties() { + System.setProperty(IOT_HOST_PROPERTY, IOT_CORE_HOST); + System.setProperty(IOT_PORT_PROPERTY, IOT_CORE_HTTPS_PORT); + System.setProperty(IOT_KEY_MANAGER_HOST_PROPERTY, IOT_KEYMANAGER_HOST); + System.setProperty(IOT_KEY_MANAGER_PORT_PROPERTY, IOT_KEYMANAGER_PORT); + } + + static void resetSystemProperties() { + System.clearProperty(IOT_HOST_PROPERTY); + System.clearProperty(IOT_PORT_PROPERTY); + System.clearProperty(IOT_KEY_MANAGER_HOST_PROPERTY); + System.clearProperty(IOT_KEY_MANAGER_PORT_PROPERTY); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockClient.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockClient.java new file mode 100644 index 0000000000..0c8ab4f6bd --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockClient.java @@ -0,0 +1,76 @@ +/* +* 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.handlers.mock; + +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HttpContext; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Mock implementation for CloseableHttpClient to be used in test cases. + */ +public class MockClient extends CloseableHttpClient { + private List responses = new ArrayList<>(); + private int responseCount = 0; + + @Override + protected CloseableHttpResponse doExecute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) + throws IOException { + if (this.responseCount < this.responses.size()) { + this.responseCount++; + CloseableHttpResponse response = this.responses.get(this.responseCount - 1); + if (response == null) { + throw new IOException("test exception"); + } + return response; + } else { + return new MockHttpResponse(); + } + } + + @Override + public void close() throws IOException { + } + + @Override + public HttpParams getParams() { + return null; + } + + @Override + public ClientConnectionManager getConnectionManager() { + return null; + } + + public void setResponse(CloseableHttpResponse reponse) { + this.responses.add(reponse); + } + + public void reset() { + this.responses.clear(); + this.responseCount = 0; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockHttpResponse.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockHttpResponse.java new file mode 100644 index 0000000000..adfd7652c5 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/java/org/wso2/carbon/apimgt/handlers/mock/MockHttpResponse.java @@ -0,0 +1,178 @@ +/* +* 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.handlers.mock; + +import org.apache.http.Header; +import org.apache.http.HeaderIterator; +import org.apache.http.HttpEntity; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.params.HttpParams; + +import java.io.IOException; +import java.util.Locale; + +/** + * Mock http response to be used in the test cases. + * + */ +public class MockHttpResponse implements CloseableHttpResponse { + private HttpEntity httpEntity; + private StatusLine statusLine; + + @Override + public void close() throws IOException { + + } + + @Override + public StatusLine getStatusLine() { + return this.statusLine; + } + + @Override + public void setStatusLine(StatusLine statusLine) { + this.statusLine = statusLine; + } + + @Override + public void setStatusLine(ProtocolVersion protocolVersion, int i) { + + } + + @Override + public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) { + + } + + @Override + public void setStatusCode(int i) throws IllegalStateException { + + } + + @Override + public void setReasonPhrase(String s) throws IllegalStateException { + + } + + @Override + public HttpEntity getEntity() { + return this.httpEntity; + } + + @Override + public void setEntity(HttpEntity httpEntity) { + this.httpEntity = httpEntity; + } + + @Override + public Locale getLocale() { + return null; + } + + @Override + public void setLocale(Locale locale) { + + } + + @Override + public ProtocolVersion getProtocolVersion() { + return null; + } + + @Override + public boolean containsHeader(String s) { + return false; + } + + @Override + public Header[] getHeaders(String s) { + return new Header[0]; + } + + @Override + public Header getFirstHeader(String s) { + return null; + } + + @Override + public Header getLastHeader(String s) { + return null; + } + + @Override + public Header[] getAllHeaders() { + return new Header[0]; + } + + @Override + public void addHeader(Header header) { + + } + + @Override + public void addHeader(String s, String s1) { + + } + + @Override + public void setHeader(Header header) { + + } + + @Override + public void setHeader(String s, String s1) { + + } + + @Override + public void setHeaders(Header[] headers) { + + } + + @Override + public void removeHeader(Header header) { + + } + + @Override + public void removeHeaders(String s) { + + } + + @Override + public HeaderIterator headerIterator() { + return null; + } + + @Override + public HeaderIterator headerIterator(String s) { + return null; + } + + @Override + public HttpParams getParams() { + return null; + } + + @Override + public void setParams(HttpParams httpParams) { + + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/accesstoken-response.json b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/accesstoken-response.json new file mode 100644 index 0000000000..11be1e29eb --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/accesstoken-response.json @@ -0,0 +1,7 @@ +{ + "scope": "API_SUBSCRIBER_SCOPE", + "token_type": "Bearer", + "expires_in": 3600, + "refresh_token": "33c3be152ebf0030b3fb76f2c1f80bf8", + "access_token": "292ff0fd256814536baca0926f483c8d" +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/carbon.xml new file mode 100644 index 0000000000..31752cf9b4 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/carbon.xml @@ -0,0 +1,656 @@ + + + + + + + + + ${product.name} + + + ${product.key} + + + ${product.version} + + + + + + + + + local:/${carbon.context}/services/ + + + + + + + ${default.server.role} + + + + + + + org.wso2.carbon + + + / + + + + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + + false + + + + + + + + 30 + + + + + + + + + 15 + + + + + + ${carbon.home}/repository/deployment/server/ + + + 15 + + + ${carbon.home}/repository/conf/axis2/axis2.xml + + + 30000 + + + ${carbon.home}/repository/deployment/client/ + + ${carbon.home}/repository/conf/axis2/axis2_client.xml + + true + + + + + + + + + + admin + Default Administrator Role + + + user + Default User Role + + + + + + + + + + + + ${carbon.home}/repository/resources/security/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + + + + + ${carbon.home}/tmp/work + + + + + + true + + + 10 + + + 30 + + + + + + 100 + + + + keystore + certificate + * + + org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor + + + + + jarZip + + org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor + + + + dbs + + org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor + + + + tools + + org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor + + + + toolsAny + + org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor + + + + + + + info + org.wso2.carbon.core.transports.util.InfoProcessor + + + wsdl + org.wso2.carbon.core.transports.util.Wsdl11Processor + + + wsdl2 + org.wso2.carbon.core.transports.util.Wsdl20Processor + + + xsd + org.wso2.carbon.core.transports.util.XsdProcessor + + + + + + false + false + true + svn + http://svnrepo.example.com/repos/ + username + password + true + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + ${p2.repo.url} + + + + + + + + true + + + + + + true + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config-invalid-xml.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config-invalid-xml.xml new file mode 100644 index 0000000000..b7519e99ac --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config-invalid-xml.xml @@ -0,0 +1,40 @@ + + + + + + https://${iot.core.host}:${iot.core.https.port}/ + + + https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ + + + testuser + testuserpwd + + + https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register + + + https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token + + + /services + + + + + + + https://${iot.core.host}:${iot.core.https.port}/ + + + https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ + + + testuser + testuserpwd + + + https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register + + + https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token + + + /services + + \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config.xml new file mode 100644 index 0000000000..fcb53bd009 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/iot-api-config.xml @@ -0,0 +1,40 @@ + + + + + + https://${iot.core.host}:${iot.core.https.port}/ + + + https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/ + + + testuser + testuserpwd + + + https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register + + + https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token + + + /services + + \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/registry.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/registry.xml new file mode 100644 index 0000000000..a226ae80a8 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/carbon-home/repository/conf/registry.xml @@ -0,0 +1,50 @@ + + + + + + + + wso2registry + false + true + / + + + jdbc:h2:./target/databasetest/CARBON_TEST + + org.h2.Driver + 80 + 60000 + 5 + + + false + + + + true + true + true + true + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/dcr-response.json b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/dcr-response.json new file mode 100644 index 0000000000..1672f812d7 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/dcr-response.json @@ -0,0 +1,6 @@ +{ + "callBackURL": "www.google.lk", + "clientName": null, + "clientId": "HfEl1jJPdg5tbtrxhAwybN05QGoa", + "clientSecret": "l6c0aoLcWR3fwezHhc7XoGOht5Aa" +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/ra_cert.pem b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/ra_cert.pem new file mode 100644 index 0000000000..516b08ccee --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/ra_cert.pem @@ -0,0 +1,33 @@ +-----BEGIN CERTIFICATE----- +MIIFqDCCA5CgAwIBAgIBAjANBgkqhkiG9w0BAQUFADCBizELMAkGA1UEBhMCVVMx +DTALBgNVBAgTBFRlc3QxDTALBgNVBAcTBFRlc3QxETAPBgNVBAoTCFRlc3QgT3Jn +MRYwFAYDVQQLEw1UZXN0IG9yZyB1bml0MRUwEwYDVQQDEwxXU08yIFJvb3QgQ0Ex +HDAaBgkqhkiG9w0BCQEWDXJvb3RAd3NvMi5jb20wHhcNMTUwMTI3MTI1MzAxWhcN +MTcxMDIzMTI1MzAxWjCBgzELMAkGA1UEBhMCVVMxGTAXBgNVBAgTEFRlc3QgUkEg +UHJvdmluY2UxFTATBgNVBAcTDFRlc3QgUkEgQ2l0eTEUMBIGA1UEChMLVGVzdCBS +QSBPcmcxGTAXBgNVBAsTEFRlc3QgUkEgb3JnIHVuaXQxETAPBgNVBAMTCFdTTzIg +UkEgMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtUMgUlYYU3/TPfEe +zNAvBaiOi/jUjfZ9IbxvMl7obDT17/5vU68TCGkZRjyfYUEiGNBisUEFWjSk/sGL +/ofYKUAxw33cd456FLMjaJX/4Zk4y8eYB1m1GGlHejoDyjPhq8S6GDmy+PXbJr8n +lSTROR2mQHkGwYrCreWeU4AYWzdctIFk7U2DKeIvZYSidIIjfSpDXURxrt9LPvig +fMzr5l/WkZfjvk5S+W7rgMtpllxlEPgyDc07pNAdNSq5FB990oaUsVX8o6l6wdCw +grYz83edPOKwZa04fsVztz2oF3ZYSGGjD3lwh0KS/jUL+awRyhMx5p/O1hySg6PP +pJjeqRuobNTuwSAXxp3nsNSY0DkGW04pSxWoDQqhnpaqBbAf71l6ya2e3so1SHm/ +jouWSYTHncq5bmGE4AN7ZGVGZvfx84+UR8fNxJxxLo+DFFE0oJNzpPGNxILpHxgT +V7IOII6mhfkrQk+AFQiW2Y5FXLVYv8r+SPXW8pYsjaWl971XZeM/HC3L9IZkCrrr +a0ID5oT6vt+xTmdo4yiBqIP5TBYm+1a9YzMAy7XGtPih9k6cufMLcfzvUZdOXw9x +3T05nM5ZtcDq0gHvUzQ7sfHTguWVnuHVEdb2ox4x2L5NzEA475fbSdXpMok9z/z7 +Xa71vIZi28InDAFBQehUlJnFtf0CAwEAAaMdMBswDAYDVR0TBAUwAwEB/zALBgNV +HQ8EBAMCBaAwDQYJKoZIhvcNAQEFBQADggIBAAO0TwnQBMJvL8wbfsnTqAGCCHM4 +x1cpW+KgTmflPEliYGOn/dJYDz/dUowCgoj5mrSxjQ3G1/qL+9Y7E33h0tyw37vH +YDL1p2Tn+fwmXRHrk+CHoPHNcImEfSIDWbbG7ehBR6erVfbQSZjmj4fwPkItp8rP +nyUtXHOLpfFYoAxYkNP9+C8vpC9W/H1pj3rzmQFA1z+EZAKVV7vDAxbe6sun84nf +YAaMSIzHx1B+XLHokgChmnZr3wV7EypBEmmKp4ITvJqK7WsIG9t1M6hI7OTPCURR +mdy+DJtIoIUbZxHyIyC9nPcVJFkdBusnfXq4uMb0KMaWYCU8ESqZPySukF2qZ5KA +acB+0ZhY+EGQ6QF/hB6iiUj96BlQ7XAPXFU6xUt6nRjDiJmb3vW1IEv0hpbs7PRl +UMlbOwQk37rXpFqQc6ZW7lsxI2RmfkD4DOkQIGH3q5foVr+PEp0uSPWrFX62eBet +1S4c/opVv6BcuUgilYABHTYxb45GfYwJAI9Qw2uQWT8DmhtVbcYu6GLYGlnRyaOC +EPzc0z0KQTjhsgHWzi60IYBBh+fy+Z7w5X1rTTvhFOoU5J7kedGEqiBatIZmhF5t +UFbT0u350ET5a0Kg83gu5aLwXdoIP9o7bp3XzLBMVNny2RX3tOHUA2HBe/p0h0OU +Ggt3G6oD0gBe9pZI +-----END CERTIFICATE----- diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/testng.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/testng.xml new file mode 100644 index 0000000000..2f9882254f --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/src/test/resources/testng.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + 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 b1e60b0c05..c8ae7b95fc 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.client - 3.0.136-SNAPSHOT + 3.0.170-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 5cc97beee5..7dcae55cd7 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.generated.client - 3.0.136-SNAPSHOT + 3.0.170-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 2a3a560981..298505cf77 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,19 +22,24 @@ apimgt-extensions org.wso2.carbon.devicemgt - 3.0.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher - 3.0.136-SNAPSHOT + 3.0.170-SNAPSHOT bundle WSO2 Carbon - API Management Webapp Publisher WSO2 Carbon - API Management Webapp Publisher http://wso2.org + + org.powermock + powermock-api-mockito + test + org.eclipse.osgi org.eclipse.osgi @@ -103,10 +108,15 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.client - + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.integration.client + + + com.h2database.wso2 + h2-database-engine + test + @@ -150,25 +160,25 @@ org.wso2.carbon.apimgt.annotations.*, org.wso2.carbon.governance.lcm.util.*, org.wso2.carbon.registry.core.*, - io.swagger.annotations, - javax.net.ssl, - org.scannotation, - org.scannotation.archiveiterator, - org.w3c.dom, - org.wso2.carbon.apimgt.integration.client.*, - org.wso2.carbon.context, - org.wso2.carbon.core.util, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.*, - org.wso2.carbon.utils.multitenancy, - org.wso2.carbon.apimgt.integration.generated.client.publisher.api, - org.wso2.carbon.apimgt.integration.generated.client.publisher.model + io.swagger.annotations, + javax.net.ssl, + org.scannotation, + org.scannotation.archiveiterator, + org.w3c.dom, + org.wso2.carbon.apimgt.integration.client.*, + org.wso2.carbon.context, + org.wso2.carbon.core.util, + org.wso2.carbon.user.api, + org.wso2.carbon.user.core.*, + org.wso2.carbon.utils.multitenancy, + org.wso2.carbon.apimgt.integration.generated.client.publisher.api, + org.wso2.carbon.apimgt.integration.generated.client.publisher.model javax.ws.rs-api, scribe;scope=compile|runtime;inline=false; - * + * @@ -200,5 +210,4 @@ - diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index f7914d3d52..bc02e33e5a 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -62,7 +62,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (APIInfo apiInfo : apiList.getList()) { if (api.getName().equals(apiInfo.getName()) && api.getVersion().equals(apiInfo.getVersion())) { api = publisherClient.getApi().apisApiIdPut(apiInfo.getId(), api, CONTENT_TYPE, null, null); - if (CREATED_STATUS.equals(api.getStatus())) { + if (api != null && CREATED_STATUS.equals(api.getStatus())) { publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null, null); } @@ -83,7 +83,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { return false; } for (APIInfo existingApi : apiList.getList()) { - if (existingApi.getName().equals(api.getName()) && existingApi.getVersion().equals(api.getVersion())) { + if (existingApi.getName() != null && existingApi.getName().equals(api. + getName()) && existingApi.getVersion() != null && + existingApi.getVersion().equals(api.getVersion())) { return true; } } 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 new file mode 100644 index 0000000000..87d27c5e52 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceTest.java @@ -0,0 +1,193 @@ +/* +* 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; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import org.wso2.carbon.apimgt.integration.client.IntegrationClientServiceImpl; +import org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor; +import org.wso2.carbon.apimgt.integration.client.model.OAuthApplication; +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.integration.generated.client.publisher.model.API; +import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIInfo; +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.exception.APIManagerPublisherException; +import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +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.*; + +import static org.mockito.Mockito.doReturn; + +/** + * This is the test class for {@link APIPublisherServiceImpl} + */ +public class APIPublisherServiceTest extends BaseAPIPublisherTest { + private static final Log log = LogFactory.getLog(APIPublisherServiceTest.class); + private APIPublisherServiceImpl apiPublisherService = new APIPublisherServiceImpl(); + + @BeforeTest + public void initialConfigs() throws Exception { + initializeOAuthApplication(); + WebappPublisherConfig.init(); + } + + @Test(description = "Publishes an API | will fail if there are any exceptions") + public void publishAPI() throws NoSuchFieldException, IllegalAccessException, + APIManagerPublisherException { + APIConfig apiConfig = new APIConfig(); + setApiConfigs(apiConfig, "testAPI-0"); + apiPublisherService.publishAPI(apiConfig); + } + + @Test(description = "Testing for API status CREATED | will fail if there are any exceptions") + public void publishCreatedAPI() throws APIManagerPublisherException, NoSuchFieldException, + IllegalAccessException { + APIConfig apiConfig = new APIConfig(); + setApiConfigs(apiConfig, "testAPI-1"); + APIPublisherDataHolder apiPublisherDataHolder = Mockito.mock(APIPublisherDataHolder.getInstance(). + getClass(), Mockito.CALLS_REAL_METHODS); + IntegrationClientService integrationClientService = Mockito.mock(IntegrationClientServiceImpl. + class, Mockito.CALLS_REAL_METHODS); + doReturn(integrationClientService).when(apiPublisherDataHolder).getIntegrationClientService(); + PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService(). + getPublisherClient(); + doReturn(publisherClient).when(integrationClientService).getPublisherClient(); + 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"); + doReturn(api).when(apIsApi).apisPost(Mockito.any(), Mockito.anyString()); + apiPublisherService.publishAPI(apiConfig); + } + + @Test(description = "createAPIListWithNoApi | will fail if there are any exceptions") + public void publishWithNoAPIListCreated() throws APIManagerPublisherException { + APIConfig apiConfig = new APIConfig(); + setApiConfigs(apiConfig, "testAPI-2"); + APIPublisherDataHolder apiPublisherDataHolder = Mockito.mock(APIPublisherDataHolder.getInstance(). + getClass(), Mockito.CALLS_REAL_METHODS); + IntegrationClientService integrationClientService = Mockito.mock(IntegrationClientServiceImpl. + class, Mockito.CALLS_REAL_METHODS); + doReturn(integrationClientService).when(apiPublisherDataHolder).getIntegrationClientService(); + PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService(). + getPublisherClient(); + doReturn(publisherClient).when(integrationClientService).getPublisherClient(); + 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"); + doReturn(api).when(apIsApi).apisPost(Mockito.any(), Mockito.anyString()); + APIList apiList = Mockito.mock(APIList.class, Mockito.CALLS_REAL_METHODS); + APIInfo apiInfo = new APIInfo(); + List apiInfoList = new ArrayList<>(); + apiInfoList.add(apiInfo); + apiList.list(apiInfoList); + doReturn(apiList).when(apIsApi).apisGet(Mockito.anyInt(), Mockito.anyInt(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + doReturn(api).when(apIsApi).apisApiIdPut(Mockito.anyString(), Mockito.any(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + apiPublisherService.publishAPI(apiConfig); + } + + @Test(description = "createAPIList | will fail if there are any exceptions") + public void publishWithAPIListCreated() throws APIManagerPublisherException { + APIConfig apiConfig = new APIConfig(); + setApiConfigs(apiConfig, "testAPI-3"); + APIPublisherDataHolder apiPublisherDataHolder = Mockito.mock(APIPublisherDataHolder.getInstance(). + getClass(), Mockito.CALLS_REAL_METHODS); + IntegrationClientService integrationClientService = Mockito.mock(IntegrationClientServiceImpl. + class, Mockito.CALLS_REAL_METHODS); + doReturn(integrationClientService).when(apiPublisherDataHolder).getIntegrationClientService(); + PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService(). + getPublisherClient(); + doReturn(publisherClient).when(integrationClientService).getPublisherClient(); + 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"); + doReturn(api).when(apIsApi).apisPost(Mockito.any(), Mockito.anyString()); + APIList apiList = Mockito.mock(APIList.class, Mockito.CALLS_REAL_METHODS); + APIInfo apiInfo = new APIInfo(); + apiInfo.setName("testAPI-3"); + apiInfo.setVersion("1.0.0"); + apiInfo.setId("test-one"); + List apiInfoList = new ArrayList<>(); + apiInfoList.add(apiInfo); + apiList.list(apiInfoList); + doReturn(apiList).when(apIsApi).apisGet(Mockito.anyInt(), Mockito.anyInt(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + doReturn(api).when(apIsApi).apisApiIdPut(Mockito.anyString(), Mockito.any(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + apiConfig.setSharedWithAllTenants(false); + apiPublisherService.publishAPI(apiConfig); + } + + @Test(description = "publish API with scope added | will fail if there are any exceptions") + public void publishWithAPIScope() throws APIManagerPublisherException { + APIConfig apiConfig = new APIConfig(); + setApiConfigs(apiConfig, "testAPI-4"); + Set scopes = new HashSet<>(); + ApiScope apiScope = new ApiScope(); + apiScope.setDescription("testing"); + scopes.add(apiScope); + apiConfig.setScopes(scopes); + apiPublisherService.publishAPI(apiConfig); + } + + private void setApiConfigs(APIConfig apiConfig, String name) { + apiConfig.setName(name); + apiConfig.setContext("api/device-mgt/windows/v1.g0/admin/devices"); + apiConfig.setOwner("admin"); + apiConfig.setEndpoint("https://localhost:9443/api/device-mgt/windows/v1.0/admin/devices"); + apiConfig.setVersion("1.0.0"); + apiConfig.setTransports("http,https"); + apiConfig.setPolicy(null); + apiConfig.setSharedWithAllTenants(true); + apiConfig.setTags(new String[]{"windows", "device_management"}); + apiConfig.setTenantDomain("carbon.super"); + apiConfig.setSecured(false); + Map apiScopes = new HashMap<>(); + Set scopes = new HashSet<>(apiScopes.values()); + apiConfig.setScopes(scopes); + TestUtils util = new TestUtils(); + util.setAPIURITemplates(apiConfig, "/reboot"); + } + + private void initializeOAuthApplication() throws NoSuchFieldException, IllegalAccessException { + OAuthApplication oAuthApplication = new OAuthApplication(); + oAuthApplication.setClientName("admin_api_integration_client"); + oAuthApplication.setIsSaasApplication("true"); + oAuthApplication.setClientId("random"); + oAuthApplication.setClientSecret("random="); + Field oAuth = OAuthRequestInterceptor.class.getDeclaredField("oAuthApplication"); + oAuth.setAccessible(true); + oAuth.set(null, oAuthApplication); + } + +} + 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 new file mode 100644 index 0000000000..45b8d71257 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtilTest.java @@ -0,0 +1,163 @@ +/* +* 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; + +import org.testng.Assert; +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 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 { + WebappPublisherConfig.init(); + setUserRealm(); + } + + @Test(description = "test buildAPIConfig method and ensures an APIConfig is created") + public void buildApiConfigTest() throws UserStoreException, RegistryException { + try { + startTenantFlowAsTestTenant(); + ServletContext servletContext = new MockServletContext(); + APIResourceConfiguration apiDef = new APIResourceConfiguration(); + List resources = new ArrayList<>(); + apiDef.setResources(resources); + APIConfig apiConfig = buildApiConfig(servletContext, apiDef); + Assert.assertNotNull(apiConfig, "API configuration is null."); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + @Test(description = "test buildAPIConfig method as SuperTenant and ensures" + + " an APIConfig is created") + public void buildApiConfigAsSuperTenant() throws UserStoreException { + ServletContext servletContext = new MockServletContext(); + APIResourceConfiguration apiDef = new APIResourceConfiguration(); + List resources = new ArrayList<>(); + apiDef.setResources(resources); + APIConfig apiConfig = buildApiConfig(servletContext, apiDef); + Assert.assertNotNull(apiConfig, "API configuration is null."); + } + + @Test(description = "test buildAPIConfig with API tags specified and ensures " + + "an APIConfig is created") + public void buildApiConfigTestWithTags() throws UserStoreException { + ServletContext servletContext = new MockServletContext(); + APIResourceConfiguration apiDef = new APIResourceConfiguration(); + List resources = new ArrayList<>(); + APIResource apiResource = new APIResource(); + resources.add(apiResource); + apiDef.setResources(resources); + apiDef.setTags(new String[]{"windows", "device_management"}); + APIConfig apiConfig = buildApiConfig(servletContext, apiDef); + Assert.assertNotNull(apiConfig, "API configuration is null."); + } + + @Test(description = "test buildAPIConfig method with API scopes specified and " + + "ensures an APIConfig is created") + public void buildApiConfigTestWithScope() throws UserStoreException, APIManagerPublisherException { + ServletContext servletContext = new MockServletContext(); + APIResourceConfiguration apiDef = new APIResourceConfiguration(); + List resources = new ArrayList<>(); + APIResource apiResource = new APIResource(); + ApiScope apiScope = new ApiScope(); + apiScope.setDescription("testing"); + apiResource.setScope(apiScope); + resources.add(apiResource); + apiDef.setResources(resources); + apiDef.setTags(new String[]{"windows", "device_management"}); + APIConfig apiConfig = buildApiConfig(servletContext, apiDef); + 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); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUserRealm(userRealm); + } + + private void startTenantFlowAsTestTenant() throws org.wso2.carbon.user.core.UserStoreException, RegistryException { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1212); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("test.com"); + setUserRealm(); + } +} 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 new file mode 100644 index 0000000000..229d11a970 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/BaseAPIPublisherTest.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.apimgt.webapp.publisher; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mockito.Mockito; +import org.testng.annotations.BeforeSuite; +import org.wso2.carbon.apimgt.integration.client.IntegrationClientServiceImpl; +import org.wso2.carbon.apimgt.integration.client.internal.APIIntegrationClientDataHolder; +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.MockApi; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.internal.OSGiDataHolder; +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.exception.JWTClientException; +import org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerServiceImpl; +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.UserStoreException; +import org.wso2.carbon.user.core.service.RealmService; + +import java.io.File; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.net.URL; + +import static org.mockito.Mockito.doReturn; + +/** + * Base class which initializes carbonContext and needed services. + */ +public abstract class BaseAPIPublisherTest { + + private static final Log log = LogFactory.getLog(BaseAPIPublisherTest.class); + + @BeforeSuite + public void initialize() throws Exception { + this.initializeCarbonContext(); + this.initServices(); + } + + private void initializeCarbonContext() throws RegistryException { + ClassLoader classLoader = getClass().getClassLoader(); + URL resourceUrl = classLoader.getResource("carbon-home"); + if (resourceUrl != null) { + File carbonHome = new File(resourceUrl.getFile()); + System.setProperty("carbon.home", carbonHome.getAbsolutePath()); + } + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants. + SUPER_TENANT_DOMAIN_NAME); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); + } + + private void initServices() throws NoSuchFieldException, IllegalAccessException, + JWTClientException, UserStoreException, RegistryException { + + IntegrationClientService integrationClientService = Mockito.mock(IntegrationClientServiceImpl.class, + Mockito.CALLS_REAL_METHODS); + APIPublisherDataHolder.getInstance().setIntegrationClientService(integrationClientService); + PublisherClient publisherClient = Mockito.mock(PublisherClient.class, Mockito.CALLS_REAL_METHODS); + doReturn(publisherClient).when(integrationClientService).getPublisherClient(); + + APIsApi api = new MockApi(); + Field field = PublisherClient.class.getDeclaredField("api"); + field.setAccessible(true); + field.set(publisherClient, api); + + AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); + final String REQUIRED_SCOPE = + "apim:api_create apim:api_view apim:api_publish apim:subscribe apim:tier_view apim:tier_manage " + + "apim:subscription_view apim:subscription_block"; + accessTokenInfo.setScopes(REQUIRED_SCOPE); + + JWTClientManagerService jwtClientManagerService = Mockito.mock(JWTClientManagerServiceImpl.class, + Mockito.CALLS_REAL_METHODS); + JWTClient jwtClient = Mockito.mock(JWTClient.class, Mockito.CALLS_REAL_METHODS); + doReturn(accessTokenInfo).when(jwtClient).getAccessToken(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString()); + doReturn(jwtClient).when(jwtClientManagerService).getJWTClient(); + + APIIntegrationClientDataHolder.getInstance().setJwtClientManagerService(jwtClientManagerService); + RegistryService registryService = this.getRegistryService(); + OSGiDataHolder.getInstance().setRegistryService(registryService); + JWTClientExtensionDataHolder.getInstance().setRegistryService(registryService); + } + + private RegistryService getRegistryService() throws RegistryException, UserStoreException { + RealmService realmService = new InMemoryRealmService(); + APIPublisherDataHolder.getInstance().setRealmService(realmService); + RegistryDataHolder.getInstance().setRealmService(realmService); + JWTClientExtensionDataHolder.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(); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockApi.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockApi.java new file mode 100644 index 0000000000..f9e22de3e8 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockApi.java @@ -0,0 +1,86 @@ +/* +* 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.integration.generated.client.publisher.api.APIsApi; +import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.API; +import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.APIList; +import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.FileInfo; + +import java.io.File; + +/** + * Class to create MockApi for testing. + */ +public class MockApi implements APIsApi { + + @Override + public void apisApiIdDelete(String apiId, String ifMatch, String ifUnmodifiedSince) { + + } + + @Override + public API apisApiIdGet(String apiId, String accept, String ifNoneMatch, String ifModifiedSince) { + return null; + } + + @Override + public API apisApiIdPut(String apiId, API body, String contentType, String ifMatch, String ifUnmodifiedSince) { + return null; + } + + @Override + public void apisApiIdSwaggerGet(String apiId, String accept, String ifNoneMatch, String ifModifiedSince) { + + } + + @Override + public void apisApiIdSwaggerPut(String apiId, String apiDefinition, String contentType, String ifMatch, String ifUnmodifiedSince) { + + } + + @Override + public void apisApiIdThumbnailGet(String apiId, String accept, String ifNoneMatch, String ifModifiedSince) { + + } + + @Override + public FileInfo apisApiIdThumbnailPost(String apiId, File file, String contentType, String ifMatch, String ifUnmodifiedSince) { + return null; + } + + @Override + public void apisChangeLifecyclePost(String action, String apiId, String lifecycleChecklist, String ifMatch, String ifUnmodifiedSince) { + + } + + @Override + public void apisCopyApiPost(String newVersion, String apiId) { + + } + + @Override + public APIList apisGet(Integer limit, Integer offset, String query, String accept, String ifNoneMatch) { + return null; + } + + @Override + public API apisPost(API body, String contentType) { + return new API(); + } +} 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 new file mode 100644 index 0000000000..c85d274a41 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockServletContext.java @@ -0,0 +1,285 @@ +/* +* 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 javax.servlet.*; +import javax.servlet.descriptor.JspConfigDescriptor; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Enumeration; +import java.util.EventListener; +import java.util.Map; +import java.util.Set; + +public class MockServletContext implements ServletContext { + @Override + public ServletContext getContext(String s) { + return null; + } + + @Override + public String getContextPath() { + return null; + } + + @Override + public int getMajorVersion() { + return 0; + } + + @Override + public int getMinorVersion() { + return 0; + } + + @Override + public int getEffectiveMajorVersion() { + return 0; + } + + @Override + public int getEffectiveMinorVersion() { + return 0; + } + + @Override + public String getMimeType(String s) { + return null; + } + + @Override + public Set getResourcePaths(String s) { + return null; + } + + @Override + public URL getResource(String s) throws MalformedURLException { + return null; + } + + @Override + public InputStream getResourceAsStream(String s) { + return null; + } + + @Override + public RequestDispatcher getRequestDispatcher(String s) { + return null; + } + + @Override + public RequestDispatcher getNamedDispatcher(String s) { + return null; + } + + @Override + public Servlet getServlet(String s) throws ServletException { + return null; + } + + @Override + public Enumeration getServlets() { + return null; + } + + @Override + public Enumeration getServletNames() { + return null; + } + + @Override + public void log(String s) { + + } + + @Override + public void log(Exception e, String s) { + + } + + @Override + public void log(String s, Throwable throwable) { + + } + + @Override + public String getRealPath(String s) { + return null; + } + + @Override + public String getServerInfo() { + return null; + } + + @Override + public String getInitParameter(String s) { + return "/*"; + } + + @Override + public Enumeration getInitParameterNames() { + return null; + } + + @Override + public boolean setInitParameter(String s, String s1) { + return false; + } + + @Override + public Object getAttribute(String s) { + return null; + } + + @Override + public Enumeration getAttributeNames() { + return null; + } + + @Override + public void setAttribute(String s, Object o) { + + } + + @Override + public void removeAttribute(String s) { + + } + + @Override + public String getServletContextName() { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String s, String s1) { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String s, Servlet servlet) { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String s, Class aClass) { + return null; + } + + @Override + public T createServlet(Class aClass) throws ServletException { + return null; + } + + @Override + public ServletRegistration getServletRegistration(String s) { + return null; + } + + @Override + public Map getServletRegistrations() { + return null; + } + + @Override + public FilterRegistration.Dynamic addFilter(String s, String s1) { + return null; + } + + @Override + public FilterRegistration.Dynamic addFilter(String s, Filter filter) { + return null; + } + + @Override + public FilterRegistration.Dynamic addFilter(String s, Class aClass) { + return null; + } + + @Override + public T createFilter(Class aClass) throws ServletException { + return null; + } + + @Override + public FilterRegistration getFilterRegistration(String s) { + return null; + } + + @Override + public Map getFilterRegistrations() { + return null; + } + + @Override + public SessionCookieConfig getSessionCookieConfig() { + return null; + } + + @Override + public void setSessionTrackingModes(Set set) throws IllegalStateException, IllegalArgumentException { + + } + + @Override + public Set getDefaultSessionTrackingModes() { + return null; + } + + @Override + public Set getEffectiveSessionTrackingModes() { + return null; + } + + @Override + public void addListener(String s) { + + } + + @Override + public void addListener(T t) { + + } + + @Override + public void addListener(Class aClass) { + + } + + @Override + public T createListener(Class aClass) throws ServletException { + return null; + } + + @Override + public void declareRoles(String... strings) { + + } + + @Override + public ClassLoader getClassLoader() { + return null; + } + + @Override + public JspConfigDescriptor getJspConfigDescriptor() { + return null; + } +} 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/dbscripts/h2.sql b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/dbscripts/h2.sql new file mode 100644 index 0000000000..f6b31c78d9 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/dbscripts/h2.sql @@ -0,0 +1,429 @@ +CREATE TABLE IF NOT EXISTS REG_CLUSTER_LOCK ( + REG_LOCK_NAME VARCHAR (20), + REG_LOCK_STATUS VARCHAR (20), + REG_LOCKED_TIME TIMESTAMP, + REG_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (REG_LOCK_NAME) +); + +CREATE TABLE IF NOT EXISTS REG_LOG ( + REG_LOG_ID INTEGER AUTO_INCREMENT, + REG_PATH VARCHAR (2000), + REG_USER_ID VARCHAR (31) NOT NULL, + REG_LOGGED_TIME TIMESTAMP NOT NULL, + REG_ACTION INTEGER NOT NULL, + REG_ACTION_DATA VARCHAR (500), + REG_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (REG_LOG_ID, REG_TENANT_ID) +); + +CREATE INDEX IF NOT EXISTS REG_LOG_IND_BY_REG_LOGTIME ON REG_LOG(REG_LOGGED_TIME, REG_TENANT_ID); + +CREATE TABLE IF NOT EXISTS REG_PATH( + REG_PATH_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_PATH_VALUE VARCHAR(2000) NOT NULL, + REG_PATH_PARENT_ID INT, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_PATH PRIMARY KEY(REG_PATH_ID, REG_TENANT_ID) +); +CREATE INDEX IF NOT EXISTS REG_PATH_IND_BY_NAME ON REG_PATH(REG_PATH_VALUE, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_PATH_IND_BY_PARENT_ID ON REG_PATH(REG_PATH_PARENT_ID, REG_TENANT_ID); + + +CREATE TABLE IF NOT EXISTS REG_CONTENT ( + REG_CONTENT_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_CONTENT_DATA LONGBLOB, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_CONTENT PRIMARY KEY(REG_CONTENT_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_CONTENT_HISTORY ( + REG_CONTENT_ID INTEGER NOT NULL, + REG_CONTENT_DATA LONGBLOB, + REG_DELETED SMALLINT, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_CONTENT_HISTORY PRIMARY KEY(REG_CONTENT_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_RESOURCE ( + REG_PATH_ID INTEGER NOT NULL, + REG_NAME VARCHAR(256), + REG_VERSION INTEGER NOT NULL AUTO_INCREMENT, + REG_MEDIA_TYPE VARCHAR(500), + REG_CREATOR VARCHAR(31) NOT NULL, + REG_CREATED_TIME TIMESTAMP NOT NULL, + REG_LAST_UPDATOR VARCHAR(31), + REG_LAST_UPDATED_TIME TIMESTAMP NOT NULL, + REG_DESCRIPTION VARCHAR(1000), + REG_CONTENT_ID INTEGER, + REG_TENANT_ID INTEGER DEFAULT 0, + REG_UUID VARCHAR(100) NOT NULL, + CONSTRAINT PK_REG_RESOURCE PRIMARY KEY(REG_VERSION, REG_TENANT_ID) +); + +ALTER TABLE REG_RESOURCE ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +ALTER TABLE REG_RESOURCE ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_FK_BY_CONTENT_ID FOREIGN KEY (REG_CONTENT_ID, REG_TENANT_ID) REFERENCES REG_CONTENT (REG_CONTENT_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_NAME ON REG_RESOURCE(REG_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_PATH_ID, REG_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_UUID ON REG_RESOURCE(REG_UUID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TENANT ON REG_RESOURCE(REG_TENANT_ID, REG_UUID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TYPE ON REG_RESOURCE(REG_TENANT_ID, REG_MEDIA_TYPE); + +CREATE TABLE IF NOT EXISTS REG_RESOURCE_HISTORY ( + REG_PATH_ID INTEGER NOT NULL, + REG_NAME VARCHAR(256), + REG_VERSION INTEGER NOT NULL, + REG_MEDIA_TYPE VARCHAR(500), + REG_CREATOR VARCHAR(31) NOT NULL, + REG_CREATED_TIME TIMESTAMP NOT NULL, + REG_LAST_UPDATOR VARCHAR(31), + REG_LAST_UPDATED_TIME TIMESTAMP NOT NULL, + REG_DESCRIPTION VARCHAR(1000), + REG_CONTENT_ID INTEGER, + REG_DELETED SMALLINT, + REG_TENANT_ID INTEGER DEFAULT 0, + REG_UUID VARCHAR(100) NOT NULL, + CONSTRAINT PK_REG_RESOURCE_HISTORY PRIMARY KEY(REG_VERSION, REG_TENANT_ID) +); + +ALTER TABLE REG_RESOURCE_HISTORY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_HIST_FK_BY_PATHID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +ALTER TABLE REG_RESOURCE_HISTORY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_HIST_FK_BY_CONTENT_ID FOREIGN KEY (REG_CONTENT_ID, REG_TENANT_ID) REFERENCES REG_CONTENT_HISTORY (REG_CONTENT_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_HISTORY_IND_BY_NAME ON REG_RESOURCE_HISTORY(REG_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_HISTORY_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_PATH_ID, REG_NAME, REG_TENANT_ID); + +CREATE TABLE IF NOT EXISTS REG_COMMENT ( + REG_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_COMMENT_TEXT VARCHAR(500) NOT NULL, + REG_USER_ID VARCHAR(31) NOT NULL, + REG_COMMENTED_TIME TIMESTAMP NOT NULL, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_COMMENT PRIMARY KEY(REG_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_RESOURCE_COMMENT ( + REG_COMMENT_ID INTEGER NOT NULL, + REG_VERSION INTEGER, + REG_PATH_ID INTEGER, + REG_RESOURCE_NAME VARCHAR(256), + REG_TENANT_ID INTEGER DEFAULT 0 +); + +ALTER TABLE REG_RESOURCE_COMMENT ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_COMMENT_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +ALTER TABLE REG_RESOURCE_COMMENT ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_COMMENT_FK_BY_COMMENT_ID FOREIGN KEY (REG_COMMENT_ID, REG_TENANT_ID) REFERENCES REG_COMMENT (REG_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_COMMENT_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_COMMENT(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_COMMENT_IND_BY_VERSION ON REG_RESOURCE_COMMENT(REG_VERSION, REG_TENANT_ID); + +CREATE TABLE IF NOT EXISTS REG_RATING ( + REG_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_RATING INTEGER NOT NULL, + REG_USER_ID VARCHAR(31) NOT NULL, + REG_RATED_TIME TIMESTAMP NOT NULL, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_RATING PRIMARY KEY(REG_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_RESOURCE_RATING ( + REG_RATING_ID INTEGER NOT NULL, + REG_VERSION INTEGER, + REG_PATH_ID INTEGER, + REG_RESOURCE_NAME VARCHAR(256), + REG_TENANT_ID INTEGER DEFAULT 0 +); + +ALTER TABLE REG_RESOURCE_RATING ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_RATING_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +ALTER TABLE REG_RESOURCE_RATING ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_RATING_FK_BY_RATING_ID FOREIGN KEY (REG_RATING_ID, REG_TENANT_ID) REFERENCES REG_RATING (REG_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_RATING_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_RATING(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_RATING_IND_BY_VERSION ON REG_RESOURCE_RATING(REG_VERSION, REG_TENANT_ID); + + +CREATE TABLE IF NOT EXISTS REG_TAG ( + REG_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_TAG_NAME VARCHAR(500) NOT NULL, + REG_USER_ID VARCHAR(31) NOT NULL, + REG_TAGGED_TIME TIMESTAMP NOT NULL, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_TAG PRIMARY KEY(REG_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_RESOURCE_TAG ( + REG_TAG_ID INTEGER NOT NULL, + REG_VERSION INTEGER, + REG_PATH_ID INTEGER, + REG_RESOURCE_NAME VARCHAR(256), + REG_TENANT_ID INTEGER DEFAULT 0 +); + +ALTER TABLE REG_RESOURCE_TAG ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_TAG_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +ALTER TABLE REG_RESOURCE_TAG ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_TAG_FK_BY_TAG_ID FOREIGN KEY (REG_TAG_ID, REG_TENANT_ID) REFERENCES REG_TAG (REG_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_TAG_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_TAG(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_TAG_IND_BY_VERSION ON REG_RESOURCE_TAG(REG_VERSION, REG_TENANT_ID); + +CREATE TABLE IF NOT EXISTS REG_PROPERTY ( + REG_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_NAME VARCHAR(100) NOT NULL, + REG_VALUE VARCHAR(1000), + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_PROPERTY PRIMARY KEY(REG_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_RESOURCE_PROPERTY ( + REG_PROPERTY_ID INTEGER NOT NULL, + REG_VERSION INTEGER, + REG_PATH_ID INTEGER, + REG_RESOURCE_NAME VARCHAR(256), + REG_TENANT_ID INTEGER DEFAULT 0 +); + +ALTER TABLE REG_RESOURCE_PROPERTY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_PROPERTY_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +ALTER TABLE REG_RESOURCE_PROPERTY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_PROPERTY_FK_BY_TAG_ID FOREIGN KEY (REG_PROPERTY_ID, REG_TENANT_ID) REFERENCES REG_PROPERTY (REG_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_PROPERTY_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_PROPERTY(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_RESOURCE_PROPERTY_IND_BY_VERSION ON REG_RESOURCE_PROPERTY(REG_VERSION, REG_TENANT_ID); + +CREATE TABLE IF NOT EXISTS REG_ASSOCIATION ( + REG_ASSOCIATION_ID INTEGER AUTO_INCREMENT, + REG_SOURCEPATH VARCHAR (2000) NOT NULL, + REG_TARGETPATH VARCHAR (2000) NOT NULL, + REG_ASSOCIATION_TYPE VARCHAR (2000) NOT NULL, + REG_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (REG_ASSOCIATION_ID, REG_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS REG_SNAPSHOT ( + REG_SNAPSHOT_ID INTEGER NOT NULL AUTO_INCREMENT, + REG_PATH_ID INTEGER NOT NULL, + REG_RESOURCE_NAME VARCHAR (256), + REG_RESOURCE_VIDS LONGBLOB NOT NULL, + REG_TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT PK_REG_SNAPSHOT PRIMARY KEY(REG_SNAPSHOT_ID, REG_TENANT_ID) +); + +ALTER TABLE REG_SNAPSHOT ADD CONSTRAINT IF NOT EXISTS REG_SNAPSHOT_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); +CREATE INDEX IF NOT EXISTS REG_SNAPSHOT_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_SNAPSHOT(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); + +-- ################################ +-- USER MANAGER TABLES +-- ################################ + +CREATE TABLE IF NOT EXISTS UM_TENANT ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DOMAIN_NAME VARCHAR(255) NOT NULL, + UM_EMAIL VARCHAR(255), + UM_ACTIVE BOOLEAN DEFAULT FALSE, + UM_CREATED_DATE TIMESTAMP NOT NULL, + UM_USER_CONFIG LONGBLOB NOT NULL, + PRIMARY KEY (UM_ID), + UNIQUE(UM_DOMAIN_NAME)); + +CREATE TABLE IF NOT EXISTS UM_DOMAIN( + UM_DOMAIN_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DOMAIN_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID) +); + +CREATE INDEX IF NOT EXISTS INDEX_UM_TENANT_UM_DOMAIN_NAME ON UM_TENANT (UM_DOMAIN_NAME); + +CREATE TABLE IF NOT EXISTS UM_USER ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_USER_PASSWORD VARCHAR(255) NOT NULL, + UM_SALT_VALUE VARCHAR(31), + UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE, + UM_CHANGED_TIME TIMESTAMP NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_USER_NAME, UM_TENANT_ID)); + +CREATE TABLE IF NOT EXISTS UM_SYSTEM_USER ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_USER_PASSWORD VARCHAR(255) NOT NULL, + UM_SALT_VALUE VARCHAR(31), + UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE, + UM_CHANGED_TIME TIMESTAMP NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_USER_NAME, UM_TENANT_ID)); + +CREATE TABLE IF NOT EXISTS UM_USER_ATTRIBUTE ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ATTR_NAME VARCHAR(255) NOT NULL, + UM_ATTR_VALUE VARCHAR(1024), + UM_PROFILE_ID VARCHAR(255), + UM_USER_ID INTEGER, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + FOREIGN KEY (UM_USER_ID, UM_TENANT_ID) REFERENCES UM_USER(UM_ID, UM_TENANT_ID)); + +CREATE INDEX IF NOT EXISTS UM_USER_ID_INDEX ON UM_USER_ATTRIBUTE(UM_USER_ID); + +CREATE TABLE IF NOT EXISTS UM_ROLE ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ROLE_NAME VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UM_SHARED_ROLE BOOLEAN DEFAULT FALSE, + PRIMARY KEY (UM_ID, UM_TENANT_ID), + UNIQUE(UM_ROLE_NAME, UM_TENANT_ID)); + +CREATE TABLE IF NOT EXISTS UM_MODULE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_MODULE_NAME VARCHAR(100), + UNIQUE(UM_MODULE_NAME), + PRIMARY KEY(UM_ID) +); + +CREATE TABLE IF NOT EXISTS UM_MODULE_ACTIONS( + UM_ACTION VARCHAR(255) NOT NULL, + UM_MODULE_ID INTEGER NOT NULL, + PRIMARY KEY(UM_ACTION, UM_MODULE_ID), + FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS UM_PERMISSION ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_RESOURCE_ID VARCHAR(255) NOT NULL, + UM_ACTION VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UM_MODULE_ID INTEGER DEFAULT 0, + UNIQUE(UM_RESOURCE_ID,UM_ACTION, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID)); + +CREATE INDEX IF NOT EXISTS INDEX_UM_PERMISSION_UM_RESOURCE_ID_UM_ACTION ON UM_PERMISSION (UM_RESOURCE_ID, UM_ACTION, UM_TENANT_ID); + +CREATE TABLE IF NOT EXISTS UM_ROLE_PERMISSION ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_PERMISSION_ID INTEGER NOT NULL, + UM_ROLE_NAME VARCHAR(255) NOT NULL, + UM_IS_ALLOWED SMALLINT NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UM_DOMAIN_ID INTEGER, + FOREIGN KEY (UM_PERMISSION_ID, UM_TENANT_ID) REFERENCES UM_PERMISSION(UM_ID, UM_TENANT_ID) ON DELETE CASCADE, + FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID, UM_TENANT_ID)); + +CREATE TABLE IF NOT EXISTS UM_USER_PERMISSION ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_PERMISSION_ID INTEGER NOT NULL, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_IS_ALLOWED SMALLINT NOT NULL, + UNIQUE (UM_PERMISSION_ID, UM_USER_NAME, UM_TENANT_ID), + UM_TENANT_ID INTEGER DEFAULT 0, + FOREIGN KEY (UM_PERMISSION_ID, UM_TENANT_ID) REFERENCES UM_PERMISSION(UM_ID, UM_TENANT_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID, UM_TENANT_ID)); + +CREATE TABLE IF NOT EXISTS UM_USER_ROLE ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ROLE_ID INTEGER NOT NULL, + UM_USER_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE (UM_USER_ID, UM_ROLE_ID, UM_TENANT_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_ROLE(UM_ID, UM_TENANT_ID), + FOREIGN KEY (UM_USER_ID, UM_TENANT_ID) REFERENCES UM_USER(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID)); + + +CREATE TABLE IF NOT EXISTS UM_SHARED_USER_ROLE( + UM_ROLE_ID INTEGER NOT NULL, + UM_USER_ID INTEGER NOT NULL, + UM_USER_TENANT_ID INTEGER NOT NULL, + UM_ROLE_TENANT_ID INTEGER NOT NULL, + UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID), + FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE , + FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS UM_ACCOUNT_MAPPING( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER NOT NULL, + UM_USER_STORE_DOMAIN VARCHAR(100), + UM_ACC_LINK_ID INTEGER NOT NULL, + UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID), + FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID) +); + + +CREATE TABLE IF NOT EXISTS UM_DIALECT( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DIALECT_URI VARCHAR(255) NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE(UM_DIALECT_URI, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + + +CREATE TABLE IF NOT EXISTS UM_CLAIM( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DIALECT_ID INTEGER NOT NULL, + UM_CLAIM_URI VARCHAR(255) NOT NULL, + UM_DISPLAY_TAG VARCHAR(255), + UM_DESCRIPTION VARCHAR(255), + UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255), + UM_MAPPED_ATTRIBUTE VARCHAR(255), + UM_REG_EX VARCHAR(255), + UM_SUPPORTED SMALLINT, + UM_REQUIRED SMALLINT, + UM_DISPLAY_ORDER INTEGER, + UM_CHECKED_ATTRIBUTE SMALLINT, + UM_READ_ONLY SMALLINT, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI,UM_MAPPED_ATTRIBUTE_DOMAIN, UM_TENANT_ID), + FOREIGN KEY(UM_DIALECT_ID, UM_TENANT_ID) REFERENCES UM_DIALECT(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS UM_PROFILE_CONFIG( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_DIALECT_ID INTEGER, + UM_PROFILE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + FOREIGN KEY(UM_DIALECT_ID, UM_TENANT_ID) REFERENCES UM_DIALECT(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + + +CREATE TABLE IF NOT EXISTS UM_HYBRID_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ROLE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS UM_HYBRID_USER_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255), + UM_ROLE_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UM_DOMAIN_ID INTEGER, + UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID,UM_DOMAIN_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_HYBRID_ROLE(UM_ID, UM_TENANT_ID) ON DELETE CASCADE, + FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS UM_HYBRID_REMEMBER_ME ( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255) NOT NULL, + UM_COOKIE_VALUE VARCHAR(1024), + UM_CREATED_TIME TIMESTAMP, + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS UM_SYSTEM_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_ROLE_NAME VARCHAR(255), + UM_TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); + +CREATE TABLE IF NOT EXISTS UM_SYSTEM_USER_ROLE( + UM_ID INTEGER NOT NULL AUTO_INCREMENT, + UM_USER_NAME VARCHAR(255), + UM_ROLE_ID INTEGER NOT NULL, + UM_TENANT_ID INTEGER DEFAULT 0, + UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID), + FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID), + PRIMARY KEY (UM_ID, UM_TENANT_ID) +); 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 new file mode 100644 index 0000000000..9e0fe964b8 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/etc/webapp-publisher-config.xml @@ -0,0 +1,39 @@ + + + + + + + + https://localhost:9445 + + + true + + + true + + + + default + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/registry.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/registry.xml new file mode 100644 index 0000000000..0bb97a7dc9 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/carbon-home/repository/conf/registry.xml @@ -0,0 +1,50 @@ + + + + + + + + wso2registry + false + true + / + + + jdbc:h2:./target/databasetest/CARBON_TEST + + org.h2.Driver + 80 + 60000 + 5 + + + false + + + + true + true + true + true + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/testng.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/testng.xml new file mode 100644 index 0000000000..7dfa0ef71a --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/testng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml new file mode 100644 index 0000000000..bac4fc7667 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/resources/user-test/user-mgt-registry-test.xml @@ -0,0 +1,80 @@ + + + + + true + admin + + admin + admin + + everyone + false + 500 + jdbc:h2:target/databasetest/CARBON_TEST + org.h2.Driver + 50 + 60000 + 5 + + + org.wso2.carbon.user.core.tenant.JDBCTenantManager + false + 100 + false + default + SHA-256 + true + true + true + false + ^[\S]{5,30}$ + Password length should be between 5 to 30 characters + + ^[\S]{5,30}$ + [a-zA-Z0-9._-|//]{3,30}$ + ^[\S]{3,30}$ + ^[^~!#$;%^*+={}\\|\\\\<>,\'\"]{3,30}$ + ^[\S]{3,30}$ + true + 100 + 100 + false + false + true + , + true + + + true + + + + login + manage-configuration + manage-security + upload-services + manage-services + manage-lc-configuration + manage-mediation + monitor-system + delegate-identity + + diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index c5e920ef96..99d7268a94 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../../pom.xml 4.0.0 apimgt-extensions - 3.0.136-SNAPSHOT + 3.0.170-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 b653352d9e..a5879b5d6a 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.136-SNAPSHOT + 3.0.170-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 ac8b84e484..97b8fc6264 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.136-SNAPSHOT + 3.0.170-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 351a0f589f..c618b5ebc9 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.core - 3.0.136-SNAPSHOT + 3.0.170-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 cb93b5abdd..a58251eda8 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt certificate-mgt - 3.0.136-SNAPSHOT + 3.0.170-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 e925abec3d..63a89bd4ec 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml @@ -74,6 +74,39 @@ org.wso2.carbon org.wso2.carbon.ndatasource.core + + org.testng + testng + + + org.powermock + powermock-module-testng + test + + + org.wso2.carbon.registry + org.wso2.carbon.registry.indexing + test + + + org.slf4j + jcl-over-slf4j + + + org.slf4j + slf4j-api + + + org.slf4j + log4j-over-slf4j + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + test + diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java index 435e3cad3b..2880177a9e 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployer.java @@ -78,7 +78,7 @@ public class DeviceTypeCAppDeployer implements AppDeploymentHandler { } - private void deployTypeSpecifiedArtifacts(List artifacts, AxisConfiguration axisConfig, + protected void deployTypeSpecifiedArtifacts(List artifacts, AxisConfiguration axisConfig, String fileType, String directory) throws DeploymentException { for (Artifact artifact : artifacts) { Deployer deployer = AppDeployerUtils.getArtifactDeployer(axisConfig, directory, fileType); @@ -118,7 +118,7 @@ public class DeviceTypeCAppDeployer implements AppDeploymentHandler { } - private void undeployTypeSpecifiedArtifacts(List artifacts, AxisConfiguration axisConfig, String fileType + protected void undeployTypeSpecifiedArtifacts(List artifacts, AxisConfiguration axisConfig, String fileType , String directory) throws DeploymentException { for (Artifact artifact : artifacts) { Deployer deployer = AppDeployerUtils.getArtifactDeployer(axisConfig, directory, fileType); diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java index eb02504d97..82d039f53e 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployer.java @@ -51,8 +51,8 @@ public class DeviceTypePluginDeployer extends AbstractDeployer { private static Log log = LogFactory.getLog(DeviceTypePluginDeployer.class); private ConfigurationContext configurationContext; - protected Map deviceTypeServiceRegistrations = new ConcurrentHashMap(); - protected Map deviceTypeConfigurationDataMap = new ConcurrentHashMap(); + private Map deviceTypeServiceRegistrations = new ConcurrentHashMap(); + private Map deviceTypeConfigurationDataMap = new ConcurrentHashMap(); @Override public void init(ConfigurationContext configurationContext) { @@ -118,7 +118,7 @@ public class DeviceTypePluginDeployer extends AbstractDeployer { } } - private ServiceRegistration registerDeviceType(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier, + protected ServiceRegistration registerDeviceType(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier, DeviceTypeConfiguration deviceManagementConfiguration) { DeviceTypeManagerService deviceTypeManagerService = new DeviceTypeManagerService(deviceTypeConfigIdentifier, deviceManagementConfiguration); diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java new file mode 100644 index 0000000000..0aa0e28839 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypeCAppDeployerTest.java @@ -0,0 +1,131 @@ +/* + * 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.extensions.device.type.deployer; + +import org.apache.axis2.deployment.DeploymentException; +import org.apache.axis2.engine.AxisConfiguration; +import org.mockito.Mockito; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.application.deployer.CarbonApplication; +import org.wso2.carbon.application.deployer.config.ApplicationConfiguration; +import org.wso2.carbon.application.deployer.config.Artifact; +import org.wso2.carbon.application.deployer.config.CappFile; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.extensions.device.type.deployer.util.DeviceTypePluginConstants; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; + +/* + Unit tests for deviceTypeCAppDeployer + */ +public class DeviceTypeCAppDeployerTest { + private DeviceTypeCAppDeployer deviceTypeCAppDeployer; + private CarbonApplication carbonApplication = null; + private AxisConfiguration axisConfiguration = null; + private ApplicationConfiguration applicationConfiguration = null; + private CappFile cappFile = new CappFile(); + + + private void initializeActifact(String type) { + Artifact tempArtifact = new Artifact(); + cappFile.setName("testCappFile"); + tempArtifact.setType(type); + tempArtifact.addFile(cappFile); + Artifact.Dependency dependency = new Artifact.Dependency(); + dependency.setArtifact(tempArtifact); + tempArtifact.addDependency(dependency); + Mockito.doReturn(tempArtifact).when(applicationConfiguration).getApplicationArtifact(); + } + + private void initializeErrorArtifact() { + Artifact errArtifact = new Artifact(); + errArtifact.setType(DeviceTypePluginConstants.CDMF_PLUGIN_TYPE); + Artifact.Dependency dependency = new Artifact.Dependency(); + dependency.setArtifact(errArtifact); + errArtifact.addDependency(dependency); + Mockito.doReturn(errArtifact).when(applicationConfiguration).getApplicationArtifact(); + } + + @BeforeClass + public void init() throws NoSuchFieldException, IllegalAccessException, IOException, RegistryException { + Field deviceTypePlugins; + Field deviceTypeUIs; + deviceTypeCAppDeployer = Mockito.mock(DeviceTypeCAppDeployer.class, Mockito.CALLS_REAL_METHODS); + carbonApplication = Mockito.mock(CarbonApplication.class, Mockito.CALLS_REAL_METHODS); + axisConfiguration = Mockito.mock(AxisConfiguration.class, Mockito.CALLS_REAL_METHODS); + applicationConfiguration = Mockito.mock(ApplicationConfiguration.class, Mockito.CALLS_REAL_METHODS); + Mockito.doReturn(applicationConfiguration).when(carbonApplication).getAppConfig(); + Mockito.doNothing().when(deviceTypeCAppDeployer).deployTypeSpecifiedArtifacts(Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any()); + Mockito.doNothing().when(deviceTypeCAppDeployer).undeployTypeSpecifiedArtifacts(Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any()); + this.initializeCarbonContext(); + deviceTypePlugins = DeviceTypeCAppDeployer.class.getDeclaredField("deviceTypePlugins"); + deviceTypePlugins.setAccessible(true); + deviceTypePlugins.set(deviceTypeCAppDeployer, new ArrayList()); + deviceTypeUIs = DeviceTypeCAppDeployer.class.getDeclaredField("deviceTypeUIs"); + deviceTypeUIs.setAccessible(true); + deviceTypeUIs.set(deviceTypeCAppDeployer, new ArrayList()); + } + + private void initializeCarbonContext() throws IOException, RegistryException { + 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 = "deploying a capp of plugin type") + public void testDeployCarbonAppsPluginType() throws DeploymentException, IllegalAccessException { + initializeActifact(DeviceTypePluginConstants.CDMF_PLUGIN_TYPE); + deviceTypeCAppDeployer.deployArtifacts(carbonApplication, axisConfiguration); + } + + @Test(description = "deploying an erroneous car file") + public void testDeployErrorArtifact() throws DeploymentException, IllegalAccessException { + initializeErrorArtifact(); + deviceTypeCAppDeployer.deployArtifacts(carbonApplication, axisConfiguration); + } + + @Test(dependsOnMethods = {"testDeployCarbonAppsPluginType"}, description = "undeploying previously deployed capp") + public void testUndeployCarbonAppsPluginType() throws DeploymentException { + deviceTypeCAppDeployer.undeployArtifacts(carbonApplication, axisConfiguration); + } + + @Test(dependsOnMethods = {"testUndeployCarbonAppsPluginType"}, description = "deploying a capp of UI type") + public void testDeployCarbonAppsUiType() throws DeploymentException, IllegalAccessException { + initializeActifact(DeviceTypePluginConstants.CDMF_UI_TYPE); + deviceTypeCAppDeployer.deployArtifacts(carbonApplication, axisConfiguration); + } + + @Test(dependsOnMethods = {"testDeployCarbonAppsUiType"}, description = "Undeploy previously deployed capp") + public void testUndeployCarbonAppsUiType() throws DeploymentException { + deviceTypeCAppDeployer.undeployArtifacts(carbonApplication, axisConfiguration); + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java new file mode 100644 index 0000000000..597575ea31 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/deployer/DeviceTypePluginDeployerTest.java @@ -0,0 +1,124 @@ +/* + * 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.extensions.device.type.deployer; + +import org.apache.axis2.deployment.DeploymentException; +import org.apache.axis2.deployment.repository.util.DeploymentFileData; +import org.junit.Assert; +import org.mockito.Mockito; +import org.osgi.framework.ServiceRegistration; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/* + Unit tests for DeviceTypePluginDeployer + */ +public class DeviceTypePluginDeployerTest { + private DeviceTypePluginDeployer deviceTypePluginDeployer; + private DeploymentFileData deploymentFileData; + private DeploymentFileData invalidDeploymentFileData; + private Field deviceTypeServiceRegistrations = null; + private Field deviceTypeConfigurationDataMap = null; + private ServiceRegistration serviceRegistration = null; + private File file = new File("src/test/resources/android.xml"); + private File invalidFile = new File("src/test/resources/invalidAndroid.xml"); + + @BeforeClass + public void init() throws NoSuchFieldException, IllegalAccessException, IOException, RegistryException { + deviceTypePluginDeployer = Mockito.mock(DeviceTypePluginDeployer.class, Mockito.CALLS_REAL_METHODS); + serviceRegistration = Mockito.mock(ServiceRegistration.class, Mockito.CALLS_REAL_METHODS); + Mockito.doReturn(serviceRegistration).when(deviceTypePluginDeployer).registerDeviceType(Mockito.any(), + Mockito.any()); + deviceTypeServiceRegistrations = DeviceTypePluginDeployer.class.getDeclaredField + ("deviceTypeServiceRegistrations"); + deviceTypeServiceRegistrations.setAccessible(true); + deviceTypeServiceRegistrations.set(deviceTypePluginDeployer, new ConcurrentHashMap()); + deviceTypeConfigurationDataMap = DeviceTypePluginDeployer.class.getDeclaredField + ("deviceTypeConfigurationDataMap"); + deviceTypeConfigurationDataMap.setAccessible(true); + deviceTypeConfigurationDataMap.set(deviceTypePluginDeployer, new ConcurrentHashMap()); + this.initializeCarbonContext(); + if (file.exists()) { + deploymentFileData = new DeploymentFileData(file); + } + if (invalidFile.exists()) { + invalidDeploymentFileData = new DeploymentFileData(invalidFile); + } + } + + private void initializeCarbonContext() throws IOException, RegistryException { + 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); + } + + @SuppressWarnings("unchecked") + @Test(description = "Testing deviceType deploy method by deploying Android device type") + public void deploy() throws DeploymentException, IllegalAccessException { + deviceTypePluginDeployer.deploy(deploymentFileData); + Map tempServiceRegistration = (Map) + deviceTypeServiceRegistrations.get(deviceTypePluginDeployer); + Assert.assertEquals(tempServiceRegistration.get(deploymentFileData.getAbsolutePath()), serviceRegistration); + Map tempDeviceTypeConfig = (Map) + deviceTypeConfigurationDataMap.get(deviceTypePluginDeployer); + DeviceTypeConfigIdentifier deviceTypeConfigIdentifier = tempDeviceTypeConfig.get(deploymentFileData + .getAbsolutePath()); + Assert.assertEquals(deviceTypeConfigIdentifier.getDeviceType(), "android"); + } + + @Test(description = "Testing exception for invalid xml files", expectedExceptions = {org.apache.axis2.deployment + .DeploymentException.class}) + public void deployInvalidXml() throws DeploymentException, IllegalAccessException { + deviceTypePluginDeployer.deploy(invalidDeploymentFileData); + } + + @Test(description = "Testing exception for non existing xml file", expectedExceptions = {org.apache.axis2.deployment + .DeploymentException.class}) + public void unDeployInvalidXml() throws DeploymentException, IllegalAccessException { + deviceTypePluginDeployer.deploy(new DeploymentFileData(new File("src/test/resources/notExist.xml"))); + } + + @SuppressWarnings("unchecked") + @Test(dependsOnMethods = {"deploy"} , description = "Testing deviceType undeploy method by un-deploying Android " + + "device type") + public void unDeploy() throws DeploymentException, IllegalAccessException { + deviceTypePluginDeployer.undeploy(deploymentFileData.getAbsolutePath()); + Map tempServiceRegistration = (Map) + deviceTypeServiceRegistrations.get(deviceTypePluginDeployer); + Assert.assertNull(tempServiceRegistration.get(deploymentFileData.getAbsolutePath())); + Map tempDeviceTypeConfig = (Map) + deviceTypeConfigurationDataMap.get(deviceTypePluginDeployer); + Assert.assertNull(tempDeviceTypeConfig.get(deploymentFileData.getAbsolutePath())); + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/android.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/android.xml new file mode 100644 index 0000000000..21db962414 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/android.xml @@ -0,0 +1,382 @@ + + + + + + + + en_US + 1.0.0 + This End User License Agreement ("Agreement") is a legal agreement between you ("You") and WSO2, + Inc., regarding the enrollment of Your personal mobile device ("Device") in SoR's mobile device + management program, and the loading to and removal from Your Device and Your use of certain + applications and any associated software and user documentation, whether provided in "online" or + electronic format, used in connection with the operation of or provision of services to WSO2, + Inc., BY SELECTING "I ACCEPT" DURING INSTALLATION, YOU ARE ENROLLING YOUR DEVICE, AND THEREBY + AUTHORIZING SOR OR ITS AGENTS TO INSTALL, UPDATE AND REMOVE THE APPS FROM YOUR DEVICE AS DESCRIBED + IN THIS AGREEMENT. YOU ARE ALSO EXPLICITLY ACKNOWLEDGING AND AGREEING THAT (1) THIS IS A BINDING + CONTRACT AND (2) YOU HAVE READ AND AGREE TO THE TERMS OF THIS AGREEMENT. + + IF YOU DO NOT ACCEPT THESE TERMS, DO NOT ENROLL YOUR DEVICE AND DO NOT PROCEED ANY FURTHER. + + You agree that: (1) You understand and agree to be bound by the terms and conditions contained in + this Agreement, and (2) You are at least 21 years old and have the legal capacity to enter into + this Agreement as defined by the laws of Your jurisdiction. SoR shall have the right, without + prior notice, to terminate or suspend (i) this Agreement, (ii) the enrollment of Your Device, or + (iii) the functioning of the Apps in the event of a violation of this Agreement or the cessation + of Your relationship with SoR (including termination of Your employment if You are an employee or + expiration or termination of Your applicable franchise or supply agreement if You are a franchisee + of or supplier to the WSO2 WSO2, Inc., system). SoR expressly reserves all rights not expressly + granted herein. + + + + + true + + + + + + + + + jdbc/MobileAndroidDM_DS + + + + DEVICE_ID + + FCM_TOKEN + DEVICE_INFO + IMEI + IMSI + OS_VERSION + DEVICE_MODEL + VENDOR + LATITUDE + LONGITUDE + SERIAL + MAC_ADDRESS + DEVICE_NAME + OS_BUILD_DATE + +
+
+
+ + + + Ring + Ring the device + + + + + Device Lock + Lock the device + + + + + Location + Request coordinates of device location + + + + + Clear Password + Clear current password + + + + + Reboot + Reboot the device + + + + + Upgrade Firmware + Upgrade Firmware + + + + + Mute + Enable mute in the device + + + + + Message + Send message + + + + + Change Lock-code + Change current lock code + + + + + Enterprise Wipe + Remove enterprise applications + + + + + Wipe Data + Factory reset the device + + + + + Wifi + Setting up wifi configuration + + + Camera + Enable or disable camera + + + Email + Configure email settings + + + Device info + Request device information + + + Application List + Request list of current installed applications + + + Install App + Install App + + + Uninstall App + Uninstall App + + + Blacklist app + Blacklist applications + + + Encrypt Storage + Encrypt storage + + + Password Policy + Set passcode policy + + + Configure VPN + Configure VPN settings + + + Disallow user to change volume + Allow or disallow user to change volume" + + + Disallow bluetooth configuration + Allow or disallow bluetooth configuration + + + Disallow user to change cell broadcast configurations + Allow or disallow user to change cell broadcast configurations + + + Disallow user to change user credentials + Allow or disallow user to change user credentials + + + Disallow user to change mobile networks configurations + Allow or disallow user to change mobile networks configurations + + + Disallow user to change tethering configurations + Allow or disallow user to change tethering configurations + + + Disallow user to change VPN configurations + Allow or disallow user to change VPN configurations + + + Disallow user to change WIFI configurations + Allow or disallow user to change WIFI configurations + + + Disallow user to change app control + Allow or disallow user to change app control + + + Disallow window creation + Allow or disallow window creation + + + Disallow user to change app control configurations + Allow or disallow user to change app control configurations + + + Disallow cross profile copy paste + Allow or disallow cross profile copy paste + + + Disallow debugging features + Allow or disallow debugging features + + + Disallow factory reset + Allow or disallow factory reset + + + Disallow add user + Allow or disallow add user + + + Disallow install apps + Allow or disallow install apps + + + Disallow install unknown sources + Allow or disallow install unknown sources + + + Disallow modify account + Allow or disallow modify account + + + Disallow mount physical media + Allow or disallow mount physical media + + + Disallow network reset + Allow or disallow network reset + + + Disallow outgoing beam + Allow or disallow outgoing beam + + + Disallow outgoing calls + Allow or disallow outgoing calls + + + Disallow remove users + Allow or disallow remove users + + + Disallow safe boot + Allow or disallow safe boot + + + Disallow share location + Allow or disallow share location + + + Disallow sms + Allow or disallow sms + + + Disallow uninstall app + Allow or disallow uninstall app + + + Disallow unmute mic + Allow or disallow unmute mic + + + Disallow usb file transfer + Allow or disallow usb file transfer + + + Disallow parent profile app linking + Allow or disallow parent profile app linking + + + Disallow ensure verify apps + Allow or disallow ensure verify apps + + + Disallow auto timing + Allow or disallow auto timing + + + Remove device owner + Remove device owner + + + Fetch device logcat + Fetch device logcat + + + Unlock the device + Unlock the device + + + + true + 60000 + + + DEVICE_INFO + 1 + + + APPLICATION_LIST + 5 + + + DEVICE_LOCATION + 1 + + + + + + + DEVICE_INFO + APPLICATION_LIST + DEVICE_LOCATION + + + + + true + 300 + 900 + 600 + +
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/invalidAndroid.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/invalidAndroid.xml new file mode 100644 index 0000000000..45ddc258b5 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/invalidAndroid.xml @@ -0,0 +1,382 @@ + + + + + + + en_US + 1.0.0 + This End User License Agreement ("Agreement") is a legal agreement between you ("You") and WSO2, + Inc., regarding the enrollment of Your personal mobile device ("Device") in SoR's mobile device + management program, and the loading to and removal from Your Device and Your use of certain + applications and any associated software and user documentation, whether provided in "online" or + electronic format, used in connection with the operation of or provision of services to WSO2, + Inc., BY SELECTING "I ACCEPT" DURING INSTALLATION, YOU ARE ENROLLING YOUR DEVICE, AND THEREBY + AUTHORIZING SOR OR ITS AGENTS TO INSTALL, UPDATE AND REMOVE THE APPS FROM YOUR DEVICE AS DESCRIBED + IN THIS AGREEMENT. YOU ARE ALSO EXPLICITLY ACKNOWLEDGING AND AGREEING THAT (1) THIS IS A BINDING + CONTRACT AND (2) YOU HAVE READ AND AGREE TO THE TERMS OF THIS AGREEMENT. + + IF YOU DO NOT ACCEPT THESE TERMS, DO NOT ENROLL YOUR DEVICE AND DO NOT PROCEED ANY FURTHER. + + You agree that: (1) You understand and agree to be bound by the terms and conditions contained in + this Agreement, and (2) You are at least 21 years old and have the legal capacity to enter into + this Agreement as defined by the laws of Your jurisdiction. SoR shall have the right, without + prior notice, to terminate or suspend (i) this Agreement, (ii) the enrollment of Your Device, or + (iii) the functioning of the Apps in the event of a violation of this Agreement or the cessation + of Your relationship with SoR (including termination of Your employment if You are an employee or + expiration or termination of Your applicable franchise or supply agreement if You are a franchisee + of or supplier to the WSO2 WSO2, Inc., system). SoR expressly reserves all rights not expressly + granted herein. + + + + + true + + + + + + + + + jdbc/MobileAndroidDM_DS + + + + DEVICE_ID + + FCM_TOKEN + DEVICE_INFO + IMEI + IMSI + OS_VERSION + DEVICE_MODEL + VENDOR + LATITUDE + LONGITUDE + SERIAL + MAC_ADDRESS + DEVICE_NAME + OS_BUILD_DATE + +
+
+
+ + + + Ring + Ring the device + + + + + Device Lock + Lock the device + + + + + Location + Request coordinates of device location + + + + + Clear Password + Clear current password + + + + + Reboot + Reboot the device + + + + + Upgrade Firmware + Upgrade Firmware + + + + + Mute + Enable mute in the device + + + + + Message + Send message + + + + + Change Lock-code + Change current lock code + + + + + Enterprise Wipe + Remove enterprise applications + + + + + Wipe Data + Factory reset the device + + + + + Wifi + Setting up wifi configuration + + + Camera + Enable or disable camera + + + Email + Configure email settings + + + Device info + Request device information + + + Application List + Request list of current installed applications + + + Install App + Install App + + + Uninstall App + Uninstall App + + + Blacklist app + Blacklist applications + + + Encrypt Storage + Encrypt storage + + + Password Policy + Set passcode policy + + + Configure VPN + Configure VPN settings + + + Disallow user to change volume + Allow or disallow user to change volume" + + + Disallow bluetooth configuration + Allow or disallow bluetooth configuration + + + Disallow user to change cell broadcast configurations + Allow or disallow user to change cell broadcast configurations + + + Disallow user to change user credentials + Allow or disallow user to change user credentials + + + Disallow user to change mobile networks configurations + Allow or disallow user to change mobile networks configurations + + + Disallow user to change tethering configurations + Allow or disallow user to change tethering configurations + + + Disallow user to change VPN configurations + Allow or disallow user to change VPN configurations + + + Disallow user to change WIFI configurations + Allow or disallow user to change WIFI configurations + + + Disallow user to change app control + Allow or disallow user to change app control + + + Disallow window creation + Allow or disallow window creation + + + Disallow user to change app control configurations + Allow or disallow user to change app control configurations + + + Disallow cross profile copy paste + Allow or disallow cross profile copy paste + + + Disallow debugging features + Allow or disallow debugging features + + + Disallow factory reset + Allow or disallow factory reset + + + Disallow add user + Allow or disallow add user + + + Disallow install apps + Allow or disallow install apps + + + Disallow install unknown sources + Allow or disallow install unknown sources + + + Disallow modify account + Allow or disallow modify account + + + Disallow mount physical media + Allow or disallow mount physical media + + + Disallow network reset + Allow or disallow network reset + + + Disallow outgoing beam + Allow or disallow outgoing beam + + + Disallow outgoing calls + Allow or disallow outgoing calls + + + Disallow remove users + Allow or disallow remove users + + + Disallow safe boot + Allow or disallow safe boot + + + Disallow share location + Allow or disallow share location + + + Disallow sms + Allow or disallow sms + + + Disallow uninstall app + Allow or disallow uninstall app + + + Disallow unmute mic + Allow or disallow unmute mic + + + Disallow usb file transfer + Allow or disallow usb file transfer + + + Disallow parent profile app linking + Allow or disallow parent profile app linking + + + Disallow ensure verify apps + Allow or disallow ensure verify apps + + + Disallow auto timing + Allow or disallow auto timing + + + Remove device owner + Remove device owner + + + Fetch device logcat + Fetch device logcat + + + Unlock the device + Unlock the device + + + + true + 60000 + + + DEVICE_INFO + 1 + + + APPLICATION_LIST + 5 + + + DEVICE_LOCATION + 1 + + + + + + + DEVICE_INFO + APPLICATION_LIST + DEVICE_LOCATION + + + + + true + 300 + 900 + 600 + +
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/log4j.properties b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/log4j.properties new file mode 100644 index 0000000000..e415fd607d --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/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-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/repository/conf/carbon.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/repository/conf/carbon.xml new file mode 100644 index 0000000000..f24ee57be2 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/repository/conf/carbon.xml @@ -0,0 +1,656 @@ + + + + + + + + + ${product.name} + + + ${product.key} + + + ${product.version} + + + + + + + + + local:/${carbon.context}/services/ + + + + + + + ${default.server.role} + + + + + + + org.wso2.carbon + + + / + + + + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + + false + + + + + + + + 30 + + + + + + + + + 15 + + + + + + ${carbon.home}/repository/deployment/server/ + + + 15 + + + ${carbon.home}/repository/conf/axis2/axis2.xml + + + 30000 + + + ${carbon.home}/repository/deployment/client/ + + ${carbon.home}/repository/conf/axis2/axis2_client.xml + + true + + + + + + + + + + admin + Default Administrator Role + + + user + Default User Role + + + + + + + + + + + + ${carbon.home}/repository/resources/security/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + + + + + ${carbon.home}/tmp/work + + + + + + true + + + 10 + + + 30 + + + + + + 100 + + + + keystore + certificate + * + + org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor + + + + + jarZip + + org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor + + + + dbs + + org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor + + + + tools + + org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor + + + + toolsAny + + org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor + + + + + + + info + org.wso2.carbon.core.transports.util.InfoProcessor + + + wsdl + org.wso2.carbon.core.transports.util.Wsdl11Processor + + + wsdl2 + org.wso2.carbon.core.transports.util.Wsdl20Processor + + + xsd + org.wso2.carbon.core.transports.util.XsdProcessor + + + + + + false + false + true + svn + http://svnrepo.example.com/repos/ + username + password + true + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + ${p2.repo.url} + + + + + + + + true + + + + + + true + + diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/testng.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/testng.xml new file mode 100644 index 0000000000..5d4a11b9b9 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/src/test/resources/testng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + 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 aeda965f48..bb021a159b 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.136-SNAPSHOT + 3.0.170-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 b3faf21c9f..f1cde4cd24 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.136-SNAPSHOT + 3.0.170-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 bbc52fa987..6b87bae552 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.136-SNAPSHOT + 3.0.170-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 10767ceb62..a132616de3 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml @@ -111,8 +111,16 @@ org.wso2.carbon.analytics-common org.wso2.carbon.event.output.adapter.core + + org.testng + testng + + + org.powermock + powermock-module-testng + test + - diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java new file mode 100644 index 0000000000..c29eb52c43 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTBasedPushNotificationProviderTest.java @@ -0,0 +1,89 @@ +/* + * 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.extensions.push.notification.provider.mqtt; + +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.push.notification.NotificationStrategy; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTDataHolder; +import org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.internal.util.MQTTAdapterConstants; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; +import org.wso2.carbon.event.output.adapter.core.internal.CarbonOutputEventAdapterService; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/* + Unit tests for MQTTBasedPushNotificationProvider class + */ +public class MQTTBasedPushNotificationProviderTest { + private MQTTBasedPushNotificationProvider mqttBasedPushNotificationProvider; + private CarbonOutputEventAdapterService carbonOutputEventAdapterService; + private static final String ADAPTER_NAME = "SampleMqttAdapterName"; + private static final String BROKER_URL = "SampleBrokerUrl"; + + @BeforeClass + public void init() throws NoSuchFieldException, IllegalAccessException, IOException, RegistryException, + OutputEventAdapterException { + initializeCarbonContext(); + mqttBasedPushNotificationProvider = Mockito.mock(MQTTBasedPushNotificationProvider.class, + Mockito.CALLS_REAL_METHODS); + carbonOutputEventAdapterService = Mockito.mock(CarbonOutputEventAdapterService.class, + Mockito.CALLS_REAL_METHODS); + Mockito.doReturn(true).when(carbonOutputEventAdapterService).isPolled(ADAPTER_NAME); + } + + private void initializeCarbonContext() throws IOException, RegistryException { + 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 = "test getType method") + public void testGetType() { + String type = mqttBasedPushNotificationProvider.getType(); + Assert.assertEquals(type, "MQTT"); + } + + @Test(description = "test get notification strategy method") + public void getNotificationStrategy() { + Map properties = new HashMap<>(); + properties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL, BROKER_URL); + properties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_NAME, ADAPTER_NAME); + PushNotificationConfig pushNotificationConfig = new PushNotificationConfig("MQTT", true, properties); + MQTTDataHolder mqttDataHolder = MQTTDataHolder.getInstance(); + mqttDataHolder.setOutputEventAdapterService(carbonOutputEventAdapterService); + NotificationStrategy notificationStrategy = mqttBasedPushNotificationProvider. + getNotificationStrategy(pushNotificationConfig); + Assert.assertNotNull(notificationStrategy, "null notificationStrategyReceived"); + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java new file mode 100644 index 0000000000..741bf2d9d2 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategyTest.java @@ -0,0 +1,176 @@ +/* + * 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.extensions.push.notification.provider.mqtt; + +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.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException; +import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; +import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; +import org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.internal.MQTTDataHolder; +import org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.internal.util.MQTTAdapterConstants; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; +import org.wso2.carbon.event.output.adapter.core.internal.CarbonOutputEventAdapterService; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import static org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation.POLICY_OPERATION_CODE; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/* + Unit tests for MQTTNotificationStrategy class + */ +public class MQTTNotificationStrategyTest { + private MQTTNotificationStrategy mqttNotificationStrategy; + private CarbonOutputEventAdapterService carbonOutputEventAdapterService; + private static final String ADAPTER_NAME = "SampleMqttAdapterName"; + private static final String BROKER_URL = "SampleBrokerUrl"; + private PushNotificationConfig pushNotificationConfig; + private static final String MQTT_ADAPTER_TOPIC = "mqtt.adapter.topic"; + private DeviceIdentifier deviceIdentifier; + private Operation operation; + private Map propertiesMap; + private NotificationContext notificationContext; + + @BeforeClass + public void init() throws NoSuchFieldException, IllegalAccessException, IOException, RegistryException, + OutputEventAdapterException { + initializeCarbonContext(); + mqttNotificationStrategy = Mockito.mock(MQTTNotificationStrategy.class, Mockito.CALLS_REAL_METHODS); + carbonOutputEventAdapterService = Mockito.mock(CarbonOutputEventAdapterService.class, + Mockito.CALLS_REAL_METHODS); + Mockito.doReturn(true).when(carbonOutputEventAdapterService).isPolled(Mockito.any()); + Mockito.doNothing().when(carbonOutputEventAdapterService).publish(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(carbonOutputEventAdapterService).destroy(ADAPTER_NAME); + } + + private void initializeCarbonContext() throws IOException, RegistryException { + 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 = "Testing the constructor of MQTTNotificationStrategy class") + public void getNotificationStrategy() { + Map properties = new HashMap<>(); + properties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL, BROKER_URL); + properties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_NAME, ADAPTER_NAME); + pushNotificationConfig = new PushNotificationConfig("MQTT", true, properties); + MQTTDataHolder mqttDataHolder = MQTTDataHolder.getInstance(); + mqttDataHolder.setOutputEventAdapterService(carbonOutputEventAdapterService); + mqttNotificationStrategy = new MQTTNotificationStrategy(pushNotificationConfig); + Assert.assertNotNull(mqttNotificationStrategy, "Null MQTTNotificationStrategy after initializing"); + } + + @Test(dependsOnMethods = {"getNotificationStrategy"}, description = "Testing getConfig method") + public void getConfigTest() { + PushNotificationConfig temp = mqttNotificationStrategy.getConfig(); + Assert.assertEquals(temp, pushNotificationConfig, "Not matching pushNotificationConfig received"); + } + + @Test(description = "testing un-deploy method") + public void testUndeploy() { + mqttNotificationStrategy.undeploy(); + } + + @Test(description = "testing build context method") + public void testBuildContext() { + Assert.assertNull(mqttNotificationStrategy.buildContext(), "not null buildContext received"); + } + + @Test(description = "testing execute method without properties and operation type command") + public void testExecuteWithoutProperties() throws PushNotificationExecutionFailedException { + deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId("1"); + deviceIdentifier.setType("SampleDeviceType"); + operation = new Operation(); + operation.setPayLoad(new Object()); + operation.setType(Operation.Type.COMMAND); + operation.setCode("SampleCode"); + operation.setId(1); + propertiesMap = new HashMap<>(); + propertiesMap.put(MQTT_ADAPTER_TOPIC, "SampleTopic"); + notificationContext = new NotificationContext(deviceIdentifier, operation); + notificationContext.setProperties(propertiesMap); + mqttNotificationStrategy.execute(notificationContext); + } + + @Test(dependsOnMethods = "testExecuteWithoutProperties", description = "testing execute method without properties " + + "and operation type config") + public void testExecutionWithoutPropertiesNonCommandType() throws PushNotificationExecutionFailedException { + operation.setType(Operation.Type.CONFIG); + operation.setProperties(null); + notificationContext = new NotificationContext(deviceIdentifier, operation); + mqttNotificationStrategy.execute(notificationContext); + } + + @Test(dependsOnMethods = {"testExecutionWithoutPropertiesNonCommandType"}, description = "test execute method " + + "with a profile operation") + public void testExecutePolicyOperation() throws PushNotificationExecutionFailedException { + PolicyOperation policyOperation = new PolicyOperation(); + policyOperation.setCode(POLICY_OPERATION_CODE); + policyOperation.setProperties(null); + ProfileOperation profileOperation = new ProfileOperation(); + profileOperation.setActivityId("1"); + profileOperation.setCode("SampleCode"); + List profileOperationList = new ArrayList<>(); + profileOperationList.add(profileOperation); + policyOperation.setProfileOperations(profileOperationList); + notificationContext = new NotificationContext(deviceIdentifier, policyOperation); + mqttNotificationStrategy.execute(notificationContext); + } + + @Test(dependsOnMethods = "testExecuteWithoutProperties", description = "testing execute method with properties") + public void testExecute() throws PushNotificationExecutionFailedException { + Properties properties = new Properties(); + properties.setProperty(MQTT_ADAPTER_TOPIC, "SampleTopic"); + operation.setProperties(properties); + notificationContext = new NotificationContext(deviceIdentifier, operation); + notificationContext.setProperties(propertiesMap); + mqttNotificationStrategy.execute(notificationContext); + } + + @Test(dependsOnMethods = {"testExecute"}, description = "testing execute method without the default tenant domain") + public void testExecutionWithoutTenantDomain() throws NoSuchFieldException, IllegalAccessException, + PushNotificationExecutionFailedException { + Field providerTenantDomain = MQTTNotificationStrategy.class.getDeclaredField("providerTenantDomain"); + providerTenantDomain.setAccessible(true); + providerTenantDomain.set(mqttNotificationStrategy, "SampleTenantDomain"); + mqttNotificationStrategy.execute(notificationContext); + } +} diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/conf/carbon.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/conf/carbon.xml new file mode 100644 index 0000000000..31752cf9b4 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/conf/carbon.xml @@ -0,0 +1,656 @@ + + + + + + + + + ${product.name} + + + ${product.key} + + + ${product.version} + + + + + + + + + local:/${carbon.context}/services/ + + + + + + + ${default.server.role} + + + + + + + org.wso2.carbon + + + / + + + + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + + false + + + + + + + + 30 + + + + + + + + + 15 + + + + + + ${carbon.home}/repository/deployment/server/ + + + 15 + + + ${carbon.home}/repository/conf/axis2/axis2.xml + + + 30000 + + + ${carbon.home}/repository/deployment/client/ + + ${carbon.home}/repository/conf/axis2/axis2_client.xml + + true + + + + + + + + + + admin + Default Administrator Role + + + user + Default User Role + + + + + + + + + + + + ${carbon.home}/repository/resources/security/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + + + + + ${carbon.home}/tmp/work + + + + + + true + + + 10 + + + 30 + + + + + + 100 + + + + keystore + certificate + * + + org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor + + + + + jarZip + + org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor + + + + dbs + + org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor + + + + tools + + org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor + + + + toolsAny + + org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor + + + + + + + info + org.wso2.carbon.core.transports.util.InfoProcessor + + + wsdl + org.wso2.carbon.core.transports.util.Wsdl11Processor + + + wsdl2 + org.wso2.carbon.core.transports.util.Wsdl20Processor + + + xsd + org.wso2.carbon.core.transports.util.XsdProcessor + + + + + + false + false + true + svn + http://svnrepo.example.com/repos/ + username + password + true + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + ${p2.repo.url} + + + + + + + + true + + + + + + true + + diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/log4j.properties b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/log4j.properties new file mode 100644 index 0000000000..90c5d0edce --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/log4j.properties @@ -0,0 +1,34 @@ +# +# 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. +# + +# +# 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-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/testng.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/testng.xml new file mode 100644 index 0000000000..d76f7ab144 --- /dev/null +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/test/resources/testng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + 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 ad578868fc..c3cb18590b 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 67004d0d2c..e9610b92d4 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml deleted file mode 100644 index 9ca2f2cbfe..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - org.wso2.carbon.devicemgt - device-mgt - 3.0.136-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.analytics.dashboard - bundle - WSO2 Carbon - Device Management Dashboard Analytics - WSO2 Carbon - Device Management Dashboard Analytics - http://wso2.org - - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - - - org.wso2.carbon - org.wso2.carbon.ndatasource.core - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.device.mgt.version} - Device Management Dashboard Analytics Bundle - - org.wso2.carbon.device.mgt.analytics.dashboard.dao, - org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl, - org.wso2.carbon.device.mgt.analytics.dashboard.impl, - org.wso2.carbon.device.mgt.analytics.dashboard.internal - - - org.wso2.carbon.device.mgt.analytics.dashboard, - org.wso2.carbon.device.mgt.analytics.dashboard.util, - org.wso2.carbon.device.mgt.analytics.dashboard.exception, - org.wso2.carbon.device.mgt.analytics.dashboard.bean - - - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging.*, - javax.sql, - org.wso2.carbon.context, - org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.core.*, - org.wso2.carbon.ndatasource.core.*; - - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java deleted file mode 100644 index 5a251fc9c2..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard; - -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.common.PaginationResult; - -import java.util.List; - -/** - * This interface exposes useful service layer functions to retrieve data - * required by high level dashboard APIs. - */ -public interface GadgetDataService { - - /** - * This method is used to get a count of devices based on a defined filter set. - * @param extendedFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total device count in the system - * wrapped by the defined return format. - * @return An object of type DeviceCountByGroup. - * @throws InvalidPotentialVulnerabilityValueException This can occur if potentialVulnerability - * value of extendedFilterSet is set with some - * value other than "NON_COMPLIANT" or "UNMONITORED". - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - DeviceCountByGroup getDeviceCount(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException; - - /** - * This method is used to get a count of devices non-compliant upon on a particular feature - * and a defined filter set. - * @param featureCode Code name of the non-compliant feature. - * @param basicFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total non-compliant device count in the system - * for the given feature-code, wrapped by the defined return format. - * @return An object of type DeviceCountByGroup. - * @throws InvalidFeatureCodeValueException This can occur if featureCode is set to null or empty. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - DeviceCountByGroup getFeatureNonCompliantDeviceCount(String featureCode, BasicFilterSet basicFilterSet, String userName) - throws InvalidFeatureCodeValueException, DataAccessLayerException; - - /** - * This method is used to get total count of devices currently enrolled under a particular tenant. - * @return An object of type DeviceCountByGroup. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - DeviceCountByGroup getTotalDeviceCount(String userName) throws DataAccessLayerException; - - /** - * This method is used to get device counts classified by connectivity statuses. - * @return A list of objects of type DeviceCountByGroup. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getDeviceCountsByConnectivityStatuses(String userName) throws DataAccessLayerException; - - /** - * This method is used to get device counts classified by potential vulnerabilities. - * @return A list of objects of type DeviceCountByGroup. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getDeviceCountsByPotentialVulnerabilities(String userName) throws DataAccessLayerException; - - /** - * This method is used to get non-compliant device counts classified by individual features. - * @param startIndex Starting index of the data set to be retrieved. - * @param resultCount Total count of the result set retrieved. - * @return An object of type PaginationResult. - * @throws InvalidStartIndexValueException This can occur if startIndex value is lesser than its minimum (0). - * @throws InvalidResultCountValueException This can occur if resultCount value is lesser than its minimum (5). - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) throws - InvalidStartIndexValueException, InvalidResultCountValueException, DataAccessLayerException; - - /** - * This method is used to get device counts classified by platforms. - * @param extendedFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total device counts per each platform in - * the system, wrapped by the defined return format. - * @return An object of type DeviceCountByGroup. - * @throws InvalidPotentialVulnerabilityValueException This can occur if potentialVulnerability - * value of extendedFilterSet is set with some - * value other than "NON_COMPLIANT" or "UNMONITORED". - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getDeviceCountsByPlatforms(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException; - - /** - * This method is used to get device counts non-compliant upon a particular feature classified by platforms. - * @param featureCode Code name of the non-compliant feature. - * @param basicFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total non-compliant device counts per each platform - * in the system, wrapped by the defined return format. - * @return A list of objects of type DeviceCountByGroup. - * @throws InvalidFeatureCodeValueException This can occur if featureCode is set to null or empty. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getFeatureNonCompliantDeviceCountsByPlatforms(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException; - - /** - * This method is used to get device counts classified by ownership types. - * @param extendedFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total device counts per each ownership - * type in the system, wrapped by the defined return format. - * @return A list of objects of type DeviceCountByGroup. - * @throws InvalidPotentialVulnerabilityValueException This can occur if potentialVulnerability - * value of extendedFilterSet is set with some - * value other than "NON_COMPLIANT" or "UNMONITORED". - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getDeviceCountsByOwnershipTypes(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException; - - /** - * This method is used to get device counts non-compliant upon a particular feature - * classified by ownership types. - * @param featureCode Code name of the non-compliant feature. - * @param basicFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total non-compliant device counts per each - * ownership type in the system, wrapped by the defined return format. - * @return A list of objects of type DeviceCountByGroup. - * @throws InvalidFeatureCodeValueException This can occur if featureCode is set to null or empty. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getFeatureNonCompliantDeviceCountsByOwnershipTypes(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException; - - /** - * This method is used to get a paginated list of devices with details, based on a defined filter set. - * @param extendedFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined - * filtering options, this method would return a paginated device list in the - * system specified by result count, starting from specified start index, and - * wrapped by the defined return format. - * @param startIndex Starting index of the data set to be retrieved. - * @param resultCount Total count of the result set retrieved. - * @return An object of type PaginationResult. - * @throws InvalidPotentialVulnerabilityValueException This can occur if potentialVulnerability - * value of extendedFilterSet is set with some - * value other than "NON_COMPLIANT" or "UNMONITORED". - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - * @throws InvalidStartIndexValueException This can occur if startIndex value is lesser than its minimum (0). - * @throws InvalidResultCountValueException This can occur if resultCount value is lesser than its minimum (5). - */ - @SuppressWarnings("unused") - PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException, - InvalidStartIndexValueException, InvalidResultCountValueException; - - /** - * This method is used to get a paginated list of non-compliant devices with details, - * upon a particular feature. - * @param featureCode Code name of the non-compliant feature. - * @param basicFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return a paginated device list in the system, - * non-compliant by specified feature-code, result count, starting from specified - * start index, and wrapped by the defined return format. - * @param startIndex Starting index of the data set to be retrieved. - * @param resultCount Total count of the result set retrieved. - * @return An object of type PaginationResult. - * @throws InvalidFeatureCodeValueException This can occur if featureCode is set to null or empty. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - * @throws InvalidStartIndexValueException This can occur if startIndex value is lesser than its minimum (0). - * @throws InvalidResultCountValueException This can occur if resultCount value is lesser than its minimum (5). - */ - @SuppressWarnings("unused") - PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, BasicFilterSet basicFilterSet, - int startIndex, int resultCount, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException, InvalidStartIndexValueException, - InvalidResultCountValueException; - - /** - * This method is used to get a list of devices with details, based on a defined filter set. - * @param extendedFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total device list in the system - * wrapped by the defined return format. - * @return A list of objects of type DeviceWithDetails. - * @throws InvalidPotentialVulnerabilityValueException This can occur if potentialVulnerability - * value of extendedFilterSet is set with some - * value other than "NON_COMPLIANT" or "UNMONITORED". - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException; - - /** - * This method is used to get a list of non-compliant devices with details, upon a particular feature. - * @param featureCode Code name of the non-compliant feature. - * @param basicFilterSet An abstract representation of possible filtering options. - * if this value is simply "null" or no values are set for the defined filtering - * options, this method would return total set of non-compliant devices in the - * system upon given feature-code, wrapped by the defined return format. - * @return A list of objects of type DeviceWithDetails. - * @throws InvalidFeatureCodeValueException This can occur if featureCode is set to null or empty. - * @throws DataAccessLayerException This can occur due to errors connecting to database, - * executing SQL query and retrieving data. - */ - @SuppressWarnings("unused") - List getFeatureNonCompliantDevicesWithDetails(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/BasicFilterSet.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/BasicFilterSet.java deleted file mode 100644 index 901949ea84..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/BasicFilterSet.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.bean; - -public class BasicFilterSet { - - private String connectivityStatus; - private String platform; - private String ownership; - - public String getConnectivityStatus() { - return connectivityStatus; - } - - public void setConnectivityStatus(String connectivityStatus) { - this.connectivityStatus = connectivityStatus; - } - - public String getPlatform() { - return platform; - } - - @SuppressWarnings("unused") - public void setPlatform(String platform) { - this.platform = platform; - } - - public String getOwnership() { - return ownership; - } - - @SuppressWarnings("unused") - public void setOwnership(String ownership) { - this.ownership = ownership; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/DeviceCountByGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/DeviceCountByGroup.java deleted file mode 100644 index 43076fb0de..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/DeviceCountByGroup.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.bean; - -public class DeviceCountByGroup { - - private String group; - private String displayNameForGroup; - private int deviceCount; - - @SuppressWarnings("unused") - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } - - @SuppressWarnings("unused") - public String getDisplayNameForGroup() { - return displayNameForGroup; - } - - public void setDisplayNameForGroup(String displayNameForGroup) { - this.displayNameForGroup = displayNameForGroup; - } - - @SuppressWarnings("unused") - public int getDeviceCount() { - return deviceCount; - } - - public void setDeviceCount(int deviceCount) { - this.deviceCount = deviceCount; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/DeviceWithDetails.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/DeviceWithDetails.java deleted file mode 100644 index becadff9c9..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/DeviceWithDetails.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.bean; - -public class DeviceWithDetails { - - private int deviceId; - private String deviceIdentification; - private String platform; - private String ownershipType; - private String connectivityStatus; - - @SuppressWarnings("unused") - public int getDeviceId() { - return deviceId; - } - - public void setDeviceId(int deviceId) { - this.deviceId = deviceId; - } - - @SuppressWarnings("unused") - public String getDeviceIdentification() { - return deviceIdentification; - } - - public void setDeviceIdentification(String deviceIdentification) { - this.deviceIdentification = deviceIdentification; - } - - @SuppressWarnings("unused") - public String getPlatform() { - return platform; - } - - public void setPlatform(String platform) { - this.platform = platform; - } - - @SuppressWarnings("unused") - public String getOwnershipType() { - return ownershipType; - } - - public void setOwnershipType(String ownershipType) { - this.ownershipType = ownershipType; - } - - @SuppressWarnings("unused") - public String getConnectivityStatus() { - return connectivityStatus; - } - - public void setConnectivityStatus(String connectivityStatus) { - this.connectivityStatus = connectivityStatus; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/ExtendedFilterSet.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/ExtendedFilterSet.java deleted file mode 100644 index b68a441a90..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/bean/ExtendedFilterSet.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.bean; - -public class ExtendedFilterSet extends BasicFilterSet { - - /* - * Following property is an abstract filter, introduced @ service layer, - * wrapping few (actual) low level database properties. - */ - private String potentialVulnerability; - - public String getPotentialVulnerability() { - return potentialVulnerability; - } - - public void setPotentialVulnerability(String potentialVulnerability) { - this.potentialVulnerability = potentialVulnerability; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java deleted file mode 100644 index 4cad3f2201..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java +++ /dev/null @@ -1,807 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.InvalidFeatureCodeValueException; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.InvalidPotentialVulnerabilityValueException; -import org.wso2.carbon.device.mgt.analytics.dashboard.util.APIUtil; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static org.wso2.carbon.device.mgt.analytics.dashboard.util.APIUtil.getAuthenticatedUser; -import static org.wso2.carbon.device.mgt.analytics.dashboard.util.APIUtil.getAuthenticatedUserTenantDomainId; - -public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceDAO { - - private static final Log log = LogFactory.getLog(AbstractGadgetDataServiceDAO.class); - @Override - public DeviceCountByGroup getTotalDeviceCount(String userName) throws SQLException { - int totalDeviceCount; - try { - totalDeviceCount = this.getFilteredDeviceCount(null, userName); - } catch (InvalidPotentialVulnerabilityValueException e) { - throw new AssertionError(e); - } - DeviceCountByGroup deviceCountByGroup = new DeviceCountByGroup(); - deviceCountByGroup.setGroup("total"); - deviceCountByGroup.setDisplayNameForGroup("Total"); - deviceCountByGroup.setDeviceCount(totalDeviceCount); - return deviceCountByGroup; - } - - @Override - public DeviceCountByGroup getDeviceCount(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException { - int filteredDeviceCount = this.getFilteredDeviceCount(extendedFilterSet, userName); - DeviceCountByGroup deviceCountByGroup = new DeviceCountByGroup(); - deviceCountByGroup.setGroup("filtered"); - deviceCountByGroup.setDisplayNameForGroup("Filtered"); - deviceCountByGroup.setDeviceCount(filteredDeviceCount); - return deviceCountByGroup; - } - - private int getFilteredDeviceCount(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException { - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - int filteredDeviceCount = 0; - try { - String sql; - con = this.getConnection(); - if (APIUtil.isDeviceAdminUser()) { - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO WHERE TENANT_ID = ?"; - } else { - sql = "SELECT COUNT(POLICY__INFO.DEVICE_ID) AS DEVICE_COUNT FROM " - + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO INNER JOIN" + - " DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID AND " + - " POLICY__INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? "; - } - // appending filters to support advanced filtering options - // [1] appending filter columns - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - sql = sql + " AND POLICY__INFO." + column + " = ? "; - } - } - // [2] appending filter column values, if exist - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - int index = 2; - if (!APIUtil.isDeviceAdminUser()) { - stmt.setString(2, userName); - index = 3; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - filteredDeviceCount = rs.getInt("DEVICE_COUNT"); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDeviceCount; - } - - @Override - public DeviceCountByGroup getFeatureNonCompliantDeviceCount(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - int filteredDeviceCount = 0; - try { - String sql; - con = this.getConnection(); - if (APIUtil.isDeviceAdminUser()) { - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO WHERE TENANT_ID =" + - " ? AND FEATURE_CODE = ?"; - } else { - sql = "SELECT COUNT(FEATURE_INFO.DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID AND " + - "FEATURE_INFO.TENANT_ID = ? AND FEATURE_INFO.FEATURE_CODE = ? AND ENR_DB.OWNER = ? "; - } - // appending filters to support advanced filtering options - // [1] appending filter columns - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - sql = sql + " AND FEATURE_INFO." + column + " = ?"; - } - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - int index = 3; - if (!APIUtil.isDeviceAdminUser()) { - stmt.setString(3, userName); - index = 4; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - filteredDeviceCount = rs.getInt("DEVICE_COUNT"); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - - DeviceCountByGroup deviceCountByGroup = new DeviceCountByGroup(); - deviceCountByGroup.setGroup("feature-non-compliant-and-filtered"); - deviceCountByGroup.setDisplayNameForGroup("Feature-non-compliant-and-filtered"); - deviceCountByGroup.setDeviceCount(filteredDeviceCount); - - return deviceCountByGroup; - } - - @Override - public List getDeviceCountsByConnectivityStatuses(String userName) throws SQLException { - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List deviceCountsByConnectivityStatuses = new ArrayList<>(); - try { - String sql; - con = this.getConnection(); - if (APIUtil.isDeviceAdminUser()) { - sql = "SELECT CONNECTIVITY_STATUS, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + - " WHERE TENANT_ID = ? GROUP BY CONNECTIVITY_STATUS"; - } else { - sql = "SELECT POLICY__INFO.CONNECTIVITY_STATUS AS CONNECTIVITY_STATUS, " + - "COUNT(POLICY__INFO.DEVICE_ID) AS DEVICE_COUNT FROM " - + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO " + - "INNER JOIN DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID " + - " AND POLICY__INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? GROUP BY POLICY__INFO.CONNECTIVITY_STATUS"; - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup deviceCountByConnectivityStatus; - while (rs.next()) { - deviceCountByConnectivityStatus = new DeviceCountByGroup(); - deviceCountByConnectivityStatus.setGroup(rs.getString("CONNECTIVITY_STATUS")); - deviceCountByConnectivityStatus.setDisplayNameForGroup(rs.getString("CONNECTIVITY_STATUS")); - deviceCountByConnectivityStatus.setDeviceCount(rs.getInt("DEVICE_COUNT")); - deviceCountsByConnectivityStatuses.add(deviceCountByConnectivityStatus); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return deviceCountsByConnectivityStatuses; - } - - @Override - public List getDeviceCountsByPotentialVulnerabilities(String userName) throws SQLException { - // getting non-compliant device count - DeviceCountByGroup nonCompliantDeviceCount = new DeviceCountByGroup(); - nonCompliantDeviceCount.setGroup(GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT); - nonCompliantDeviceCount.setDisplayNameForGroup("Non-compliant"); - nonCompliantDeviceCount.setDeviceCount(getNonCompliantDeviceCount()); - - // getting unmonitored device count - DeviceCountByGroup unmonitoredDeviceCount = new DeviceCountByGroup(); - unmonitoredDeviceCount.setGroup(GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED); - unmonitoredDeviceCount.setDisplayNameForGroup("Unmonitored"); - unmonitoredDeviceCount.setDeviceCount(getUnmonitoredDeviceCount()); - - List deviceCountsByPotentialVulnerabilities = new ArrayList<>(); - deviceCountsByPotentialVulnerabilities.add(nonCompliantDeviceCount); - deviceCountsByPotentialVulnerabilities.add(unmonitoredDeviceCount); - - return deviceCountsByPotentialVulnerabilities; - } - - private int getNonCompliantDeviceCount() throws SQLException { - ExtendedFilterSet extendedFilterSet = new ExtendedFilterSet(); - extendedFilterSet.setPotentialVulnerability(GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT); - try { - String userName = getAuthenticatedUser(); - return this.getFilteredDeviceCount(extendedFilterSet, userName); - } catch (InvalidPotentialVulnerabilityValueException e) { - throw new AssertionError(e); - } - } - - private int getUnmonitoredDeviceCount() throws SQLException { - ExtendedFilterSet extendedFilterSet = new ExtendedFilterSet(); - extendedFilterSet.setPotentialVulnerability(GadgetDataServiceDAOConstants. - PotentialVulnerability.UNMONITORED); - try { - String userName = getAuthenticatedUser(); - return this.getFilteredDeviceCount(extendedFilterSet, userName); - } catch (InvalidPotentialVulnerabilityValueException e) { - throw new AssertionError(e); - } - } - - @Override - public List getDeviceCountsByPlatforms(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException { - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDeviceCountsByPlatforms = new ArrayList<>(); - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + " AND POLICY__INFO." + column + " = ? "; - } - } - if (APIUtil.isDeviceAdminUser()) { - sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO WHERE TENANT_ID = ? " + advancedSqlFiltering + - " GROUP BY PLATFORM"; - } else { - sql = "SELECT POLICY__INFO.PLATFORM, COUNT(POLICY__INFO.DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID AND " + - "POLICY__INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? " + advancedSqlFiltering + " GROUP BY " + - "POLICY__INFO.PLATFORM"; - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - int index = 2; - if (!APIUtil.isDeviceAdminUser()) { - stmt.setString(2, userName); - index = 3; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredDeviceCountByPlatform; - while (rs.next()) { - filteredDeviceCountByPlatform = new DeviceCountByGroup(); - filteredDeviceCountByPlatform.setGroup(rs.getString("PLATFORM")); - filteredDeviceCountByPlatform.setDisplayNameForGroup(rs.getString("PLATFORM").toUpperCase()); - filteredDeviceCountByPlatform.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredDeviceCountsByPlatforms.add(filteredDeviceCountByPlatform); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDeviceCountsByPlatforms; - } - - @Override - public List - getFeatureNonCompliantDeviceCountsByPlatforms(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDeviceCountsByPlatforms = new ArrayList<>(); - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + " AND FEATURE_INFO." + column + " = ? "; - } - } - if (APIUtil.isDeviceAdminUser()) { - sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + - advancedSqlFiltering + " GROUP BY PLATFORM"; - } else { - sql = "SELECT FEATURE_INFO.PLATFORM, COUNT(FEATURE_INFO.DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID " + - " AND FEATURE_INFO.TENANT_ID = ? AND FEATURE_INFO.FEATURE_CODE = ? AND ENR_DB.OWNER = ? " + - advancedSqlFiltering + " GROUP BY FEATURE_INFO.PLATFORM"; - } - - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - int index = 3; - if (!APIUtil.isDeviceAdminUser()) { - stmt.setString(3, userName); - index = 4; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredDeviceCountByPlatform; - while (rs.next()) { - filteredDeviceCountByPlatform = new DeviceCountByGroup(); - filteredDeviceCountByPlatform.setGroup(rs.getString("PLATFORM")); - filteredDeviceCountByPlatform.setDisplayNameForGroup(rs.getString("PLATFORM").toUpperCase()); - filteredDeviceCountByPlatform.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredDeviceCountsByPlatforms.add(filteredDeviceCountByPlatform); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDeviceCountsByPlatforms; - } - - @Override - public List getDeviceCountsByOwnershipTypes(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException { - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDeviceCountsByOwnershipTypes = new ArrayList<>(); - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + " AND POLICY__INFO." + column + " = ? "; - } - } - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO WHERE TENANT_ID = ? " + - advancedSqlFiltering + "GROUP BY OWNERSHIP"; - }else{ - sql = "SELECT POLICY__INFO.OWNERSHIP, COUNT(POLICY__INFO.DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID AND POLICY__INFO.TENANT_ID" + - " = ? AND ENR_DB.OWNER = ? " + advancedSqlFiltering + " GROUP BY POLICY__INFO.OWNERSHIP"; - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - int index = 2; - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - index = 3; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredDeviceCountByOwnershipType; - while (rs.next()) { - filteredDeviceCountByOwnershipType = new DeviceCountByGroup(); - filteredDeviceCountByOwnershipType.setGroup(rs.getString("OWNERSHIP")); - filteredDeviceCountByOwnershipType.setDisplayNameForGroup(rs.getString("OWNERSHIP")); - filteredDeviceCountByOwnershipType.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredDeviceCountsByOwnershipTypes.add(filteredDeviceCountByOwnershipType); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDeviceCountsByOwnershipTypes; - } - - @Override - public List - getFeatureNonCompliantDeviceCountsByOwnershipTypes(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDeviceCountsByOwnershipTypes = new ArrayList<>(); - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + " AND FEATURE_INFO." + column + " = ? "; - } - } - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + - advancedSqlFiltering + "GROUP BY OWNERSHIP"; - }else{ - sql = "SELECT FEATURE_INFO.OWNERSHIP, COUNT(FEATURE_INFO.DEVICE_ID) AS DEVICE_COUNT FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID AND FEATURE_INFO.TENANT_ID " + - "= ? AND FEATURE_INFO.FEATURE_CODE = ? AND ENR_DB.OWNER = ? " + advancedSqlFiltering - + " GROUP BY FEATURE_INFO.OWNERSHIP"; - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - int index = 3; - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(3, userName); - index = 4; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredDeviceCountByOwnershipType; - while (rs.next()) { - filteredDeviceCountByOwnershipType = new DeviceCountByGroup(); - filteredDeviceCountByOwnershipType.setGroup(rs.getString("OWNERSHIP")); - filteredDeviceCountByOwnershipType.setDisplayNameForGroup(rs.getString("OWNERSHIP")); - filteredDeviceCountByOwnershipType.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredDeviceCountsByOwnershipTypes.add(filteredDeviceCountByOwnershipType); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDeviceCountsByOwnershipTypes; - } - - @Override - public List getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException { - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDevicesWithDetails = new ArrayList<>(); - try { - con = this.getConnection(); - String sql; - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO WHERE TENANT_ID = ?"; - }else{ - sql = "SELECT POLICY__INFO.DEVICE_ID, POLICY__INFO.DEVICE_IDENTIFICATION, POLICY__INFO.PLATFORM," + - " POLICY__INFO.OWNERSHIP, POLICY__INFO.CONNECTIVITY_STATUS FROM "+ - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1+" POLICY__INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID AND " + - "POLICY__INFO.TENANT_ID = ? AND ENR_DB.OWNER = ?"; - } - // appending filters to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - sql = sql + " AND POLICY__INFO." + column + " = ?"; - } - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - int index = 2; - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - index = 3; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDevicesWithDetails; - } - - @Override - public List getFeatureNonCompliantDevicesWithDetails(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDevicesWithDetails = new ArrayList<>(); - try { - con = this.getConnection(); - String sql; - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + - " WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; - }else{ - sql = "SELECT FEATURE_INFO.DEVICE_ID, FEATURE_INFO.DEVICE_IDENTIFICATION, FEATURE_INFO.PLATFORM, " + - "FEATURE_INFO.OWNERSHIP, FEATURE_INFO.CONNECTIVITY_STATUS FROM "+ - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2+" FEATURE_INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID AND FEATURE_INFO.TENANT_ID" + - " = ? AND FEATURE_INFO.FEATURE_CODE = ? AND ENR_DB.OWNER = ? "; - } - // appending filters to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - sql = sql + " AND FEATURE_INFO." + column + " = ?"; - } - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - int index = 3; - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(3, userName); - index = 4; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return filteredDevicesWithDetails; - } - - protected Map extractDatabaseFiltersFromBean(BasicFilterSet basicFilterSet) { - if (basicFilterSet == null) { - return null; - } - - Map filters = new LinkedHashMap<>(); - - String connectivityStatus = basicFilterSet.getConnectivityStatus(); - if (connectivityStatus != null && !connectivityStatus.isEmpty()) { - filters.put("CONNECTIVITY_STATUS", connectivityStatus); - } - - String platform = basicFilterSet.getPlatform(); - if (platform != null && !platform.isEmpty()) { - filters.put("PLATFORM", platform); - } - - String ownership = basicFilterSet.getOwnership(); - if (ownership != null && !ownership.isEmpty()) { - filters.put("OWNERSHIP", ownership); - } - - return filters; - } - - protected Map extractDatabaseFiltersFromBean(ExtendedFilterSet extendedFilterSet) - throws InvalidPotentialVulnerabilityValueException { - if (extendedFilterSet == null) { - return null; - } - - Map filters = this.extractDatabaseFiltersFromBean((BasicFilterSet) extendedFilterSet); - - String potentialVulnerability = extendedFilterSet.getPotentialVulnerability(); - if (potentialVulnerability != null && !potentialVulnerability.isEmpty()) { - if (GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT.equals(potentialVulnerability) || - GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED.equals(potentialVulnerability)) { - if (GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT.equals(potentialVulnerability)) { - filters.put("IS_COMPLIANT", 0); - } else { - filters.put("POLICY_ID", -1); - } - } else { - throw new InvalidPotentialVulnerabilityValueException("Invalid use of value for potential " + - "vulnerability. Value of potential vulnerability could only be either " + - GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT + " or " + - GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED + "."); - } - } - - return filters; - } - - protected Connection getConnection() throws SQLException { - return GadgetDataServiceDAOFactory.getConnection(); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java deleted file mode 100644 index 0033f19327..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao; - -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.common.PaginationResult; - -import java.sql.SQLException; -import java.util.List; - -public interface GadgetDataServiceDAO { - - DeviceCountByGroup getDeviceCount(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException; - - DeviceCountByGroup getFeatureNonCompliantDeviceCount(String featureCode, BasicFilterSet basicFilterSet, String userName) - throws InvalidFeatureCodeValueException, SQLException; - - DeviceCountByGroup getTotalDeviceCount(String userName) throws SQLException; - - List getDeviceCountsByConnectivityStatuses(String userName) throws SQLException; - - List getDeviceCountsByPotentialVulnerabilities(String userName) throws SQLException; - - PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) throws - InvalidStartIndexValueException, InvalidResultCountValueException, SQLException; - - List getDeviceCountsByPlatforms(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException; - - List getFeatureNonCompliantDeviceCountsByPlatforms(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException; - - List getDeviceCountsByOwnershipTypes(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException; - - List getFeatureNonCompliantDeviceCountsByOwnershipTypes(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException; - - PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount, String userName) - throws InvalidPotentialVulnerabilityValueException, - InvalidStartIndexValueException, InvalidResultCountValueException, SQLException; - - PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, BasicFilterSet basicFilterSet, - int startIndex, int resultCount, String userName) throws InvalidFeatureCodeValueException, - InvalidStartIndexValueException, InvalidResultCountValueException, SQLException; - - List getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, SQLException; - - List getFeatureNonCompliantDevicesWithDetails(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, SQLException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java deleted file mode 100644 index cd770b9651..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOConstants.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao; - -public final class GadgetDataServiceDAOConstants { - - public static class DatabaseView { - - public static final String DEVICES_VIEW_1 = "POLICY_COMPLIANCE_INFO"; - public static final String DEVICES_VIEW_2 = "FEATURE_NON_COMPLIANCE_INFO"; - - private DatabaseView() { - throw new AssertionError(); - } - - } - - public static class Pagination { - - // Minimum acceptable values for start index and result count - public static final int MIN_START_INDEX = 0; - public static final int MIN_RESULT_COUNT = 5; - - private Pagination() { - throw new AssertionError(); - } - - } - - public static class PotentialVulnerability { - - // These constants do not hold actual database values - // These are just abstract values defined and used @ Gadget Data Service DAO Implementation layer - public static final String NON_COMPLIANT = "NON_COMPLIANT"; - public static final String UNMONITORED = "UNMONITORED"; - - private PotentialVulnerability() { - throw new AssertionError(); - } - - } - - private GadgetDataServiceDAOConstants() { throw new AssertionError(); } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java deleted file mode 100644 index d202b685c1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.GenericGadgetDataServiceDAOImpl; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.MSSQLGadgetDataServiceDAOImpl; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.OracleGadgetDataServiceDAOImpl; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.PostgreSQLGadgetDataServiceDAOImpl; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; -import org.wso2.carbon.device.mgt.common.UnsupportedDatabaseEngineException; -import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; -import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Hashtable; -import java.util.List; - -@SuppressWarnings("unused") -public class GadgetDataServiceDAOFactory { - - private static final Log log = LogFactory.getLog(GadgetDataServiceDAOFactory.class); - private static DataSource dataSource; - private static String databaseEngine; - private static ThreadLocal currentConnection = new ThreadLocal<>(); - - public static GadgetDataServiceDAO getGadgetDataServiceDAO() { - if (databaseEngine != null) { - switch (databaseEngine) { - case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: - return new GenericGadgetDataServiceDAOImpl(); - case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: - return new GenericGadgetDataServiceDAOImpl(); - case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: - return new MSSQLGadgetDataServiceDAOImpl(); - case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: - return new PostgreSQLGadgetDataServiceDAOImpl(); - case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: - return new OracleGadgetDataServiceDAOImpl(); - default: - throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); - } - } - throw new IllegalStateException("Database engine has not initialized properly."); - } - - public static void init(DataSourceConfig config) { - dataSource = resolveDataSource(config); - try { - databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); - } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection.", e); - } - } - - public static void init(DataSource dtSource) { - dataSource = dtSource; - try { - databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); - } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection.", e); - } - } - - public static void openConnection() throws SQLException { - Connection conn = currentConnection.get(); - if (conn != null) { - throw new IllegalTransactionStateException("A transaction is already active within the context of " + - "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + - "transaction is already active is a sign of improper transaction handling."); - } - conn = dataSource.getConnection(); - currentConnection.set(conn); - } - - public static Connection getConnection() throws SQLException { - Connection conn = currentConnection.get(); - if (conn == null) { - throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + - "This might have ideally been caused by not properly initiating the transaction via " + - "'beginTransaction'/'openConnection' methods."); - } - return conn; - } - - public static void closeConnection() { - Connection conn = currentConnection.get(); - if (conn == null) { - throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + - "This might have ideally been caused by not properly initiating the transaction via " + - "'beginTransaction'/'openConnection' methods."); - } - try { - conn.close(); - } catch (SQLException e) { - log.warn("Error occurred while close the connection."); - } - currentConnection.remove(); - } - - - /** - * Resolve data source from the data source definition. - * - * @param config data source configuration. - * @return data source resolved from the data source definition. - */ - private static DataSource resolveDataSource(DataSourceConfig config) { - DataSource dataSource = null; - if (config == null) { - throw new RuntimeException( - "Device Management Repository data source configuration is null and " + - "thus, is not initialized."); - } - JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); - if (jndiConfig != null) { - if (log.isDebugEnabled()) { - log.debug("Initializing Device Management Repository data source using the JNDI Lookup Definition."); - } - List jndiPropertyList = jndiConfig.getJndiProperties(); - if (jndiPropertyList != null) { - Hashtable jndiProperties = new Hashtable<>(); - for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { - jndiProperties.put(prop.getName(), prop.getValue()); - } - dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); - } else { - dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null); - } - } - return dataSource; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java deleted file mode 100644 index 68defcc788..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOConstants; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.analytics.dashboard.util.APIUtil; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static org.wso2.carbon.device.mgt.analytics.dashboard.util.APIUtil.getAuthenticatedUserTenantDomainId; - -public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO { - - private static final Log log = LogFactory.getLog(GenericGadgetDataServiceDAOImpl.class); - - @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) - throws InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>(); - int totalRecordsCount = 0; - try { - String sql; - con = this.getConnection(); - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? GROUP BY FEATURE_CODE " + - "ORDER BY DEVICE_COUNT DESC LIMIT ?, ?"; - }else{ - sql = "SELECT FEATURE_INFO.FEATURE_CODE, COUNT(FEATURE_INFO.DEVICE_ID) AS DEVICE_COUNT " + - "FROM "+GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2+" FEATURE_INFO INNER JOIN " + - "DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID AND " + - "FEATURE_INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? GROUP BY FEATURE_INFO.FEATURE_CODE ORDER BY" + - " DEVICE_COUNT DESC LIMIT ?, ?"; - } - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - stmt.setInt(3, startIndex); - stmt.setInt(4, resultCount); - }else{ - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredNonCompliantDeviceCountByFeature; - while (rs.next()) { - filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroup(); - filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature); - } - // fetching total records count - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM (SELECT DISTINCT FEATURE_CODE FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ?) " + - "NON_COMPLIANT_FEATURE_CODE"; - }else{ - sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM (SELECT DISTINCT " + - "FEATURE_INFO.FEATURE_CODE FROM "+GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 - +" FEATURE_INFO INNER JOIN DM_ENROLMENT ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID " + - "AND FEATURE_INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? ) NON_COMPLIANT_FEATURE_CODE"; - } - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, - int resultCount, String userName) throws InvalidPotentialVulnerabilityValueException, - InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + " AND POLICY__INFO." + column + " = ? "; - } - } - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO WHERE TENANT_ID = ? " + - advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; - }else{ - sql = "SELECT POLICY__INFO.DEVICE_ID, POLICY__INFO.DEVICE_IDENTIFICATION, POLICY__INFO.PLATFORM, " + - "POLICY__INFO.OWNERSHIP, POLICY__INFO.CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " POLICY__INFO INNER JOIN DM_ENROLMENT " + - "ENR_DB ON ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID AND " + - "POLICY__INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? " + advancedSqlFiltering + " ORDER BY " + - "POLICY__INFO.DEVICE_ID ASC LIMIT ?,?"; - } - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - int index = 2; - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - index = 3; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(3, startIndex); - stmt.setInt(4, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ?"; - }else{ - sql = "SELECT COUNT(POLICY__INFO.DEVICE_ID) AS DEVICE_COUNT FROM "+GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1+" POLICY__INFO INNER JOIN DM_ENROLMENT ENR_DB ON " + - "ENR_DB.DEVICE_ID = POLICY__INFO.DEVICE_ID AND POLICY__INFO.TENANT_ID = ? AND ENR_DB.OWNER = ? "; - } - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(2, userName); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, - BasicFilterSet basicFilterSet, int startIndex, int resultCount, String userName) - throws InvalidFeatureCodeValueException, InvalidStartIndexValueException, - InvalidResultCountValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = getAuthenticatedUserTenantDomainId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND FEATURE_INFO." + column + " = ? "; - } - } - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + - " FEATURE_INFO WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + - "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; - }else{ - sql = "SELECT FEATURE_INFO.DEVICE_ID, FEATURE_INFO.DEVICE_IDENTIFICATION, FEATURE_INFO.PLATFORM, " + - "FEATURE_INFO.OWNERSHIP, FEATURE_INFO.CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO INNER JOIN DM_ENROLMENT " + - "ENR_DB ON ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID " + - " AND FEATURE_INFO.TENANT_ID = ? AND FEATURE_INFO.FEATURE_CODE = ? AND ENR_DB.OWNER = ? " + - advancedSqlFiltering + " ORDER BY DEVICE_ID ASC LIMIT ?,?"; - } - - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - int index = 3; - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(3, userName); - index = 4; - } - if (filters != null && filters.values().size() > 0) { - int i = index; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(index, startIndex); - stmt.setInt(++index, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - if(APIUtil.isDeviceAdminUser()){ - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; - }else{ - sql = "SELECT COUNT(FEATURE_INFO.DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " FEATURE_INFO INNER JOIN DM_ENROLMENT ENR_DB ON " + - "ENR_DB.DEVICE_ID = FEATURE_INFO.DEVICE_ID AND FEATURE_INFO.TENANT_ID = ? AND " + - "FEATURE_INFO.FEATURE_CODE = ? AND ENR_DB.OWNER = ? "; - } - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - if(!APIUtil.isDeviceAdminUser()){ - stmt.setString(3, userName); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while checking device access authorization"; - log.error(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java deleted file mode 100644 index 23374a3fc2..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl; - -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOConstants; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class MSSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO { - - @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) - throws InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC " + - "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredNonCompliantDeviceCountByFeature; - while (rs.next()) { - filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroup(); - filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature); - } - // fetching total records count - sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " + - "(SELECT DISTINCT FEATURE_CODE FROM " + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + - " WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount, String userName) - throws InvalidPotentialVulnerabilityValueException, - InvalidStartIndexValueException, - InvalidResultCountValueException, - SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; - } - } - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ? " + - advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - if (filters != null && filters.values().size() > 0) { - int i = 2; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - - // fetching total records count - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, - BasicFilterSet basicFilterSet, int startIndex, int resultCount, String userName) - throws InvalidFeatureCodeValueException, InvalidStartIndexValueException, - InvalidResultCountValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; - } - } - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + - advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - if (filters != null && filters.values().size() > 0) { - int i = 3; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(3, startIndex); - stmt.setInt(4, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - - // fetching total records count - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java deleted file mode 100644 index 4d58e508e7..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl; - -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOConstants; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO { - - @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) - throws InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 - + " WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC " - + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredNonCompliantDeviceCountByFeature; - while (rs.next()) { - filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroup(); - filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature); - } - // fetching total records count - sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " + - "(SELECT DISTINCT FEATURE_CODE FROM " + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + - " WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount, String userName) - throws InvalidPotentialVulnerabilityValueException, InvalidStartIndexValueException, - InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; - } - } - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " - + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ? " - + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - if (filters != null && filters.values().size() > 0) { - int i = 2; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - - // fetching total records count - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, BasicFilterSet basicFilterSet, - int startIndex, int resultCount, String userName) throws InvalidFeatureCodeValueException, - InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; - } - } - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + - advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - if (filters != null && filters.values().size() > 0) { - int i = 3; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(3, startIndex); - stmt.setInt(4, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - - // fetching total records count - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java deleted file mode 100644 index 5f859ec8b2..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl; - -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOConstants; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class PostgreSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO { - - @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) - throws InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? GROUP BY FEATURE_CODE " + - "ORDER BY DEVICE_COUNT DESC OFFSET ? LIMIT ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceCountByGroup filteredNonCompliantDeviceCountByFeature; - while (rs.next()) { - filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroup(); - filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE")); - filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT")); - filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature); - } - // fetching total records count - sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " + - "(SELECT DISTINCT FEATURE_CODE FROM " + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + - " WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount, String userName) - throws InvalidPotentialVulnerabilityValueException, InvalidStartIndexValueException, - InvalidResultCountValueException, SQLException { - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; - } - } - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ? " + - advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?"; - - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - if (filters != null && filters.values().size() > 0) { - int i = 2; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(2, startIndex); - stmt.setInt(3, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - - // fetching total records count - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - - @Override - public PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, BasicFilterSet basicFilterSet, - int startIndex, int resultCount, String userName) throws InvalidFeatureCodeValueException, - InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { - - if (featureCode == null || featureCode.isEmpty()) { - throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); - } - - if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { - throw new InvalidStartIndexValueException("Start index should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); - } - - if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { - throw new InvalidResultCountValueException("Result count should be equal to " + - GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); - } - - Map filters = this.extractDatabaseFiltersFromBean(basicFilterSet); - - Connection con; - PreparedStatement stmt = null; - ResultSet rs = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List filteredDevicesWithDetails = new ArrayList<>(); - int totalRecordsCount = 0; - try { - con = this.getConnection(); - String sql, advancedSqlFiltering = ""; - // appending filters if exist, to support advanced filtering options - // [1] appending filter columns, if exist - if (filters != null && filters.size() > 0) { - for (String column : filters.keySet()) { - advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; - } - } - sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + - GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + - advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?"; - - stmt = con.prepareStatement(sql); - // [2] appending filter column values, if exist - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - if (filters != null && filters.values().size() > 0) { - int i = 3; - for (Object value : filters.values()) { - if (value instanceof Integer) { - stmt.setInt(i, (Integer) value); - } else if (value instanceof String) { - stmt.setString(i, (String) value); - } - i++; - } - stmt.setInt(i, startIndex); - stmt.setInt(++i, resultCount); - } else { - stmt.setInt(3, startIndex); - stmt.setInt(4, resultCount); - } - // executing query - rs = stmt.executeQuery(); - // fetching query results - DeviceWithDetails filteredDeviceWithDetails; - while (rs.next()) { - filteredDeviceWithDetails = new DeviceWithDetails(); - filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); - filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); - filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); - filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); - filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); - filteredDevicesWithDetails.add(filteredDeviceWithDetails); - } - - // fetching total records count - sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. - DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; - - stmt = con.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, featureCode); - - // executing query - rs = stmt.executeQuery(); - // fetching query results - while (rs.next()) { - totalRecordsCount = rs.getInt("DEVICE_COUNT"); - } - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setData(filteredDevicesWithDetails); - paginationResult.setRecordsTotal(totalRecordsCount); - return paginationResult; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/DataAccessLayerException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/DataAccessLayerException.java deleted file mode 100644 index 69bd5a9f6a..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/DataAccessLayerException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.exception; - -/** - * Custom exception class for communicating data access layer issues - * relevant to Gadget Data Service DAO layer. - * (In this particular instance, SQL exceptions related to database access). - */ -public class DataAccessLayerException extends Exception { - - private String errorMessage; - private static final long serialVersionUID = 2021891706072918864L; - - /** - * Constructs a new exception with the specific error message and nested exception. - * @param errorMessage specific error message. - * @param nestedException Nested exception. - */ - @SuppressWarnings("unused") - public DataAccessLayerException(String errorMessage, Exception nestedException) { - super(errorMessage, nestedException); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param errorMessage Specific error message. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public DataAccessLayerException(String errorMessage, Throwable cause) { - super(errorMessage, cause); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message. - * @param errorMessage Specific error message. - */ - public DataAccessLayerException(String errorMessage) { - super(errorMessage); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public DataAccessLayerException(Throwable cause) { - super(cause); - } - - @SuppressWarnings("unused") - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidFeatureCodeValueException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidFeatureCodeValueException.java deleted file mode 100644 index 0ba644a611..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidFeatureCodeValueException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.exception; - -/** - * Custom exception class for catching invalid parameter values, - * relevant to Gadget Data Service DAO layer. - */ -public class InvalidFeatureCodeValueException extends Exception { - - private String errorMessage; - private static final long serialVersionUID = 2021891706072918864L; - - /** - * Constructs a new exception with the specific error message and nested exception. - * @param errorMessage specific error message. - * @param nestedException Nested exception. - */ - @SuppressWarnings("unused") - public InvalidFeatureCodeValueException(String errorMessage, Exception nestedException) { - super(errorMessage, nestedException); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param errorMessage Specific error message. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidFeatureCodeValueException(String errorMessage, Throwable cause) { - super(errorMessage, cause); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message. - * @param errorMessage Specific error message. - */ - public InvalidFeatureCodeValueException(String errorMessage) { - super(errorMessage); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidFeatureCodeValueException(Throwable cause) { - super(cause); - } - - @SuppressWarnings("unused") - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidPotentialVulnerabilityValueException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidPotentialVulnerabilityValueException.java deleted file mode 100644 index a31b68f8fa..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidPotentialVulnerabilityValueException.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.exception; - -/** - * Custom exception class for catching invalid parameter values, - * relevant to Gadget Data Service DAO layer. - */ -public class InvalidPotentialVulnerabilityValueException extends Exception { - - private String errorMessage; - private static final long serialVersionUID = 2021891706072918864L; - - /** - * Constructs a new exception with the specific error message and nested exception. - * @param errorMessage specific error message. - * @param nestedException Nested exception. - */ - @SuppressWarnings("unused") - public InvalidPotentialVulnerabilityValueException(String errorMessage, Exception nestedException) { - super(errorMessage, nestedException); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param errorMessage Specific error message. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidPotentialVulnerabilityValueException(String errorMessage, Throwable cause) { - super(errorMessage, cause); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message. - * @param errorMessage Specific error message. - */ - public InvalidPotentialVulnerabilityValueException(String errorMessage) { - super(errorMessage); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidPotentialVulnerabilityValueException(Throwable cause) { - super(cause); - } - - @SuppressWarnings("unused") - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidResultCountValueException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidResultCountValueException.java deleted file mode 100644 index 9d20a6971d..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidResultCountValueException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.exception; - -/** - * Custom exception class for catching invalid parameter values, - * relevant to Gadget Data Service DAO layer. - */ -public class InvalidResultCountValueException extends Exception { - - private String errorMessage; - private static final long serialVersionUID = 2021891706072918864L; - - /** - * Constructs a new exception with the specific error message and nested exception. - * @param errorMessage specific error message. - * @param nestedException Nested exception. - */ - @SuppressWarnings("unused") - public InvalidResultCountValueException(String errorMessage, Exception nestedException) { - super(errorMessage, nestedException); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param errorMessage Specific error message. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidResultCountValueException(String errorMessage, Throwable cause) { - super(errorMessage, cause); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message. - * @param errorMessage Specific error message. - */ - public InvalidResultCountValueException(String errorMessage) { - super(errorMessage); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidResultCountValueException(Throwable cause) { - super(cause); - } - - @SuppressWarnings("unused") - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidStartIndexValueException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidStartIndexValueException.java deleted file mode 100644 index 39370c0ab1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/exception/InvalidStartIndexValueException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.exception; - -/** - * Custom exception class for catching invalid parameter values, - * relevant to Gadget Data Service DAO layer. - */ -public class InvalidStartIndexValueException extends Exception { - - private String errorMessage; - private static final long serialVersionUID = 2021891706072918864L; - - /** - * Constructs a new exception with the specific error message and nested exception. - * @param errorMessage specific error message. - * @param nestedException Nested exception. - */ - @SuppressWarnings("unused") - public InvalidStartIndexValueException(String errorMessage, Exception nestedException) { - super(errorMessage, nestedException); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param errorMessage Specific error message. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidStartIndexValueException(String errorMessage, Throwable cause) { - super(errorMessage, cause); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message. - * @param errorMessage Specific error message. - */ - public InvalidStartIndexValueException(String errorMessage) { - super(errorMessage); - setErrorMessage(errorMessage); - } - - /** - * Constructs a new exception with the specific error message and cause. - * @param cause Cause of this exception. - */ - @SuppressWarnings("unused") - public InvalidStartIndexValueException(Throwable cause) { - super(cause); - } - - @SuppressWarnings("unused") - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/impl/GadgetDataServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/impl/GadgetDataServiceImpl.java deleted file mode 100644 index 9a392ab8df..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/impl/GadgetDataServiceImpl.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.impl; - -import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory; -import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; -import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; -import org.wso2.carbon.device.mgt.common.PaginationResult; - -import java.sql.SQLException; -import java.util.List; - -/** - * Implementation class of GadgetDataService. - */ -public class GadgetDataServiceImpl implements GadgetDataService { - - @Override - public DeviceCountByGroup getDeviceCount(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException { - DeviceCountByGroup filteredDeviceCount; - try { - - GadgetDataServiceDAOFactory.openConnection(); - filteredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDeviceCount(extendedFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return filteredDeviceCount; - } - - @Override - public DeviceCountByGroup getFeatureNonCompliantDeviceCount(String featureCode, BasicFilterSet basicFilterSet, String userName) - throws InvalidFeatureCodeValueException, DataAccessLayerException { - DeviceCountByGroup featureNonCompliantDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(featureCode, basicFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDeviceCount; - } - - @Override - public DeviceCountByGroup getTotalDeviceCount(String userName) throws DataAccessLayerException { - DeviceCountByGroup totalDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount(userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return totalDeviceCount; - } - - @Override - public List getDeviceCountsByConnectivityStatuses(String userName) throws DataAccessLayerException { - List deviceCountsByConnectivityStatuses; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByConnectivityStatuses = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getDeviceCountsByConnectivityStatuses(userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCountsByConnectivityStatuses; - } - - @Override - public List getDeviceCountsByPotentialVulnerabilities(String userName) throws DataAccessLayerException { - List deviceCountsByPotentialVulnerabilities; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByPotentialVulnerabilities = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDeviceCountsByPotentialVulnerabilities(userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCountsByPotentialVulnerabilities; - } - - @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount, String userName) - throws InvalidStartIndexValueException, InvalidResultCountValueException, - DataAccessLayerException { - PaginationResult paginationResult; - try { - GadgetDataServiceDAOFactory.openConnection(); - paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getNonCompliantDeviceCountsByFeatures(startIndex, resultCount, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return paginationResult; - } - - @Override - public List getDeviceCountsByPlatforms(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException { - List deviceCountsByPlatforms; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDeviceCountsByPlatforms(extendedFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCountsByPlatforms; - } - - @Override - public List getFeatureNonCompliantDeviceCountsByPlatforms(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException { - List featureNonCompliantDeviceCountsByPlatforms; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDeviceCountsByPlatforms(featureCode, basicFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDeviceCountsByPlatforms; - } - - @Override - public List getDeviceCountsByOwnershipTypes(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, - DataAccessLayerException { - List deviceCountsByOwnershipTypes; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDeviceCountsByOwnershipTypes(extendedFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCountsByOwnershipTypes; - } - - @Override - public List - getFeatureNonCompliantDeviceCountsByOwnershipTypes(String featureCode, BasicFilterSet basicFilterSet, String userName) - throws InvalidFeatureCodeValueException, DataAccessLayerException { - List featureNonCompliantDeviceCountsByOwnershipTypes; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDeviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDeviceCountsByOwnershipTypes(featureCode, basicFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDeviceCountsByOwnershipTypes; - } - - @Override - public PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException, - InvalidStartIndexValueException, InvalidResultCountValueException { - PaginationResult paginationResult; - try { - GadgetDataServiceDAOFactory.openConnection(); - paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDevicesWithDetails(extendedFilterSet, startIndex, resultCount, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return paginationResult; - } - - @Override - public PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, BasicFilterSet basicFilterSet, - int startIndex, int resultCount, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException, InvalidStartIndexValueException, - InvalidResultCountValueException { - PaginationResult paginationResult; - try { - GadgetDataServiceDAOFactory.openConnection(); - paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDevicesWithDetails(featureCode, basicFilterSet, startIndex, resultCount, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return paginationResult; - } - - @Override - public List getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, String userName) - throws InvalidPotentialVulnerabilityValueException, DataAccessLayerException { - List devicesWithDetails; - try { - GadgetDataServiceDAOFactory.openConnection(); - devicesWithDetails = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getDevicesWithDetails(extendedFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return devicesWithDetails; - } - - @Override - public List getFeatureNonCompliantDevicesWithDetails(String featureCode, - BasicFilterSet basicFilterSet, String userName) throws InvalidFeatureCodeValueException, - DataAccessLayerException { - List featureNonCompliantDevicesWithDetails; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDevicesWithDetails(featureCode, basicFilterSet, userName); - } catch (SQLException e) { - throw new DataAccessLayerException("Error in either opening a database connection or " + - "accessing the database to fetch corresponding results.", e); - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDevicesWithDetails; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java deleted file mode 100644 index 5dda71d849..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory; -import org.wso2.carbon.device.mgt.analytics.dashboard.impl.GadgetDataServiceImpl; -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.datasource.DataSourceConfig; -import org.wso2.carbon.ndatasource.core.DataSourceService; - -@SuppressWarnings("unused") -/** - * @scr.component name="org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService" immediate="true" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - */ -public class GadgetDataServiceComponent { - - private static final Log log = LogFactory.getLog(GadgetDataServiceComponent.class); - - protected void activate(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("Starting Device Management Dashboard Analytics Bundle..."); - } - try { - DeviceConfigurationManager.getInstance().initConfig(); - DeviceManagementConfig config = - DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); - - DataSourceConfig dsConfig = config.getDeviceManagementConfigRepository().getDataSourceConfig(); - GadgetDataServiceDAOFactory.init(dsConfig); - //Register GadgetDataService to expose corresponding data to external parties. - componentContext.getBundleContext(). - registerService(GadgetDataService.class.getName(), new GadgetDataServiceImpl(), null); - if (log.isDebugEnabled()) { - log.debug("Device Management Dashboard Analytics Bundle has been started successfully."); - } - } catch (Throwable e) { - log.error("Error occurred while initializing the bundle.", e); - } - } - - protected void deactivate(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("Deactivating Device Management Dashboard Analytics Bundle..."); - } - //do nothing - } - - protected void setDataSourceService(DataSourceService dataSourceService) { - if (log.isDebugEnabled()) { - log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService..."); - } - //do nothing - } - - protected void unsetDataSourceService(DataSourceService dataSourceService) { - if (log.isDebugEnabled()) { - log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService..."); - } - //do nothing - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/util/APIUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/util/APIUtil.java deleted file mode 100644 index e9635e5d58..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/util/APIUtil.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -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.service.DeviceManagementProviderService; -import org.wso2.carbon.user.api.UserStoreException; - -import java.net.SocketException; - - -/** - * This class provides utility functions used by REST-API. - */ -public class APIUtil { - - private static Log log = LogFactory.getLog(APIUtil.class); - - public static String getAuthenticatedUser() { - PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - String username = threadLocalCarbonContext.getUsername(); - String tenantDomain = threadLocalCarbonContext.getTenantDomain(); - if (username.endsWith(tenantDomain)) { - return username.substring(0, username.lastIndexOf("@")); - } - return username; - } - - public static int getAuthenticatedUserTenantDomainId() { - PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - return threadLocalCarbonContext.getTenantId(); - } - - public static boolean isDeviceAdminUser() throws DeviceAccessAuthorizationException { - return getDeviceAccessAuthorizationService().isDeviceAdminUser(); - } - - private static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceAccessAuthorizationService deviceAccessAuthorizationService = - (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null); - if (deviceAccessAuthorizationService == null) { - String msg = "DeviceAccessAuthorization service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return deviceAccessAuthorizationService; - } -} 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 fb5e95c2db..b9eefdfc8e 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml @@ -75,16 +75,12 @@ org.wso2.carbon.databridge.commons - org.wso2.carbon.registry - org.wso2.carbon.registry.indexing - - - org.wso2.carbon.registry - org.wso2.carbon.registry.common + org.wso2.carbon + org.wso2.carbon.securevault - org.json.wso2 - json + org.apache.sling + org.apache.sling.testing.osgi-mock @@ -118,9 +114,6 @@ org.wso2.carbon.context;version="${carbon.kernel.version.range}", org.wso2.carbon.utils;version="${carbon.kernel.version.range}", org.wso2.carbon.databridge.*;version="${carbon.analytics.common.version.range}", - org.wso2.carbon.registry.core.*;resolution:=optional, - org.wso2.carbon.registry.common.*;version="${carbon.registry.imp.pkg.version.range}", - org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", org.json;version="${commons-json.version}", javax.xml.*, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, @@ -157,7 +150,15 @@ - + + org.apache.maven.plugins + maven-surefire-plugin + + + src/test/resources/testng.xml + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java index da430d5fd4..086b04c4a7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherUtil.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.analytics.data.publisher; import org.w3c.dom.Document; +import org.wso2.carbon.databridge.agent.DataPublisher; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import javax.xml.XMLConstants; @@ -28,6 +29,9 @@ import java.io.File; public class DataPublisherUtil { + private DataPublisherUtil(){ + } + public static Document convertToDocument(File file) throws DataPublisherConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java index 537e5b01b4..8753dc2af7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java @@ -18,13 +18,6 @@ */ package org.wso2.carbon.device.mgt.analytics.data.publisher; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONException; -import org.json.JSONObject; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.databridge.agent.DataPublisher; import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; @@ -32,38 +25,16 @@ import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationExcep import org.wso2.carbon.databridge.agent.exception.DataEndpointException; import org.wso2.carbon.databridge.commons.exception.TransportException; import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherAlreadyExistsException; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherDataHolder; -import org.wso2.carbon.registry.core.Registry; -import org.wso2.carbon.registry.core.Resource; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.registry.core.service.TenantRegistryLoader; - -import java.nio.charset.Charset; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** * This is used to manage data publisher per tenant. */ public class DeviceDataPublisher { - private static final Log log = LogFactory.getLog(DeviceDataPublisher.class); - private static final String TENANT_DAS_CONFIG_LOCATION = "/das/config.json"; - private static final String USERNAME_CONFIG_TAG = "username"; - private static final String PASSWORD_CONFIG_TAG = "password"; - /** - * map to store data publishers for each tenant. - */ - private static Map dataPublisherMap; + private DataPublisher dataPublisher; private static DeviceDataPublisher deviceDataPublisher; - public DeviceDataPublisher() { - dataPublisherMap = new ConcurrentHashMap<>(); - } - public static DeviceDataPublisher getInstance() { if (deviceDataPublisher == null) { synchronized (DeviceDataPublisher.class) { @@ -78,144 +49,43 @@ public class DeviceDataPublisher { /** * this return the data publisher for the tenant. * - * @return + * @return instance of data publisher * @throws DataPublisherConfigurationException * */ public DataPublisher getDataPublisher() throws DataPublisherConfigurationException { - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); - //Get LoadBalancingDataPublisher which has been registered for the tenant. - DataPublisher dataPublisher = getDataPublisher(tenantDomain); - //If a LoadBalancingDataPublisher had not been registered for the tenant. - if (dataPublisher == null) { - AnalyticsConfiguration analyticsConfig = AnalyticsConfiguration.getInstance(); - if (!analyticsConfig.isEnable()) { - return null; - } - String analyticsServerUrlGroups = analyticsConfig.getReceiverServerUrl(); - String analyticsServerUsername = analyticsConfig.getAdminUsername(); - String analyticsServerPassword = analyticsConfig.getAdminPassword(); - if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - String userInfo[] = getAnalyticsServerUserInfo(tenantId); - if (userInfo != null) { - analyticsServerUsername = userInfo[0]; - analyticsServerPassword = userInfo[1]; - } - } - //Create new DataPublisher for the tenant. - try { - dataPublisher = new DataPublisher(analyticsServerUrlGroups, analyticsServerUsername, - analyticsServerPassword); - //Add created DataPublisher. - addDataPublisher(tenantDomain, dataPublisher); - } catch (DataEndpointAgentConfigurationException e) { - throw new DataPublisherConfigurationException("Configuration Exception on data publisher for " + - "ReceiverGroup = " + analyticsServerUrlGroups + " for username " + analyticsServerUsername, e); - } catch (DataEndpointException e) { - throw new DataPublisherConfigurationException("Invalid ReceiverGroup = " + analyticsServerUrlGroups, e); - } catch (DataEndpointConfigurationException e) { - throw new DataPublisherConfigurationException("Invalid Data endpoint configuration.", e); - } catch (DataEndpointAuthenticationException e) { - throw new DataPublisherConfigurationException("Authentication Failed for user " + - analyticsServerUsername, e); - } catch (TransportException e) { - throw new DataPublisherConfigurationException("Error occurred while retrieving data publisher", e); - } catch (DataPublisherAlreadyExistsException e) { - log.warn("Attempting to register a data publisher for the tenant " + tenantDomain + - " when one already exists. Returning existing data publisher"); - return getDataPublisher(tenantDomain); - } - } - return dataPublisher; - } - - /** - * Fetch the data publisher which has been registered under the tenant domain. - * - * @param tenantDomain - The tenant domain under which the data publisher is registered - * @return - Instance of the DataPublisher which was registered. Null if not registered. - */ - private DataPublisher getDataPublisher(String tenantDomain) { - if (dataPublisherMap.containsKey(tenantDomain)) { - return dataPublisherMap.get(tenantDomain); - } - return null; - } - - /** - * Adds a LoadBalancingDataPublisher to the data publisher map. - * - * @param tenantDomain - The tenant domain under which the data publisher will be registered. - * @param dataPublisher - Instance of the LoadBalancingDataPublisher - * @throws DataPublisherAlreadyExistsException - * - - * If a data publisher has already been registered under the tenant - * domain - */ - private void addDataPublisher(String tenantDomain, DataPublisher dataPublisher) - throws DataPublisherAlreadyExistsException { - if (dataPublisherMap.containsKey(tenantDomain)) { - throw new DataPublisherAlreadyExistsException( - "A DataPublisher has already been created for the tenant " + tenantDomain); - } - - dataPublisherMap.put(tenantDomain, dataPublisher); - } - - /** - * retrieve the credential from registry - */ - private String[] getAnalyticsServerUserInfo(int tenantId) throws DataPublisherConfigurationException { - try { - String config = getConfigRegistryResourceContent(tenantId, TENANT_DAS_CONFIG_LOCATION); - JSONObject jsonConfigforDas = new JSONObject(config); - String credential[] = new String[2]; - credential[0] = jsonConfigforDas.getString(USERNAME_CONFIG_TAG); - credential[1] = jsonConfigforDas.getString(PASSWORD_CONFIG_TAG); - return credential; - } catch (RegistryException e) { - throw new DataPublisherConfigurationException("Failed to load the registry for tenant " + tenantId, e); - } catch (JSONException e) { - throw new DataPublisherConfigurationException( - "Failed to parse the credential from the registry for tenant " + tenantId, e); - } - } - - /** - * get the credential detail from the registry for tenants. - * - * @param tenantId for identify tenant space. - * @param registryLocation retrieve the config file from tenant space. - * @return the config for tenant - * @throws RegistryException - */ - private String getConfigRegistryResourceContent(int tenantId, final String registryLocation) - throws RegistryException { - String content = null; - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); - RegistryService registryService = DataPublisherDataHolder.getInstance().getRegistryService(); - if (registryService != null) { - Registry registry = registryService.getConfigSystemRegistry(tenantId); - this.loadTenantRegistry(tenantId); - if (registry.resourceExists(registryLocation)) { - Resource resource = registry.get(registryLocation); - content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); + if (this.dataPublisher == null) { + synchronized (this) { + if (this.dataPublisher == null) { + AnalyticsConfiguration analyticsConfig = AnalyticsConfiguration.getInstance(); + if (!analyticsConfig.isEnable()) { + return null; + } + String analyticsServerUrlGroups = analyticsConfig.getReceiverServerUrl(); + String analyticsServerUsername = analyticsConfig.getAdminUsername(); + String analyticsServerPassword = analyticsConfig.getAdminPassword(); + try { + this.dataPublisher = new DataPublisher(analyticsServerUrlGroups, analyticsServerUsername, + analyticsServerPassword); + } catch (DataEndpointAgentConfigurationException e) { + throw new DataPublisherConfigurationException("Configuration Exception on data publisher for " + + "ReceiverGroup = " + analyticsServerUrlGroups + " for username " + analyticsServerUsername, e); + } catch (DataEndpointException e) { + throw new DataPublisherConfigurationException("Invalid ReceiverGroup = " + analyticsServerUrlGroups, e); + } catch (DataEndpointConfigurationException e) { + throw new DataPublisherConfigurationException("Invalid Data endpoint configuration.", e); + } catch (DataEndpointAuthenticationException e) { + throw new DataPublisherConfigurationException("Authentication Failed for user " + + analyticsServerUsername, e); + } catch (TransportException e) { + throw new DataPublisherConfigurationException("Error occurred while retrieving data publisher", e); + } + } else { + return this.dataPublisher; } } - } finally { - PrivilegedCarbonContext.endTenantFlow(); } - - return content; - } - - private void loadTenantRegistry(int tenantId) throws RegistryException { - TenantRegistryLoader tenantRegistryLoader = DataPublisherDataHolder.getInstance().getTenantRegistryLoader(); - DataPublisherDataHolder.getInstance().getIndexLoaderService().loadTenantIndex(tenantId); - tenantRegistryLoader.loadTenantRegistry(tenantId); + return this.dataPublisher; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java index 8c08d5eccf..b758d4cf1c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/AnalyticsConfiguration.java @@ -98,8 +98,12 @@ public class AnalyticsConfiguration { } public static void init() throws DataPublisherConfigurationException { + init(AnalyticsConfiguration.DEVICE_ANALYTICS_CONFIG_PATH); + } + + public static void init(String analyticsConfigPath) throws DataPublisherConfigurationException { try { - File authConfig = new File(AnalyticsConfiguration.DEVICE_ANALYTICS_CONFIG_PATH); + File authConfig = new File(analyticsConfigPath); Document doc = DataPublisherUtil.convertToDocument(authConfig); /* Un-marshaling device analytics configuration */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java index 8603b21f16..b9686bac42 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/config/InvalidConfigurationStateException.java @@ -26,20 +26,4 @@ public class InvalidConfigurationStateException extends RuntimeException { super(message); } - public InvalidConfigurationStateException(String message, Throwable cause) { - super(message, cause); - } - - public InvalidConfigurationStateException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public InvalidConfigurationStateException() { - super(); - } - - public InvalidConfigurationStateException(Throwable cause) { - super(cause); - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherAlreadyExistsException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherAlreadyExistsException.java deleted file mode 100644 index 8646d92e57..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherAlreadyExistsException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - * - */ - -package org.wso2.carbon.device.mgt.analytics.data.publisher.exception; - -public class DataPublisherAlreadyExistsException extends Exception { - public DataPublisherAlreadyExistsException() { - super(); - } - - public DataPublisherAlreadyExistsException(String message) { - super(message); - } - - public DataPublisherAlreadyExistsException(String message, Throwable cause) { - super(message, cause); - } - - public DataPublisherAlreadyExistsException(Throwable cause) { - super(cause); - } - - protected DataPublisherAlreadyExistsException(String message, Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java index 7db8ae1009..ea93c62a31 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/exception/DataPublisherConfigurationException.java @@ -19,9 +19,6 @@ package org.wso2.carbon.device.mgt.analytics.data.publisher.exception; public class DataPublisherConfigurationException extends Exception { - public DataPublisherConfigurationException() { - super(); - } public DataPublisherConfigurationException(String message) { super(message); @@ -31,14 +28,4 @@ public class DataPublisherConfigurationException extends Exception { super(message, cause); } - public DataPublisherConfigurationException(Throwable cause) { - super(cause); - } - - protected DataPublisherConfigurationException(String message, Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherDataHolder.java deleted file mode 100644 index 6f132b3fb8..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherDataHolder.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - * - */ -package org.wso2.carbon.device.mgt.analytics.data.publisher.internal; - -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.registry.core.service.TenantRegistryLoader; -import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; - -public class DataPublisherDataHolder { - private static DataPublisherDataHolder thisInstance = new DataPublisherDataHolder(); - - private TenantRegistryLoader tenantRegistryLoader; - private TenantIndexingLoader indexLoader; - private RegistryService registryService; - private DataPublisherDataHolder() { - } - - - public static DataPublisherDataHolder getInstance() { - return thisInstance; - } - - public void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader){ - this.tenantRegistryLoader = tenantRegistryLoader; - } - - public TenantRegistryLoader getTenantRegistryLoader(){ - return tenantRegistryLoader; - } - - public void setIndexLoaderService(TenantIndexingLoader indexLoader) { - this.indexLoader = indexLoader; - } - - public TenantIndexingLoader getIndexLoaderService(){ - return indexLoader; - } - - public RegistryService getRegistryService() { - return registryService; - } - - public void setRegistryService(RegistryService registryService) { - this.registryService = registryService; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java index 2314b73806..fe2cad0ea1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/internal/DataPublisherServiceComponent.java @@ -26,30 +26,10 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; 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.registry.core.service.RegistryService; -import org.wso2.carbon.registry.core.service.TenantRegistryLoader; -import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; /** * @scr.component name="org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent" * immediate="true" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - * @scr.reference name="tenant.registryloader" - * interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader" - * cardinality="1..1" policy="dynamic" - * bind="setTenantRegistryLoader" - * unbind="unsetTenantRegistryLoader" - * @scr.reference name="tenant.indexloader" - * interface="org.wso2.carbon.registry.indexing.service.TenantIndexingLoader" - * cardinality="1..1" - * policy="dynamic" - * bind="setIndexLoader" - * unbind="unsetIndexLoader" */ public class DataPublisherServiceComponent { @@ -62,11 +42,9 @@ public class DataPublisherServiceComponent { log.debug("Initializing device analytics bundle"); } AnalyticsConfiguration.init(); - BundleContext bundleCtx = componentCtx.getBundleContext(); this.analyticsServiceRef = bundleCtx.registerService(EventsPublisherService.class, new EventsPublisherServiceImpl(), null); - if (log.isDebugEnabled()) { log.debug("Device management analytics bundle has been successfully initialized"); } @@ -86,35 +64,4 @@ public class DataPublisherServiceComponent { log.debug("Device analytics bundle has been successfully deactivated"); } } - - protected void setRegistryService(RegistryService registryService) { - if (registryService != null && log.isDebugEnabled()) { - log.debug("Registry service initialized"); - } - DataPublisherDataHolder.getInstance().setRegistryService(registryService); - } - - protected void unsetRegistryService(RegistryService registryService) { - DataPublisherDataHolder.getInstance().setRegistryService(null); - } - - protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) { - DataPublisherDataHolder.getInstance().setTenantRegistryLoader(tenantRegistryLoader); - } - - protected void unsetTenantRegistryLoader(TenantRegistryLoader tenantRegistryLoader) { - DataPublisherDataHolder.getInstance().setTenantRegistryLoader(null); - } - - protected void setIndexLoader(TenantIndexingLoader indexLoader) { - if (indexLoader != null && log.isDebugEnabled()) { - log.debug("IndexLoader service initialized"); - } - DataPublisherDataHolder.getInstance().setIndexLoaderService(indexLoader); - } - - protected void unsetIndexLoader(TenantIndexingLoader indexLoader) { - DataPublisherDataHolder.getInstance().setIndexLoaderService(null); - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/BaseAnalyticsDataPublisherTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/BaseAnalyticsDataPublisherTest.java new file mode 100644 index 0000000000..3d42a3020b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/BaseAnalyticsDataPublisherTest.java @@ -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. +* +*/ +package org.wso2.carbon.device.mgt.analytics.data.publisher; + +import org.testng.annotations.BeforeSuite; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.io.File; + +public class BaseAnalyticsDataPublisherTest { + + @BeforeSuite + public void init() { + setUpCarbonHome(); + } + + private void setUpCarbonHome() { + 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("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); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherConfigTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherConfigTest.java new file mode 100644 index 0000000000..0e04de8a56 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherConfigTest.java @@ -0,0 +1,83 @@ +/* +* 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.analytics.data.publisher; + +import junit.framework.Assert; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; +import org.wso2.carbon.device.mgt.analytics.data.publisher.config.InvalidConfigurationStateException; +import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; + +import java.io.File; +import java.lang.reflect.Field; +import java.net.URL; + +/** + * This test class will validate the Data publisher configuration creation. + */ +public class DataPublisherConfigTest extends BaseAnalyticsDataPublisherTest { + + @Test(description = "Validating the behaviour of getInstance config before calling the init", + expectedExceptions = InvalidConfigurationStateException.class) + public void testGetInstanceWithoutInit() throws NoSuchFieldException, IllegalAccessException { + Field configField = AnalyticsConfiguration.class.getDeclaredField("config"); + configField.setAccessible(true); + configField.set(configField, null); + AnalyticsConfiguration.getInstance(); + } + + @Test(description = "Analytics configuration initialization with invalid config", + expectedExceptions = DataPublisherConfigurationException.class, + dependsOnMethods = "testGetInstanceWithoutInit") + public void testInitWithInvalidConfig() throws DataPublisherConfigurationException { + ClassLoader classLoader = this.getClass().getClassLoader(); + URL invalidConfig = classLoader.getResource("carbon-home/repository/conf/etc/" + + "device-analytics-config-invalid.xml"); + Assert.assertTrue("No configuration - device-analytics-config-invalid.xml found in resource dir", + invalidConfig != null); + File file = new File(invalidConfig.getFile()); + AnalyticsConfiguration.init(file.getAbsolutePath()); + } + + + @Test(description = "Analytics config initialization with invalid xml", + expectedExceptions = DataPublisherConfigurationException.class, + dependsOnMethods = "testInitWithInvalidConfig") + public void testInitWithInvalidXML() throws DataPublisherConfigurationException { + ClassLoader classLoader = this.getClass().getClassLoader(); + URL invalidConfig = classLoader.getResource("carbon-home/repository/conf/etc/" + + "device-analytics-config-invalid-xml.xml"); + Assert.assertTrue("No configuration - device-analytics-config-invalid-xml.xml found in resource dir", + invalidConfig != null); + File file = new File(invalidConfig.getFile()); + AnalyticsConfiguration.init(file.getAbsolutePath()); + } + + + @Test(description = "Validating the init method with all required params", + dependsOnMethods = "testInitWithInvalidXML") + public void testInitWithValidConfig() throws DataPublisherConfigurationException { + AnalyticsConfiguration.init(); + AnalyticsConfiguration analyticsConfiguration = AnalyticsConfiguration.getInstance(); + Assert.assertEquals(analyticsConfiguration.getAdminPassword(), "testuserpwd"); + Assert.assertEquals(analyticsConfiguration.getAdminUsername(), "testuser"); + Assert.assertEquals(analyticsConfiguration.getReceiverServerUrl(), "tcp://localhost:7615"); + Assert.assertTrue(analyticsConfiguration.isEnable()); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherServiceComponentTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherServiceComponentTest.java new file mode 100644 index 0000000000..d5ffb75d48 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DataPublisherServiceComponentTest.java @@ -0,0 +1,67 @@ +/* +* 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.analytics.data.publisher; + + +import org.apache.sling.testing.mock.osgi.MockOsgi; +import org.osgi.service.component.ComponentContext; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent; +import org.wso2.carbon.device.mgt.analytics.data.publisher.util.TestComponentContext; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * This tesclass will be validating the behaviour of {@link DataPublisherServiceComponent} + */ +public class DataPublisherServiceComponentTest extends BaseAnalyticsDataPublisherTest { + private DataPublisherServiceComponent serviceComponent; + + @BeforeClass + public void initTest() { + this.serviceComponent = new DataPublisherServiceComponent(); + } + + @Test (description = "Test bundle activation with exception thrown when service resgistration") + public void activateWithException() throws NoSuchMethodException, IllegalAccessException, + InvocationTargetException { + this.activate(new TestComponentContext()); + } + + @Test(dependsOnMethods = "activateWithException", description = "Test the bundle activation with succesful path") + public void activateWithoutException() throws NoSuchMethodException, InvocationTargetException, + IllegalAccessException { + this.activate(MockOsgi.newComponentContext()); + } + + @Test(dependsOnMethods = "activateWithoutException", description = "Test bundle deactivation") + public void deActivate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method method = this.serviceComponent.getClass().getDeclaredMethod("deactivate", ComponentContext.class); + method.setAccessible(true); + method.invoke(this.serviceComponent, MockOsgi.newComponentContext()); + } + + private void activate(ComponentContext componentContext) throws NoSuchMethodException, InvocationTargetException, + IllegalAccessException { + Method method = this.serviceComponent.getClass().getDeclaredMethod("activate", ComponentContext.class); + method.setAccessible(true); + method.invoke(this.serviceComponent, componentContext); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/EventPublisherServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/EventPublisherServiceTest.java new file mode 100644 index 0000000000..a7e5e8083d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/EventPublisherServiceTest.java @@ -0,0 +1,144 @@ +/* +* 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.analytics.data.publisher; + +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.databridge.agent.AgentHolder; +import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; +import org.wso2.carbon.device.mgt.analytics.data.publisher.config.AnalyticsConfiguration; +import org.wso2.carbon.device.mgt.analytics.data.publisher.config.InvalidConfigurationStateException; +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 java.lang.reflect.Field; + +/** + * This test class will test the methods that are exposed from {@link EventsPublisherService} + */ +public class EventPublisherServiceTest extends BaseAnalyticsDataPublisherTest { + + private static final String STREAM_NAME = "org.wso2.test.stream"; + private static final String TENANT_DOMAIN = "test.com"; + + private EventsPublisherService eventsPublisherService; + + @BeforeClass + public void initTest() { + this.eventsPublisherService = new EventsPublisherServiceImpl(); + } + + @Test(description = "Publish the event before initializing", + expectedExceptions = InvalidConfigurationStateException.class) + public void publishBeforeInit() throws DataPublisherConfigurationException, NoSuchFieldException, + IllegalAccessException, InstantiationException { + Field configField = AnalyticsConfiguration.class.getDeclaredField("config"); + configField.setAccessible(true); + configField.set(configField, null); + this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), getEventProps(), + getEventProps()); + } + + @Test(description = "Publish with analytics config disabled", dependsOnMethods = "publishBeforeInit") + public void publishWhenAnalyticsConfigDisabled() throws DataPublisherConfigurationException { + AnalyticsConfiguration.init(); + AnalyticsConfiguration.getInstance().setEnable(false); + boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), + getEventProps(), getEventProps()); + Assert.assertFalse(published); + } + + @Test(description = "Publish the event after initializing", dependsOnMethods = "publishWhenAnalyticsConfigDisabled") + public void publishAfterInit() throws DataPublisherConfigurationException { + AnalyticsConfiguration.getInstance().setEnable(true); + boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", getEventProps(), + getEventProps(), getEventProps()); + Assert.assertTrue(published); + } + + @Test(description = "Publish as tenant", dependsOnMethods = "publishAfterInit") + public void publishAsTenant() throws DataPublisherConfigurationException { + publishAsTenant(getEventProps()); + } + + @Test(description = "Publish the with no meta data as tenant", dependsOnMethods = "publishAsTenant", + expectedExceptions = DataPublisherConfigurationException.class) + public void publishAsTenantWithNoMetaData() throws DataPublisherConfigurationException { + publishAsTenant(null); + } + + @Test(description = "Publish the with empty meta data as tenant", dependsOnMethods = "publishAsTenant", + expectedExceptions = DataPublisherConfigurationException.class) + public void publishAsTenantWithEmptyMetaData() throws DataPublisherConfigurationException { + publishAsTenant(new Object[0]); + } + + @Test(description = "Publishing with invalid data publisher config", + dependsOnMethods = {"publishAsTenantWithEmptyMetaData", "publishAsTenantWithNoMetaData"}, + expectedExceptions = DataPublisherConfigurationException.class) + public void publishWithDataEndpointConfigException() throws DataPublisherConfigurationException, + NoSuchFieldException, IllegalAccessException { + AnalyticsConfiguration analyticsConfiguration = AnalyticsConfiguration.getInstance(); + analyticsConfiguration.setReceiverServerUrl(""); + Field dataPublisherField = DeviceDataPublisher.class.getDeclaredField("deviceDataPublisher"); + dataPublisherField.setAccessible(true); + dataPublisherField.set(dataPublisherField, null); + publishAsTenant(getEventProps()); + } + + @Test(description = "Publishing with invalid data publisher config", + dependsOnMethods = "publishWithDataEndpointConfigException", + expectedExceptions = DataPublisherConfigurationException.class) + public void publishWithDataAgentConfigException() throws DataPublisherConfigurationException, + NoSuchFieldException, IllegalAccessException, DataEndpointAgentConfigurationException { + AnalyticsConfiguration.init(); + Field defaultAgentName = AgentHolder.getInstance().getClass().getDeclaredField("defaultDataEndpointAgentName"); + defaultAgentName.setAccessible(true); + defaultAgentName.set(AgentHolder.getInstance(), "dummyAgent"); + publishAsTenant(getEventProps()); + } + + @Test(description = "Publishing with invalid data publisher config", + dependsOnMethods = "publishWithDataAgentConfigException") + public void publishWithDataEndpointException() throws DataPublisherConfigurationException, + NoSuchFieldException, IllegalAccessException, DataEndpointAgentConfigurationException { + AnalyticsConfiguration.init(); + + } + + private void publishAsTenant(Object[] metaData) throws DataPublisherConfigurationException { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(TENANT_DOMAIN, true); + try { + boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", metaData, + getEventProps(), getEventProps()); + Assert.assertTrue(published); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + private Object[] getEventProps() { + return new Object[]{"123"}; + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/util/TestComponentContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/util/TestComponentContext.java new file mode 100644 index 0000000000..adcb3cba2f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/java/org/wso2/carbon/device/mgt/analytics/data/publisher/util/TestComponentContext.java @@ -0,0 +1,81 @@ +/* +* 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.analytics.data.publisher.util; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.ComponentInstance; + +import java.util.Dictionary; + +/** + * Mock implementation for component context. + */ +public class TestComponentContext implements ComponentContext { + @Override + public Dictionary getProperties() { + return null; + } + + @Override + public Object locateService(String s) { + return null; + } + + @Override + public Object locateService(String s, ServiceReference serviceReference) { + return null; + } + + @Override + public Object[] locateServices(String s) { + return new Object[0]; + } + + @Override + public BundleContext getBundleContext() { + return null; + } + + @Override + public Bundle getUsingBundle() { + return null; + } + + @Override + public ComponentInstance getComponentInstance() { + return null; + } + + @Override + public void enableComponent(String s) { + + } + + @Override + public void disableComponent(String s) { + + } + + @Override + public ServiceReference getServiceReference() { + return null; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/carbon.xml new file mode 100644 index 0000000000..31752cf9b4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/carbon.xml @@ -0,0 +1,656 @@ + + + + + + + + + ${product.name} + + + ${product.key} + + + ${product.version} + + + + + + + + + local:/${carbon.context}/services/ + + + + + + + ${default.server.role} + + + + + + + org.wso2.carbon + + + / + + + + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + + false + + + + + + + + 30 + + + + + + + + + 15 + + + + + + ${carbon.home}/repository/deployment/server/ + + + 15 + + + ${carbon.home}/repository/conf/axis2/axis2.xml + + + 30000 + + + ${carbon.home}/repository/deployment/client/ + + ${carbon.home}/repository/conf/axis2/axis2_client.xml + + true + + + + + + + + + + admin + Default Administrator Role + + + user + Default User Role + + + + + + + + + + + + ${carbon.home}/repository/resources/security/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + + + + + ${carbon.home}/tmp/work + + + + + + true + + + 10 + + + 30 + + + + + + 100 + + + + keystore + certificate + * + + org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor + + + + + jarZip + + org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor + + + + dbs + + org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor + + + + tools + + org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor + + + + toolsAny + + org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor + + + + + + + info + org.wso2.carbon.core.transports.util.InfoProcessor + + + wsdl + org.wso2.carbon.core.transports.util.Wsdl11Processor + + + wsdl2 + org.wso2.carbon.core.transports.util.Wsdl20Processor + + + xsd + org.wso2.carbon.core.transports.util.XsdProcessor + + + + + + false + false + true + svn + http://svnrepo.example.com/repos/ + username + password + true + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + ${p2.repo.url} + + + + + + + + true + + + + + + true + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config-invalid.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config-invalid.xml new file mode 100644 index 0000000000..2d0264e368 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config-invalid.xml @@ -0,0 +1,69 @@ + + + + + + Thrift + org.wso2.carbon.databridge.agent.endpoint.thrift.ThriftDataEndpointNoClass + src/test/resources/client-truststore.jks + wso2carbon + 32768 + 200 + 1 + 30000 + 1 + 20 + 30 + 250 + 250 + 5500 + 5000 + 250 + 250 + 5500 + 5000 + + + + + + Binary + org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint + src/test/resources/client-truststore.jks + wso2carbon + 32768 + 200 + 1 + 1 + 30000 + 20 + 30 + 250 + 250 + 5500 + 5000 + 250 + 250 + 5500 + 5000 + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config.xml new file mode 100644 index 0000000000..05215f7fc0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/data-bridge/data-agent-config.xml @@ -0,0 +1,69 @@ + + + + + + Thrift + org.wso2.carbon.databridge.agent.endpoint.thrift.ThriftDataEndpoint + src/test/resources/client-truststore.jks + wso2carbon + 32768 + 200 + 1 + 30000 + 1 + 20 + 30 + 250 + 250 + 5500 + 5000 + 250 + 250 + 5500 + 5000 + + + + + + Binary + org.wso2.carbon.databridge.agent.endpoint.binary.BinaryDataEndpoint + src/test/resources/client-truststore.jks + wso2carbon + 32768 + 200 + 1 + 1 + 30000 + 20 + 30 + 250 + 250 + 5500 + 5000 + 250 + 250 + 5500 + 5000 + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid-xml.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid-xml.xml new file mode 100644 index 0000000000..4353624e50 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid-xml.xml @@ -0,0 +1,35 @@ + + + + + + tcp://localhost:7615 + testuser + testuserpwd diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid.xml new file mode 100644 index 0000000000..624a05b5f4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config-invalid.xml @@ -0,0 +1,35 @@ + + + + + + tcp://localhost:7615 + testuser + testuserpwd + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config.xml new file mode 100644 index 0000000000..8edea74667 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/etc/device-analytics-config.xml @@ -0,0 +1,36 @@ + + + + + + true + tcp://localhost:7615 + testuser + testuserpwd + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/registry.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/registry.xml new file mode 100644 index 0000000000..a226ae80a8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/carbon-home/repository/conf/registry.xml @@ -0,0 +1,50 @@ + + + + + + + + wso2registry + false + true + / + + + jdbc:h2:./target/databasetest/CARBON_TEST + + org.h2.Driver + 80 + 60000 + 5 + + + false + + + + true + true + true + true + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/client-truststore.jks b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/client-truststore.jks new file mode 100644 index 0000000000..3b9fdfb9e8 Binary files /dev/null and b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/client-truststore.jks differ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/testng.xml new file mode 100644 index 0000000000..8a3669fd4d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/test/resources/testng.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + 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 4f7611215c..b6a1cc8543 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.136-SNAPSHOT + 3.0.170-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 @@ -300,11 +329,6 @@ org.wso2.carbon.apimgt.annotations provided - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.dashboard - provided - org.wso2.orbit.com.fasterxml.jackson.core jackson-annotations @@ -383,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/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index d1e816a430..49f0b4ad76 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -54,13 +54,12 @@ public class GroupManagementServiceImpl implements GroupManagementService { private static final String DEFAULT_ADMIN_ROLE = "admin"; private static final String[] DEFAULT_ADMIN_PERMISSIONS = {"/permission/device-mgt/admin/groups", "/permission/device-mgt/user/groups"}; - private static final String EMPTY_RESULT = "EMPTY"; @Override public Response getGroups(String name, String owner, int offset, int limit) { try { RequestValidationUtil.validatePaginationParameters(offset, limit); - String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); request.setGroupName(name); request.setOwner(owner); @@ -85,7 +84,7 @@ public class GroupManagementServiceImpl implements GroupManagementService { @Override public Response getGroupCount() { try { - String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(currentUser); return Response.status(Response.Status.OK).entity(count).build(); } catch (GroupManagementException e) { @@ -194,7 +193,7 @@ public class GroupManagementServiceImpl implements GroupManagementService { deviceGroupRolesList.setList(groupRoles); deviceGroupRolesList.setCount(groupRoles.size()); } else { - deviceGroupRolesList.setList(new ArrayList()); + deviceGroupRolesList.setList(new ArrayList<>()); deviceGroupRolesList.setCount(0); } return Response.status(Response.Status.OK).entity(deviceGroupRolesList).build(); @@ -215,7 +214,7 @@ public class GroupManagementServiceImpl implements GroupManagementService { if (deviceList != null) { deviceListWrapper.setList(deviceList); } else { - deviceListWrapper.setList(new ArrayList()); + deviceListWrapper.setList(new ArrayList<>()); } deviceListWrapper.setCount(deviceCount); return Response.status(Response.Status.OK).entity(deviceListWrapper).build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index 3bc4fec7df..8e2322cd0a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -80,8 +80,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement @PUT @Path("/{id}/mark-checked") - public Response updateNotificationStatus( - @PathParam("id") @Max(45)int id) { + public Response updateNotificationStatus(@PathParam("id") @Max(45)int id) { String msg; Notification.Status status = Notification.Status.CHECKED; Notification notification; @@ -90,8 +89,8 @@ public class NotificationManagementServiceImpl implements NotificationManagement } catch (NotificationManagementException e) { msg = "Error occurred while updating notification status."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } try { notification = DeviceMgtAPIUtils.getNotificationManagementService().getNotification(id); @@ -99,7 +98,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement } catch (NotificationManagementException e) { msg = "Notification updated successfully. But the retrial of the updated notification failed"; log.error(msg, e); - return Response.status(Response.Status.OK).build(); + return Response.status(Response.Status.OK).entity(msg).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index cafed10856..25794c833b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -22,7 +22,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; @@ -86,7 +85,6 @@ public class UserManagementServiceImpl implements UserManagementService { private static final Log log = LogFactory.getLog(UserManagementServiceImpl.class); private static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user"; - private static final String DEFAULT_DEVICE_ADMIN = "Internal/devicemgt-admin"; // Permissions that are given for a normal device user. private static final Permission[] PERMISSIONS_FOR_DEVICE_USER = { @@ -253,7 +251,11 @@ public class UserManagementServiceImpl implements UserManagementService { log.debug("User credential of username: " + username + " has been changed"); } List currentRoles = this.getFilteredRoles(userStoreManager, username); - List newRoles = Arrays.asList(userInfo.getRoles()); + + List newRoles = new ArrayList<>(); + if (userInfo.getRoles() != null) { + newRoles = Arrays.asList(userInfo.getRoles()); + } List rolesToAdd = new ArrayList<>(newRoles); List rolesToDelete = new ArrayList<>(); @@ -288,7 +290,7 @@ public class UserManagementServiceImpl implements UserManagementService { private List getFilteredRoles(UserStoreManager userStoreManager, String username) throws UserStoreException { - String[] roleListOfUser = new String[0]; + String[] roleListOfUser; roleListOfUser = userStoreManager.getRoleListOfUser(username); List filteredRoles = new ArrayList<>(); for (String role : roleListOfUser) { @@ -429,8 +431,8 @@ public class UserManagementServiceImpl implements UserManagementService { public Response getUserCount() { try { UserStoreCountRetriever userStoreCountRetrieverService = DeviceMgtAPIUtils.getUserStoreCountRetrieverService(); - RealmConfiguration secondaryRealmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getRealmConfiguration().getSecondaryRealmConfig(); + RealmConfiguration secondaryRealmConfiguration = DeviceMgtAPIUtils.getUserRealm().getRealmConfiguration() + .getSecondaryRealmConfig(); if (secondaryRealmConfiguration != null) { if (!secondaryRealmConfiguration.isPrimary() && !Constants.JDBC_USERSTOREMANAGER. @@ -488,12 +490,10 @@ public class UserManagementServiceImpl implements UserManagementService { public Response isUserExists(@QueryParam("username") String userName) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - boolean userExists = false; if (userStoreManager.isExistingUser(userName)) { - userExists = true; - return Response.status(Response.Status.OK).entity(userExists).build(); + return Response.status(Response.Status.OK).entity(true).build(); } else { - return Response.status(Response.Status.OK).entity(userExists).build(); + return Response.status(Response.Status.OK).entity(false).build(); } } catch (UserStoreException e) { String msg = "Error while retrieving the user."; @@ -605,9 +605,7 @@ public class UserManagementServiceImpl implements UserManagementService { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); try { Set recipients = new HashSet<>(); - for (String recipient : enrollmentInvitation.getRecipients()) { - recipients.add(recipient); - } + recipients.addAll(enrollmentInvitation.getRecipients()); Properties props = new Properties(); String username = DeviceMgtAPIUtils.getAuthenticatedUser(); String firstName = getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME); @@ -621,6 +619,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (DeviceManagementException e) { String msg = "Error occurred while inviting user to enrol their device"; log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UserStoreException e) { String msg = "Error occurred while getting claim values to invite user"; log.error(msg, e); 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 d719e90e00..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 @@ -35,7 +35,6 @@ import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.Utils; -import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -102,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"; @@ -438,15 +436,6 @@ public class DeviceMgtAPIUtils { return searchManagerService; } - public static GadgetDataService getGadgetDataService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - GadgetDataService gadgetDataService = (GadgetDataService) ctx.getOSGiService(GadgetDataService.class, null); - if (gadgetDataService == null) { - throw new IllegalStateException("Gadget Data Service has not been initialized."); - } - return gadgetDataService; - } - public static GeoLocationProviderService getGeoService() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); GeoLocationProviderService diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java new file mode 100644 index 0000000000..5a4b0cd13b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java @@ -0,0 +1,140 @@ +/* + * 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.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.configuration.mgt.ConfigurationEntry; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.api.ConfigurationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +/** + * This is a test class for {@link ConfigurationServiceImpl}. + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.CarbonContext"}) +@PrepareForTest({DeviceMgtAPIUtils.class, PolicyManagerUtil.class}) +public class ConfigurationServiceImplTest { + private ConfigurationManagementService configurationManagementService; + private PlatformConfigurationManagementService platformConfigurationManagementService; + private PlatformConfiguration platformConfiguration; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() { + configurationManagementService = new ConfigurationServiceImpl(); + platformConfigurationManagementService = Mockito.mock(PlatformConfigurationManagementService.class); + platformConfiguration = new PlatformConfiguration(); + platformConfiguration.setType("test"); + } + + @Test(description = "This method tests the getConfiguration method of ConfigurationManagementService under valid " + + "conditions") + public void testGetConfigurationWithSuccessConditions() throws ConfigurationManagementException { + PowerMockito.stub(PowerMockito.method(PolicyManagerUtil.class, "getMonitoringFrequency")).toReturn(60); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + Response response = configurationManagementService.getConfiguration("test"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getConfiguration request " + "failed with valid parameters"); + + List configurationEntryList = new ArrayList<>(); + ConfigurationEntry configurationEntry = new ConfigurationEntry(); + configurationEntry.setContentType("String"); + configurationEntry.setName("test"); + configurationEntry.setValue("test"); + configurationEntryList.add(configurationEntry); + platformConfiguration.setConfiguration(configurationEntryList); + Mockito.reset(platformConfigurationManagementService); + Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + response = configurationManagementService.getConfiguration("test"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getConfiguration request " + "failed with valid parameters"); + } + + @Test(description = "This method tests the getConfiguration method under negative conditions") + public void testGetConfigurationUnderNegativeConditions() throws ConfigurationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + Mockito.reset(platformConfigurationManagementService); + Mockito.doThrow(new ConfigurationManagementException()).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + Response response = configurationManagementService.getConfiguration("test"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getConfiguration request " + "succeeded under negative conditions"); + } + + @Test(description = "This method tests the updateConfiguration method under valid conditions.", dependsOnMethods + = {"testGetConfigurationWithSuccessConditions"}) + public void testUpdateConfigurationUnderValidConditions() throws ConfigurationManagementException { + Mockito.reset(platformConfigurationManagementService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + PowerMockito + .stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotifierFrequency", PlatformConfiguration.class)) + .toReturn(60); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "scheduleTaskService", int.class)) + .toReturn(null); + Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + Mockito.doReturn(true).when(platformConfigurationManagementService) + .saveConfiguration(Mockito.any(), Mockito.any()); + Response response = configurationManagementService.updateConfiguration(platformConfiguration); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "updateConfiguration request failed with valid parameters"); + } + + @Test(description = "This method tests the updateConfiguration method under negative conditions.", + dependsOnMethods = {"testGetConfigurationWithSuccessConditions"}) + public void testUpdateConfigurationUnderNegativeConditions() throws ConfigurationManagementException { + Mockito.reset(platformConfigurationManagementService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + Mockito.doThrow(new ConfigurationManagementException()).when(platformConfigurationManagementService) + .saveConfiguration(Mockito.any(), Mockito.any()); + Response response = configurationManagementService.updateConfiguration(platformConfiguration); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "updateConfiguration request succeeded with in-valid parameters"); + } +} 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..f934687cd6 --- /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,1169 @@ +/* + * 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.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +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.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; +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.ArrayList; +import java.util.HashMap; +import java.util.List; +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 final String MONITOR_OPERATION = "POLICY_MONITOR"; + 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"); + + List payloadList = null; + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, + TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.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"); + + List payloadList = new ArrayList<>(); + Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response2, "Response should not be null"); + Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test the get pending operation method which return empty device type list.") + public void testGetPendingOperationsWithNoDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(new ArrayList() { + }); + Response response = this.deviceAgentService.getPendingOperations(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(this.deviceManagementProviderService); + } + + @Test(description = "Test the get pending operation method with invalid device identifier.") + public void testGetPendingOperationsWithInvalidDeviceIdentifier() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(false); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Response response = this.deviceAgentService.getPendingOperations(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"); + Mockito.reset(this.deviceManagementProviderService); + } + + @Test(description = "Test the get pending operations success scenario.") + public void testGetPendingOperationsSuccess() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertNotNull(response.getEntity(), "Response entity 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 scenario when get pending operations throw OperationManagementException.") + public void testGetPendingOperationsWithOperationManagementException() throws DeviceManagementException, OperationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Mockito.when(this.deviceManagementProviderService.getPendingOperations(Mockito.any())).thenThrow(new + OperationManagementException()); + Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertNotNull(response.getEntity(), "Response entity 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 the scenario when getAvailableDeviceTypes throw DeviceManagementException.") + public void testGetPendingOperationsWithDeviceManagementException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceAgentService.getPendingOperations(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertNotNull(response.getEntity(), "Response entity 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 get next pending operation with device type is invalid.") + public void getNextPendingOperationWithInvalidDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(new ArrayList() { + }); + Response response = this.deviceAgentService.getNextPendingOperation(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(this.deviceManagementProviderService); + } + + @Test(description = "Test get next pending operation with invalid device identifier.") + public void getNextPendingOperationWithInvalidDeviceIdentifier() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(false); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Response response = this.deviceAgentService.getNextPendingOperation(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(this.deviceManagementProviderService); + } + + @Test(description = "Test the getNextPendingOperation success scenario.") + public void testGetNextPendingOperationSuccess() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertNotNull(response.getEntity(), "Response entity 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 get next pending operation with operation management exception.") + public void getNextPendingOperationWithOperationManagementException() throws DeviceManagementException, OperationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Mockito.when(this.deviceManagementProviderService.getNextPendingOperation(Mockito.any())).thenThrow(new + OperationManagementException()); + Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertNotNull(response.getEntity(), "Response entity 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 the get next pending operation method with device management exception.") + public void getNextPendingOperationWithDeviceManagementException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceAgentService.getNextPendingOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); + Assert.assertNotNull(response, "Response should not be null"); + Assert.assertNotNull(response.getEntity(), "Response entity 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 operation method with invalid device type.") + public void testUpdateOperationWithInvalidDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(new ArrayList() { + }); + Operation operation = new Operation(); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The 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 update operation when operation is null.") + public void testUpdateOperationWithNullOperation() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + null); + Assert.assertNotNull(response, "The 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 update operation method with invalid device identifier.") + public void testUpdateOperationWithInvalidDeviceIdentifier() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(false); + + Operation operation = new Operation(); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The 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 update operation success scenario.") + public void testUpdateOperationSuccess() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + + Operation operation = new Operation(); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The 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 update Operation method with Policy Monitoring Operation.") + public void testUpdateOperationSuccessWithPolicyMonitorOperation() throws DeviceManagementException, PolicyComplianceException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + PolicyManagerService policyManagementService = Mockito.mock(PolicyManagerServiceImpl.class, Mockito + .RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) + .toReturn(policyManagementService); + Mockito.when(policyManagementService.checkCompliance(Mockito.any(), Mockito.any())).thenReturn(true); + + Operation operation = new Operation(); + operation.setCode(MONITOR_OPERATION); + operation.setStatus(Operation.Status.PENDING); + operation.setPayLoad(null); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200"); + } + + @Test(description = "Test Update Operation with Operation Management Exception.") + public void testUpdateOperationWithOperationManagementException() throws DeviceManagementException, + OperationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + + Operation operation = new Operation(); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + + Mockito.doThrow(new OperationManagementException()).when(this.deviceManagementProviderService) + .updateOperation(Mockito.any(), Mockito.any()); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The 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 operation with Device Management exception.") + public void testUpdateOperationWithDeviceManagementException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + + Operation operation = new Operation(); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenThrow(new DeviceManagementException()); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The 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 operation with Policy Compliance operation.") + public void testUpdateOperationWithPolicyComplianceException() throws PolicyComplianceException, + DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "isValidDeviceIdentifier")) + .toReturn(true); + PolicyManagerService policyManagementService = Mockito.mock(PolicyManagerServiceImpl.class, Mockito + .RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) + .toReturn(policyManagementService); + Mockito.when(policyManagementService.checkCompliance(Mockito.any(), Mockito.any())) + .thenThrow(new PolicyComplianceException()); + + Operation operation = new Operation(); + operation.setCode(MONITOR_OPERATION); + operation.setStatus(Operation.Status.PENDING); + operation.setPayLoad(null); + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + + Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + operation); + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "The response status should be 500"); + } + + @Test(description = "Test get operations with null operation status.") + public void getOperationsWithStatusNull() { + Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, + TEST_DEVICE_IDENTIFIER, null); + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test get operations with invalid device types.") + public void getOperationWithInvalidDeviceType() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(new ArrayList() {}); + + Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + Operation.Status.COMPLETED); + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "The response status should be 400"); + } + + @Test(description = "Test get operations success scenario.") + public void testGetOperationSuccess() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + + Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + Operation.Status.COMPLETED); + Assert.assertNotNull(response, "The response should not be null"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "The response status should be 200"); + } + + @Test(description = "Test the get operation method with operation management exception.") + public void testGetOperationWithOperationManagementException() throws DeviceManagementException, + OperationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenReturn(deviceTypes); + Mockito.when(this.deviceManagementProviderService.getOperationsByDeviceAndStatus(Mockito.any(), Mockito.any() + )).thenThrow(new OperationManagementException()); + + Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + Operation.Status.COMPLETED); + Assert.assertNotNull(response, "The 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 the get operation method with device management exception.") + public void testGetOperationsWithDeviceManagementException() throws DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + + List deviceTypes = new ArrayList<>(); + deviceTypes.add(TEST_DEVICE_TYPE); + Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) + .thenThrow(new DeviceManagementException()); + Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, + Operation.Status.COMPLETED); + Assert.assertNotNull(response, "The 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); + } +} 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/GroupManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImplTest.java new file mode 100644 index 0000000000..d3c42b794a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImplTest.java @@ -0,0 +1,397 @@ +/* + * 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.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.CarbonConstants; +import org.wso2.carbon.context.CarbonContext; +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.DeviceNotFoundException; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; +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.common.group.mgt.GroupNotExistException; +import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceToGroupsAssignment; +import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +/** + * This is a test case for {@link GroupManagementServiceImpl}. + */ +@PowerMockIgnore({"javax.ws.rs.*", "javax.xml.parsers"}) +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.PrivilegedCarbonContext"}) +@PrepareForTest({DeviceMgtAPIUtils.class, CarbonContext.class}) +public class GroupManagementServiceImplTest { + private GroupManagementService groupManagementService; + private GroupManagementProviderService groupManagementProviderService; + private PrivilegedCarbonContext context; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() { + groupManagementService = new GroupManagementServiceImpl(); + groupManagementProviderService = Mockito.mock(GroupManagementProviderService.class); + context = Mockito.mock(PrivilegedCarbonContext.class); + Mockito.doReturn("admin").when(context).getUsername(); + } + + @Test(description = "This method tests the behaviour of getGroups under valid conditions") + public void testGetGroups() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(context); + PaginationResult paginationResult = new PaginationResult(); + Mockito.doReturn(paginationResult).when(groupManagementProviderService) + .getGroups(Mockito.anyString(), Mockito.any(GroupPaginationRequest.class)); + Response response = groupManagementService.getGroups("test", "admin", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "GetGroups request failed with valid parameters"); + + Mockito.reset(groupManagementProviderService); + List deviceGroupList = new ArrayList<>(); + deviceGroupList.add(new DeviceGroup("test")); + paginationResult.setData(deviceGroupList); + paginationResult.setRecordsTotal(1); + Mockito.doReturn(paginationResult).when(groupManagementProviderService) + .getGroups(Mockito.anyString(), Mockito.any(GroupPaginationRequest.class)); + response = groupManagementService.getGroups("test", "admin", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "GetGroups request failed with valid parameters"); + } + + @Test(description = "This method tests the behaviour of getGroups method under negative circumstances", + dependsOnMethods = {"testGetGroups"}) + public void testGetGroupUnderNegativeConditions() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(context); + Mockito.reset(groupManagementProviderService); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) + .getGroups(Mockito.anyString(), Mockito.any(GroupPaginationRequest.class)); + Response response = groupManagementService.getGroups("test", "admin", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "GetGroups request succeeded with in-valid parameters"); + } + + @Test(description = "This method tests the behaviour of getGroupCount method under valid conditions and invalid " + + "conditions") + public void testGetGroupCount() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(context); + Mockito.doReturn(2).when(groupManagementProviderService).getGroupCount(Mockito.anyString()); + Response response = groupManagementService.getGroupCount(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "GetGroupCount request failed with valid parameters"); + Mockito.reset(groupManagementProviderService); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) + .getGroupCount(Mockito.anyString()); + response = groupManagementService.getGroupCount(); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "GetGroupCount request succeeded with in-valid parameters"); + } + + @Test(description = "This method tests the behaviour of createGroup method under valid and invalid scenarios") + public void testCreateGroup() throws GroupManagementException, GroupAlreadyExistException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(context); + Response response = groupManagementService.createGroup(null); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "createGroup request succeeded with the group equals to null"); + Mockito.doNothing().when(groupManagementProviderService) + .createGroup(Mockito.any(), Mockito.any(), Mockito.any()); + response = groupManagementService.createGroup(new DeviceGroup()); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), + "createGroup request failed for a request with valid parameters"); + Mockito.reset(groupManagementProviderService); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) + .createGroup(Mockito.any(), Mockito.any(), Mockito.any()); + response = groupManagementService.createGroup(new DeviceGroup()); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "createGroup request succeeded for a request with in-valid parameters"); + Mockito.reset(groupManagementProviderService); + Mockito.doThrow(new GroupAlreadyExistException()).when(groupManagementProviderService) + .createGroup(Mockito.any(), Mockito.any(), Mockito.any()); + response = groupManagementService.createGroup(new DeviceGroup()); + Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(), + "createGroup request succeeded for a request with in-valid parameters"); + } + + @Test(description = "This method tests the functionality of getGroup method under various conditions") + public void testGetGroup() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.doReturn(new DeviceGroup()).when(groupManagementProviderService).getGroup(1); + Mockito.doReturn(null).when(groupManagementProviderService).getGroup(2); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).getGroup(3); + Response response = groupManagementService.getGroup(1); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getGroup request failed for a request with valid parameters"); + response = groupManagementService.getGroup(2); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "getGroup request returned a group for a non-existing group"); + response = groupManagementService.getGroup(3); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getGroup request returned a group for a in-valid request"); + } + + @Test(description = "This method tests the functionality of updateGroup method under various conditions") + public void testUpdateGroup() throws GroupManagementException, GroupNotExistException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + DeviceGroup deviceGroup = new DeviceGroup(); + deviceGroup.setGroupId(1); + Mockito.doNothing().when(groupManagementProviderService).updateGroup(deviceGroup, 1); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) + .updateGroup(deviceGroup, 2); + Mockito.doThrow(new GroupNotExistException()).when(groupManagementProviderService).updateGroup(deviceGroup, 3); + Response response = groupManagementService.updateGroup(1, deviceGroup); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "update request failed for a request with valid parameters"); + response = groupManagementService.updateGroup(2, deviceGroup); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "update request succeeded for a in-valid request"); + response = groupManagementService.updateGroup(3, deviceGroup); + Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(), + "update request succeeded for a in-valid request"); + response = groupManagementService.updateGroup(4, null); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "update request succeeded for a in-valid request"); + } + + @Test(description = "This method tests the functionality of deleteGroup method under various scenarios") + public void testDeleteGroup() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.doReturn(true).when(groupManagementProviderService).deleteGroup(1); + Mockito.doReturn(false).when(groupManagementProviderService).deleteGroup(2); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).deleteGroup(3); + Response response = groupManagementService.deleteGroup(1); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "delete group request failed for a request with valid parameters"); + response = groupManagementService.deleteGroup(2); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Non-existing group was successfully deleted"); + response = groupManagementService.deleteGroup(3); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Deletion succeeded with an erroneous condition."); + } + + @Test(description = "This method tests the functionality of manageGroupSharing under various conditions") + public void testManageGroupSharing() throws GroupManagementException, RoleDoesNotExistException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.doNothing().when(groupManagementProviderService).manageGroupSharing(1, null); + Mockito.doThrow(new GroupManagementException("test")).when(groupManagementProviderService) + .manageGroupSharing(2, null); + Mockito.doThrow(new RoleDoesNotExistException()).when(groupManagementProviderService) + .manageGroupSharing(3, null); + Response response = groupManagementService.manageGroupSharing(1, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "managegroupSharing request failed for a request with valid parameters"); + response = groupManagementService.manageGroupSharing(2, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "managegroupSharing request succeeded for a request with in-valid parameters"); + response = groupManagementService.manageGroupSharing(3, null); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "managegroupSharing request succeeded for a request with in-valid parameters"); + } + + @Test(description = "This method tests the functionality of getGroupRoles under various conditions") + public void testGetGroupRoles() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.doReturn(new ArrayList()).when(groupManagementProviderService).getRoles(1); + Mockito.doReturn(null).when(groupManagementProviderService).getRoles(2); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).getRoles(3); + Response response = groupManagementService.getRolesOfGroup(1); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getRolesOfGroup request failed for a request with valid parameters"); + response = groupManagementService.getRolesOfGroup(2); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getRolesOfGroup request failed for a request with valid parameters"); + response = groupManagementService.getRolesOfGroup(3); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getRolesOfGroup request failed for a request with in-valid parameters"); + } + + @Test(description = "This method tests the getDevicesOfGroup under various conditions") + public void testGetDevicesOfGroup() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.doReturn(1).when(groupManagementProviderService).getDeviceCount(Mockito.anyInt()); + Mockito.doReturn(new ArrayList()).when(groupManagementProviderService).getDevices(1, 0, 10); + Mockito.doReturn(null).when(groupManagementProviderService).getDevices(2, 0, 10); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).getDevices(3, 0, 10); + Response response = groupManagementService.getDevicesOfGroup(1, 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getDevicesOfGroup request failed for a request with valid parameters"); + response = groupManagementService.getDevicesOfGroup(2, 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getDevicesOfGroup request failed for a request with valid parameters"); + response = groupManagementService.getDevicesOfGroup(3, 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getDevicesOfGroup request succeded for a request with in-valid parameters"); + } + + @Test(description = "This method tests the getDeviceCountOfGroup function under various different conditions.") + public void testGetDeviceCountOfGroup() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.doReturn(1).when(groupManagementProviderService).getDeviceCount(1); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).getDeviceCount(2); + Response response = groupManagementService.getDeviceCountOfGroup(1); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getDeviceCountOfGroup request failed for a request with valid parameters"); + response = groupManagementService.getDeviceCountOfGroup(2); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getDeviceCountOfGroup request succeded for a request with in-valid parameters"); + } + + @Test(description = "This method tests the addDevicesToGroup method under various conditions.") + public void testAddDevicesToGroup() throws GroupManagementException, DeviceNotFoundException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + List deviceIdentifiers = new ArrayList<>(); + Mockito.doNothing().when(groupManagementProviderService).addDevices(1, deviceIdentifiers); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).addDevices(2, + deviceIdentifiers); + Mockito.doThrow(new DeviceNotFoundException()).when(groupManagementProviderService).addDevices(3, + deviceIdentifiers); + Response response = groupManagementService.addDevicesToGroup(1, deviceIdentifiers); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "addDevicesToGroup request failed for a request with valid parameters"); + response = groupManagementService.addDevicesToGroup(2, deviceIdentifiers); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "addDevicesToGroup request succeded for a request with in-valid parameters"); + response = groupManagementService.addDevicesToGroup(3, deviceIdentifiers); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "addDevicesToGroup request succeded for a request with in-valid parameters"); + } + + @Test(description = "This method tests the removeDevicesFromGroup method under various conditions.") + public void testRemoveDevicesFromGroup() throws GroupManagementException, DeviceNotFoundException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + List deviceIdentifiers = new ArrayList<>(); + Mockito.doNothing().when(groupManagementProviderService).removeDevice(1, deviceIdentifiers); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).removeDevice(2, + deviceIdentifiers); + Mockito.doThrow(new DeviceNotFoundException()).when(groupManagementProviderService).removeDevice(3, + deviceIdentifiers); + Response response = groupManagementService.removeDevicesFromGroup(1, deviceIdentifiers); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "removeDevicesFromGroup request failed for a request with valid parameters"); + response = groupManagementService.removeDevicesFromGroup(2, deviceIdentifiers); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "removeDevicesFromGroup request succeeded for a request with in-valid parameters"); + response = groupManagementService.removeDevicesFromGroup(3, deviceIdentifiers); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "removeDevicesFromGroup request succeeded for a request with in-valid parameters"); + } + + @Test(description = "This method tests the getGroups with device id and device type under different conditions") + public void testGetGroupsWithDeviceId() throws GroupManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier("test", "android"); + Mockito.doReturn(new ArrayList()).when(groupManagementProviderService).getGroups(deviceIdentifier); + Response response = groupManagementService.getGroups("test", "android"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getGroups request failed with valid parameters"); + Mockito.reset(groupManagementProviderService); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) + .getGroups(Mockito.any(DeviceIdentifier.class)); + response = groupManagementService.getGroups("test", "android2"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getGroups request succeeded with in-valid parameters"); + } + + @Test(description = "This method tests updateDeviceAssigningToGroups under different conditions.") + public void testUpdateDeviceAssigningToGroups() throws GroupManagementException, DeviceNotFoundException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService")) + .toReturn(groupManagementProviderService); + Mockito.reset(groupManagementProviderService); + DeviceToGroupsAssignment deviceToGroupsAssignment = new DeviceToGroupsAssignment(); + List groupIds = new ArrayList<>(); + groupIds.add(1); + groupIds.add(2); + deviceToGroupsAssignment.setDeviceGroupIds(groupIds); + deviceToGroupsAssignment.setDeviceIdentifier(new DeviceIdentifier("test", "android")); + List deviceGroups = new ArrayList<>(); + DeviceGroup deviceGroup = new DeviceGroup(); + deviceGroup.setGroupId(1); + deviceGroups.add(deviceGroup); + deviceGroup = new DeviceGroup(); + deviceGroup.setGroupId(3); + deviceGroup.setOwner(CarbonConstants.REGISTRY_SYSTEM_USERNAME); + deviceGroups.add(deviceGroup); + deviceGroup = new DeviceGroup(); + deviceGroup.setGroupId(4); + deviceGroup.setOwner("test"); + deviceGroups.add(deviceGroup); + Mockito.doReturn(deviceGroups).when(groupManagementProviderService) + .getGroups(Mockito.any(DeviceIdentifier.class)); + Mockito.doNothing().when(groupManagementProviderService).addDevices(Mockito.anyInt(), Mockito.any()); + Mockito.doNothing().when(groupManagementProviderService).removeDevice(Mockito.anyInt(), Mockito.any()); + Response response = groupManagementService.updateDeviceAssigningToGroups(deviceToGroupsAssignment); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "updateDeviceAssigningToGroups request failed with valid parameters"); + Mockito.doThrow(new DeviceNotFoundException()).when(groupManagementProviderService) + .removeDevice(Mockito.anyInt(), Mockito.any()); + response = groupManagementService.updateDeviceAssigningToGroups(deviceToGroupsAssignment); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), + "updateDeviceAssigningToGroups request succeeded with in-valid parameters"); + Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService) + .getGroups(Mockito.any(DeviceIdentifier.class)); + response = groupManagementService.updateDeviceAssigningToGroups(deviceToGroupsAssignment); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "updateDeviceAssigningToGroups request succeeded with in-valid parameters"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java new file mode 100644 index 0000000000..92e321745f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java @@ -0,0 +1,117 @@ +/* + * 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.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.PaginationResult; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This is a test class for {@link NotificationManagementServiceImpl}. + */ +@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 NotificationManagementServiceImplTest { + private NotificationManagementService notificationManagementService; + private org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService notificationManagement; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void setup() throws UserStoreException, NotificationManagementException { + initMocks(this); + notificationManagementService = Mockito.mock(NotificationManagementService.class); + PaginationResult paginationResult = new PaginationResult(); + List notifications = new ArrayList<>(); + notifications.add(new Notification()); + paginationResult.setData(notifications); + paginationResult.setRecordsTotal(1); + Mockito.doReturn(paginationResult).when(notificationManagementService).getAllNotifications(Mockito.any()); + Mockito.doReturn(paginationResult).when(notificationManagementService) + .getNotificationsByStatus(Mockito.any(), Mockito.any()); + notificationManagement = new NotificationManagementServiceImpl(); + } + + @Test(description = "This method tests the behaviour of getNotifications method under different conditions") + public void testGetNotifications() throws NotificationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotificationManagementService")) + .toReturn(this.notificationManagementService); + Response response = notificationManagement.getNotifications("NEW", "test", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Notification retrieval failed"); + response = notificationManagement.getNotifications(null, "test", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Notification retrieval failed"); + Mockito.reset(this.notificationManagementService); + Mockito.doThrow(new NotificationManagementException()).when(notificationManagementService) + .getAllNotifications(Mockito.any()); + response = notificationManagement.getNotifications(null, "test", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Notification retrieval succeeded with issues in NotificationManagement OSGI service"); + Mockito.reset(this.notificationManagementService); + } + + @Test(description = "This method tests the behaviour of updateNotificationStatus method under different conditions") + public void testUpdateNotificationStatus() throws NotificationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotificationManagementService")) + .toReturn(this.notificationManagementService); + Mockito.doReturn(true).when(notificationManagementService) + .updateNotificationStatus(1, Notification.Status.CHECKED); + Mockito.doThrow(NotificationManagementException.class).when(notificationManagementService) + .updateNotificationStatus(2, Notification.Status.CHECKED); + Mockito.doReturn(true).when(notificationManagementService) + .updateNotificationStatus(3, Notification.Status.CHECKED); + Mockito.doReturn(new Notification()).when(notificationManagementService).getNotification(1); + Mockito.doThrow(new NotificationManagementException()).when(notificationManagementService).getNotification(3); + Response response = notificationManagement.updateNotificationStatus(1); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Notification status update failed under correct conditions"); + response = notificationManagement.updateNotificationStatus(2); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Notification status update succeeded under erroneous conditions"); + response = notificationManagement.updateNotificationStatus(3); + Assert.assertEquals(response.getEntity(), + "Notification updated successfully. But the retrial of the updated " + "notification failed", + "Notification status update succeeded under erroneous conditions"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java new file mode 100644 index 0000000000..bcee738b6e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -0,0 +1,384 @@ +/* + * 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.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +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.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +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.beans.BasicUserInfo; +import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentInvitation; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserInfo; +import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +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.user.api.UserStoreManager; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import javax.ws.rs.core.Response; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This is a test case for {@link UserManagementService}. + */ +@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 UserManagementServiceImplTest { + private UserStoreManager userStoreManager; + private UserManagementService userManagementService; + private DeviceManagementProviderService deviceManagementProviderService; + private static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user"; + private UserRealm userRealm; + private EnrollmentInvitation enrollmentInvitation; + private List userList; + private static final String TEST_USERNAME = "test"; + private static final String TEST2_USERNAME = "test2"; + private static final String TEST3_USERNAME = "test3"; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void setup() throws UserStoreException { + initMocks(this); + userManagementService = new UserManagementServiceImpl(); + userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS); + deviceManagementProviderService = Mockito + .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS); + userRealm = Mockito.mock(UserRealm.class); + RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class); + Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig(); + Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration(); + enrollmentInvitation = new EnrollmentInvitation(); + List recipients = new ArrayList<>(); + recipients.add(TEST_USERNAME); + enrollmentInvitation.setDeviceType("android"); + enrollmentInvitation.setRecipients(recipients); + userList = new ArrayList<>(); + userList.add(TEST_USERNAME); + } + + @Test(description = "This method tests the addUser method of UserManagementService") + public void testAddUser() throws UserStoreException, ConfigurationManagementException, DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.doReturn(true).when(userStoreManager).isExistingUser("admin"); + Mockito.doAnswer(new Answer() { + private int count = 0; + + public Object answer(InvocationOnMock invocation) { + if (count == 0) { + count++; + return false; + } else { + return true; + } + } + }).when(userStoreManager).isExistingUser(TEST_USERNAME); + + Mockito.doReturn("test@test.com").when(userStoreManager) + .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_EMAIL_ADDRESS, null); + Mockito.doReturn(TEST_USERNAME).when(userStoreManager) + .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_FIRST_NAME, null); + Mockito.doReturn(TEST_USERNAME).when(userStoreManager) + .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_LAST_NAME, null); + Mockito.doNothing().when(userStoreManager) + .addUser(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + UserInfo userInfo = new UserInfo(); + userInfo.setUsername("admin"); + Response response = userManagementService.addUser(userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(), + "Same user can be added " + "twice"); + userInfo = getUserInfo(); + Mockito.doReturn(true).when(userStoreManager).isExistingRole(DEFAULT_DEVICE_USER); + Mockito.doNothing().when(deviceManagementProviderService).sendRegistrationEmail(Mockito.any()); + response = userManagementService.addUser(userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), "User addition failed"); + } + + @Test(description = "This method tests the getUser method of UserManagementService", dependsOnMethods = + "testAddUser") + public void testGetUser() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.getUser(TEST_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "User retrieval failed"); + BasicUserInfo userInfo = (BasicUserInfo) response.getEntity(); + Assert.assertEquals(userInfo.getFirstname(), TEST_USERNAME, + "Retrieved user object is different from the original one " + "saved"); + + Mockito.doReturn(false).when(userStoreManager).isExistingUser(TEST2_USERNAME); + response = userManagementService.getUser(TEST2_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Non-existing user was retrieved successfully"); + } + + @Test(description = "This method tests the updateUser method of UserManagementService", dependsOnMethods = + {"testGetUser"}) + public void testUpdateUser() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.updateUser(TEST2_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Non-existing user was successfully updated"); + String[] roles = { "Internal/everyone", DEFAULT_DEVICE_USER }; + Mockito.doReturn(roles).when(userStoreManager).getRoleListOfUser(TEST_USERNAME); + Mockito.doNothing().when(userStoreManager).updateRoleListOfUser(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(userStoreManager).setUserClaimValues(Mockito.any(), Mockito.any(), Mockito.any()); + response = userManagementService.updateUser(TEST_USERNAME, null, getUserInfo()); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Updating the user info failed"); + } + + + @Test(description = "This method tests the getRolesOfUser method of UserManagementService", dependsOnMethods = + {"testUpdateUser"}) + public void testGetRolesOfUser() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.getRolesOfUser(TEST2_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Roles of a non-existing user was successfully retrieved"); + response = userManagementService.getRolesOfUser(TEST_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Retrieval of roles of a existing user failed."); + } + + @Test(description = "This method tests the IsUserExists method of UserManagementService", dependsOnMethods = + {"testGetRolesOfUser"}) + public void testIsUserExists() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.isUserExists(TEST2_USERNAME); + boolean responseEntity = (boolean) response.getEntity(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Check for existence of user failed"); + Assert.assertFalse(responseEntity, "Non-existing user is identified as already existing user"); + response = userManagementService.isUserExists(TEST_USERNAME); + responseEntity = (boolean) response.getEntity(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Check for existence of user failed"); + Assert.assertTrue(responseEntity, "Existing user is identified as non-existing user"); + } + + @Test(description = "This method tests the send invitation method of UserManagementService", dependsOnMethods = + {"testIsUserExists"}) + public void testSendInvitation() throws ConfigurationManagementException, DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.doNothing().when(deviceManagementProviderService).sendEnrolmentInvitation(Mockito.any(), Mockito.any()); + Response response = userManagementService.inviteExistingUsersToEnrollDevice(userList); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Inviting existing users to enroll device failed"); + } + + @Test(description = "This method tests the getUserNames method of UserManagementService", dependsOnMethods = + {"testSendInvitation"}) + public void testGetUserNames() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Mockito.doReturn(new String[] { TEST_USERNAME }).when(userStoreManager) + .listUsers(Mockito.anyString(), Mockito.anyInt()); + Response response = userManagementService.getUserNames(TEST_USERNAME, null, "00", 0, 0); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Getting user names is failed for a valid request"); + + } + + @Test(description = "This method tests the getUsers method of UserManagementService", + dependsOnMethods = {"testGetUserNames"}) + public void testGetUsers() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(userStoreManager); + Response response = userManagementService.getUsers(null, "00", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "GetUsers request failed"); + } + + @Test(description = "This method tests the inviteToEnrollDevice method of UserManagementService", + dependsOnMethods = "testGetUsers") + public void testInviteToEnrollDevice() { + URL resourceUrl = ClassLoader.getSystemResource("testng.xml"); + System.setProperty("carbon.home", resourceUrl.getPath()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(TEST_USERNAME); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + EnrollmentInvitation enrollmentInvitation = new EnrollmentInvitation(); + List recipients = new ArrayList<>(); + recipients.add(TEST_USERNAME); + enrollmentInvitation.setDeviceType("android"); + enrollmentInvitation.setRecipients(recipients); + Response response = userManagementService.inviteToEnrollDevice(enrollmentInvitation); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Inviting users to enroll device failed"); + } + + @Test(description = "This method tests the removeUser method of UserManagementService", dependsOnMethods = + "testInviteToEnrollDevice") + public void testRemoveUser() throws DeviceManagementException, UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.doReturn(true).when(deviceManagementProviderService).setStatus(Mockito.anyString(), Mockito.any()); + Mockito.doNothing().when(userStoreManager).deleteUser(Mockito.anyString()); + Response response = userManagementService.removeUser(TEST_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Cannot remove user, the request failed"); + response = userManagementService.removeUser(TEST2_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Successfully removed non-existing user"); + } + + @Test(description = "This method tests the behaviour of getUserCount method of UserManagementService", + dependsOnMethods = {"testRemoveUser"}) + public void testGetUserCount() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserRealm")).toReturn(userRealm); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreCountRetrieverService")) + .toReturn(null); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.getUserCount(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "User count retrieval failed"); + } + + @Test(description = "This method tests the behaviour of methods when there is an issue with " + + "DeviceManagementProviderService", dependsOnMethods = {"testGetUserCount"}) + public void testNegativeScenarios1() throws ConfigurationManagementException, DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(TEST_USERNAME); + Mockito.reset(deviceManagementProviderService); + Mockito.doThrow(new DeviceManagementException()).when(deviceManagementProviderService) + .sendEnrolmentInvitation(Mockito.any(), Mockito.any()); + Response response = userManagementService.inviteExistingUsersToEnrollDevice(userList); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + response = userManagementService.inviteToEnrollDevice(enrollmentInvitation); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + } + + @Test(description = "This method tests the behaviour of the different methods when there is an issue is " + + "userStoreManager", dependsOnMethods = {"testNegativeScenarios1"}) + public void testNegativeScenarios2() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Mockito.doThrow(new UserStoreException()).when(userStoreManager).isExistingUser(TEST3_USERNAME); + Response response = userManagementService.getUser(TEST3_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user retrieval with problematic inputs"); + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(TEST3_USERNAME); + response = userManagementService.addUser(userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user addition with problematic inputs"); + response = userManagementService.updateUser(TEST3_USERNAME, null, userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user updating request with problematic inputs"); + response = userManagementService.removeUser(TEST3_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user removal request with problematic inputs"); + response = userManagementService.getRolesOfUser(TEST3_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user role retrieval request with problematic inputs"); + response = userManagementService.isUserExists(TEST3_USERNAME); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for checking existence of user under problematic conditions"); + } + + @Test(description = "This method tests the behaviour of various methods when there is an issue with UserStore " + + "Manager", dependsOnMethods = {"testNegativeScenarios2"}) + public void testNegativeScenarios3() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserRealm")).toReturn(userRealm); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreCountRetrieverService")) + .toReturn(null); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(TEST_USERNAME); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.reset(this.userStoreManager); + Mockito.doThrow(new UserStoreException()).when(userStoreManager) + .getUserClaimValue(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doThrow(new UserStoreException()).when(userStoreManager) + .listUsers(Mockito.anyString(), Mockito.anyInt()); + Response response = userManagementService.getUsers(TEST_USERNAME, "00", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a users retrieval request."); + response = userManagementService.getUserCount(); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user count retrieval request."); + response = userManagementService.getUserNames(TEST_USERNAME, null, "00", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user count retrieval request."); + response = userManagementService.inviteToEnrollDevice(enrollmentInvitation); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + response = userManagementService.inviteExistingUsersToEnrollDevice(userList); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + } + + /** + * To get the user info of a user + * + * @return UserInfo of the User. + */ + private UserInfo getUserInfo() { + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(TEST_USERNAME); + userInfo.setFirstname(TEST_USERNAME); + userInfo.setLastname(TEST_USERNAME); + userInfo.setEmailAddress("test@test.com"); + return userInfo; + } + +} 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..8eef632459 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + 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 531e9f28b3..6f4c255bdd 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.136-SNAPSHOT + 3.0.170-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 ff1280a6ed..3818921cab 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml @@ -139,7 +139,11 @@ file:src/test/resources/log4j.properties - src/test/resources/testng.xml + src/test/resources/testng.xml + src/test/resources/mysql-testng.xml + src/test/resources/mssql-testng.xml + src/test/resources/oracle-testng.xml + src/test/resources/postgre-testng.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index bf0d93bc7e..c3fa26c20b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -105,16 +105,6 @@ public interface DeviceDAO { */ boolean updateDevice(Device device, int tenantId) throws DeviceManagementDAOException; - /** - * This method is used to remove a device. - * - * @param deviceId id of the device that should be removed. - * @param tenantId tenant id. - * @return returns the id of removed device. - * @throws DeviceManagementDAOException - */ - int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; - /** * This method is used to retrieve a device of a given device-identifier and tenant-id. * @@ -212,16 +202,6 @@ public interface DeviceDAO { */ List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; - /** - * This method is used to retrieve the devices of a given tenant and type as a paginated result. - * - * @param request PaginationRequest object holding the data for pagination and search. - * @param tenantId tenant id. - * @return returns paginated list of devices of provided type. - * @throws DeviceManagementDAOException - */ - List getDevicesByType(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; - /** * This method is used to retrieve all the devices of a given tenant and device type. * @@ -249,7 +229,7 @@ public interface DeviceDAO { * @param username user name. * @param type device type. * @param tenantId tenant id. - * @return + * @return List of devices. * @throws DeviceManagementDAOException */ List getDevicesOfUser(String username, String type, int tenantId) throws DeviceManagementDAOException; @@ -371,16 +351,6 @@ public interface DeviceDAO { EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; - /** - * This method is used to retrieve current enrollment of a given device. - * - * @param deviceId device id. - * @param tenantId tenant id. - * @return returns EnrolmentInfo object. - * @throws DeviceManagementDAOException - */ - EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException; - /** * This method is used to retrieve current active enrollment of a given device and tenant id. * @@ -423,29 +393,6 @@ public interface DeviceDAO { List getDevicesByStatus(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; - /** - * This method is used to retrieve the enrollment id of a given device and status. - * - * @param deviceId device id. - * @param status enrollment status. - * @param tenantId tenant id. - * @return returns the id of current enrollment. - * @throws DeviceManagementDAOException - */ - int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status, - int tenantId) throws DeviceManagementDAOException; - - /** - * This method is used to retrieve the enrollment info of a given list of devices and status. - * - * @param deviceIds A list of device identifiers. - * @param status enrollment status. - * @param tenantId tenant id. - * @return returns a list of enrolment info objects. - * @throws DeviceManagementDAOException - */ - List getEnrolmentsByStatus(List deviceIds, Status status, - int tenantId) throws DeviceManagementDAOException; List getDeviceEnrolledTenants() throws DeviceManagementDAOException; } 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..214e050d90 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 @@ -104,11 +104,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } - @Override - public int removeDevice(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException { - return 0; - } - @Override public Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException { Connection conn; @@ -914,37 +909,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } - @Override - public EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - EnrolmentInfo enrolmentInfo = null; - try { - conn = this.getConnection(); - String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + - "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + - "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + - "AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceId.getId()); - stmt.setString(2, deviceId.getType()); - stmt.setInt(3, tenantId); - stmt.setInt(4, tenantId); - rs = stmt.executeQuery(); - if (rs.next()) { - enrolmentInfo = DeviceManagementDAOUtil.loadMatchingEnrolment(rs); - } - return enrolmentInfo; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + - "of device '" + deviceId + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - @Override public EnrolmentInfo getActiveEnrolment(DeviceIdentifier deviceId, int tenantId) throws DeviceManagementDAOException { Connection conn; @@ -977,81 +941,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } - public int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status, - int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "SELECT e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) dtm " + - "WHERE e.DEVICE_ID = dtm.ID AND e.STATUS = ? AND e.TENANT_ID = ?;"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceId.getId()); - stmt.setString(2, deviceId.getType()); - stmt.setInt(3, tenantId); - stmt.setString(4, status.toString()); - stmt.setInt(5, tenantId); - rs = stmt.executeQuery(); - if (rs.next()) { - return rs.getInt("ENROLMENT_ID"); - } else { - return -1; // if no results found - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + - "id of device '" + deviceId + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - public List getEnrolmentsByStatus(List deviceIds, Status status, - int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List enrolments = new ArrayList<>(); - try { - conn = this.getConnection(); - StringBuilder sql = new StringBuilder(); - sql.append("SELECT e.ID AS ENROLMENT_ID, e.OWNER, e.OWNERSHIP, e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, " + - "e.STATUS FROM DM_ENROLMENT e WHERE e.DEVICE_ID IN (SELECT d.ID FROM DM_DEVICE d " + - "WHERE d.DEVICE_IDENTIFICATION IN ("); - - // adding arguments to the sql query - Iterator iterator = deviceIds.iterator(); - while (iterator.hasNext()) { - iterator.next(); - sql.append(" ?"); - if (iterator.hasNext()) { - sql.append(","); - } - } - sql.append(") AND d.TENANT_ID = ?) AND e.STATUS = ? AND e.TENANT_ID = ?"); - - stmt = conn.prepareStatement(sql.toString()); - int index = 1; - for (DeviceIdentifier id : deviceIds) { - stmt.setString(index++, id.getId()); - } - stmt.setInt(index++, tenantId); - stmt.setString(index++, status.toString()); - stmt.setInt(index, tenantId); - rs = stmt.executeQuery(); - while (rs.next()) { - enrolments.add(DeviceManagementDAOUtil.loadEnrolment(rs)); - } - return enrolments; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + - "ids of devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - public List getDevicesByStatus(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException { Connection conn; @@ -1062,9 +951,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/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index 33371e3c9d..b7a4086d0e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -23,9 +23,12 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -201,25 +204,53 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { return true; } - @Override - public boolean setStatus(String currentOwner, EnrolmentInfo.Status status, - int tenantId) throws DeviceManagementDAOException { + private int getCountOfDevicesOfOwner(String owner, int tenantID) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; + ResultSet rs = null; + int count = 0; try { conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE OWNER = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, status.toString()); - stmt.setString(2, currentOwner); - stmt.setInt(3, tenantId); - stmt.executeUpdate(); + String checkQuery = "SELECT COUNT(ID) AS COUNT FROM DM_ENROLMENT WHERE OWNER = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(checkQuery); + stmt.setString(1, owner); + stmt.setInt(2, tenantID); + rs = stmt.executeQuery(); + if(rs.next()){ + count = rs.getInt("COUNT"); + } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e); + throw new DeviceManagementDAOException("Error occurred while trying to get device " + + "count of Owner : "+owner, e); } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return count; + } + + @Override + public boolean setStatus(String currentOwner, EnrolmentInfo.Status status, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + if(getCountOfDevicesOfOwner(currentOwner, tenantId) > 0){ + try { + conn = this.getConnection(); + String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE OWNER = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, status.toString()); + stmt.setString(2, currentOwner); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return true; + } else { + return false; } - return true; } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 353eaedb38..872ea7c285 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -153,41 +153,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } - @Override - public List getDevicesByType(PaginationRequest request, int tenantId) - throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List devices = null; - try { - conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, request.getDeviceType()); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); - stmt.setInt(4, request.getStartIndex()); - stmt.setInt(5, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 2f96e94d00..33875fc9c7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -159,42 +159,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } - @Override - public List getDevicesByType(PaginationRequest request, int tenantId) - throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List devices = null; - try { - conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " - + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " - + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " - + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " - + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " - + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID" - + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, request.getDeviceType()); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); - stmt.setInt(4, request.getStartIndex()); - stmt.setInt(5, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { @@ -401,36 +365,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } - public int getEnrolmentByStatus(DeviceIdentifier deviceId, EnrolmentInfo.Status status, - int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "SELECT e.ID ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) dtm " + - "WHERE e.DEVICE_ID = dtm.ID AND e.STATUS = ? AND e.TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceId.getId()); - stmt.setString(2, deviceId.getType()); - stmt.setInt(3, tenantId); - stmt.setString(4, status.toString()); - stmt.setInt(5, tenantId); - rs = stmt.executeQuery(); - if (rs.next()) { - return rs.getInt("ENROLMENT_ID"); - } else { - return -1; // if no results found - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + - "id of device '" + deviceId + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 8578892885..f8bce9b286 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -140,41 +140,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } - @Override - public List getDevicesByType(PaginationRequest request, int tenantId) - throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List devices = null; - try { - conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, request.getDeviceType()); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); - stmt.setInt(4, request.getRowCount()); - stmt.setInt(5, request.getStartIndex()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index c1b4dc0529..ee60068fa8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -156,42 +156,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { return devices; } - @Override - public List getDevicesByType(PaginationRequest request, int tenantId) - throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List devices = null; - try { - conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID" + - " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, request.getDeviceType()); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); - stmt.setInt(4, request.getStartIndex()); - stmt.setInt(5, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index a575d18cf3..500e48b0ee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -394,28 +394,6 @@ public class GenericOperationDAOImpl implements OperationDAO { List activities = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - -/* - String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + - "op.OPERATION_CODE, op.TYPE as OPERATION_TYPE, opm.STATUS, en.DEVICE_ID,\n" + - "ops.RECEIVED_TIMESTAMP, ops.ID as OP_RES_ID, ops.OPERATION_RESPONSE,\n" + - "de.DEVICE_IDENTIFICATION, dt.NAME as DEVICE_TYPE\n" + - "FROM DM_ENROLMENT_OP_MAPPING AS opm\n" + - "LEFT JOIN DM_OPERATION AS op ON opm.OPERATION_ID = op.ID \n" + - "LEFT JOIN DM_ENROLMENT as en ON opm.ENROLMENT_ID = en.ID \n" + - "LEFT JOIN DM_DEVICE as de ON en.DEVICE_ID = de.ID \n" + - "LEFT JOIN DM_DEVICE_TYPE as dt ON dt.ID = de.DEVICE_TYPE_ID \n" + - "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE as ops ON \n" + - "opm.ENROLMENT_ID = ops.ENROLMENT_ID AND opm.OPERATION_ID = ops.OPERATION_ID \n" + - "WHERE opm.UPDATED_TIMESTAMP > ? \n" + - "AND de.TENANT_ID = ? \n"; - - if (timestamp == 0) { - sql += "ORDER BY opm.OPERATION_ID LIMIT ? OFFSET ?;"; - } else { - sql += "ORDER BY opm.UPDATED_TIMESTAMP asc LIMIT ? OFFSET ?"; - } -*/ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String sql = "SELECT " + " opr.ENROLMENT_ID, " + @@ -650,11 +628,6 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); -// if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { -// operation.setReceivedTimeStamp(""); -// } else { -// operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); -// } if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { @@ -696,11 +669,6 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setId(rs.getInt("ID")); operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); -// if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { -// operation.setReceivedTimeStamp(""); -// } else { -// operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); -// } if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java index cf7a1eb069..f96e2e4048 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -251,7 +251,7 @@ public class ProcessorImpl implements Processor { if (log.isDebugEnabled()) { log.debug("Query : " + queryHolder.getQuery()); } - Connection conn; + Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List devices = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index d5d0b1700a..65b6af46fa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -23,7 +23,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.search.Condition; -import org.wso2.carbon.device.mgt.core.search.mgt.*; +import org.wso2.carbon.device.mgt.core.search.mgt.Constants; +import org.wso2.carbon.device.mgt.core.search.mgt.InvalidOperatorException; +import org.wso2.carbon.device.mgt.core.search.mgt.QueryBuilder; +import org.wso2.carbon.device.mgt.core.search.mgt.QueryHolder; +import org.wso2.carbon.device.mgt.core.search.mgt.ValueType; import java.util.ArrayList; import java.util.HashMap; @@ -93,8 +97,8 @@ public class QueryBuilderImpl implements QueryBuilder { intArr[0] = 1; //int x = 1; String query = this.getGenericQueryPart(valueTypeArray) + - this.processAND(andColumns, valueTypeArray, intArr) + - this.processOR(orColumns, valueTypeArray, intArr); + this.processAND(andColumns, valueTypeArray, intArr) + + this.processOR(orColumns, valueTypeArray, intArr); List queryHolders = new ArrayList<>(); QueryHolder queryHolder = new QueryHolder(); queryHolder.setQuery(query); @@ -135,20 +139,13 @@ public class QueryBuilderImpl implements QueryBuilder { + " LIKE ? "; ValueType type = new ValueType(); type.setColumnType(ValueType.columnType.STRING); - type.setStringValue("%"+con.getValue()+"%"); + type.setStringValue("%" + con.getValue() + "%"); valueType[x] = type; x++; } else { querySuffix = querySuffix + " AND DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + con .getOperator() + " ? "; - ValueType type = new ValueType(); - if (Utils.checkColumnType(con.getKey())) { - type.setColumnType(ValueType.columnType.STRING); - type.setStringValue(con.getValue()); - } else { - type.setColumnType(ValueType.columnType.INTEGER); - type.setIntValue(Integer.parseInt(con.getValue())); - } + ValueType type = this.getValueType(con); valueType[x] = type; x++; } @@ -182,21 +179,15 @@ public class QueryBuilderImpl implements QueryBuilder { + " LIKE ? "; ValueType type = new ValueType(); type.setColumnType(ValueType.columnType.STRING); - type.setStringValue("%"+con.getValue()+"%"); + type.setStringValue("%" + con.getValue() + "%"); valueType[x] = type; x++; } else { querySuffix = querySuffix + " OR DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + con .getOperator() + " ? "; - ValueType type = new ValueType(); - if (Utils.checkColumnType(con.getKey())) { - type.setColumnType(ValueType.columnType.STRING); - type.setStringValue(con.getValue()); - } else { - type.setColumnType(ValueType.columnType.INTEGER); - type.setIntValue(Integer.parseInt(con.getValue())); - } + ValueType type = this.getValueType(con); + valueType[x] = type; x++; } @@ -386,4 +377,35 @@ public class QueryBuilderImpl implements QueryBuilder { throw new InvalidOperatorException("Error occurred while building the sql", e); } } + + /** + * Returns a Value type based on the Condition data. + * + * @param con : The condition that passed. + * @re + */ + private ValueType getValueType(Condition con) { + ValueType type = new ValueType(); + String colValue = Utils.checkColumnType(con.getKey()); + + switch (colValue) { + case "String": + type.setColumnType(ValueType.columnType.STRING); + type.setStringValue(con.getValue()); + break; + case "Double": + type.setColumnType(ValueType.columnType.DOUBLE); + type.setDoubleValue(Double.parseDouble(con.getValue())); + break; + case "Integer": + type.setColumnType(ValueType.columnType.INTEGER); + type.setIntValue(Integer.parseInt(con.getValue())); + break; + case "Long": + type.setColumnType(ValueType.columnType.STRING); + type.setLongValue(Long.parseLong(con.getValue())); + } + + return type; + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java index 9e0d044e1e..fb5251acf4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java @@ -75,32 +75,56 @@ public class Utils { } - public static boolean checkColumnType(String column) { + public static String checkColumnType(String column) { - boolean bool = false; + String type; switch (column) { case "deviceModel": - bool = true; + type = "String"; break; case "vendor": - bool = true; + type = "String"; break; case "osVersion": - bool = true; + type = "String"; break; case "connectionType": - bool = true; + type = "String"; break; case "ssid": - bool = true; + type = "String"; + break; + case "imei": + type = "String"; + break; + case "imsi": + type = "String"; + break; + case "batteryLevel": + type = "Double"; + break; + case "internalTotalMemory": + type = "Double"; + break; + case "internalAvailableMemory": + type = "Double"; + break; + case "externalAvailableMemory": + type = "Double"; + break; + case "externalTotalMemory": + type = "Double"; + break; + case "cpuUsage": + type = "Double"; break; default: - bool = false; + type = "String"; break; } - return bool; + return type; } public static Map getDeviceDetailsColumnNames() { 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 4c1454015b..9ee72d040a 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 @@ -144,7 +144,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()) { @@ -237,10 +237,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String msg = "Error occurred while adding enrolment related metadata for device: " + device.getId(); log.error(msg, e); throw new DeviceManagementException(msg, e); - } catch (TransactionManagementException e) { - String msg = "Error occurred while initiating transaction to enrol device: " + device.getId(); - log.error(msg); - throw new DeviceManagementException(msg, e); } catch (Exception e) { String msg = "Error occurred while enrolling device: " + device.getId(); log.error(msg, e); @@ -251,13 +247,20 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } } else { - int enrolmentId = 0; + int enrolmentId; try { DeviceManagementDAOFactory.beginTransaction(); DeviceType type = deviceTypeDAO.getDeviceType(device.getType(), tenantId); - int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId); - enrolmentId = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); - DeviceManagementDAOFactory.commitTransaction(); + if (type != null) { + int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId); + enrolmentId = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } else { + DeviceManagementDAOFactory.rollbackTransaction(); + throw new DeviceManagementException("No device type registered with name - " + device.getType() + + " and hence unable to find succeed the enrollment of device - " + + device.getDeviceIdentifier()); + } } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while adding metadata of '" + device.getType() + @@ -357,7 +360,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Get enrollments for user '" + user + "' device: " + deviceId); } - List enrolmentInfos = new ArrayList<>(); + List enrolmentInfos; try { DeviceManagementDAOFactory.openConnection(); enrolmentInfos = enrollmentDAO.getEnrollmentsOfUser(deviceId, user, this.getTenantId()); @@ -447,10 +450,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { Device device = this.getDevice(deviceId, false); - if (device != null) { - return true; - } - return false; + return device != null; } @Override @@ -621,8 +621,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv + requireDeviceInfo); } PaginationResult paginationResult = new PaginationResult(); - List allDevices = new ArrayList<>(); - int count = 0; + List allDevices; + int count; int tenantId = this.getTenantId(); String deviceType = request.getDeviceType(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -673,9 +673,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Get devices with pagination " + request.toString() + " and requiredDeviceInfo: " + requireDeviceInfo); } - List devicesForRoles = null; + List devicesForRoles; PaginationResult paginationResult = new PaginationResult(); - List allDevices = new ArrayList<>(); + List allDevices; int count = 0; int tenantId = this.getTenantId(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -779,7 +779,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv " and owner '" + owner + "' and requiredDeviceInfo: " + requireDeviceInfo); } int tenantId = this.getTenantId(); - Device device = null; + Device device; try { DeviceManagementDAOFactory.openConnection(); device = deviceDAO.getDevice(deviceId, owner, tenantId); @@ -829,12 +829,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); - params.put(key, new TypedValue, Object>(String.class, props.getProperty(key))); + params.put(key, new TypedValue<>(String.class, props.getProperty(key))); } params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); try { EmailContext ctx = new EmailContext.EmailContextBuilder(new ContentProviderInfo(templateName, params), @@ -869,17 +869,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (emailSenderService != null) { Map, Object>> params = new HashMap<>(); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.FIRST_NAME, - new TypedValue, Object>(String.class, metaInfo.getProperty("first-name"))); + new TypedValue<>(String.class, metaInfo.getProperty("first-name"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.USERNAME, - new TypedValue, Object>(String.class, metaInfo.getProperty("username"))); + new TypedValue<>(String.class, metaInfo.getProperty("username"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.PASSWORD, - new TypedValue, Object>(String.class, metaInfo.getProperty("password"))); + new TypedValue<>(String.class, metaInfo.getProperty("password"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.DOMAIN, - new TypedValue, Object>(String.class, metaInfo.getProperty("domain"))); + new TypedValue<>(String.class, metaInfo.getProperty("domain"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); try { EmailContext ctx = new EmailContext.EmailContextBuilder( @@ -1278,7 +1278,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Update enrollment with status"); } try { - boolean success = false; + boolean success; int tenantId = this.getTenantId(); DeviceManagementDAOFactory.beginTransaction(); success = enrollmentDAO.setStatus(currentOwner, status, tenantId); @@ -1601,10 +1601,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv + requireDeviceInfo); } PaginationResult result = new PaginationResult(); - int deviceCount = 0; + int deviceCount; int tenantId = this.getTenantId(); String username = request.getOwner(); - List userDevices = new ArrayList<>(); + List userDevices; request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); @@ -1656,7 +1656,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } PaginationResult result = new PaginationResult(); List allDevices; - int deviceCount = 0; + int deviceCount; int tenantId = this.getTenantId(); String ownerShip = request.getOwnership(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -1723,7 +1723,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List userDevices; for (String user : users) { - userDevices = new ArrayList<>(); try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(user, tenantId); @@ -1859,7 +1858,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } PaginationResult result = new PaginationResult(); int tenantId = this.getTenantId(); - List allDevices = new ArrayList<>(); + List allDevices; String deviceName = request.getDeviceName(); request = DeviceManagerUtil.validateDeviceListPageSize(request); try { @@ -2013,10 +2012,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean isEnrolled(DeviceIdentifier deviceId, String user) throws DeviceManagementException { Device device = this.getDevice(deviceId, false); - if (device != null && device.getEnrolmentInfo() != null && device.getEnrolmentInfo().getOwner().equals(user)) { - return true; - } - return false; + return device != null && device.getEnrolmentInfo() != null && device.getEnrolmentInfo().getOwner().equals(user); } @Override @@ -2050,7 +2046,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Change device status of device: " + deviceIdentifier.getId() + " of type '" + deviceIdentifier.getType() + "'"); } - boolean isDeviceUpdated = false; + boolean isDeviceUpdated; Device device = getDevice(deviceIdentifier, false); int deviceId = device.getId(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); @@ -2245,7 +2241,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * @param service {@link GroupManagementProviderService} instance. * @param groupName of the group to create. * @return Group with details. - * @throws GroupManagementException + * @throws GroupManagementException Group Management Exception */ private DeviceGroup createDefaultGroup(GroupManagementProviderService service, String groupName) throws GroupManagementException { @@ -2454,27 +2450,25 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Get all device info of devices, num of devices: " + allDevices.size()); } List devices = new ArrayList<>(); - if (allDevices != null) { - for (Device device : allDevices) { - device.setDeviceInfo(this.getDeviceInfo(device)); - device.setApplications(this.getInstalledApplications(device)); - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); + for (Device device : allDevices) { + device.setDeviceInfo(this.getDeviceInfo(device)); + device.setApplications(this.getInstalledApplications(device)); + DeviceManager deviceManager = this.getDeviceManager(device.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + + "Therefore, not attempting method 'isEnrolled'"); } devices.add(device); + continue; + } + Device dmsDevice = + deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); } + devices.add(device); } return devices; } 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 f55e8fb0c9..d2e4efdcb0 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 @@ -450,11 +450,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()); } @@ -527,7 +522,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) { @@ -551,10 +553,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 010b47b8d0..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 @@ -20,6 +20,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; +import java.util.ArrayList; import java.util.List; public class TestDeviceManager implements DeviceManager { @@ -80,19 +81,27 @@ public class TestDeviceManager implements DeviceManager { @Override public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - return null; + List features = new ArrayList(); + List properties = new ArrayList(); + Device.Property prop1 = new Device.Property(); + prop1.setName("Prop1"); + prop1.setValue("Prop1-value"); + properties.add(prop1); + Device device = new Device(deviceId.getType()+"-"+deviceId.getId(), deviceId.getType(), + "This is a test Device", deviceId.getId(), null, features, properties); + return device; } @Override public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { - return false; + return true; } @Override public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) 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/common/BaseDeviceManagementTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java index 21261bef2b..b5565814b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java @@ -21,12 +21,11 @@ package org.wso2.carbon.device.mgt.core.common; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -38,13 +37,13 @@ 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.mock.MockDataSource; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; 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.GroupManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; -import org.wso2.carbon.email.sender.core.service.EmailSenderServiceImpl; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryDataHolder; @@ -60,17 +59,21 @@ import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.InputStream; import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; import java.sql.Statement; public abstract class BaseDeviceManagementTest { - + protected static final String DATASOURCE_EXT = ".xml"; private DataSource dataSource; - private static final Log log = LogFactory.getLog(BaseDeviceManagementTest.class); + private static String datasourceLocation; + private static boolean mock; @BeforeSuite - public void setupDataSource() throws Exception { + @Parameters({"datasource", "isMock"}) + public void setupDataSource(@Optional("src/test/resources/config/datasource/data-source-config") String datasource, + @Optional("false") boolean isMock) + throws Exception { + datasourceLocation = datasource; + mock = isMock; this.initDataSource(); this.initSQLScript(); this.initializeCarbonContext(); @@ -78,14 +81,15 @@ public abstract class BaseDeviceManagementTest { } protected void initDataSource() throws Exception { - this.dataSource = this.getDataSource(this.readDataSourceConfig()); + this.dataSource = this.getDataSource(this. + readDataSourceConfig(datasourceLocation + DATASOURCE_EXT)); DeviceManagementDAOFactory.init(dataSource); GroupManagementDAOFactory.init(dataSource); OperationManagementDAOFactory.init(dataSource); NotificationManagementDAOFactory.init(dataSource); } - protected void initServices() throws DeviceManagementException, RegistryException { + private void initServices() throws DeviceManagementException, RegistryException, AxisFault { DeviceConfigurationManager.getInstance().initConfig(); DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl(); DeviceManagementServiceComponent.notifyStartupListeners(); @@ -108,29 +112,26 @@ public abstract class BaseDeviceManagementTest { return context.getEmbeddedRegistryService(); } - private ConfigurationContextService getConfigContextService() throws RegistryException { - ConfigurationContext context = - null; - try { - context = ConfigurationContextFactory.createConfigurationContextFromFileSystem - ("src/test/resources/carbon-home/repository/conf/axis2/axis2.xml"); - } catch (AxisFault axisFault) { - axisFault.printStackTrace(); - } - ConfigurationContextService service = new ConfigurationContextService(context, null); - return service; + private ConfigurationContextService getConfigContextService() throws RegistryException, AxisFault { + ConfigurationContext context = ConfigurationContextFactory.createConfigurationContextFromFileSystem + ("src/test/resources/carbon-home/repository/conf/axis2/axis2.xml"); + return new ConfigurationContextService(context, null); } @BeforeClass public abstract void init() throws Exception; - private DataSource getDataSource(DataSourceConfig config) { - PoolProperties properties = new PoolProperties(); - properties.setUrl(config.getUrl()); - properties.setDriverClassName(config.getDriverClassName()); - properties.setUsername(config.getUser()); - properties.setPassword(config.getPassword()); - return new org.apache.tomcat.jdbc.pool.DataSource(properties); + protected DataSource getDataSource(DataSourceConfig config) { + if (!isMock()) { + PoolProperties properties = new PoolProperties(); + properties.setUrl(config.getUrl()); + properties.setDriverClassName(config.getDriverClassName()); + properties.setUsername(config.getUser()); + properties.setPassword(config.getPassword()); + return new org.apache.tomcat.jdbc.pool.DataSource(properties); + } else { + return new MockDataSource(config.getUrl()); + } } private void initializeCarbonContext() { @@ -159,9 +160,9 @@ public abstract class BaseDeviceManagementTest { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); } - private DataSourceConfig readDataSourceConfig() throws DeviceManagementException { + protected DataSourceConfig readDataSourceConfig(String configLocation) throws DeviceManagementException { try { - File file = new File("src/test/resources/config/datasource/data-source-config.xml"); + File file = new File(configLocation); Document doc = DeviceManagerUtil.convertToDocument(file); JAXBContext testDBContext = JAXBContext.newInstance(DataSourceConfig.class); Unmarshaller unmarshaller = testDBContext.createUnmarshaller(); @@ -183,49 +184,18 @@ public abstract class BaseDeviceManagementTest { } } - public void deleteData() { - Connection conn = null; - try { - conn = getDataSource().getConnection(); - conn.setAutoCommit(false); - String[] cleanupTables = new String[]{"DM_NOTIFICATION","DM_DEVICE_OPERATION_RESPONSE","DM_ENROLMENT_OP_MAPPING", "DM_CONFIG_OPERATION", - "DM_POLICY_OPERATION", "DM_COMMAND_OPERATION", "DM_PROFILE_OPERATION", "DM_DEVICE_GROUP_MAP", - "DM_GROUP", "DM_ENROLMENT", "DM_DEVICE_APPLICATION_MAPPING", - "DM_APPLICATION", "DM_DEVICE", "DM_DEVICE_TYPE"}; - for (String table : cleanupTables) { - this.cleanData(conn, table); - } - conn.commit(); - } catch (SQLException e) { - try { - if (conn != null) { - conn.rollback(); - } - } catch (SQLException e1) { - log.error("Error occurred while roll-backing the transaction", e); - } - String msg = "Error occurred while cleaning up temporary data generated during test execution"; - log.error(msg, e); - Assert.fail(msg, e); - } finally { - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing the connection", e); - } - } - } + protected DataSource getDataSource() { + return dataSource; } - private void cleanData(Connection conn, String tableName) throws SQLException { - try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM " + tableName)) { - stmt.execute(); + protected String getDatasourceLocation() throws Exception { + if (datasourceLocation == null) { + throw new Exception("Data source location is null!!!"); } + return datasourceLocation; } - protected DataSource getDataSource() { - return dataSource; + protected boolean isMock() { + return mock; } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java index dea79ea662..1320f99e5b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java @@ -44,19 +44,26 @@ public class TestDataHolder { public static Device generateDummyDeviceData(String deviceType) { Device device = new Device(); - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setOwner(OWNER); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); - device.setEnrolmentInfo(enrolmentInfo); + device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo + .OwnerShip.BYOD, EnrolmentInfo.Status.CREATED)); device.setDescription("Test Description"); device.setDeviceIdentifier(initialDeviceIdentifier); device.setType(deviceType); 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 generateDummyDeviceInfo() { DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.setDeviceModel("DUMMY_MODEL"); @@ -98,6 +105,7 @@ public class TestDataHolder { device.setDescription("Test Description"); device.setDeviceIdentifier(deviceIdentifier); device.setType(deviceType); + device.setName(deviceType + "-" + deviceIdentifier); return device; } @@ -121,17 +129,13 @@ public class TestDataHolder { } public static Device generateDummyDeviceData(DeviceIdentifier deviceIdentifier) { - Device device = new Device(); - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setOwner(OWNER); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); - device.setEnrolmentInfo(enrolmentInfo); - device.setDescription("Test Description"); - device.setDeviceIdentifier(deviceIdentifier.getId()); - device.setType(deviceIdentifier.getType()); + Device device = new Device(); + device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo + .OwnerShip.BYOD, EnrolmentInfo.Status.CREATED)); + device.setDescription("Test Description"); + device.setDeviceIdentifier(deviceIdentifier.getId()); + device.setType(deviceIdentifier.getType()); + device.setName(deviceIdentifier.getType() + "-" + deviceIdentifier.getId()); return device; } @@ -165,7 +169,7 @@ public class TestDataHolder { } public static OperationMonitoringTaskConfig generateMonitoringTaskConfig(boolean enabled, int frequency, - int numberOfOperations) { + int numberOfOperations) { OperationMonitoringTaskConfig taskConfig = new OperationMonitoringTaskConfig(); List operationList = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/ApplicationPersistenceTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/ApplicationPersistenceTests.java index 7d697ca6c7..6bbeb5393a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/ApplicationPersistenceTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/ApplicationPersistenceTests.java @@ -56,9 +56,10 @@ public class ApplicationPersistenceTests extends BaseDeviceManagementTest { Assert.fail(msg, e); } - Assert.assertEquals(target.getApplicationIdentifier(), testAppIdentifier, "Application added is not as same as " + - "what's " + - "retrieved"); + if (!isMock()) { + Assert.assertEquals(target.getApplicationIdentifier(), testAppIdentifier, + "Application added is not as same as what's retrieved"); + } } private Application getApplication(String appIdentifier, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java index 22914836b7..c1143b9198 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java @@ -174,8 +174,7 @@ public class DevicePersistTests extends BaseDeviceManagementTest { } @Test(dependsOnMethods = "testAddDeviceTest") - public void testSetEnrolmentStatus() { - + public void testSetEnrolmentStatus() throws DeviceManagementDAOException, TransactionManagementException { Device device = TestDataHolder.initialTestDevice; try { DeviceManagementDAOFactory.beginTransaction(); @@ -203,9 +202,11 @@ public class DevicePersistTests extends BaseDeviceManagementTest { log.error(msg, e); Assert.fail(msg, e); } - Assert.assertNotNull(target, "Enrolment status retrieved for the device carrying its identifier as '" + - device.getDeviceIdentifier() + "' is null"); - Assert.assertEquals(target, Status.ACTIVE, "Enrolment status retrieved is not as same as what's configured"); + if (!isMock()) { + Assert.assertNotNull(target, "Enrolment status retrieved for the device carrying its identifier as '" + + device.getDeviceIdentifier() + "' is null"); + Assert.assertEquals(target, Status.ACTIVE, "Enrolment status retrieved is not as same as what's configured"); + } } private Status getEnrolmentStatus(String identifier, String deviceType, int tenantId) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java index 7ba74caa10..5ab8c7577d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java @@ -85,5 +85,4 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest { public void init() throws Exception { this.initDataSource(); } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index cc57e51b85..442e4ae06a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -70,8 +70,10 @@ public class GroupPersistTests extends BaseDeviceManagementTest { Assert.fail(msg, e); } DeviceGroup group = getGroupById(groupId); - Assert.assertNotNull(group, "Group is null"); - log.debug("Group name: " + group.getName()); + if (!isMock()) { + Assert.assertNotNull(group, "Group is null"); + log.debug("Group name: " + group.getName()); + } } @Test(dependsOnMethods = {"addGroupTest"}) @@ -83,9 +85,11 @@ public class GroupPersistTests extends BaseDeviceManagementTest { request.setOwner(null); List groups = groupDAO.getGroups(request, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.closeConnection(); - Assert.assertNotEquals(groups.size(), 0, "No groups found"); - Assert.assertNotNull(groups.get(0), "Group is null"); - log.debug("No of Groups found: " + groups.size()); + if (!isMock()) { + Assert.assertNotEquals(groups.size(), 0, "No groups found"); + Assert.assertNotNull(groups.get(0), "Group is null"); + log.debug("No of Groups found: " + groups.size()); + } } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.closeConnection(); String msg = "Error occurred while find group by name."; @@ -112,7 +116,9 @@ public class GroupPersistTests extends BaseDeviceManagementTest { GroupManagementDAOFactory.commitTransaction(); List roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.closeConnection(); - Assert.assertEquals(roles, addedRoles, "Added roles are not equal to returned roles."); + if (!isMock()) { + Assert.assertEquals(roles, addedRoles, "Added roles are not equal to returned roles."); + } log.debug("Group shared with roles."); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.closeConnection(); @@ -132,11 +138,15 @@ public class GroupPersistTests extends BaseDeviceManagementTest { try { GroupManagementDAOFactory.openConnection(); List roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID); - roles.remove(0); + if (!isMock()) { + roles.remove(0); + } List deviceGroups = groupDAO.getGroups(roles.toArray(new String[roles.size()]), TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.closeConnection(); - Assert.assertEquals(deviceGroups.size(), 1, "Unexpected number of device groups found with role."); - Assert.assertEquals(deviceGroups.get(0).getGroupId(), groupId, "Unexpected groupId found with role."); + if (!isMock()) { + Assert.assertEquals(deviceGroups.size(), 1, "Unexpected number of device groups found with role."); + Assert.assertEquals(deviceGroups.get(0).getGroupId(), groupId, "Unexpected groupId found with role."); + } log.debug("Group found for given roles."); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.closeConnection(); @@ -162,7 +172,9 @@ public class GroupPersistTests extends BaseDeviceManagementTest { GroupManagementDAOFactory.commitTransaction(); List roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.closeConnection(); - Assert.assertNotEquals(roles, rolesToRemove, "Roles not removed."); + if (!isMock()) { + Assert.assertNotEquals(roles, rolesToRemove, "Roles not removed."); + } log.debug("Group unshared with given roles."); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.closeConnection(); @@ -205,9 +217,11 @@ public class GroupPersistTests extends BaseDeviceManagementTest { GroupManagementDAOFactory.openConnection(); List groupedDevices = groupDAO.getDevices(deviceGroup.getGroupId(), 0, 10, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.closeConnection(); - Assert.assertNotEquals(groupedDevices.size(), 0, "No device found"); - Assert.assertNotNull(groupedDevices.get(0), "Device is null"); - Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched"); + if (!isMock()) { + Assert.assertNotEquals(groupedDevices.size(), 0, "No device found"); + Assert.assertNotNull(groupedDevices.get(0), "Device is null"); + Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched"); + } } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.closeConnection(); String msg = "Error occurred while retrieving group details."; @@ -272,11 +286,12 @@ public class GroupPersistTests extends BaseDeviceManagementTest { log.error(msg, e); Assert.fail(msg, e); } - - group = getGroupById(groupId); - Assert.assertNotNull(group, "Group is null"); - Assert.assertEquals(group.getName(), name, "Group name"); - Assert.assertEquals(group.getDescription(), desc, "Group description"); + if (!isMock()) { + group = getGroupById(groupId); + Assert.assertNotNull(group, "Group is null"); + Assert.assertEquals(group.getName(), name, "Group name"); + Assert.assertEquals(group.getDescription(), desc, "Group description"); + } } @Test(dependsOnMethods = {"updateGroupTest"}) @@ -302,14 +317,20 @@ public class GroupPersistTests extends BaseDeviceManagementTest { Assert.fail(msg, e); } group = getGroupById(groupId); - Assert.assertNull(group, "Group is not deleted"); + if (!isMock()) { + Assert.assertNull(group, "Group is not deleted"); + } } private DeviceGroup getGroupById(int groupId) { try { GroupManagementDAOFactory.openConnection(); - DeviceGroup deviceGroup = groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID); + DeviceGroup deviceGroup = groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.closeConnection(); + if (deviceGroup == null && isMock()) { + deviceGroup = new DeviceGroup(); + deviceGroup.setGroupId(groupId); + } return deviceGroup; } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.closeConnection(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockConnection.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockConnection.java new file mode 100644 index 0000000000..1425005f71 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockConnection.java @@ -0,0 +1,342 @@ +/* +* 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.mock; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.RowIdLifetime; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; + +/** + * This is mock class which provides mock database connection. + */ +public class MockConnection implements Connection { + + private String url; + private List statements = new ArrayList<>(); + private int statementCounter = 0; + + public MockConnection(String url) { + this.url = url; + } + + @Override + public Statement createStatement() throws SQLException { + return getStatement(); + } + + private MockStatement getStatement() { + if (!statements.isEmpty()) { + MockStatement statement = this.statements.get(this.statementCounter); + statementCounter++; + return statement; + } + return new MockStatement(); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + return getStatement(); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + return null; + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return null; + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + + } + + @Override + public boolean getAutoCommit() throws SQLException { + return false; + } + + @Override + public void commit() throws SQLException { + + } + + @Override + public void rollback() throws SQLException { + + } + + @Override + public void close() throws SQLException { + + } + + @Override + public boolean isClosed() throws SQLException { + return false; + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return new MockDatabaseMetaData(this.url); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + + } + + @Override + public boolean isReadOnly() throws SQLException { + return false; + } + + @Override + public void setCatalog(String catalog) throws SQLException { + + } + + @Override + public String getCatalog() throws SQLException { + return null; + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + + } + + @Override + public int getTransactionIsolation() throws SQLException { + return 0; + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return null; + } + + @Override + public void clearWarnings() throws SQLException { + + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return null; + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + return null; + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + return null; + } + + @Override + public Map> getTypeMap() throws SQLException { + return null; + } + + @Override + public void setTypeMap(Map> map) throws SQLException { + + } + + @Override + public void setHoldability(int holdability) throws SQLException { + + } + + @Override + public int getHoldability() throws SQLException { + return 0; + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return null; + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return null; + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + return null; + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return null; + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return null; + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return null; + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return null; + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return new MockStatement(); + } + + @Override + public Clob createClob() throws SQLException { + return null; + } + + @Override + public Blob createBlob() throws SQLException { + return null; + } + + @Override + public NClob createNClob() throws SQLException { + return null; + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return null; + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return false; + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + + } + + @Override + public String getClientInfo(String name) throws SQLException { + return null; + } + + @Override + public Properties getClientInfo() throws SQLException { + return null; + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return null; + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return null; + } + + @Override + public void setSchema(String schema) throws SQLException { + + } + + @Override + public String getSchema() throws SQLException { + return null; + } + + @Override + public void abort(Executor executor) throws SQLException { + + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + + } + + @Override + public int getNetworkTimeout() throws SQLException { + return 0; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public void addMockStatement(MockStatement mockStatement) { + this.statements.add(mockStatement); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockDataSource.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockDataSource.java new file mode 100644 index 0000000000..6c799a1fcc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockDataSource.java @@ -0,0 +1,124 @@ +/* +* 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.mock; + +import org.mockito.Mock; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; +import javax.sql.DataSource; + +/** + * This is the mock data source implementation that will be used in the test cases. + */ +public class MockDataSource implements DataSource { + private boolean throwException = false; + private List connections = new ArrayList<>(); + private int connectionCounter = 0; + private String url; + + public MockDataSource(String url) { + this.url = url; + } + + @Override + public Connection getConnection() throws SQLException { + if (throwException) { + throw new SQLException("Cannot created test connection."); + } else { + if (!connections.isEmpty()) { + if (this.connectionCounter < this.connections.size()) { + Connection connection = this.connections.get(this.connectionCounter); + this.connectionCounter++; + return connection; + } else { + return new MockConnection(url); + } + } + return new MockConnection(url); + } + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return null; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public PrintWriter getLogWriter() throws SQLException { + return null; + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + + } + + @Override + public int getLoginTimeout() throws SQLException { + return 0; + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null; + } + + public void setThrowException(boolean throwException) { + this.throwException = throwException; + } + + public void reset() { + this.throwException = false; + this.connections.clear(); + this.connectionCounter = 0; + } + + public void setConnection(Connection connection) { + this.connections.add(connection); + } + + public String getUrl() { + return this.url; + } + + public MockConnection getConnection(int id) { + return (MockConnection) this.connections.get(id); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockDatabaseMetaData.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockDatabaseMetaData.java new file mode 100644 index 0000000000..2ab645ba9b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockDatabaseMetaData.java @@ -0,0 +1,926 @@ +/* +* 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.mock; + +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.RowIdLifetime; +import java.sql.SQLException; + +public class MockDatabaseMetaData implements DatabaseMetaData { + private String url; + + public MockDatabaseMetaData(String url) { + this.url = url; + } + + @Override + public boolean allProceduresAreCallable() throws SQLException { + return false; + } + + @Override + public boolean allTablesAreSelectable() throws SQLException { + return false; + } + + @Override + public String getURL() throws SQLException { + return null; + } + + @Override + public String getUserName() throws SQLException { + return null; + } + + @Override + public boolean isReadOnly() throws SQLException { + return false; + } + + @Override + public boolean nullsAreSortedHigh() throws SQLException { + return false; + } + + @Override + public boolean nullsAreSortedLow() throws SQLException { + return false; + } + + @Override + public boolean nullsAreSortedAtStart() throws SQLException { + return false; + } + + @Override + public boolean nullsAreSortedAtEnd() throws SQLException { + return false; + } + + @Override + public String getDatabaseProductName() throws SQLException { + if (this.url.contains("mysql")) { + return DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL; + } else if (this.url.contains("h2")) { + return DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2; + } else if (this.url.contains("oracle")) { + return DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE; + } else if (this.url.contains("postgresql")) { + return DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL; + } else if (this.url.contains("sqlserver")) { + return DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL; + } else { + return null; + } + } + + @Override + public String getDatabaseProductVersion() throws SQLException { + return null; + } + + @Override + public String getDriverName() throws SQLException { + return null; + } + + @Override + public String getDriverVersion() throws SQLException { + return null; + } + + @Override + public int getDriverMajorVersion() { + return 0; + } + + @Override + public int getDriverMinorVersion() { + return 0; + } + + @Override + public boolean usesLocalFiles() throws SQLException { + return false; + } + + @Override + public boolean usesLocalFilePerTable() throws SQLException { + return false; + } + + @Override + public boolean supportsMixedCaseIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean storesUpperCaseIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean storesLowerCaseIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean storesMixedCaseIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { + return false; + } + + @Override + public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { + return false; + } + + @Override + public String getIdentifierQuoteString() throws SQLException { + return null; + } + + @Override + public String getSQLKeywords() throws SQLException { + return null; + } + + @Override + public String getNumericFunctions() throws SQLException { + return null; + } + + @Override + public String getStringFunctions() throws SQLException { + return null; + } + + @Override + public String getSystemFunctions() throws SQLException { + return null; + } + + @Override + public String getTimeDateFunctions() throws SQLException { + return null; + } + + @Override + public String getSearchStringEscape() throws SQLException { + return null; + } + + @Override + public String getExtraNameCharacters() throws SQLException { + return null; + } + + @Override + public boolean supportsAlterTableWithAddColumn() throws SQLException { + return false; + } + + @Override + public boolean supportsAlterTableWithDropColumn() throws SQLException { + return false; + } + + @Override + public boolean supportsColumnAliasing() throws SQLException { + return false; + } + + @Override + public boolean nullPlusNonNullIsNull() throws SQLException { + return false; + } + + @Override + public boolean supportsConvert() throws SQLException { + return false; + } + + @Override + public boolean supportsConvert(int fromType, int toType) throws SQLException { + return false; + } + + @Override + public boolean supportsTableCorrelationNames() throws SQLException { + return false; + } + + @Override + public boolean supportsDifferentTableCorrelationNames() throws SQLException { + return false; + } + + @Override + public boolean supportsExpressionsInOrderBy() throws SQLException { + return false; + } + + @Override + public boolean supportsOrderByUnrelated() throws SQLException { + return false; + } + + @Override + public boolean supportsGroupBy() throws SQLException { + return false; + } + + @Override + public boolean supportsGroupByUnrelated() throws SQLException { + return false; + } + + @Override + public boolean supportsGroupByBeyondSelect() throws SQLException { + return false; + } + + @Override + public boolean supportsLikeEscapeClause() throws SQLException { + return false; + } + + @Override + public boolean supportsMultipleResultSets() throws SQLException { + return false; + } + + @Override + public boolean supportsMultipleTransactions() throws SQLException { + return false; + } + + @Override + public boolean supportsNonNullableColumns() throws SQLException { + return false; + } + + @Override + public boolean supportsMinimumSQLGrammar() throws SQLException { + return false; + } + + @Override + public boolean supportsCoreSQLGrammar() throws SQLException { + return false; + } + + @Override + public boolean supportsExtendedSQLGrammar() throws SQLException { + return false; + } + + @Override + public boolean supportsANSI92EntryLevelSQL() throws SQLException { + return false; + } + + @Override + public boolean supportsANSI92IntermediateSQL() throws SQLException { + return false; + } + + @Override + public boolean supportsANSI92FullSQL() throws SQLException { + return false; + } + + @Override + public boolean supportsIntegrityEnhancementFacility() throws SQLException { + return false; + } + + @Override + public boolean supportsOuterJoins() throws SQLException { + return false; + } + + @Override + public boolean supportsFullOuterJoins() throws SQLException { + return false; + } + + @Override + public boolean supportsLimitedOuterJoins() throws SQLException { + return false; + } + + @Override + public String getSchemaTerm() throws SQLException { + return null; + } + + @Override + public String getProcedureTerm() throws SQLException { + return null; + } + + @Override + public String getCatalogTerm() throws SQLException { + return null; + } + + @Override + public boolean isCatalogAtStart() throws SQLException { + return false; + } + + @Override + public String getCatalogSeparator() throws SQLException { + return null; + } + + @Override + public boolean supportsSchemasInDataManipulation() throws SQLException { + return false; + } + + @Override + public boolean supportsSchemasInProcedureCalls() throws SQLException { + return false; + } + + @Override + public boolean supportsSchemasInTableDefinitions() throws SQLException { + return false; + } + + @Override + public boolean supportsSchemasInIndexDefinitions() throws SQLException { + return false; + } + + @Override + public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { + return false; + } + + @Override + public boolean supportsCatalogsInDataManipulation() throws SQLException { + return false; + } + + @Override + public boolean supportsCatalogsInProcedureCalls() throws SQLException { + return false; + } + + @Override + public boolean supportsCatalogsInTableDefinitions() throws SQLException { + return false; + } + + @Override + public boolean supportsCatalogsInIndexDefinitions() throws SQLException { + return false; + } + + @Override + public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { + return false; + } + + @Override + public boolean supportsPositionedDelete() throws SQLException { + return false; + } + + @Override + public boolean supportsPositionedUpdate() throws SQLException { + return false; + } + + @Override + public boolean supportsSelectForUpdate() throws SQLException { + return false; + } + + @Override + public boolean supportsStoredProcedures() throws SQLException { + return false; + } + + @Override + public boolean supportsSubqueriesInComparisons() throws SQLException { + return false; + } + + @Override + public boolean supportsSubqueriesInExists() throws SQLException { + return false; + } + + @Override + public boolean supportsSubqueriesInIns() throws SQLException { + return false; + } + + @Override + public boolean supportsSubqueriesInQuantifieds() throws SQLException { + return false; + } + + @Override + public boolean supportsCorrelatedSubqueries() throws SQLException { + return false; + } + + @Override + public boolean supportsUnion() throws SQLException { + return false; + } + + @Override + public boolean supportsUnionAll() throws SQLException { + return false; + } + + @Override + public boolean supportsOpenCursorsAcrossCommit() throws SQLException { + return false; + } + + @Override + public boolean supportsOpenCursorsAcrossRollback() throws SQLException { + return false; + } + + @Override + public boolean supportsOpenStatementsAcrossCommit() throws SQLException { + return false; + } + + @Override + public boolean supportsOpenStatementsAcrossRollback() throws SQLException { + return false; + } + + @Override + public int getMaxBinaryLiteralLength() throws SQLException { + return 0; + } + + @Override + public int getMaxCharLiteralLength() throws SQLException { + return 0; + } + + @Override + public int getMaxColumnNameLength() throws SQLException { + return 0; + } + + @Override + public int getMaxColumnsInGroupBy() throws SQLException { + return 0; + } + + @Override + public int getMaxColumnsInIndex() throws SQLException { + return 0; + } + + @Override + public int getMaxColumnsInOrderBy() throws SQLException { + return 0; + } + + @Override + public int getMaxColumnsInSelect() throws SQLException { + return 0; + } + + @Override + public int getMaxColumnsInTable() throws SQLException { + return 0; + } + + @Override + public int getMaxConnections() throws SQLException { + return 0; + } + + @Override + public int getMaxCursorNameLength() throws SQLException { + return 0; + } + + @Override + public int getMaxIndexLength() throws SQLException { + return 0; + } + + @Override + public int getMaxSchemaNameLength() throws SQLException { + return 0; + } + + @Override + public int getMaxProcedureNameLength() throws SQLException { + return 0; + } + + @Override + public int getMaxCatalogNameLength() throws SQLException { + return 0; + } + + @Override + public int getMaxRowSize() throws SQLException { + return 0; + } + + @Override + public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { + return false; + } + + @Override + public int getMaxStatementLength() throws SQLException { + return 0; + } + + @Override + public int getMaxStatements() throws SQLException { + return 0; + } + + @Override + public int getMaxTableNameLength() throws SQLException { + return 0; + } + + @Override + public int getMaxTablesInSelect() throws SQLException { + return 0; + } + + @Override + public int getMaxUserNameLength() throws SQLException { + return 0; + } + + @Override + public int getDefaultTransactionIsolation() throws SQLException { + return 0; + } + + @Override + public boolean supportsTransactions() throws SQLException { + return false; + } + + @Override + public boolean supportsTransactionIsolationLevel(int level) throws SQLException { + return false; + } + + @Override + public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { + return false; + } + + @Override + public boolean supportsDataManipulationTransactionsOnly() throws SQLException { + return false; + } + + @Override + public boolean dataDefinitionCausesTransactionCommit() throws SQLException { + return false; + } + + @Override + public boolean dataDefinitionIgnoredInTransactions() throws SQLException { + return false; + } + + @Override + public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { + return null; + } + + @Override + public ResultSet getSchemas() throws SQLException { + return null; + } + + @Override + public ResultSet getCatalogs() throws SQLException { + return null; + } + + @Override + public ResultSet getTableTypes() throws SQLException { + return null; + } + + @Override + public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { + return null; + } + + @Override + public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { + return null; + } + + @Override + public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { + return null; + } + + @Override + public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { + return null; + } + + @Override + public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { + return null; + } + + @Override + public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { + return null; + } + + @Override + public ResultSet getTypeInfo() throws SQLException { + return null; + } + + @Override + public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { + return null; + } + + @Override + public boolean supportsResultSetType(int type) throws SQLException { + return false; + } + + @Override + public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { + return false; + } + + @Override + public boolean ownUpdatesAreVisible(int type) throws SQLException { + return false; + } + + @Override + public boolean ownDeletesAreVisible(int type) throws SQLException { + return false; + } + + @Override + public boolean ownInsertsAreVisible(int type) throws SQLException { + return false; + } + + @Override + public boolean othersUpdatesAreVisible(int type) throws SQLException { + return false; + } + + @Override + public boolean othersDeletesAreVisible(int type) throws SQLException { + return false; + } + + @Override + public boolean othersInsertsAreVisible(int type) throws SQLException { + return false; + } + + @Override + public boolean updatesAreDetected(int type) throws SQLException { + return false; + } + + @Override + public boolean deletesAreDetected(int type) throws SQLException { + return false; + } + + @Override + public boolean insertsAreDetected(int type) throws SQLException { + return false; + } + + @Override + public boolean supportsBatchUpdates() throws SQLException { + return false; + } + + @Override + public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { + return null; + } + + @Override + public Connection getConnection() throws SQLException { + return null; + } + + @Override + public boolean supportsSavepoints() throws SQLException { + return false; + } + + @Override + public boolean supportsNamedParameters() throws SQLException { + return false; + } + + @Override + public boolean supportsMultipleOpenResults() throws SQLException { + return false; + } + + @Override + public boolean supportsGetGeneratedKeys() throws SQLException { + return false; + } + + @Override + public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { + return null; + } + + @Override + public boolean supportsResultSetHoldability(int holdability) throws SQLException { + return false; + } + + @Override + public int getResultSetHoldability() throws SQLException { + return 0; + } + + @Override + public int getDatabaseMajorVersion() throws SQLException { + return 0; + } + + @Override + public int getDatabaseMinorVersion() throws SQLException { + return 0; + } + + @Override + public int getJDBCMajorVersion() throws SQLException { + return 0; + } + + @Override + public int getJDBCMinorVersion() throws SQLException { + return 0; + } + + @Override + public int getSQLStateType() throws SQLException { + return 0; + } + + @Override + public boolean locatorsUpdateCopy() throws SQLException { + return false; + } + + @Override + public boolean supportsStatementPooling() throws SQLException { + return false; + } + + @Override + public RowIdLifetime getRowIdLifetime() throws SQLException { + return null; + } + + @Override + public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { + return null; + } + + @Override + public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { + return false; + } + + @Override + public boolean autoCommitFailureClosesAllResultSets() throws SQLException { + return false; + } + + @Override + public ResultSet getClientInfoProperties() throws SQLException { + return null; + } + + @Override + public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { + return null; + } + + @Override + public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { + return null; + } + + @Override + public boolean generatedKeyAlwaysReturned() throws SQLException { + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockJDBCDriver.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockJDBCDriver.java new file mode 100644 index 0000000000..d19a6b9fb6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockJDBCDriver.java @@ -0,0 +1,69 @@ +/* +* 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.mock; + +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.Properties; +import java.util.logging.Logger; + +/** + * This is the mock JDBC driver which is used in the testcases to mock other database operations. + */ +public class MockJDBCDriver implements Driver { + + @Override + public Connection connect(String url, Properties info) throws SQLException { + return new MockConnection(url); + } + + @Override + public boolean acceptsURL(String url) throws SQLException { + return true; + } + + @Override + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + return new DriverPropertyInfo[0]; + } + + @Override + public int getMajorVersion() { + return 0; + } + + @Override + public int getMinorVersion() { + return 0; + } + + @Override + public boolean jdbcCompliant() { + return true; + } + + @Override + public Logger getParentLogger() throws SQLFeatureNotSupportedException { + return null; + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockResultSet.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockResultSet.java new file mode 100644 index 0000000000..f8882653d7 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockResultSet.java @@ -0,0 +1,1112 @@ +/* +* 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.mock; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.NClob; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Statement; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +public class MockResultSet implements ResultSet { + private List stringList = new ArrayList<>(); + private List integerList = new ArrayList<>(); + private List doubleList = new ArrayList<>(); + private List booleanList = new ArrayList<>(); + private List timestamps = new ArrayList<>(); + + private AtomicInteger stringCounter = new AtomicInteger(0); + private AtomicInteger integerCounter = new AtomicInteger(0); + private AtomicInteger doubleCounter = new AtomicInteger(0); + private AtomicInteger booleanCounter = new AtomicInteger(0); + private AtomicInteger timestampCounter = new AtomicInteger(0); + + private boolean iterated = false; + private boolean hasData = false; + + @Override + public boolean next() throws SQLException { + if (!this.iterated && this.hasData) { + this.iterated = true; + return true; + } else { + return false; + } + } + + @Override + public void close() throws SQLException { + + } + + @Override + public boolean wasNull() throws SQLException { + return false; + } + + @Override + public String getString(int columnIndex) throws SQLException { + Object item = getItem(this.stringList, this.stringCounter); + if (item != null) { + return (String) item; + } else { + return ""; + } + } + + private Object getItem(List list, AtomicInteger counter) { + if (!list.isEmpty()) { + return list.get(counter.getAndIncrement()); + } + return null; + } + + @Override + public boolean getBoolean(int columnIndex) throws SQLException { + Object item = getItem(this.booleanList, this.booleanCounter); + if (item != null) { + return (Boolean) item; + } else { + return false; + } + } + + @Override + public byte getByte(int columnIndex) throws SQLException { + return 0; + } + + @Override + public short getShort(int columnIndex) throws SQLException { + return 0; + } + + @Override + public int getInt(int columnIndex) throws SQLException { + Object item = getItem(this.integerList, this.integerCounter); + if (item != null) { + return (Integer) item; + } else { + return 0; + } + } + + @Override + public long getLong(int columnIndex) throws SQLException { + return 0; + } + + @Override + public float getFloat(int columnIndex) throws SQLException { + return 0; + } + + @Override + public double getDouble(int columnIndex) throws SQLException { + Object item = getItem(this.doubleList, this.doubleCounter); + if (item != null) { + return (Double) item; + } else { + return 0.0; + } + } + + @Override + public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { + return null; + } + + @Override + public byte[] getBytes(int columnIndex) throws SQLException { + return new byte[0]; + } + + @Override + public Date getDate(int columnIndex) throws SQLException { + return null; + } + + @Override + public Time getTime(int columnIndex) throws SQLException { + return null; + } + + @Override + public Timestamp getTimestamp(int columnIndex) throws SQLException { + Object item = getItem(this.timestamps, this.timestampCounter); + if (item != null) { + return (Timestamp) item; + } else { + return new Timestamp(System.currentTimeMillis()); + } + } + + @Override + public InputStream getAsciiStream(int columnIndex) throws SQLException { + return null; + } + + @Override + public InputStream getUnicodeStream(int columnIndex) throws SQLException { + return null; + } + + @Override + public InputStream getBinaryStream(int columnIndex) throws SQLException { + return null; + } + + @Override + public String getString(String columnLabel) throws SQLException { + Object item = getItem(this.stringList, this.stringCounter); + if (item != null) { + return (String) item; + } else { + return ""; + } + } + + @Override + public boolean getBoolean(String columnLabel) throws SQLException { + Object item = getItem(this.booleanList, this.booleanCounter); + if (item != null) { + return (Boolean) item; + } else { + return false; + } + } + + @Override + public byte getByte(String columnLabel) throws SQLException { + return 0; + } + + @Override + public short getShort(String columnLabel) throws SQLException { + return 0; + } + + @Override + public int getInt(String columnLabel) throws SQLException { + Object item = getItem(this.integerList, this.integerCounter); + if (item != null) { + return (Integer) item; + } else { + return 0; + } + } + + @Override + public long getLong(String columnLabel) throws SQLException { + return 0; + } + + @Override + public float getFloat(String columnLabel) throws SQLException { + return 0; + } + + @Override + public double getDouble(String columnLabel) throws SQLException { + Object item = getItem(this.doubleList, this.doubleCounter); + if (item != null) { + return (Double) item; + } else { + return 0.0; + } + } + + @Override + public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException { + return null; + } + + @Override + public byte[] getBytes(String columnLabel) throws SQLException { + return new byte[0]; + } + + @Override + public Date getDate(String columnLabel) throws SQLException { + return null; + } + + @Override + public Time getTime(String columnLabel) throws SQLException { + return null; + } + + @Override + public Timestamp getTimestamp(String columnLabel) throws SQLException { + Object item = getItem(this.timestamps, this.timestampCounter); + if (item != null) { + return (Timestamp) item; + } else { + return new Timestamp(System.currentTimeMillis()); + } + } + + @Override + public InputStream getAsciiStream(String columnLabel) throws SQLException { + return null; + } + + @Override + public InputStream getUnicodeStream(String columnLabel) throws SQLException { + return null; + } + + @Override + public InputStream getBinaryStream(String columnLabel) throws SQLException { + return null; + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return null; + } + + @Override + public void clearWarnings() throws SQLException { + + } + + @Override + public String getCursorName() throws SQLException { + return null; + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException { + return null; + } + + @Override + public Object getObject(int columnIndex) throws SQLException { + return null; + } + + @Override + public Object getObject(String columnLabel) throws SQLException { + return null; + } + + @Override + public int findColumn(String columnLabel) throws SQLException { + return 0; + } + + @Override + public Reader getCharacterStream(int columnIndex) throws SQLException { + return null; + } + + @Override + public Reader getCharacterStream(String columnLabel) throws SQLException { + return null; + } + + @Override + public BigDecimal getBigDecimal(int columnIndex) throws SQLException { + return null; + } + + @Override + public BigDecimal getBigDecimal(String columnLabel) throws SQLException { + return null; + } + + @Override + public boolean isBeforeFirst() throws SQLException { + return false; + } + + @Override + public boolean isAfterLast() throws SQLException { + return false; + } + + @Override + public boolean isFirst() throws SQLException { + return false; + } + + @Override + public boolean isLast() throws SQLException { + return false; + } + + @Override + public void beforeFirst() throws SQLException { + + } + + @Override + public void afterLast() throws SQLException { + + } + + @Override + public boolean first() throws SQLException { + return false; + } + + @Override + public boolean last() throws SQLException { + return false; + } + + @Override + public int getRow() throws SQLException { + return 0; + } + + @Override + public boolean absolute(int row) throws SQLException { + return false; + } + + @Override + public boolean relative(int rows) throws SQLException { + return false; + } + + @Override + public boolean previous() throws SQLException { + return false; + } + + @Override + public void setFetchDirection(int direction) throws SQLException { + + } + + @Override + public int getFetchDirection() throws SQLException { + return 0; + } + + @Override + public void setFetchSize(int rows) throws SQLException { + + } + + @Override + public int getFetchSize() throws SQLException { + return 0; + } + + @Override + public int getType() throws SQLException { + return 0; + } + + @Override + public int getConcurrency() throws SQLException { + return 0; + } + + @Override + public boolean rowUpdated() throws SQLException { + return false; + } + + @Override + public boolean rowInserted() throws SQLException { + return false; + } + + @Override + public boolean rowDeleted() throws SQLException { + return false; + } + + @Override + public void updateNull(int columnIndex) throws SQLException { + + } + + @Override + public void updateBoolean(int columnIndex, boolean x) throws SQLException { + + } + + @Override + public void updateByte(int columnIndex, byte x) throws SQLException { + + } + + @Override + public void updateShort(int columnIndex, short x) throws SQLException { + + } + + @Override + public void updateInt(int columnIndex, int x) throws SQLException { + + } + + @Override + public void updateLong(int columnIndex, long x) throws SQLException { + + } + + @Override + public void updateFloat(int columnIndex, float x) throws SQLException { + + } + + @Override + public void updateDouble(int columnIndex, double x) throws SQLException { + + } + + @Override + public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { + + } + + @Override + public void updateString(int columnIndex, String x) throws SQLException { + + } + + @Override + public void updateBytes(int columnIndex, byte[] x) throws SQLException { + + } + + @Override + public void updateDate(int columnIndex, Date x) throws SQLException { + + } + + @Override + public void updateTime(int columnIndex, Time x) throws SQLException { + + } + + @Override + public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { + + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { + + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { + + } + + @Override + public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { + + } + + @Override + public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException { + + } + + @Override + public void updateObject(int columnIndex, Object x) throws SQLException { + + } + + @Override + public void updateNull(String columnLabel) throws SQLException { + + } + + @Override + public void updateBoolean(String columnLabel, boolean x) throws SQLException { + + } + + @Override + public void updateByte(String columnLabel, byte x) throws SQLException { + + } + + @Override + public void updateShort(String columnLabel, short x) throws SQLException { + + } + + @Override + public void updateInt(String columnLabel, int x) throws SQLException { + + } + + @Override + public void updateLong(String columnLabel, long x) throws SQLException { + + } + + @Override + public void updateFloat(String columnLabel, float x) throws SQLException { + + } + + @Override + public void updateDouble(String columnLabel, double x) throws SQLException { + + } + + @Override + public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException { + + } + + @Override + public void updateString(String columnLabel, String x) throws SQLException { + + } + + @Override + public void updateBytes(String columnLabel, byte[] x) throws SQLException { + + } + + @Override + public void updateDate(String columnLabel, Date x) throws SQLException { + + } + + @Override + public void updateTime(String columnLabel, Time x) throws SQLException { + + } + + @Override + public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException { + + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { + + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { + + } + + @Override + public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { + + } + + @Override + public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException { + + } + + @Override + public void updateObject(String columnLabel, Object x) throws SQLException { + + } + + @Override + public void insertRow() throws SQLException { + + } + + @Override + public void updateRow() throws SQLException { + + } + + @Override + public void deleteRow() throws SQLException { + + } + + @Override + public void refreshRow() throws SQLException { + + } + + @Override + public void cancelRowUpdates() throws SQLException { + + } + + @Override + public void moveToInsertRow() throws SQLException { + + } + + @Override + public void moveToCurrentRow() throws SQLException { + + } + + @Override + public Statement getStatement() throws SQLException { + return null; + } + + @Override + public Object getObject(int columnIndex, Map> map) throws SQLException { + return null; + } + + @Override + public Ref getRef(int columnIndex) throws SQLException { + return null; + } + + @Override + public Blob getBlob(int columnIndex) throws SQLException { + return null; + } + + @Override + public Clob getClob(int columnIndex) throws SQLException { + return null; + } + + @Override + public Array getArray(int columnIndex) throws SQLException { + return null; + } + + @Override + public Object getObject(String columnLabel, Map> map) throws SQLException { + return null; + } + + @Override + public Ref getRef(String columnLabel) throws SQLException { + return null; + } + + @Override + public Blob getBlob(String columnLabel) throws SQLException { + return null; + } + + @Override + public Clob getClob(String columnLabel) throws SQLException { + return null; + } + + @Override + public Array getArray(String columnLabel) throws SQLException { + return null; + } + + @Override + public Date getDate(int columnIndex, Calendar cal) throws SQLException { + return null; + } + + @Override + public Date getDate(String columnLabel, Calendar cal) throws SQLException { + return null; + } + + @Override + public Time getTime(int columnIndex, Calendar cal) throws SQLException { + return null; + } + + @Override + public Time getTime(String columnLabel, Calendar cal) throws SQLException { + return null; + } + + @Override + public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { + Object item = getItem(this.timestamps, this.timestampCounter); + if (item != null) { + return (Timestamp) item; + } else { + return new Timestamp(System.currentTimeMillis()); + } + } + + @Override + public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException { + Object item = getItem(this.timestamps, this.timestampCounter); + if (item != null) { + return (Timestamp) item; + } else { + return new Timestamp(System.currentTimeMillis()); + } + } + + @Override + public URL getURL(int columnIndex) throws SQLException { + return null; + } + + @Override + public URL getURL(String columnLabel) throws SQLException { + return null; + } + + @Override + public void updateRef(int columnIndex, Ref x) throws SQLException { + + } + + @Override + public void updateRef(String columnLabel, Ref x) throws SQLException { + + } + + @Override + public void updateBlob(int columnIndex, Blob x) throws SQLException { + + } + + @Override + public void updateBlob(String columnLabel, Blob x) throws SQLException { + + } + + @Override + public void updateClob(int columnIndex, Clob x) throws SQLException { + + } + + @Override + public void updateClob(String columnLabel, Clob x) throws SQLException { + + } + + @Override + public void updateArray(int columnIndex, Array x) throws SQLException { + + } + + @Override + public void updateArray(String columnLabel, Array x) throws SQLException { + + } + + @Override + public RowId getRowId(int columnIndex) throws SQLException { + return null; + } + + @Override + public RowId getRowId(String columnLabel) throws SQLException { + return null; + } + + @Override + public void updateRowId(int columnIndex, RowId x) throws SQLException { + + } + + @Override + public void updateRowId(String columnLabel, RowId x) throws SQLException { + + } + + @Override + public int getHoldability() throws SQLException { + return 0; + } + + @Override + public boolean isClosed() throws SQLException { + return false; + } + + @Override + public void updateNString(int columnIndex, String nString) throws SQLException { + + } + + @Override + public void updateNString(String columnLabel, String nString) throws SQLException { + + } + + @Override + public void updateNClob(int columnIndex, NClob nClob) throws SQLException { + + } + + @Override + public void updateNClob(String columnLabel, NClob nClob) throws SQLException { + + } + + @Override + public NClob getNClob(int columnIndex) throws SQLException { + return null; + } + + @Override + public NClob getNClob(String columnLabel) throws SQLException { + return null; + } + + @Override + public SQLXML getSQLXML(int columnIndex) throws SQLException { + return null; + } + + @Override + public SQLXML getSQLXML(String columnLabel) throws SQLException { + return null; + } + + @Override + public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { + + } + + @Override + public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { + + } + + @Override + public String getNString(int columnIndex) throws SQLException { + return null; + } + + @Override + public String getNString(String columnLabel) throws SQLException { + return null; + } + + @Override + public Reader getNCharacterStream(int columnIndex) throws SQLException { + return null; + } + + @Override + public Reader getNCharacterStream(String columnLabel) throws SQLException { + return null; + } + + @Override + public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { + + } + + @Override + public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { + + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { + + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { + + } + + @Override + public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { + + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { + + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { + + } + + @Override + public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { + + } + + @Override + public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { + + } + + @Override + public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { + + } + + @Override + public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { + + } + + @Override + public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { + + } + + @Override + public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { + + } + + @Override + public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { + + } + + @Override + public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { + + } + + @Override + public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { + + } + + @Override + public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { + + } + + @Override + public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { + + } + + @Override + public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { + + } + + @Override + public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { + + } + + @Override + public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { + + } + + @Override + public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { + + } + + @Override + public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { + + } + + @Override + public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { + + } + + @Override + public void updateClob(int columnIndex, Reader reader) throws SQLException { + + } + + @Override + public void updateClob(String columnLabel, Reader reader) throws SQLException { + + } + + @Override + public void updateNClob(int columnIndex, Reader reader) throws SQLException { + + } + + @Override + public void updateNClob(String columnLabel, Reader reader) throws SQLException { + + } + + @Override + public T getObject(int columnIndex, Class type) throws SQLException { + return null; + } + + @Override + public T getObject(String columnLabel, Class type) throws SQLException { + return null; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + public void addString(String string) { + this.stringList.add(string); + this.hasData = true; + } + + public void addInteger(Integer integer) { + this.integerList.add(integer); + this.hasData = true; + } + + public void addBoolean(Boolean bool) { + this.booleanList.add(bool); + this.hasData = true; + } + + public void addDouble(Double doubleVal) { + this.doubleList.add(doubleVal); + this.hasData = true; + } + + public void addTimestamp(Timestamp timestamp){ + this.timestamps.add(timestamp); + this.hasData = true; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockStatement.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockStatement.java new file mode 100644 index 0000000000..3b8fa5fe60 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/mock/MockStatement.java @@ -0,0 +1,561 @@ +/* +* 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.mock; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.Date; +import java.sql.NClob; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.RowId; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Statement; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +/** + * This is the mock statement for the test cases. + */ +public class MockStatement implements PreparedStatement { + private List resultSets = new ArrayList<>(); + private int resultSetCounter; + + @Override + public ResultSet executeQuery(String sql) throws SQLException { + return this.getMockResultSet(); + } + + private ResultSet getMockResultSet() { + if (!this.resultSets.isEmpty()) { + ResultSet resultSet = this.resultSets.get(this.resultSetCounter); + this.resultSetCounter++; + return resultSet; + } else { + return new MockResultSet(); + } + } + + @Override + public int executeUpdate(String sql) throws SQLException { + return 0; + } + + @Override + public void close() throws SQLException { + + } + + @Override + public int getMaxFieldSize() throws SQLException { + return 0; + } + + @Override + public void setMaxFieldSize(int max) throws SQLException { + + } + + @Override + public int getMaxRows() throws SQLException { + return 0; + } + + @Override + public void setMaxRows(int max) throws SQLException { + + } + + @Override + public void setEscapeProcessing(boolean enable) throws SQLException { + + } + + @Override + public int getQueryTimeout() throws SQLException { + return 0; + } + + @Override + public void setQueryTimeout(int seconds) throws SQLException { + + } + + @Override + public void cancel() throws SQLException { + + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return null; + } + + @Override + public void clearWarnings() throws SQLException { + + } + + @Override + public void setCursorName(String name) throws SQLException { + + } + + @Override + public boolean execute(String sql) throws SQLException { + return false; + } + + @Override + public ResultSet getResultSet() throws SQLException { + return getMockResultSet(); + } + + @Override + public int getUpdateCount() throws SQLException { + return 0; + } + + @Override + public boolean getMoreResults() throws SQLException { + return false; + } + + @Override + public void setFetchDirection(int direction) throws SQLException { + + } + + @Override + public int getFetchDirection() throws SQLException { + return 0; + } + + @Override + public void setFetchSize(int rows) throws SQLException { + + } + + @Override + public int getFetchSize() throws SQLException { + return 0; + } + + @Override + public int getResultSetConcurrency() throws SQLException { + return 0; + } + + @Override + public int getResultSetType() throws SQLException { + return 0; + } + + @Override + public void addBatch(String sql) throws SQLException { + + } + + @Override + public void clearBatch() throws SQLException { + + } + + @Override + public int[] executeBatch() throws SQLException { + return new int[0]; + } + + @Override + public Connection getConnection() throws SQLException { + return null; + } + + @Override + public boolean getMoreResults(int current) throws SQLException { + return false; + } + + @Override + public ResultSet getGeneratedKeys() throws SQLException { + return getMockResultSet(); + } + + @Override + public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { + return 0; + } + + @Override + public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { + return 0; + } + + @Override + public int executeUpdate(String sql, String[] columnNames) throws SQLException { + return 0; + } + + @Override + public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { + return false; + } + + @Override + public boolean execute(String sql, int[] columnIndexes) throws SQLException { + return false; + } + + @Override + public boolean execute(String sql, String[] columnNames) throws SQLException { + return false; + } + + @Override + public int getResultSetHoldability() throws SQLException { + return 0; + } + + @Override + public boolean isClosed() throws SQLException { + return false; + } + + @Override + public void setPoolable(boolean poolable) throws SQLException { + + } + + @Override + public boolean isPoolable() throws SQLException { + return false; + } + + @Override + public void closeOnCompletion() throws SQLException { + + } + + @Override + public boolean isCloseOnCompletion() throws SQLException { + return false; + } + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public ResultSet executeQuery() throws SQLException { + return getMockResultSet(); + } + + @Override + public int executeUpdate() throws SQLException { + return 0; + } + + @Override + public void setNull(int parameterIndex, int sqlType) throws SQLException { + + } + + @Override + public void setBoolean(int parameterIndex, boolean x) throws SQLException { + + } + + @Override + public void setByte(int parameterIndex, byte x) throws SQLException { + + } + + @Override + public void setShort(int parameterIndex, short x) throws SQLException { + + } + + @Override + public void setInt(int parameterIndex, int x) throws SQLException { + + } + + @Override + public void setLong(int parameterIndex, long x) throws SQLException { + + } + + @Override + public void setFloat(int parameterIndex, float x) throws SQLException { + + } + + @Override + public void setDouble(int parameterIndex, double x) throws SQLException { + + } + + @Override + public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { + + } + + @Override + public void setString(int parameterIndex, String x) throws SQLException { + + } + + @Override + public void setBytes(int parameterIndex, byte[] x) throws SQLException { + + } + + @Override + public void setDate(int parameterIndex, Date x) throws SQLException { + + } + + @Override + public void setTime(int parameterIndex, Time x) throws SQLException { + + } + + @Override + public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { + + } + + @Override + public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { + + } + + @Override + public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { + + } + + @Override + public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { + + } + + @Override + public void clearParameters() throws SQLException { + + } + + @Override + public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { + + } + + @Override + public void setObject(int parameterIndex, Object x) throws SQLException { + + } + + @Override + public boolean execute() throws SQLException { + return false; + } + + @Override + public void addBatch() throws SQLException { + + } + + @Override + public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { + + } + + @Override + public void setRef(int parameterIndex, Ref x) throws SQLException { + + } + + @Override + public void setBlob(int parameterIndex, Blob x) throws SQLException { + + } + + @Override + public void setClob(int parameterIndex, Clob x) throws SQLException { + + } + + @Override + public void setArray(int parameterIndex, Array x) throws SQLException { + + } + + @Override + public ResultSetMetaData getMetaData() throws SQLException { + return null; + } + + @Override + public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { + + } + + @Override + public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { + + } + + @Override + public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { + + } + + @Override + public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { + + } + + @Override + public void setURL(int parameterIndex, URL x) throws SQLException { + + } + + @Override + public ParameterMetaData getParameterMetaData() throws SQLException { + return null; + } + + @Override + public void setRowId(int parameterIndex, RowId x) throws SQLException { + + } + + @Override + public void setNString(int parameterIndex, String value) throws SQLException { + + } + + @Override + public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { + + } + + @Override + public void setNClob(int parameterIndex, NClob value) throws SQLException { + + } + + @Override + public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + + } + + @Override + public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { + + } + + @Override + public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { + + } + + @Override + public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { + + } + + @Override + public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { + + } + + @Override + public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { + + } + + @Override + public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { + + } + + @Override + public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { + + } + + @Override + public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { + + } + + @Override + public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { + + } + + @Override + public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { + + } + + @Override + public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + + } + + @Override + public void setClob(int parameterIndex, Reader reader) throws SQLException { + + } + + @Override + public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { + + } + + @Override + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + + } + + public void addResultSet(MockResultSet resultSet){ + this.resultSets.add(resultSet); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java new file mode 100644 index 0000000000..767cde63ed --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementNegativeDBOperationTest.java @@ -0,0 +1,228 @@ +/* +* 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.operation; + +import org.testng.annotations.AfterClass; +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.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; +import org.wso2.carbon.device.mgt.core.TestDeviceManagementService; +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.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.mock.MockDataSource; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import javax.sql.DataSource; + +/** + * Negative test cases for {@link OperationManagerImpl} + * regarding the database connectivity. + */ +public class OperationManagementNegativeDBOperationTest extends BaseDeviceManagementTest { + + private static final String DEVICE_TYPE = "NEGDB_OP_TEST_TYPE"; + private static final String DEVICE_ID_PREFIX = "NEGDB_OP-TEST-DEVICE-ID-"; + private static final int NO_OF_DEVICES = 5; + private static final String ADMIN_USER = "admin"; + + private List deviceIds = new ArrayList<>(); + private OperationManager operationMgtService; + private MockDataSource dataSource; + + + @BeforeClass + @Override + public void init() throws Exception { + DataSource datasource = this.getDataSource(this. + readDataSourceConfig(getDatasourceLocation() + "-mock" + DATASOURCE_EXT)); + OperationManagementDAOFactory.init(datasource); + for (int i = 0; i < NO_OF_DEVICES; i++) { + deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE)); + } + List devices = TestDataHolder.generateDummyDeviceData(this.deviceIds); + DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider(); + deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE, + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); + for (Device device : devices) { + deviceMgtService.enrollDevice(device); + } + List returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE); + for (Device device : returnedDevices) { + if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) { + throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!"); + } + } + NotificationStrategy notificationStrategy = new TestNotificationStrategy(); + this.operationMgtService = new OperationManagerImpl(DEVICE_TYPE, notificationStrategy); + this.setMockDataSource(); + } + + @Test(description = "Get operation by device id", expectedExceptions = OperationManagementException.class) + public void getOperations() throws OperationManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperations(this.deviceIds.get(0)); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get operations with paginated request", + expectedExceptions = OperationManagementException.class) + public void getOperationsPaginatedRequest() throws OperationManagementException { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); + PaginationRequest request = new PaginationRequest(1, 2); + request.setDeviceType(DEVICE_TYPE); + request.setOwner(ADMIN_USER); + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperations(this.deviceIds.get(0), request); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + this.dataSource.reset(); + } + } + + @Test(description = "Get pending operations", expectedExceptions = OperationManagementException.class) + public void getPendingOperations() throws OperationManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getPendingOperations(this.deviceIds.get(0)); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get next pending operations", expectedExceptions = OperationManagementException.class) + public void getNextPendingOperations() throws OperationManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getNextPendingOperation(this.deviceIds.get(0)); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get operation by device and operation id", + expectedExceptions = OperationManagementException.class) + public void getOperationByDeviceAndOperationId() throws OperationManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperationByDeviceAndOperationId(this.deviceIds.get(0), 1); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get operation by device and status", + expectedExceptions = OperationManagementException.class) + public void getOperationByDeviceAndStatus() throws OperationManagementException, DeviceManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperationsByDeviceAndStatus(this.deviceIds.get(0), Operation.Status.PENDING); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get operation by operation id", + expectedExceptions = OperationManagementException.class) + public void getOperationByOperationId() throws OperationManagementException, DeviceManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperation(1); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get operation by activity id", + expectedExceptions = OperationManagementException.class) + public void getOperationByActivityId() throws OperationManagementException, DeviceManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperationByActivityId("ACTIVITY_1"); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get operation by activity id and device id", + expectedExceptions = OperationManagementException.class) + public void getOperationByActivityAndDeviceID() throws OperationManagementException, DeviceManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getOperationByActivityIdAndDevice("ACTIVITY_1", deviceIds.get(0)); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get activities updated after some timestamp", + expectedExceptions = OperationManagementException.class) + public void getActivitiesUpdatedAfter() throws OperationManagementException, DeviceManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getActivitiesUpdatedAfter(System.currentTimeMillis() / 1000, 10, 0); + } finally { + this.dataSource.reset(); + } + } + + @Test(description = "Get activities count updated after some timestamp", + expectedExceptions = OperationManagementException.class) + public void getActivityCountUpdatedAfter() throws OperationManagementException, DeviceManagementException { + this.dataSource.setThrowException(true); + try { + this.operationMgtService.getActivityCountUpdatedAfter(System.currentTimeMillis() / 1000); + } finally { + this.dataSource.reset(); + } + } + + private void setMockDataSource() throws NoSuchFieldException, IllegalAccessException { + Field datasource = OperationManagementDAOFactory.class.getDeclaredField("dataSource"); + datasource.setAccessible(true); + this.dataSource = new MockDataSource(null); + datasource.set(datasource, this.dataSource); + } + + @AfterClass + public void resetDatabase() throws Exception { + OperationManagementDAOFactory.init(this.getDataSource(this. + readDataSourceConfig(getDatasourceLocation() + DATASOURCE_EXT))); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java new file mode 100644 index 0000000000..4bc7b45278 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementNoDBSchemaTests.java @@ -0,0 +1,196 @@ +/* +* 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.operation; + +import org.testng.annotations.AfterClass; +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.common.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; +import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; +import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.core.TestDeviceManagementService; +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.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import java.util.ArrayList; +import java.util.List; +import javax.sql.DataSource; + +/** + * This is the testcase which covers the methods from {@link OperationManager} + */ +public class OperationManagementNoDBSchemaTests extends BaseDeviceManagementTest { + + private static final String DEVICE_TYPE = "NEG_OP_TEST_TYPE"; + private static final String DEVICE_ID_PREFIX = "NEG_OP-TEST-DEVICE-ID-"; + private static final String COMMAND_OPERATON_CODE = "COMMAND-TEST"; + private static final int NO_OF_DEVICES = 5; + private static final String ADMIN_USER = "admin"; + + private List deviceIds = new ArrayList<>(); + private OperationManager operationMgtService; + + @BeforeClass + public void init() throws Exception { + DataSource datasource = this.getDataSource(this. + readDataSourceConfig(getDatasourceLocation() + "-no-table" + DATASOURCE_EXT)); + OperationManagementDAOFactory.init(datasource); + for (int i = 0; i < NO_OF_DEVICES; i++) { + deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE)); + } + List devices = TestDataHolder.generateDummyDeviceData(this.deviceIds); + DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider(); + deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE, + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); + for (Device device : devices) { + deviceMgtService.enrollDevice(device); + } + List returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE); + for (Device device : returnedDevices) { + if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) { + throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!"); + } + } + NotificationStrategy notificationStrategy = new TestNotificationStrategy(); + this.operationMgtService = new OperationManagerImpl(DEVICE_TYPE, notificationStrategy); + } + + @Test(description = "add operation", expectedExceptions = OperationManagementException.class) + public void addCommandOperation() throws DeviceManagementException, OperationManagementException, + InvalidDeviceException { + this.operationMgtService.addOperation( + OperationManagementTests.getOperation(new CommandOperation(), + Operation.Type.COMMAND, COMMAND_OPERATON_CODE), + this.deviceIds); + } + + @Test(description = "Get operations", expectedExceptions = OperationManagementException.class) + public void getOperations() throws DeviceManagementException, OperationManagementException, + InvalidDeviceException { + for (DeviceIdentifier deviceIdentifier : deviceIds) { + this.operationMgtService.getOperations(deviceIdentifier); + } + } + + + @Test(description = "Get Pending operations", expectedExceptions = OperationManagementException.class) + public void getPendingOperations() throws DeviceManagementException, OperationManagementException, + InvalidDeviceException { + for (DeviceIdentifier deviceIdentifier : deviceIds) { + this.operationMgtService.getPendingOperations(deviceIdentifier); + } + } + + @Test(description = "Get paginated request", expectedExceptions = OperationManagementException.class) + public void getPaginatedRequestAsAdmin() throws OperationManagementException { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); + PaginationRequest request = new PaginationRequest(1, 2); + request.setDeviceType(DEVICE_TYPE); + request.setOwner(ADMIN_USER); + for (DeviceIdentifier deviceIdentifier : deviceIds) { + this.operationMgtService.getOperations(deviceIdentifier, request); + } + PrivilegedCarbonContext.endTenantFlow(); + } + + @Test(description = "Update operation", expectedExceptions = OperationManagementException.class) + public void updateOperation() throws OperationManagementException { + DeviceIdentifier deviceIdentifier = this.deviceIds.get(0); + Operation operation = OperationManagementTests.getOperation(new CommandOperation(), Operation.Type.COMMAND, + COMMAND_OPERATON_CODE); + operation.setStatus(Operation.Status.COMPLETED); + operation.setOperationResponse("The operation is successfully completed"); + this.operationMgtService.updateOperation(deviceIdentifier, operation); + } + + @Test(description = "Get next pending operation", expectedExceptions = OperationManagementException.class) + public void getNextPendingOperation() throws OperationManagementException { + DeviceIdentifier deviceIdentifier = this.deviceIds.get(0); + this.operationMgtService.getNextPendingOperation(deviceIdentifier); + } + + + @Test(description = "get operation by device and operation id", + expectedExceptions = OperationManagementException.class) + public void getOperationByDeviceAndOperationId() throws OperationManagementException { + DeviceIdentifier deviceIdentifier = this.deviceIds.get(0); + this.operationMgtService.getOperationByDeviceAndOperationId(deviceIdentifier, 1); + } + + @Test(description = "Get operation by device and status", + expectedExceptions = OperationManagementException.class) + public void getOperationsByDeviceAndStatus() throws OperationManagementException, DeviceManagementException { + DeviceIdentifier deviceIdentifier = this.deviceIds.get(0); + this.operationMgtService.getOperationsByDeviceAndStatus(deviceIdentifier, + Operation.Status.PENDING); + } + + @Test(description = "Get operation by operation id", expectedExceptions = OperationManagementException.class) + public void getOperation() throws OperationManagementException, DeviceManagementException { + this.operationMgtService.getOperation(1); + } + + @Test(description = "Get operation activity", expectedExceptions = OperationManagementException.class) + public void getOperationActivity() throws OperationManagementException { + this.operationMgtService.getOperationByActivityId + (DeviceManagementConstants.OperationAttributes.ACTIVITY + "1"); + } + + @Test(description = "Get operation by activity id and device", + expectedExceptions = OperationManagementException.class) + public void getOperationByActivityIdAndDevice() throws OperationManagementException { + this.operationMgtService.getOperationByActivityIdAndDevice( + DeviceManagementConstants.OperationAttributes.ACTIVITY + "1", this.deviceIds.get(0)); + } + + @Test(description = "Get activities updated after some time", + expectedExceptions = OperationManagementException.class) + public void getOperationUpdatedAfterWithLimitAndOffset() throws OperationManagementException { + this.operationMgtService.getActivitiesUpdatedAfter(System.currentTimeMillis() / 1000, 10, 0); + } + + @Test(description = "Get activity count updated after", + expectedExceptions = OperationManagementException.class) + public void getActivityCountUpdatedAfter() throws OperationManagementException { + this.operationMgtService.getActivityCountUpdatedAfter(System.currentTimeMillis() / 1000); + } + + @AfterClass + public void resetDatabase() throws Exception { + OperationManagementDAOFactory.init(this.getDataSource(this. + readDataSourceConfig(getDatasourceLocation() + DATASOURCE_EXT))); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/ProcessorImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/ProcessorImplTest.java new file mode 100644 index 0000000000..4e5f26a548 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/ProcessorImplTest.java @@ -0,0 +1,174 @@ +/* + * 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.search; + +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.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.common.search.Condition; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.TestDeviceManagementService; +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.dao.DeviceManagementDAOFactory; +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.search.mgt.InvalidOperatorException; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.ProcessorImpl; +import org.wso2.carbon.device.mgt.core.search.util.ChangeEnumValues; +import org.wso2.carbon.device.mgt.core.search.util.Utils; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import javax.sql.DataSource; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class holds unit test cases for org.wso2.carbon.device.mgt.core.search.mgt.impl.ProcessorImpl + * */ +public class ProcessorImplTest extends BaseDeviceManagementTest{ + + private DeviceAccessAuthorizationService deviceAccessAuthorizationService; + private static final Log log = LogFactory.getLog(SearchManagementServiceTest.class); + private static List deviceIdentifiers = new ArrayList<>(); + private static final String DEVICE_ID_PREFIX = "SEARCH-DEVICE-ID-"; + private static final String DEVICE_TYPE = "SEARCH_TYPE"; + + @BeforeClass + public void init() throws Exception { + deviceAccessAuthorizationService = DeviceManagementDataHolder.getInstance() + .getDeviceAccessAuthorizationService(); + + for (int i = 0; i < 5; i++) { + deviceIdentifiers.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE)); + } + DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl(); + DeviceManagementServiceComponent.notifyStartupListeners(); + DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService); + deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE, + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); + + List devices = TestDataHolder.generateDummyDeviceData(deviceIdentifiers); + for (Device device : devices) { + device.setDeviceInfo(Utils.getDeviceInfo()); + deviceMgtService.enrollDevice(device); + } + List returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE, true); + for (Device device : returnedDevices) { + if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) { + throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!"); + } + } + } + + @Test(description = "Test the Search Processor") + public void testWithNoDeviceAccessAuthorization() throws Exception { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("batteryLevel"); + cond.setOperator("="); + cond.setValue("40"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + ProcessorImpl processor = new ProcessorImpl(); + Field deviceAccessAuthorizationServiceField = ProcessorImpl.class.getDeclaredField + ("deviceAccessAuthorizationService"); + deviceAccessAuthorizationServiceField.setAccessible(true); + deviceAccessAuthorizationServiceField.set(processor, null); + + List searchedDevices = processor.execute(context); + + Assert.assertEquals(0, searchedDevices.size()); + } + + + @Test(description = "Test for invalid state") + public void testInvalidState() throws SearchMgtException { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + ChangeEnumValues.addEnum(Condition.State.class, "BLA"); + + Condition.State state = Condition.State.valueOf("BLA"); + + Condition cond = new Condition(); + cond.setKey("batteryLevel"); + cond.setOperator("="); + cond.setValue("40"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + Condition cond2 = new Condition(); + cond2.setKey("LOCATION"); + cond2.setOperator("="); + cond2.setValue("Karandeniya"); + cond2.setState(Condition.State.AND); + conditions.add(cond2); + + Condition cond3 = new Condition(); + cond3.setKey("batteryLevel"); + cond3.setOperator("="); + cond3.setValue("23.0"); + cond3.setState(state); + conditions.add(cond3); + + context.setConditions(conditions); + + ProcessorImpl processor = new ProcessorImpl(); + try { + processor.execute(context); + } catch (SearchMgtException e) { + if (!(e.getCause() instanceof InvalidOperatorException)) { + throw e; + } + } + } + + @Test(description = "Test when Device Access Authorization is null", expectedExceptions = {IllegalStateException + .class}, dependsOnMethods = {"testWithNoDeviceAccessAuthorization", "testInvalidState"}) + public void testProcessorInitializationError() throws ClassNotFoundException, NoSuchMethodException, + NoSuchFieldException, + IllegalAccessException, SearchMgtException { + DeviceManagementDataHolder deviceManagementDataHolder = DeviceManagementDataHolder.getInstance(); + Field field = DeviceManagementDataHolder.class.getDeclaredField("deviceAccessAuthorizationService"); + field.setAccessible(true); + field.set(deviceManagementDataHolder, null); + + ProcessorImpl processor = new ProcessorImpl(); + processor.execute(null); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchDevice.java deleted file mode 100644 index d624bfa4e6..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchDevice.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * 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. - */ - - -package org.wso2.carbon.device.mgt.core.search; - -import com.google.gson.Gson; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.search.Condition; -import org.wso2.carbon.device.mgt.common.search.SearchContext; -import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; -import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; -import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; -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 java.util.ArrayList; -import java.util.List; - -public class SearchDevice extends BaseDeviceManagementTest { - - private static final Log log = LogFactory.getLog(SearchDevice.class); - - @BeforeClass - @Override - public void init() throws Exception { - DeviceManagementProviderService deviceManagementProviderService = new DeviceManagementProviderServiceImpl(); - DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProviderService); - } - - @Test - public void searchDeviceDetails() throws Exception { - - SearchContext context = new SearchContext(); - List conditions = new ArrayList<>(); - - - Condition cond = new Condition(); - cond.setKey("BATTERY_VOLTAGE"); - cond.setOperator("="); - cond.setValue("40"); - cond.setState(Condition.State.AND); - conditions.add(cond); - -// Condition cond2 = new Condition(); -// cond2.setKey("CPU_USAGE"); -// cond2.setOperator(">"); -// cond2.setValue("40"); -// cond2.setState(Condition.State.OR); -// conditions.add(cond2); -// -// Condition cond3 = new Condition(); -// cond3.setKey("LOCATION"); -// cond3.setOperator("="); -// cond3.setValue("Colombo"); -// cond3.setState(Condition.State.AND); -// conditions.add(cond3); - - context.setConditions(conditions); - - SearchManagerService service = new SearchManagerServiceImpl(); - List devices = service.search(context); - - Gson gson = new Gson(); - String bbbb = gson.toJson(devices); - log.info(bbbb); - - - for (Device device : devices) { - log.debug(device.getDescription()); - log.debug(device.getDeviceIdentifier()); - } - - } - - @Test - public void doValidLocationSearch() throws Exception { - - SearchContext context = new SearchContext(); - List conditions = new ArrayList<>(); - - Condition cond = new Condition(); - cond.setKey("LOCATION"); - cond.setOperator("="); - cond.setValue("Karan"); - cond.setState(Condition.State.AND); - conditions.add(cond); - - context.setConditions(conditions); - - SearchManagerService service = new SearchManagerServiceImpl(); - List devices = service.search(context); - - Gson gson = new Gson(); - String bbbb = gson.toJson(devices); - log.info("Valid Search " + bbbb); - - - for (Device device : devices) { - log.debug(device.getDescription()); - log.debug(device.getDeviceIdentifier()); - } - } - - @Test - public void doInvalidLocationSearch() throws Exception { - - SearchContext context = new SearchContext(); - List conditions = new ArrayList<>(); - - Condition cond = new Condition(); - cond.setKey("LOCATION"); - cond.setOperator("="); - cond.setValue("Colombo"); - cond.setState(Condition.State.AND); - conditions.add(cond); - - context.setConditions(conditions); - - SearchManagerService service = new SearchManagerServiceImpl(); - List devices = service.search(context); - - Gson gson = new Gson(); - String bbbb = gson.toJson(devices); - log.info("Invalid Search " + bbbb); - - - for (Device device : devices) { - log.debug(device.getDescription()); - log.debug(device.getDeviceIdentifier()); - } - } - - @Test - public void doStringSearch() throws Exception { - - SearchContext context = new SearchContext(); - List conditions = new ArrayList<>(); - - Condition cond = new Condition(); - cond.setKey("deviceModel"); - cond.setOperator("="); - cond.setValue("SM-T520"); - cond.setState(Condition.State.AND); - conditions.add(cond); - - context.setConditions(conditions); - - SearchManagerService service = new SearchManagerServiceImpl(); - List devices = service.search(context); - - Gson gson = new Gson(); - String bbbb = gson.toJson(devices); - log.info("Invalid Search " + bbbb); - - - for (Device device : devices) { - log.debug(device.getDescription()); - log.debug(device.getDeviceIdentifier()); - } - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchManagementServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchManagementServiceTest.java new file mode 100644 index 0000000000..49641d16ab --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchManagementServiceTest.java @@ -0,0 +1,341 @@ +/* + * 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.search; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +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.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.search.Condition; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.TestDeviceManagementService; +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.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.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; +import org.wso2.carbon.device.mgt.core.search.mgt.InvalidOperatorException; +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.search.util.Utils; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +/** + * This class contains unit tests for the class SearchManagerService + */ +public class SearchManagementServiceTest extends BaseDeviceManagementTest { + + private static final Log log = LogFactory.getLog(SearchManagementServiceTest.class); + private static List deviceIdentifiers = new ArrayList<>(); + private static final String DEVICE_ID_PREFIX = "SEARCH-DEVICE-ID-"; + private static final String DEVICE_TYPE = "SEARCH_TYPE"; + + @BeforeClass + public void init() throws Exception { + DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(); + + for (int i = 0; i < 5; i++) { + deviceIdentifiers.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE)); + } + DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl(); + DeviceManagementServiceComponent.notifyStartupListeners(); + DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService); + deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE, + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); + DeviceInformationManager deviceInformationManager = new DeviceInformationManagerImpl(); + + List devices = TestDataHolder.generateDummyDeviceData(deviceIdentifiers); + for (Device device : devices) { + deviceMgtService.enrollDevice(device); + } + + for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { + DeviceInfo deviceInfo = Utils.getDeviceInfo(); + try { + deviceInformationManager.addDeviceInfo(deviceIdentifier, deviceInfo); + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while adding device info for the device " + deviceIdentifier; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + } + + List returnedDevices = deviceMgtService.getAllDevices(DEVICE_TYPE, true); + for (Device device : returnedDevices) { + if (!device.getDeviceIdentifier().startsWith(DEVICE_ID_PREFIX)) { + throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!"); + } + } + } + + @Test(description = "Search for device details.") + public void searchDeviceDetails() throws Exception { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("batteryVoltage"); + cond.setOperator("="); + cond.setValue("40"); + cond.setState(Condition.State.OR); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + Assert.assertTrue(devices != null); + } + + @Test(description = "Search devices by location") + public void doValidLocationSearch() throws Exception { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("LOCATION"); + cond.setOperator("="); + cond.setValue("Karandeniya"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + Assert.assertTrue(devices != null); + } + + @Test(description = "Search devices by location.") + public void doInvalidLocationSearch() throws Exception { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("LOCATION"); + cond.setOperator("="); + cond.setValue("Colombo"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + Assert.assertTrue(devices.size() == 0); + } + + @Test(description = "Search devices by string parameter.") + public void testStringSearch() throws Exception { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("deviceModel"); + cond.setOperator("="); + cond.setValue("SM-T520"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + + Assert.assertTrue(devices != null); + } + + @Test(description = "Search devices by Double parameter.") + public void testDoubleSearch() throws Exception { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("internalAvailableMemory"); + cond.setOperator("="); + cond.setValue("3.56"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + + Assert.assertTrue(devices != null); + } + + @Test(expectedExceptions = {SearchMgtException.class}) + public void testInvalidOperator() throws SearchMgtException { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("deviceModel"); + cond.setOperator("=/"); + cond.setValue("SM-T520"); + cond.setState(Condition.State.OR); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + + Assert.assertTrue(devices != null); + } + + @Test(description = "Test for search updated devices in given time.") + public void testGetUpdatedDevices() throws SearchMgtException { + SearchManagerService service = new SearchManagerServiceImpl(); + List updatedDevices = service.getUpdated(Calendar.getInstance().getTimeInMillis()); + Assert.assertEquals(updatedDevices.size(), 0); + } + + @Test(description = "Test for invalid number") + public void testInvalidNumber() throws SearchMgtException { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("batteryLevel"); + cond.setOperator("="); + cond.setValue("bbb"); + cond.setState(Condition.State.OR); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + try { + service.search(context); + } catch (SearchMgtException e) { + if (!(e.getCause() instanceof InvalidOperatorException)) { + throw e; + } + } + } + + @Test(description = "Test multiple search conditions") + public void testMultipleConditions() throws SearchMgtException { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("batteryLevel"); + cond.setOperator("%"); + cond.setValue("40"); + cond.setState(Condition.State.OR); + conditions.add(cond); + + Condition cond2 = new Condition(); + cond2.setKey("availableTotalMemory"); + cond2.setOperator("="); + cond2.setValue("40.0"); + cond2.setState(Condition.State.OR); + conditions.add(cond2); + + Condition cond3 = new Condition(); + cond3.setKey("LOCATION"); + cond3.setOperator("="); + cond3.setValue("Karandeniya"); + cond3.setState(Condition.State.OR); + conditions.add(cond3); + + Condition cond4 = new Condition(); + cond4.setKey("deviceModel"); + cond4.setOperator("="); + cond4.setValue("SM-T520"); + cond4.setState(Condition.State.AND); + conditions.add(cond4); + + Condition cond5 = new Condition(); + cond5.setKey("vendor"); + cond5.setOperator("="); + cond5.setValue("Samsung"); + cond5.setState(Condition.State.AND); + conditions.add(cond5); + + Condition cond6 = new Condition(); + cond6.setKey("osVersion"); + cond6.setOperator("="); + cond6.setValue("Marshmellow"); + cond6.setState(Condition.State.OR); + conditions.add(cond6); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + Assert.assertTrue(devices != null); + } + + @Test(description = "Test with wildcard operator") + public void testWithWildcardOperator() throws SearchMgtException { + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition condition = new Condition(); + condition.setKey("batteryLevel"); + condition.setOperator("="); + condition.setValue("40"); + condition.setState(Condition.State.AND); + conditions.add(condition); + + Condition condition2 = new Condition(); + condition2.setKey("LOCATION"); + condition2.setOperator("%"); + condition2.setValue("Karandeniya"); + condition2.setState(Condition.State.OR); + conditions.add(condition2); + + Condition condition3 = new Condition(); + condition3.setKey("internalTotalMemory"); + condition3.setOperator("%"); + condition3.setValue("23.2"); + condition3.setState(Condition.State.OR); + conditions.add(condition3); + + Condition condition4 = new Condition(); + condition4.setKey("connectionType"); + condition4.setOperator("%"); + condition4.setValue("DIALOG"); + condition4.setState(Condition.State.AND); + conditions.add(condition4); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List devices = service.search(context); + Assert.assertTrue(devices != null); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchMgtUtilTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchMgtUtilTest.java new file mode 100644 index 0000000000..df99f82bff --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/SearchMgtUtilTest.java @@ -0,0 +1,115 @@ +/* + * 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.search; + +import org.junit.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.core.common.TestDataHolder; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This class holds the Unit test cases to test org.wso2.carbon.device.mgt.core.search.mgt.impl.Util + * */ +public class SearchMgtUtilTest { + + private static List deviceIdentifiers = new ArrayList<>(); + private static final String DEVICE_ID_PREFIX = "SEARCH-DEVICE-ID-"; + private static final String DEVICE_TYPE = "SEARCH_TYPE"; + private static final String DEVICE_IDS = "0,0,0,0,0"; + private static final Integer[] DEVICE_IDS_INT = {0,0,0,0,0}; + private List devices; + + @BeforeClass + public void init() throws Exception { + for (int i = 0; i < 5; i++) { + deviceIdentifiers.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE)); + } + devices = TestDataHolder.generateDummyDeviceData(deviceIdentifiers); + } + + @Test(description = "Test for converting given devices list to string") + public void testConvertDeviceListToString() { + String ids = Utils.getDeviceIdsAsString(devices); + Assert.assertEquals(ids, DEVICE_IDS); + } + + @Test(description = "Test for get all the device ids as an array") + public void testGetArrayOfDeviceIds() { + Integer[] deviceIds = Utils.getArrayOfDeviceIds(devices); + Assert.assertArrayEquals(deviceIds, DEVICE_IDS_INT); + } + + @Test(description = "Test to convert given String to a List") + public void testConvertStringToList() { + List stringList = Utils.convertStringToList("some string"); + List expected = this.getStringList(); + + Assert.assertEquals(stringList, expected); + } + + @Test(description = "Test to check what type of data the specified column can hold") + public void testColumnTypes() { + Map colTypes = this.buildColumnMap(); + + for (String key : colTypes.keySet()) { + String result = Utils.checkColumnType(key); + Assert.assertEquals(result, colTypes.get(key)); + } + } + + /** + * Generates a map of columns and particular data type. + * @return HashMap of column name and data type. + * */ + private Map buildColumnMap() { + Map columnTypes = new HashMap<>(); + + columnTypes.put("deviceModel", "String"); + columnTypes.put("vendor", "String"); + columnTypes.put("osVersion", "String"); + columnTypes.put("connectionType", "String"); + columnTypes.put("ssid", "String"); + columnTypes.put("imei", "String"); + columnTypes.put("imsi", "String"); + columnTypes.put("batteryLevel", "Double"); + columnTypes.put("externalAvailableMemory", "Double"); + columnTypes.put("externalTotalMemory", "Double"); + columnTypes.put("internalAvailableMemory", "Double"); + columnTypes.put("cpuUsage", "Double"); + columnTypes.put("someProperty", "String"); + return columnTypes; + } + + /** + * Generates a list of Strings. + * @return List + * */ + private List getStringList() { + List strings = new ArrayList<>(); + strings.add("some string"); + return strings; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/ChangeEnumValues.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/ChangeEnumValues.java new file mode 100644 index 0000000000..2d0163e7c3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/ChangeEnumValues.java @@ -0,0 +1,131 @@ +/* + * 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.search.util; + +import org.wso2.carbon.device.mgt.common.search.Condition; +import sun.reflect.ConstructorAccessor; +import sun.reflect.FieldAccessor; +import sun.reflect.ReflectionFactory; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Changes the Enum values of a given class. + */ +public class ChangeEnumValues { + + private static ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory(); + + public ChangeEnumValues() {} + + private static void setFailSafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException, + IllegalAccessException { + + field.setAccessible(true); + + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + int modifiers = modifiersField.getInt(field); + + modifiers &= ~Modifier.FINAL; + modifiersField.setInt(field, modifiers); + + FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false); + fa.set(target, value); + } + + private static void blankField(Class enumClass, String fieldName) throws NoSuchFieldException, + IllegalAccessException { + for (Field field : Class.class.getDeclaredFields()) { + if (field.getName().contains(fieldName)) { + AccessibleObject.setAccessible(new Field[]{field}, true); + setFailSafeFieldValue(field, enumClass, null); + break; + } + } + } + + private static void cleanEnumCache(Class enumClass) throws NoSuchFieldException, IllegalAccessException { + blankField(enumClass, "enumConstantDirectory"); + blankField(enumClass, "enumConstants"); + } + + private static ConstructorAccessor getConstructorAccessor(Class enumClass, Class[] additionalParameterTypes) + throws NoSuchMethodException { + Class[] parameterTypes = new Class[additionalParameterTypes.length + 2]; + parameterTypes[0] = String.class; + parameterTypes[1] = int.class; + System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length); + return reflectionFactory.newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes)); + } + + private static Object makeEnum(Class enumClass, String value, int ordinal, Class[] additionalTypes, + Object[] additionalValues) throws Exception { + Object[] parms = new Object[additionalValues.length + 2]; + parms[0] = value; + parms[1] = ordinal; + System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length); + return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms)); + } + + /** + * Add an enum instance to the enum class given as argument + * + * @param the type of the enum + * @param enumType the class of the enum to be modified + * @param enumName the name of the new enum instance to be added to the class. + */ + public static > void addEnum(Class enumType, String enumName) { + + if (!Enum.class.isAssignableFrom(enumType)) { + throw new RuntimeException("class " + enumType + " is not an instance of Enum"); + } + + Field valuesField = null; + Field[] fields = Condition.State.class.getDeclaredFields(); + for (Field field : fields) { + if (field.getName().contains("$VALUES")) { + valuesField = field; + break; + } + } + AccessibleObject.setAccessible(new Field[]{valuesField}, true); + + try { + T[] previousValues = (T[]) valuesField.get(enumType); + List values = new ArrayList(Arrays.asList(previousValues)); + + T newValue = (T) makeEnum(enumType, enumName, values.size(), new Class[]{}, new Object[]{}); + + values.add(newValue); + + setFailSafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0))); + + cleanEnumCache(enumType); + + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/Utils.java index 9e02b3f970..ce3db26cee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/search/util/Utils.java @@ -15,27 +15,31 @@ * specific language governing permissions and limitations * under the License. */ - - package org.wso2.carbon.device.mgt.core.search.util; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.search.Condition; +import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.core.common.TestDataHolder; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import static org.wso2.carbon.device.mgt.common.search.Condition.State.AND; +import static org.wso2.carbon.device.mgt.common.search.Condition.State.OR; + public class Utils { public static DeviceInfo getDeviceInfo() { - DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.setSsid("FAFDA"); deviceInfo.setAvailableRAMMemory(1.24); - deviceInfo.setBatteryLevel(27.3); + deviceInfo.setBatteryLevel(40.0); deviceInfo.setConnectionType("GSM"); deviceInfo.setCpuUsage(82.34); deviceInfo.setDeviceModel("SM-T520"); @@ -51,7 +55,7 @@ public class Utils { deviceInfo.setSsid("SSSSSS"); deviceInfo.setTotalRAMMemory(4.00); deviceInfo.setVendor("SAMSUNG"); - + deviceInfo.setLocation(getSampleDeviceLocation()); Map propertyMap = new HashMap<>(); @@ -72,8 +76,6 @@ public class Utils { public static DeviceLocation getSampleDeviceLocation(){ - - DeviceLocation deviceLocation = new DeviceLocation(); deviceLocation.setDeviceIdentifier(Utils.getDeviceIdentifier()); deviceLocation.setLatitude(76.2422); 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 1975a56828..badedd8d56 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 @@ -17,6 +17,8 @@ package org.wso2.carbon.device.mgt.core.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.mockito.Mock; +import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -25,6 +27,7 @@ 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.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.License; @@ -39,23 +42,34 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDA import org.wso2.carbon.device.mgt.core.dto.DeviceType; 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.mock.MockConnection; +import org.wso2.carbon.device.mgt.core.mock.MockDataSource; +import org.wso2.carbon.device.mgt.core.mock.MockResultSet; +import org.wso2.carbon.device.mgt.core.mock.MockStatement; 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.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.InputStream; +import java.lang.reflect.Field; +import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Properties; +import javax.sql.DataSource; public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTest { private static final Log log = LogFactory.getLog(DeviceManagementProviderServiceTest.class); + public static final String DEVICE_ID = "9999"; + private static final String ALTERNATE_DEVICE_ID = "1128"; private DeviceManagementProviderService providerService; private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE"; private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); @@ -89,63 +103,85 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes } @Test - public void testGetAvailableDeviceTypes() { - try { - List deviceTypes = deviceMgtService.getDeviceTypes(); + public void testGetAvailableDeviceTypes() throws DeviceManagementException { + List deviceTypes = deviceMgtService.getDeviceTypes(); + if (!isMock()) { Assert.assertTrue(deviceTypes.size() > 0); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting the device types"; - Assert.fail(msg, e); } } @Test - public void testNullDeviceEnrollment() { - try { - boolean enrollmentStatus = deviceMgtService.enrollDevice(null); - } catch (DeviceManagementException e) { - Assert.assertTrue(true); + public void testGetAvailableDeviceType() throws DeviceManagementException { + DeviceType deviceType = deviceMgtService.getDeviceType(DEVICE_TYPE); + if (!isMock()) { + Assert.assertTrue(deviceType.getName().equalsIgnoreCase(DEVICE_TYPE)); } } @Test - public void testSuccessfulDeviceEnrollment() { - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); + public void addLicense() throws DeviceManagementException { + License license = new License(); + license.setLanguage("ENG"); + license.setName("RANDON_DEVICE_LICENSE"); + deviceMgtService.addLicense(DEVICE_TYPE, license); + } + + @Test(expectedExceptions = DeviceManagementException.class) + public void testNullDeviceEnrollment() throws DeviceManagementException { + deviceMgtService.enrollDevice(null); + } + + @Test + public void testSuccessfulDeviceEnrollment() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)); + MockDataSource dataSource = null; + if (isMock()) { + Field datasourceField = DeviceManagementDAOFactory.class.getDeclaredField("dataSource"); + datasourceField.setAccessible(true); + dataSource = (MockDataSource) getDataSource(); + dataSource.setConnection(new MockConnection(dataSource.getUrl())); + + MockConnection connection = new MockConnection(dataSource.getUrl()); + dataSource.setConnection(connection); + MockStatement mockStatement = new MockStatement(); + MockResultSet resultSet = new MockResultSet(); + resultSet.addInteger(1); + resultSet.addString(null); + + mockStatement.addResultSet(resultSet); + connection.addMockStatement(mockStatement); + + datasourceField.set(datasourceField, dataSource); + } try { boolean enrollmentStatus = deviceMgtService.enrollDevice(device); Assert.assertTrue(enrollmentStatus); - } catch (DeviceManagementException e) { - String msg = "Error occurred while enrolling device"; - Assert.fail(msg, e); + } finally { + if (dataSource != null) { + dataSource.reset(); + } } } @Test(dependsOnMethods = "testSuccessfulDeviceEnrollment") - public void testIsEnrolled() { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier); - deviceIdentifier.setType(DEVICE_TYPE); - boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier); + public void testIsEnrolled() throws DeviceManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(DEVICE_ID); + deviceIdentifier.setType(DEVICE_TYPE); + boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier); + if (!isMock()) { Assert.assertTrue(enrollmentStatus); - } catch (DeviceManagementException e) { - String msg = "Error occurred while checking enrollment status."; - Assert.fail(msg, e); } } @Test - public void testIsEnrolledForNonExistingDevice() { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId("34535235235235235"); - deviceIdentifier.setType(DEVICE_TYPE); - boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier); - Assert.assertFalse(enrollmentStatus); - } catch (DeviceManagementException e) { - String msg = "Error occurred while checking enrollment status."; - Assert.fail(msg, e); - } + public void testIsEnrolledForNonExistingDevice() throws DeviceManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId("34535235235235235"); + deviceIdentifier.setType(DEVICE_TYPE); + boolean enrollmentStatus = deviceMgtService.isEnrolled(deviceIdentifier); + Assert.assertFalse(enrollmentStatus); } @Test(expectedExceptions = DeviceManagementException.class) @@ -154,112 +190,113 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes } @Test - public void testNonExistentDeviceType() { + public void testNonExistentDeviceType() throws DeviceManagementException { Device device = TestDataHolder.generateDummyDeviceData("abc"); - try { - boolean enrollmentStatus = deviceMgtService.enrollDevice(device); - Assert.assertFalse(enrollmentStatus); - } catch (DeviceManagementException e) { - String msg = "Error occurred while enrolling device"; - Assert.fail(msg, e); - } + boolean enrollmentStatus = deviceMgtService.enrollDevice(device); + Assert.assertFalse(enrollmentStatus); } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testReEnrollmentofSameDeviceUnderSameUser() { - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - - try { + public void testReEnrollmentofSameDeviceUnderSameUser() throws DeviceManagementException { + if (!isMock()) { + Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)); boolean enrollment = deviceMgtService.enrollDevice(device); - Assert.assertTrue(enrollment); - } catch (DeviceManagementException e) { - String msg = "Error occurred while enrolling device"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"}) - public void testReEnrollmentofSameDeviceWithOtherUser() { - - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setOwner("user1"); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); - - Device alternateDevice = TestDataHolder.generateDummyDeviceData("12345", DEVICE_TYPE, - enrolmentInfo); - - try { - Device retrievedDevice1 = deviceMgtService.getDevice(new DeviceIdentifier("12345", DEVICE_TYPE)); + public void testReEnrollmentofSameDeviceWithOtherUser() throws DeviceManagementException { + if (!isMock()) { + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setOwner("user1"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); + + Device alternateDevice = TestDataHolder.generateDummyDeviceData(DEVICE_ID, DEVICE_TYPE, + enrolmentInfo); + Device retrievedDevice1 = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); deviceMgtService.enrollDevice(alternateDevice); Device retrievedDevice2 = deviceMgtService.getDevice(new DeviceIdentifier(alternateDevice .getDeviceIdentifier(), alternateDevice.getType())); - log.info(retrievedDevice1.getEnrolmentInfo().getOwner()); - log.info(retrievedDevice2.getEnrolmentInfo().getOwner()); - Assert.assertFalse(retrievedDevice1.getEnrolmentInfo().getOwner().equalsIgnoreCase (retrievedDevice2.getEnrolmentInfo().getOwner())); - } catch (DeviceManagementException e) { - String msg = "Error Occured while enrolling device"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"}) - public void testDisenrollment() { - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - try { + public void testDisenrollment() throws DeviceManagementException { + if (!isMock()) { + Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)); boolean disenrollmentStatus = deviceMgtService.disenrollDevice(new DeviceIdentifier - (device - .getDeviceIdentifier(), - device.getType())); + (device.getDeviceIdentifier(), device.getType())); log.info(disenrollmentStatus); - Assert.assertTrue(disenrollmentStatus); - } catch (DeviceManagementException e) { - String msg = "Error occurred while enrolling device"; - Assert.fail(msg, e); + } + } + + @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"}, expectedExceptions = + DeviceManagementException.class) + public void testDisenrollmentWithNullDeviceID() throws DeviceManagementException { + deviceMgtService.disenrollDevice(null); + } + + @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"}) + public void testDisenrollmentWithNonExistentDT() throws DeviceManagementException { + Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, + "NON_EXISTENT_DT")); + boolean result = deviceMgtService.disenrollDevice(new DeviceIdentifier( + device.getDeviceIdentifier(), device.getType())); + Assert.assertTrue(!result); + } + + @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceWithOtherUser"}) + public void testDisenrollmentWithNonExistentDevice() throws DeviceManagementException { + Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(ALTERNATE_DEVICE_ID, + DEVICE_TYPE)); + boolean result = deviceMgtService.disenrollDevice(new DeviceIdentifier( + device.getDeviceIdentifier(), device.getType())); + Assert.assertTrue(!result); + } + + @Test(dependsOnMethods = {"testDisenrollment"}) + public void testDisenrollAlreadyDisEnrolledDevice() throws DeviceManagementException { + if (!isMock()) { + Device device = TestDataHolder.generateDummyDeviceData(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); + boolean result = deviceMgtService.disenrollDevice(new DeviceIdentifier( + device.getDeviceIdentifier(), device.getType())); + Assert.assertTrue(result); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetDeviceCount() { - try { - int count = deviceMgtService.getDeviceCount(); + public void testGetDeviceCount() throws DeviceManagementException { + int count = deviceMgtService.getDeviceCount(); + if (!isMock()) { Assert.assertTrue(count > 0); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting the device count"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetDeviceCountForUser() { - try { - int count = deviceMgtService.getDeviceCount(TestDataHolder.OWNER); + public void testGetDeviceCountForUser() throws DeviceManagementException { + int count = deviceMgtService.getDeviceCount(TestDataHolder.OWNER); + if (!isMock()) { Assert.assertTrue(count > 0); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting the device count"; - Assert.fail(msg, e); } } @Test - public void testGetDeviceCountForNonExistingUser() { - try { - int count = deviceMgtService.getDeviceCount("ABCD"); - Assert.assertEquals(count, 0); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting the device count"; - Assert.fail(msg, e); - } + public void testGetDeviceCountForNonExistingUser() throws DeviceManagementException { + int count = deviceMgtService.getDeviceCount("ABCD"); + Assert.assertEquals(count, 0); } @Test(expectedExceptions = DeviceManagementException.class) @@ -268,214 +305,376 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testIsActive() { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier); - deviceIdentifier.setType(DEVICE_TYPE); - Assert.assertTrue(deviceMgtService.isActive(deviceIdentifier)); - } catch (DeviceManagementException e) { - String msg = "Error occurred while checking the device status"; - Assert.fail(msg, e); - } + public void testIsActive() throws DeviceManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier); + deviceIdentifier.setType(DEVICE_TYPE); + Assert.assertTrue(deviceMgtService.isActive(deviceIdentifier)); } @Test - public void testIsActiveForNonExistingDevice() { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId("34535235235235235"); - deviceIdentifier.setType("TEST_TYPE"); - Assert.assertFalse(deviceMgtService.isActive(deviceIdentifier)); - } catch (DeviceManagementException e) { - String msg = "Error occurred while checking the device status"; - Assert.fail(msg, e); - } + public void testIsActiveForNonExistingDevice() throws DeviceManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId("34535235235235235"); + deviceIdentifier.setType("TEST_TYPE"); + Assert.assertFalse(deviceMgtService.isActive(deviceIdentifier)); } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testSetActive() { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier); - deviceIdentifier.setType(DEVICE_TYPE); - Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true)); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); - } + public void testSetActive() throws DeviceManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(TestDataHolder.initialDeviceIdentifier); + deviceIdentifier.setType(DEVICE_TYPE); + Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true)); } @Test - public void testSetActiveForNonExistingDevice() { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId("34535235235235235"); - deviceIdentifier.setType("TEST_TYPE"); - Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true)); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status for non-existing device"; - Assert.fail(msg, e); - } + public void testSetActiveForNonExistingDevice() throws DeviceManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId("34535235235235235"); + deviceIdentifier.setType("TEST_TYPE"); + Assert.assertFalse(deviceMgtService.setActive(deviceIdentifier, true)); } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetDeviceEnrolledTenants() { - try { - List tenants = deviceMgtService.getDeviceEnrolledTenants(); + public void testGetDeviceEnrolledTenants() throws DeviceManagementException { + List tenants = deviceMgtService.getDeviceEnrolledTenants(); + if (!isMock()) { Assert.assertEquals(tenants.size(), 1); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetDevice() { - try { - Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345",DEVICE_TYPE)); - Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase("12345")); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); - } + public void testGetDevice() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { + MockDataSource dataSource = setDatasourceForGetDevice(); + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)); + cleanupMockDatasource(dataSource); + Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase(DEVICE_ID)); } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetDeviceWithInfo() { - try { - Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", DEVICE_TYPE) - , true); + public void testGetDeviceWithInfo() throws DeviceManagementException { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE) + , true); + if (!isMock()) { Assert.assertTrue(device.getDeviceInfo() != null); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetDeviceWithOutInfo() { - try { - Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", DEVICE_TYPE) - , false); + public void testGetDeviceTypeWithProps() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + MockDataSource dataSource = setDatasourceForGetDevice(); + Device device = deviceMgtService.getDeviceWithTypeProperties(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE)); + cleanupMockDatasource(dataSource); + Assert.assertTrue(!device.getProperties().isEmpty()); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviceWithOutInfo() throws DeviceManagementException { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE) + , false); + if (!isMock()) { Assert.assertTrue(device.getDeviceInfo() == null); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetAllDevicesOfRole() { + public void testGetAllDevicesOfRole() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { + MockDataSource dataSource = setDatasourceForGetDevice(); + List devices = deviceMgtService.getAllDevicesOfRole("admin"); + cleanupMockDatasource(dataSource); + Assert.assertTrue(devices.size() > 0); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetAllDevicesOfRoleFailureFlow() throws DeviceManagementException, UserStoreException, NoSuchFieldException, IllegalAccessException { + int tenantID = -1234; + RealmService mockRealmService = Mockito.mock(RealmService.class, Mockito.CALLS_REAL_METHODS); + + Mockito.doThrow(new UserStoreException("Mocked Exception when obtaining Tenant Realm")) + .when(mockRealmService).getTenantUserRealm(tenantID); + RealmService currentRealm = DeviceManagementDataHolder.getInstance().getRealmService(); + DeviceManagementDataHolder.getInstance().setRealmService(mockRealmService); try { - List devices = deviceMgtService.getAllDevicesOfRole("admin"); - Assert.assertTrue(devices.size() > 0); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); + deviceMgtService.getAllDevicesOfRole("admin"); + } finally { + DeviceManagementDataHolder.getInstance().setRealmService(currentRealm); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testDeviceByOwner() { - try { - Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", - DEVICE_TYPE), "admin", true); + public void testGetAllDevicesOfRoleWithNonExistentRole() throws DeviceManagementException { + List devices = deviceMgtService.getAllDevicesOfRole("non-existent-role"); + Assert.assertTrue(devices.size() == 0); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetAllDevicesOfRoleWithNullArgs() throws DeviceManagementException { + deviceMgtService.getAllDevicesOfRole(null); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testDeviceByOwner() throws DeviceManagementException { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE), "admin", true); + if (!isMock()) { Assert.assertTrue(device != null); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testDeviceByDate() { - try { - Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier("12345", - DEVICE_TYPE)); + public void testDeviceByOwnerAndNonExistentDeviceID() throws DeviceManagementException { + String nonExistentDeviceID = "4455"; + Device device = deviceMgtService.getDevice(new DeviceIdentifier(nonExistentDeviceID, + DEVICE_TYPE), "admin", true); + Assert.assertTrue(device == null); + } - DeviceManagementDAOFactory.beginTransaction(); - - //Device details table will be reffered when looking for last updated time - //This dao entry is to mimic a device info operation - deviceDetailsDAO.addDeviceInformation(initialDevice.getId(), TestDataHolder - .generateDummyDeviceInfo()); - } catch (DeviceManagementException e) { - e.printStackTrace(); - } catch (TransactionManagementException e) { - e.printStackTrace(); - } catch (DeviceDetailsMgtDAOException e) { - e.printStackTrace(); - } finally { - DeviceManagementDAOFactory.closeConnection(); - } + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testDeviceByOwnerWithNullDeviceID() throws DeviceManagementException { + deviceMgtService.getDevice(null, "admin", true); + } - try { - Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", - DEVICE_TYPE), yesterday()); + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testDeviceByDate() throws DeviceManagementException, TransactionManagementException, + DeviceDetailsMgtDAOException, NoSuchFieldException, IllegalAccessException { + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); + } + Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); + addDeviceInformation(initialDevice); + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE), yesterday()); + cleanupMockDatasource(dataSource); + if (!isMock()) { Assert.assertTrue(device != null); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } + private MockResultSet getMockGetDeviceResult() { + MockResultSet resultSet = new MockResultSet(); + resultSet.addInteger(1); + resultSet.addString("Test"); + resultSet.addString(null); + resultSet.addString(DEVICE_TYPE); + resultSet.addString(DEVICE_ID); + resultSet.addInteger(0); + resultSet.addString("admin"); + resultSet.addString("BYOD"); + resultSet.addTimestamp(new Timestamp(System.currentTimeMillis())); + resultSet.addTimestamp(new Timestamp(System.currentTimeMillis())); + resultSet.addString("ACTIVE"); + return resultSet; + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testUpdateDeviceInfo() throws DeviceManagementException, + TransactionManagementException, DeviceDetailsMgtDAOException { + if (!isMock()) { + 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 { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(ALTERNATE_DEVICE_ID, + DEVICE_TYPE), yesterday()); + Assert.assertTrue(device == null); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testDeviceByDateWithNullDeviceID() throws DeviceManagementException { + deviceMgtService.getDevice(null, yesterday()); + } + + private void addDeviceInformation(Device initialDevice) throws TransactionManagementException, DeviceDetailsMgtDAOException { + DeviceManagementDAOFactory.beginTransaction(); + + //Device details table will be reffered when looking for last updated time + //This dao entry is to mimic a device info operation + deviceDetailsDAO.addDeviceInformation(initialDevice.getId(), TestDataHolder + .generateDummyDeviceInfo()); + + DeviceManagementDAOFactory.closeConnection(); + } + @Test(dependsOnMethods = {"testDeviceByDate"}) - public void testDeviceByDateAndOwner() { - try { - Device device = deviceMgtService.getDevice(new DeviceIdentifier("12345", + public void testDeviceByDateAndOwner() throws DeviceManagementException { + if (!isMock()) { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE), "admin", yesterday(), true); Assert.assertTrue(device != null); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } @Test - public void testGetAvaliableDeviceTypes() { - try { - List deviceTypes = deviceMgtService.getAvailableDeviceTypes(); + public void testGetAvaliableDeviceTypes() throws DeviceManagementException { + List deviceTypes = deviceMgtService.getAvailableDeviceTypes(); + if (!isMock()) { Assert.assertTrue(!deviceTypes.isEmpty()); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); } } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) - public void testGetAllDevices() { - try { - List devices = deviceMgtService.getAllDevices(); - Assert.assertTrue(!devices.isEmpty()); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); + public void testGetAllDevices() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { + MockDataSource dataSource = setDatasourceForGetDevice(); + List devices = deviceMgtService.getAllDevices(); + cleanupMockDatasource(dataSource); + Assert.assertTrue(!devices.isEmpty()); + } + + private MockDataSource setDatasourceForGetDevice() throws IllegalAccessException, NoSuchFieldException { + MockDataSource dataSource = null; + if (isMock()) { + Field datasourceField = DeviceManagementDAOFactory.class.getDeclaredField("dataSource"); + datasourceField.setAccessible(true); + dataSource = (MockDataSource) getDataSource(); + + //connection used for first get device operation. + MockConnection connection = new MockConnection(dataSource.getUrl()); + dataSource.setConnection(connection); + MockStatement mockStatement = new MockStatement(); + mockStatement.addResultSet(getMockGetDeviceResult()); + connection.addMockStatement(mockStatement); + + datasourceField.set(datasourceField, dataSource); } + return dataSource; } - @Test(dependsOnMethods = {"testDeviceByDate"}) - public void testGetAllDevicesWithInfo() { - try { - List devices = deviceMgtService.getAllDevices(true); - Assert.assertTrue(!devices.isEmpty()); - Assert.assertTrue(devices.get(0).getDeviceInfo() != null); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); + private void cleanupMockDatasource(MockDataSource dataSource) { + if (isMock()) { + if (dataSource != null) { + dataSource.reset(); + } } } - @Test(dependsOnMethods = {"testDeviceByDate"}) - public void testGetLicense() { - try { - License license = deviceMgtService.getLicense(DEVICE_TYPE, "ENG"); - Assert.assertTrue(license.getLanguage().equalsIgnoreCase("ENG")); - } catch (DeviceManagementException e) { - String msg = "Error occurred while updating the device status"; - Assert.fail(msg, e); + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetAllDevicesPaginated() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setOwnerRole("admin"); + MockDataSource dataSource = setDatasourceForGetDevice(); + PaginationResult result = deviceMgtService.getAllDevices(request); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetAllDevicesWithNullRequest() throws DeviceManagementException { + PaginationRequest request = null; + deviceMgtService.getAllDevices(request); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetAllDevicesByName() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setDeviceName(DEVICE_TYPE + "-" + DEVICE_ID); + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); } + PaginationResult result = deviceMgtService.getDevicesByName(request); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetAllDevicesByNameAndType() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setDeviceName(DEVICE_TYPE + "-" + DEVICE_ID); + request.setDeviceType(DEVICE_TYPE); + MockDataSource dataSource = setDatasourceForGetDevice(); + List devices = deviceMgtService.getDevicesByNameAndType(request, true); + cleanupMockDatasource(dataSource); + Assert.assertTrue(!devices.isEmpty()); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetAllDevicesByStatus() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setStatus(EnrolmentInfo.Status.ACTIVE.toString()); + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); + } + PaginationResult result = deviceMgtService.getDevicesByStatus(request, true); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + } + + private void setMockDeviceCount(MockConnection connection) { + MockStatement statement = new MockStatement(); + connection.addMockStatement(statement); + MockResultSet resultSet = new MockResultSet(); + resultSet.addInteger(1); + statement.addResultSet(resultSet); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDevicesOfTypePaginated() throws DeviceManagementException { + if (!isMock()) { + PaginationRequest request = new PaginationRequest(0, 100); + request.setDeviceType(DEVICE_TYPE); + PaginationResult result = deviceMgtService.getDevicesByType(request); + Assert.assertTrue(result.getRecordsTotal() > 0); + } + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetAllDevicesWithInfo() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + MockDataSource dataSource = setDatasourceForGetDevice(); + List devices = deviceMgtService.getAllDevices(true); + cleanupMockDatasource(dataSource); + Assert.assertTrue(!devices.isEmpty()); + Assert.assertTrue(devices.get(0).getDeviceInfo() != null); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetAllDevicesWithInfoPaginated() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); + } + PaginationResult result = deviceMgtService.getAllDevices(request, true); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetTenantedDevice() throws DeviceManagementException { + HashMap deviceMap = deviceMgtService.getTenantedDevice(new + DeviceIdentifier + (DEVICE_ID, DEVICE_TYPE)); + if (!isMock()) { + Assert.assertTrue(!deviceMap.isEmpty()); + } + } + + @Test + public void testGetLicense() throws DeviceManagementException { + License license = deviceMgtService.getLicense(DEVICE_TYPE, "ENG"); + Assert.assertTrue(license.getLanguage().equalsIgnoreCase("ENG")); } @Test(expectedExceptions = DeviceManagementException.class) @@ -484,26 +683,167 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes Assert.assertTrue(false); } - @Test - public void testSendRegistrationEmailSuccessFlow() { - try { - String recipient = "test-user@wso2.com"; - Properties props = new Properties(); - props.setProperty("first-name", "Test"); - props.setProperty("username", "User"); - props.setProperty("password", "!@#$$$%"); + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetDeviesOfUser() throws DeviceManagementException { + String username = null; + deviceMgtService.getDevicesOfUser(username); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviesOfUserWhileUserNull() throws DeviceManagementException { + if (!isMock()) { + List devices = deviceMgtService.getDevicesOfUser("admin"); + Assert.assertTrue(!devices.isEmpty()); + } + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDevieByStatus() throws DeviceManagementException { + if (!isMock()) { + Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE), EnrolmentInfo.Status.ACTIVE); + Assert.assertTrue(device != null); + } + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDevieByDate() throws DeviceManagementException { + if (!isMock()) { + List devices = deviceMgtService.getDevices(yesterday()); + Assert.assertTrue(!devices.isEmpty()); + } + } - EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviesOfUserPaginated() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setOwner("admin"); + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); + } + PaginationResult result = deviceMgtService.getDevicesOfUser(request, true); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + + } - deviceMgtService.sendRegistrationEmail(metaInfo); - Assert.assertTrue(true); - } catch (ConfigurationManagementException e) { - Assert.assertTrue(false, "Error in sending registration email : Configration " + - "related error" + e.getMessage()); - } catch (DeviceManagementException e) { - Assert.assertTrue(false, "Error in sending registration email" + - e.getMessage()); + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetDeviesOfUserWhileNullOwnerPaginated() throws DeviceManagementException { + PaginationRequest request = null; + deviceMgtService.getDevicesOfUser(request, true); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviesByOwnership() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setOwnership(EnrolmentInfo.OwnerShip.BYOD.toString()); + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); } + PaginationResult result = deviceMgtService.getDevicesByOwnership(request); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testSetOwnership() throws DeviceManagementException { + boolean status = deviceMgtService.setOwnership(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE), EnrolmentInfo.OwnerShip.COPE.toString()); + Assert.assertTrue(status); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testSetOwnershipNonExistentDT() throws DeviceManagementException { + boolean status = deviceMgtService.setOwnership(new DeviceIdentifier(DEVICE_ID, + "non-existent-dt"), EnrolmentInfo.OwnerShip.COPE.toString()); + Assert.assertFalse(status); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testSetOwnershipOfNullDevice() throws DeviceManagementException { + deviceMgtService.setOwnership(null, EnrolmentInfo.OwnerShip.COPE.toString()); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviesByStatus() throws DeviceManagementException, NoSuchFieldException, + IllegalAccessException { + PaginationRequest request = new PaginationRequest(0, 100); + request.setStatus("ACTIVE"); + MockDataSource dataSource = setDatasourceForGetDevice(); + if (dataSource != null) { + setMockDeviceCount(dataSource.getConnection(0)); + } + PaginationResult result = deviceMgtService.getDevicesByStatus(request); + cleanupMockDatasource(dataSource); + Assert.assertTrue(result.getRecordsTotal() > 0); + } + + @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"}) + public void testUpdateDevicesStatus() throws DeviceManagementException { + if (!isMock()) { + boolean status = deviceMgtService.setStatus("user1", EnrolmentInfo.Status.REMOVED); + Assert.assertTrue(status); + } + } + + @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"}) + public void testUpdateDevicesStatusWithDeviceID() throws DeviceManagementException { + if (!isMock()) { + boolean status = deviceMgtService.setStatus(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE), "user1", + EnrolmentInfo.Status.ACTIVE); + Assert.assertTrue(status); + } + } + + @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"}) + public void testUpdateDevicesStatusOfNonExistingUser() throws DeviceManagementException { + boolean status = deviceMgtService.setStatus("random-user", EnrolmentInfo.Status.REMOVED); + Assert.assertFalse(status); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviesOfUserAndDeviceType() throws DeviceManagementException { + if (!isMock()) { + List devices = deviceMgtService.getDevicesOfUser("admin", DEVICE_TYPE, true); + Assert.assertTrue(!devices.isEmpty() && devices.get(0).getType().equalsIgnoreCase + (DEVICE_TYPE) && devices.get(0).getDeviceInfo() != null); + } + } + + @Test + public void testSendRegistrationEmailSuccessFlow() throws ConfigurationManagementException, DeviceManagementException { + String recipient = "test-user@wso2.com"; + Properties props = new Properties(); + props.setProperty("first-name", "Test"); + props.setProperty("username", "User"); + props.setProperty("password", "!@#$$$%"); + + EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); + deviceMgtService.sendRegistrationEmail(metaInfo); + Assert.assertTrue(true); + } + + @Test + public void testSendEnrollmentInvitation() throws ConfigurationManagementException, + DeviceManagementException { + String recipient = "test-user@wso2.com"; + Properties props = new Properties(); + props.setProperty("first-name", "Test"); + props.setProperty("username", "User"); + props.setProperty("password", "!@#$$$%"); + + EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); + + deviceMgtService.sendEnrolmentInvitation("template-name", metaInfo); + Assert.assertTrue(true); } private Date yesterday() { @@ -511,6 +851,4 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes cal.add(Calendar.DATE, -1); return cal.getTime(); } - - } \ No newline at end of file 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..ccaf84652e --- /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(getDatasourceLocation() + "-no-table" + DATASOURCE_EXT)); + 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/config/datasource/data-source-config-mock.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config-mock.xml new file mode 100644 index 0000000000..91d25ac9ad --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config-mock.xml @@ -0,0 +1,33 @@ + + + + + jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml new file mode 100644 index 0000000000..7781e61ea2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config-no-table.xml @@ -0,0 +1,33 @@ + + + + + jdbc:h2:mem:nodb-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true + org.h2.Driver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config-mock.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config-mock.xml new file mode 100644 index 0000000000..bdd1fca814 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config-mock.xml @@ -0,0 +1,33 @@ + + + + + jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config-no-table.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config-no-table.xml new file mode 100644 index 0000000000..bdd1fca814 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config-no-table.xml @@ -0,0 +1,33 @@ + + + + + jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config.xml new file mode 100644 index 0000000000..bdd1fca814 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mssql/data-source-config.xml @@ -0,0 +1,33 @@ + + + + + jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config-mock.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config-mock.xml new file mode 100644 index 0000000000..e89ec94229 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config-mock.xml @@ -0,0 +1,33 @@ + + + + + jdbc:mysql://localhost/test + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config-no-table.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config-no-table.xml new file mode 100644 index 0000000000..1f129e7e6e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config-no-table.xml @@ -0,0 +1,33 @@ + + + + + jdbc:mysql://localhost/noTableTest + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config.xml new file mode 100644 index 0000000000..e89ec94229 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/mysql/data-source-config.xml @@ -0,0 +1,33 @@ + + + + + jdbc:mysql://localhost/test + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config-mock.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config-mock.xml new file mode 100644 index 0000000000..badd2738f2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config-mock.xml @@ -0,0 +1,33 @@ + + + + + jdbc:oracle:thin:@myhost:1521:orcl + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config-no-table.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config-no-table.xml new file mode 100644 index 0000000000..f5ec80f750 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config-no-table.xml @@ -0,0 +1,33 @@ + + + + + jdbc:oracle:thin:@myhost:1521:orclt + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config.xml new file mode 100644 index 0000000000..badd2738f2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/oracle/data-source-config.xml @@ -0,0 +1,33 @@ + + + + + jdbc:oracle:thin:@myhost:1521:orcl + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config-mock.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config-mock.xml new file mode 100644 index 0000000000..e89ec94229 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config-mock.xml @@ -0,0 +1,33 @@ + + + + + jdbc:mysql://localhost/test + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config-no-table.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config-no-table.xml new file mode 100644 index 0000000000..1f129e7e6e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config-no-table.xml @@ -0,0 +1,33 @@ + + + + + jdbc:mysql://localhost/noTableTest + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config.xml new file mode 100644 index 0000000000..acd82eb55f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/postgre/data-source-config.xml @@ -0,0 +1,33 @@ + + + + + jdbc:postgresql://localhost/test + org.wso2.carbon.device.mgt.core.mock.MockJDBCDriver + wso2carbon + wso2carbon + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/mssql-testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/mssql-testng.xml new file mode 100644 index 0000000000..5c1f4cbe4e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/mssql-testng.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/mysql-testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/mysql-testng.xml new file mode 100644 index 0000000000..7b02276ea6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/mysql-testng.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/oracle-testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/oracle-testng.xml new file mode 100644 index 0000000000..cb41dfc620 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/oracle-testng.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/postgre-testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/postgre-testng.xml new file mode 100644 index 0000000000..6c516bc74d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/postgre-testng.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 7830b7fbe3..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 @@ -1,4 +1,3 @@ - - + + + + - + + + + + + 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 4a60638986..754640a4e2 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml @@ -122,6 +122,11 @@ + + org.apache.sling + org.apache.sling.testing.osgi-mock + test + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java index 1f1ee0d868..6e2aff8b35 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java @@ -83,9 +83,7 @@ public class DeviceTypeManager implements DeviceManager { if (deviceTypeConfiguration.getFeatures() != null && deviceTypeConfiguration.getFeatures(). getFeature() != null) { List features = deviceTypeConfiguration.getFeatures().getFeature(); - if (features != null) { - featureManager = new ConfigurationBasedFeatureManager(features); - } + featureManager = new ConfigurationBasedFeatureManager(features); } if (deviceTypeConfiguration.getDeviceAuthorizationConfig() != null) { requiredDeviceTypeAuthorization = deviceTypeConfiguration.getDeviceAuthorizationConfig(). @@ -119,7 +117,8 @@ public class DeviceTypeManager implements DeviceManager { try { defaultPlatformConfiguration = this.getDefaultConfiguration(); } catch (DeviceManagementException e) { - String msg = "Error occurred while default platform configuration"; + String msg = + "Error occurred while getting default platform configuration for the device type " + deviceType; throw new DeviceTypeDeployerPayloadException(msg, e); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java index ceedeb7454..0e1502f34a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/dao/PropertyBasedPluginDAOImpl.java @@ -126,14 +126,13 @@ public class PropertyBasedPluginDAOImpl implements PluginDAO { } public boolean updateDevice(Device device) throws DeviceTypeMgtPluginException { - boolean status = false; - Connection conn = null; + Connection conn; PreparedStatement stmt = null; try { conn = deviceTypeDAOHandler.getConnection(); stmt = conn.prepareStatement( - "UPDATE DM_DEVICE_PROPERTIES SET PROPERTY_VALUE = ? WHERE DEVICE_TYPE_NAME = ? AND " + - "DEVICE_IDENTIFICATION = ? AND PROPERTY_NAME = ? AND TENANT_ID= ?"); + "UPDATE DM_DEVICE_PROPERTIES SET PROPERTY_VALUE = ? WHERE DEVICE_TYPE_NAME = ? AND " + + "DEVICE_IDENTIFICATION = ? AND PROPERTY_NAME = ? AND TENANT_ID= ?"); for (Device.Property property : device.getProperties()) { if (!deviceProps.contains(property.getName())) { @@ -149,8 +148,8 @@ public class PropertyBasedPluginDAOImpl implements PluginDAO { stmt.executeBatch(); return true; } catch (SQLException e) { - String msg = "Error occurred while modifying the device '" + - device.getDeviceIdentifier() + "' data on" + deviceType; + String msg = "Error occurred while modifying the device '" + device.getDeviceIdentifier() + "' data on" + + deviceType; log.error(msg, e); throw new DeviceTypeMgtPluginException(msg, e); } finally { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java index 1919e88f42..a07808a9ff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/exception/DeviceTypeMgtPluginException.java @@ -22,6 +22,10 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template.exception; */ public class DeviceTypeMgtPluginException extends Exception{ + public DeviceTypeMgtPluginException(String msg) { + super(msg); + } + public DeviceTypeMgtPluginException(String msg, Exception nestedEx) { super(msg, nestedEx); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java index 3486446343..8a0bc9c292 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/policy/mgt/DefaultPolicyMonitoringManager.java @@ -54,7 +54,6 @@ public class DefaultPolicyMonitoringManager implements PolicyMonitoringManager { if (!complianceFeature.isCompliant()) { nonComplianceFeatures.add(complianceFeature); nonComplianceData.setStatus(false); - break; } } nonComplianceData.setComplianceFeatures(nonComplianceFeatures); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java index d409d22b38..56ab67d7bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypeUtils.java @@ -25,6 +25,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import org.wso2.carbon.device.mgt.extensions.internal.DeviceTypeExtensionDataHolder; import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.RegistryService; import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.core.Registry; @@ -101,25 +102,28 @@ public class DeviceTypeUtils { public static Registry getConfigurationRegistry() throws DeviceTypeMgtPluginException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - return DeviceTypeExtensionDataHolder.getInstance().getRegistryService() - .getConfigSystemRegistry(tenantId); + org.wso2.carbon.registry.core.service.RegistryService registryService = DeviceTypeExtensionDataHolder + .getInstance().getRegistryService(); + if (registryService == null) { + throw new DeviceTypeMgtPluginException("Registry Service is not initialized properly"); + } + return registryService.getConfigSystemRegistry(tenantId); } catch (RegistryException e) { throw new DeviceTypeMgtPluginException("Error in retrieving conf registry instance: " + e.getMessage(), e); } } public static boolean putRegistryResource(String path, Resource resource) throws DeviceTypeMgtPluginException { - boolean status; try { - DeviceTypeUtils.getConfigurationRegistry().beginTransaction(); - DeviceTypeUtils.getConfigurationRegistry().put(path, resource); - DeviceTypeUtils.getConfigurationRegistry().commitTransaction(); - status = true; + Registry registry = getConfigurationRegistry(); + registry.beginTransaction(); + registry.put(path, resource); + registry.commitTransaction(); + return true; } catch (RegistryException e) { - throw new DeviceTypeMgtPluginException("Error occurred while persisting registry resource : " + - e.getMessage(), e); + throw new DeviceTypeMgtPluginException( + "Error occurred while persisting registry resource : " + e.getMessage(), e); } - return status; } public static Resource getRegistryResource(String path) throws DeviceTypeMgtPluginException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java index 180e9717e3..e29af46f12 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponent.java @@ -44,11 +44,18 @@ public class DeviceTypeExtensionServiceComponent { private static final Log log = LogFactory.getLog(DeviceTypeExtensionServiceComponent.class); protected void activate(ComponentContext ctx) { - if (log.isDebugEnabled()) { - log.debug("Activating DeviceType Deployer Service Component"); + try { + if (log.isDebugEnabled()) { + log.debug("Activating Device Type Extension Service Component"); + } + ctx.getBundleContext() + .registerService(DeviceTypeGeneratorService.class, new DeviceTypeGeneratorServiceImpl(), null); + if (log.isDebugEnabled()) { + log.debug("Device Type Extension Service Component successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while initializing device type extension component ", e); } - ctx.getBundleContext().registerService(DeviceTypeGeneratorService.class, new DeviceTypeGeneratorServiceImpl() - , null); } protected void deactivate(ComponentContext ctx) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java index d2d9060d12..0d177c6c26 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java @@ -18,13 +18,26 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; -import org.testng.annotations.BeforeTest; +import org.h2.jdbcx.JdbcDataSource; +import org.mockito.Mockito; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; +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.extensions.device.type.template.config.DataSource; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypeDAOHandler; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOImpl; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; +import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import org.wso2.carbon.device.mgt.extensions.utils.Utils; import org.xml.sax.SAXException; @@ -32,7 +45,11 @@ import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; +import java.lang.reflect.Field; import java.net.URL; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; /** * This class tests the negative scenarios in {@link DeviceTypeManager} initialization; @@ -40,15 +57,22 @@ import java.net.URL; public class DeviceTypeManagerNegativeTest { private DeviceTypeConfiguration defectiveDeviceTypeConfiguration1; private DeviceTypeConfiguration defectiveDeviceTypeConfiguration2; + private DeviceTypeConfiguration defectiveDeviceTypeConfiguration3; private DeviceTypeConfiguration androidDeviceTypeConfiguration; private DeviceTypeConfigIdentifier deviceTypeConfigIdentifier; + private DeviceTypeManager androidDeviceTypeManager; + private DeviceTypeDAOHandler deviceTypeDAOHandler; private final String DEFECTIVE_DEVICE_TYPE = "defectiveDeviceType"; private final String TABLE_NAME = "DEFECTIVE_DEVICE"; + private DeviceIdentifier deviceIdentifier; + private final String ANDROID_DEVICE_TYPE = "android"; + private PropertyBasedPluginDAOImpl propertyBasedPluginDAO; + private Device sampleDevice; - @BeforeTest + @BeforeClass public void setup() throws SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException, - IOException { + IOException, NoSuchFieldException, IllegalAccessException { ClassLoader classLoader = getClass().getClassLoader(); URL resourceUrl = classLoader.getResource(Utils.DEVICE_TYPE_FOLDER + "defective-devicetype.xml"); File configurationFile = null; @@ -76,6 +100,37 @@ public class DeviceTypeManagerNegativeTest { if (configurationFile != null) { androidDeviceTypeConfiguration = Utils.getDeviceTypeConfiguration(configurationFile.getAbsoluteFile()); } + + resourceUrl = classLoader.getResource(Utils.DEVICE_TYPE_FOLDER + "defective-devicetype3.xml"); + if (resourceUrl != null) { + configurationFile = new File(resourceUrl.getFile()); + } + if (configurationFile != null) { + defectiveDeviceTypeConfiguration3 = Utils + .getDeviceTypeConfiguration(configurationFile.getAbsoluteFile()); + } + createDefectiveDeviceTypeManager(); + deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(Utils.TEST_STRING); + deviceIdentifier.setType(ANDROID_DEVICE_TYPE); + + DeviceDetails deviceDetails = new DeviceDetails(); + Properties properties = new Properties(); + List propertyList = new ArrayList<>(); + propertyList.add(Utils.TEST_STRING); + properties.addProperties(propertyList); + + deviceDetails.setProperties(properties); + propertyBasedPluginDAO = new PropertyBasedPluginDAOImpl(deviceDetails, + deviceTypeDAOHandler, ANDROID_DEVICE_TYPE); + sampleDevice = new Device(); + sampleDevice.setDeviceIdentifier(Utils.TEST_STRING); + List deviceProperties = new ArrayList<>(); + Device.Property property = new Device.Property(); + property.setName(Utils.TEST_STRING); + property.setValue(Utils.TEST_STRING); + deviceProperties.add(property); + sampleDevice.setProperties(deviceProperties); } @Test(description = "This test case tests the behaviour of the DeviceTypeManager creation without defining the " @@ -121,4 +176,168 @@ public class DeviceTypeManagerNegativeTest { new DeviceTypeManager(deviceTypeConfigIdentifier, androidDeviceTypeConfiguration); } + + @Test(description = "This test case tests the behaviour of the DeviceTypeManager creation when having a " + + "defective platform configuration ", expectedExceptions = {DeviceTypeDeployerPayloadException.class}, + expectedExceptionsMessageRegExp = "Error occurred while getting default platform configuration for the " + + "device type wrong *") + public void testWithDefectivePlatformConfiguration() { + DeviceTypeConfigIdentifier wrongDeviceTypeConfigIdentifier = new DeviceTypeConfigIdentifier("wrong", + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + new DeviceTypeManager(wrongDeviceTypeConfigIdentifier, androidDeviceTypeConfiguration); + } + + @Test(description = "This test case tests the behaviour of the DeviceTypeManager creation when having a " + + "defective platform configuration ", expectedExceptions = {DeviceTypeDeployerPayloadException.class}, + expectedExceptionsMessageRegExp = "Error while looking up the data source:.*") + public void testWithoutDeviceSpecificTable() { + new DeviceTypeManager(deviceTypeConfigIdentifier, defectiveDeviceTypeConfiguration3); + } + + @Test(description = "This test case tests the behaviour of the isEnrolled when the relevant tables are not there", + expectedExceptions = {DeviceManagementException.class}, + expectedExceptionsMessageRegExp = "Error while checking the enrollment status of android device.*") + public void testIsEnrolled() throws DeviceManagementException { + androidDeviceTypeManager.isEnrolled(deviceIdentifier); + } + + @Test(description = "This test case tests the behaviour of the modifyEnrollment when the relevant tables " + + "are not there", + expectedExceptions = {DeviceManagementException.class}, + expectedExceptionsMessageRegExp = "Error while updating the enrollment of the.*") + public void testModifyEnrollment() throws DeviceManagementException { + Device device = new Device(); + device.setDeviceIdentifier(deviceIdentifier.getId()); + device.setType(deviceIdentifier.getType()); + androidDeviceTypeManager.modifyEnrollment(device); + } + + @Test(description = "This test case tests the behaviour of the getAllDevices when the relevant tables " + + "are not there", + expectedExceptions = {DeviceManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while fetching all.*") + public void testGetAllDevices() throws DeviceManagementException { + androidDeviceTypeManager.getAllDevices(); + } + + @Test(description = "This test case tests the behaviour of the updateDeviceInfo when the relevant tables " + + "are not there", + expectedExceptions = {DeviceManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while fetching the.*") + public void testUpdateDeviceInfo() throws DeviceManagementException { + Device device = new Device(); + device.setDeviceIdentifier(deviceIdentifier.getId()); + device.setType(deviceIdentifier.getType()); + androidDeviceTypeManager.updateDeviceInfo(deviceIdentifier, device); + } + + @Test(description = ("This test case tests the behaviour of the enrollDevice when the relevant tables are not " + + "there"), expectedExceptions = {DeviceManagementException.class}, + expectedExceptionsMessageRegExp = "Error while enrolling the.*", dependsOnMethods = {"testIsEnrolled"}) + public void testEnrollDevice() throws DeviceManagementException { + Device device = new Device(); + device.setDeviceIdentifier(deviceIdentifier.getId()); + device.setType(deviceIdentifier.getType()); + Mockito.doReturn(false).when(androidDeviceTypeManager).isEnrolled(Mockito.any()); + androidDeviceTypeManager.enrollDevice(device); + } + + @Test(description = ("This test case tests the behaviour of the updateDeviceInfo when the relevant tables are not " + + "there"), expectedExceptions = {DeviceManagementException.class}, + expectedExceptionsMessageRegExp = "Error occurred while updating the.*", dependsOnMethods = + {"testUpdateDeviceInfo"}) + public void testUpdateDeviceWithMock() throws DeviceManagementException { + Mockito.doReturn(new Device()).when(androidDeviceTypeManager).getDevice(Mockito.any()); + androidDeviceTypeManager.updateDeviceInfo(deviceIdentifier, sampleDevice); + } + + @Test(description = "This test case tests the behaviour of addDevice when the relevant tables are not available", + expectedExceptions = { DeviceTypeMgtPluginException.class }, + expectedExceptionsMessageRegExp = "Error occurred while adding the device .*") + public void testAddDevice() throws DeviceTypeMgtPluginException { + propertyBasedPluginDAO.addDevice(sampleDevice); + } + + @Test(description = "This test case tests the behaviour of getDevice when the relevant tables are not available", + expectedExceptions = { DeviceTypeMgtPluginException.class }, + expectedExceptionsMessageRegExp = "Error occurred while fetching device .*") + public void testGetPropertyBasedDevice() throws DeviceTypeMgtPluginException { + propertyBasedPluginDAO.getDevice("id"); + } + + @Test(description = "This test case tests the behaviour of the getAllDevices method of the PropertyBasedPuginDAO", + expectedExceptions = {DeviceTypeMgtPluginException.class}, expectedExceptionsMessageRegExp = "Error " + + "occurred while fetching all.*") + public void testGetAllPropertyBasedDevices() throws DeviceTypeMgtPluginException { + propertyBasedPluginDAO.getAllDevices(); + } + + @Test(description = "This test case tests the behaviour of the updateDevice method of the PropertyBasedPuginDAO", + expectedExceptions = {DeviceTypeMgtPluginException.class}, expectedExceptionsMessageRegExp = "Error " + + "occurred while modifying the device.*") + public void testUpdateDevice() throws DeviceTypeMgtPluginException { + propertyBasedPluginDAO.updateDevice(sampleDevice); + } + + /** + * To create a defective device type manager for testing. + * @throws NoSuchFieldException No Such Field Exception. + * @throws SAXException SAX Exception. + * @throws JAXBException JAXB Exception + * @throws ParserConfigurationException Parser Configuration Exception. + * @throws DeviceTypeConfigurationException Device Type Configuration Exception. + * @throws IOException IO Exception. + * @throws IllegalAccessException Illegal Access Exception. + */ + private void createDefectiveDeviceTypeManager() + throws NoSuchFieldException, SAXException, JAXBException, ParserConfigurationException, + DeviceTypeConfigurationException, IOException, IllegalAccessException { + Field datasourceField = DeviceTypeDAOHandler.class.getDeclaredField("dataSource"); + datasourceField.setAccessible(true); + Field currentConnection = DeviceTypeDAOHandler.class.getDeclaredField("currentConnection"); + currentConnection.setAccessible(true); + Field deviceTypePluginDAOField = DeviceTypePluginDAOManager.class.getDeclaredField("deviceTypePluginDAO"); + deviceTypePluginDAOField.setAccessible(true); + Field deviceTypeDAOHandlerField = DeviceTypePluginDAOManager.class.getDeclaredField("deviceTypeDAOHandler"); + deviceTypeDAOHandlerField.setAccessible(true); + + ClassLoader classLoader = getClass().getClassLoader(); + URL resourceUrl = classLoader.getResource(Utils.DEVICE_TYPE_FOLDER + "android.xml"); + File androidConfiguration = null; + if (resourceUrl != null) { + androidConfiguration = new File(resourceUrl.getFile()); + } + DeviceTypeConfiguration androidDeviceConfiguration = Utils.getDeviceTypeConfiguration(androidConfiguration); + androidDeviceTypeManager = Mockito.mock(DeviceTypeManager.class, Mockito.CALLS_REAL_METHODS); + + deviceTypeDAOHandler = Mockito + .mock(DeviceTypeDAOHandler.class, Mockito.CALLS_REAL_METHODS); + + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL("jdbc:h2:mem:notexist;DB_CLOSE_DELAY=-1"); + dataSource.setUser("sa"); + dataSource.setPassword("sa"); + datasourceField.set(deviceTypeDAOHandler, dataSource); + currentConnection.set(deviceTypeDAOHandler, new ThreadLocal()); + + DeviceDAODefinition deviceDAODefinition = Utils.getDeviceDAODefinition(androidDeviceConfiguration); + DeviceTypePluginDAOImpl deviceTypePluginDAO = new DeviceTypePluginDAOImpl(deviceDAODefinition, + deviceTypeDAOHandler); + DeviceTypePluginDAOManager deviceTypePluginDAOManager = Mockito + .mock(DeviceTypePluginDAOManager.class, Mockito.CALLS_REAL_METHODS); + deviceTypePluginDAOField.set(deviceTypePluginDAOManager, deviceTypePluginDAO); + deviceTypeDAOHandlerField.set(deviceTypePluginDAOManager, deviceTypeDAOHandler); + + Field deviceTypePluginDAOManagerField = DeviceTypeManager.class.getDeclaredField("deviceTypePluginDAOManager"); + deviceTypePluginDAOManagerField.setAccessible(true); + deviceTypePluginDAOManagerField.set(androidDeviceTypeManager, deviceTypePluginDAOManager); + + Field propertiesExist = DeviceTypeManager.class.getDeclaredField("propertiesExist"); + propertiesExist.setAccessible(true); + Field deviceType = DeviceTypeManager.class.getDeclaredField("deviceType"); + deviceType.setAccessible(true); + + deviceType.set(androidDeviceTypeManager, ANDROID_DEVICE_TYPE); + propertiesExist.set(androidDeviceTypeManager, true); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java index f90d33bd34..b512a2965d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java @@ -21,14 +21,16 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.mockito.Mockito; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.InitialOperationConfig; +import org.wso2.carbon.device.mgt.common.InitialOperationConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.license.mgt.License; @@ -75,7 +77,7 @@ public class DeviceTypeManagerServiceTest { private Method setPolicyMonitoringManager; private Method setPullNotificationSubscriber; - @BeforeTest + @BeforeClass public void setup() throws NoSuchMethodException, SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException, IOException, NoSuchFieldException, IllegalAccessException, DeviceManagementException, RegistryException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java index 27ebd3f827..49a6a7c9ff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.mockito.Mockito; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -73,7 +73,7 @@ public class DeviceTypeManagerTest { private String[] customDeviceTypeProperties = {"custom_property", "custom_property2"}; private final String SQL_FOLDER = "sql-files" + File.separator; - @BeforeTest(description = "Mocking the classes for testing") + @BeforeClass(description = "Mocking the classes for testing") public void setup() throws NoSuchFieldException, IllegalAccessException, IOException, SQLException, SAXException, ParserConfigurationException, DeviceTypeConfigurationException, JAXBException { ClassLoader classLoader = getClass().getClassLoader(); @@ -170,8 +170,8 @@ public class DeviceTypeManagerTest { Assert.assertTrue(customDeviceTypeManager.enrollDevice(customDevice), "Custom device type enrollment failed."); List properties = customDevice.getProperties(); Device.Property property = new Device.Property(); - property.setName("test"); - property.setValue("test"); + property.setName(Utils.TEST_STRING); + property.setValue(Utils.TEST_STRING); properties.add(property); customDevice.setProperties(properties); Assert.assertFalse(customDeviceTypeManager.enrollDevice(customDevice), @@ -239,8 +239,8 @@ public class DeviceTypeManagerTest { list.add(property); } - sampleDevice1 = new Device("testdevice", androidDeviceType, "test", "testdevice", null, null, list); - sampleDevice2 = new Device("testdevice1", androidDeviceType, "test", "testdevice", null, null, list); + sampleDevice1 = new Device("testdevice", androidDeviceType, Utils.TEST_STRING, "testdevice", null, null, list); + sampleDevice2 = new Device("testdevice1", androidDeviceType, Utils.TEST_STRING, "testdevice", null, null, list); } /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java index 7c4ff9ec2c..09435166dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java @@ -19,7 +19,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -42,9 +42,13 @@ import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * This test case contains the tests for {@link HTTPDeviceTypeManagerService} and {@link DeviceTypeGeneratorServiceImpl} @@ -56,7 +60,7 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { private String androidSenseDeviceType = "androidsense"; private DeviceManagementService generatedDeviceManagementService; - @BeforeTest + @BeforeClass public void setup() throws RegistryException, IOException, SAXException, ParserConfigurationException, DeviceTypeConfigurationException, JAXBException { createSampleDeviceTypeMetaDefinition(); @@ -75,7 +79,8 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { @Test(description = "This test case tests the enrollment of newly added device type") public void testEnrollDevice() throws DeviceManagementException { String deviceId = "testdevice1"; - Device sampleDevice1 = new Device(deviceId, androidSenseDeviceType, "test", "testdevice", null, null, null); + Device sampleDevice1 = new Device(deviceId, androidSenseDeviceType, Utils.TEST_STRING, "testdevice", null, null, + null); Assert.assertTrue(httpDeviceTypeManagerService.getDeviceManager().enrollDevice(sampleDevice1), "Enrollment of " + androidSenseDeviceType + " device failed"); Assert.assertTrue(httpDeviceTypeManagerService.getDeviceManager() @@ -108,7 +113,7 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { ConfigurationEntry configurationEntry = configurationEntries.get(0); - Assert.assertEquals(configurationEntry.getName(), "test", + Assert.assertEquals(configurationEntry.getName(), Utils.TEST_STRING, "Platform Configuration for device type " + "sample is not saved correctly"); String contentType = configurationEntry.getContentType(); @@ -142,6 +147,28 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { httpDeviceTypeManagerService.getDeviceManager().enrollDevice(null); } + @Test(description = "This test case tests the getDeviceTypeConfiguration method", + dependsOnMethods = {"testPopulateDeviceManagementService"}) + public void testGetDeviceTypeConfiguration() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method getDeviceTypeConfiguration = HTTPDeviceTypeManagerService.class + .getDeclaredMethod("getDeviceTypeConfiguration", String.class, DeviceTypeMetaDefinition.class); + getDeviceTypeConfiguration.setAccessible(true); + List properties = new ArrayList<>(); + properties.add(Utils.TEST_STRING); + deviceTypeMetaDefinition.setProperties(properties); + Map mapProperties = new HashMap<>(); + mapProperties.put(Utils.TEST_STRING, Utils.TEST_STRING); + PushNotificationConfig pushNotificationConfig = new PushNotificationConfig("push", true, mapProperties); + deviceTypeMetaDefinition.setPushNotificationConfig(pushNotificationConfig); + DeviceTypeConfiguration deviceTypeConfiguration = (DeviceTypeConfiguration) getDeviceTypeConfiguration + .invoke(httpDeviceTypeManagerService, "android", deviceTypeMetaDefinition); + Assert.assertEquals(deviceTypeMetaDefinition.getProperties().size(), + deviceTypeConfiguration.getDeviceDetails().getProperties().getProperty().size(), "Number of " + + "properties added in device-type meta definition is not equal to the properties added in " + + "the DeviceType Configuration"); + } + /** * To create a sample device type meta defintion. * @throws SAXException SAX Exception. @@ -180,6 +207,13 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { commonFeature.setCode(feature.getCode()); commonFeature.setDescription(feature.getDescription()); commonFeature.setName(feature.getName()); + org.wso2.carbon.device.mgt.common.Feature.MetadataEntry metadataEntry = new org.wso2.carbon.device.mgt + .common.Feature.MetadataEntry(); + metadataEntry.setId(1); + metadataEntry.setValue(Utils.TEST_STRING); + List metadataEntries = new ArrayList<>(); + metadataEntries.add(metadataEntry); + commonFeature.setMetadataEntries(metadataEntries); features.add(commonFeature); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponentTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponentTest.java new file mode 100644 index 0000000000..b4673712f4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/internal/DeviceTypeExtensionServiceComponentTest.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.device.mgt.extensions.internal; + +import org.apache.sling.testing.mock.osgi.MockOsgi; +import org.testng.annotations.Test; + +/** + * This is a test case for {@link DeviceTypeExtensionServiceComponent}. + */ +public class DeviceTypeExtensionServiceComponentTest { + @Test(description = "This test case tests the behaviour of the Service Component when there is a possible " + + "exception") + public void testActivateWithException() { + DeviceTypeExtensionServiceComponent deviceTypeExtensionServiceComponent = new + DeviceTypeExtensionServiceComponent(); + deviceTypeExtensionServiceComponent.activate(null); + } + + @Test(description = "This test case tests the behaviour of the Service Component when the pre-conditions are " + + "satisfied") + public void testActivateWithoutException() { + DeviceTypeExtensionServiceComponent deviceTypeExtensionServiceComponent = new + DeviceTypeExtensionServiceComponent(); + deviceTypeExtensionServiceComponent.activate(MockOsgi.newComponentContext()); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/Utils.java index d35b8eba93..8a2634d0f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/Utils.java @@ -56,6 +56,7 @@ import java.util.List; */ public class Utils { public static final String DEVICE_TYPE_FOLDER = "device-types" + File.separator; + public static final String TEST_STRING = "test"; /** * To get the device type configuration based on the configuration file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java index 01651d3b2c..feb549a22f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java @@ -20,17 +20,30 @@ package org.wso2.carbon.device.mgt.extensions.utils; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier; +import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; +import org.wso2.carbon.device.mgt.extensions.device.type.template.policy.mgt.DefaultPolicyMonitoringManager; import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceSchemaInitializer; +import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils; import org.wso2.carbon.device.mgt.extensions.license.mgt.file.FileSystemBasedLicenseManager; +import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; /** * This is a test case for testing common utilities used. @@ -38,7 +51,7 @@ import java.lang.reflect.Method; public class UtilsTest { private FileSystemBasedLicenseManager fileSystemBasedLicenseManager; - @BeforeTest + @BeforeClass public void setup() { fileSystemBasedLicenseManager = new FileSystemBasedLicenseManager(); } @@ -63,7 +76,7 @@ public class UtilsTest { @Test(description = "This test case tests the getLicense method of the FileBasedLicenseManager") public void testFileBasedLicenseManagerGetLicense() throws LicenseManagementException { - License fileBasedLicense = fileSystemBasedLicenseManager.getLicense("test","en_US"); + License fileBasedLicense = fileSystemBasedLicenseManager.getLicense(Utils.TEST_STRING,"en_US"); Assert.assertEquals(fileBasedLicense.getText(), "This is a file based license", "FileBased License cannot " + "be retrieved by FileBasedLicenseManager"); } @@ -79,6 +92,64 @@ public class UtilsTest { + "file system", expectedExceptions = {UnsupportedOperationException.class}, expectedExceptionsMessageRegExp = "'addLicense' method is not supported in FileSystemBasedLicenseManager") public void testFileBasedLicenseManagerAddLicense() throws LicenseManagementException { - fileSystemBasedLicenseManager.addLicense("test", null); + fileSystemBasedLicenseManager.addLicense(Utils.TEST_STRING, null); + } + + @Test(description = "This test case tests the DeviceTypeConfigIdentifier equals method") + public void testDeviceTypeConfigIdentifier() { + DeviceTypeConfigIdentifier deviceTypeConfigIdentifier = new DeviceTypeConfigIdentifier("sample", + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + DeviceTypeConfigIdentifier clonedDeviceTypeConfigIdentifier = new DeviceTypeConfigIdentifier("sample", + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + Assert.assertTrue(deviceTypeConfigIdentifier.equals(clonedDeviceTypeConfigIdentifier), + "Clone device type config identifier gives wrong results for equals check."); + Assert.assertFalse(deviceTypeConfigIdentifier.equals(null), + "Device Type config identifier object comparison gives wrong results."); + } + + @Test(description = "This test cases tests the registry based license addition") + public void testAddRegistryBasedLicense() throws LicenseManagementException { + String newLicenseString = "New License"; + License fileBasedLicense = fileSystemBasedLicenseManager.getLicense(Utils.TEST_STRING, "en_US"); + RegistryBasedLicenseManager registryBasedLicenseManager = new RegistryBasedLicenseManager(); + registryBasedLicenseManager.addLicense(Utils.TEST_STRING, fileBasedLicense); + Assert.assertEquals(fileBasedLicense.getText(), + registryBasedLicenseManager.getLicense(Utils.TEST_STRING, "en_US").getText(), + "Registry license addition failed"); + fileBasedLicense.setText(newLicenseString); + registryBasedLicenseManager.addLicense(Utils.TEST_STRING, fileBasedLicense); + Assert.assertEquals(registryBasedLicenseManager.getLicense(Utils.TEST_STRING, "en_US").getText(), + newLicenseString, "Registry license update failed"); + } + + @Test(description = "This test case tests the GetConfigurationRegistry method when the registry service is " + + "unavailable", dependsOnMethods = {"testDeviceSchemaInitializer", "testDeviceTypeConfigIdentifier", + "testAddRegistryBasedLicense"}, + expectedExceptions = {DeviceTypeMgtPluginException.class}, + expectedExceptionsMessageRegExp = "Error in retrieving conf registry instance:.*") + public void testGetConfigurationRegistry() throws DeviceTypeMgtPluginException { + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(4); + DeviceTypeUtils.getConfigurationRegistry(); + } + + @Test(description = "This test case tests DefaultPolicyMonitoringManager functionality") + public void testDefaultPolicyMonitoringManager() throws PolicyComplianceException { + List complianceFeatures = new ArrayList<>(); + ComplianceFeature complianceFeature = new ComplianceFeature(); + complianceFeature.setCompliance(true); + complianceFeatures.add(complianceFeature); + ComplianceFeature nonCompliant = new ComplianceFeature(); + nonCompliant.setCompliance(false); + complianceFeatures.add(nonCompliant); + DefaultPolicyMonitoringManager policyMonitoringManager = new DefaultPolicyMonitoringManager(); + NonComplianceData nonComplianceData = policyMonitoringManager + .checkPolicyCompliance(new DeviceIdentifier("android", "test"), null, complianceFeatures); + Policy policy = new Policy(); + Assert.assertNull(nonComplianceData.getComplianceFeatures(), + "When policy is null policy manager returns a " + "list of non-compilance features"); + nonComplianceData = policyMonitoringManager + .checkPolicyCompliance(new DeviceIdentifier("android", "test"), policy, complianceFeatures); + Assert.assertEquals(nonComplianceData.getComplianceFeatures().size(), 1, + "Non-compliant feature count does " + "not match with expected count"); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/etc/device-mgt-plugin-configs/mobile/wrong-default-platform-configuration.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/etc/device-mgt-plugin-configs/mobile/wrong-default-platform-configuration.xml new file mode 100644 index 0000000000..645805d7a8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/etc/device-mgt-plugin-configs/mobile/wrong-default-platform-configuration.xml @@ -0,0 +1,23 @@ + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/registry.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/registry.xml index 0bb97a7dc9..036b3dda06 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/registry.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/carbon-home/repository/conf/registry.xml @@ -24,7 +24,7 @@ wso2registry false - true + false / diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/device-types/android.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/device-types/android.xml index 176469c329..0320698ff4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/device-types/android.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/device-types/android.xml @@ -51,6 +51,11 @@ true + + + true + + + + + + + defective + + + + + + + Control Bulb + Control Bulb on Arduino Uno + + + state + + + + + + + true + + + + en_US + 1.0.0 + This is license text + + + + + jdbc/MobileAndroidDM_DS + + + +
+
+
+ +
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/testng.xml index 661e7dd0dd..61740e5007 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/resources/testng.xml @@ -19,9 +19,7 @@ - - - + @@ -30,6 +28,7 @@ + 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 8756a1527b..01fe8844f1 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.136-SNAPSHOT + 3.0.170-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index 34e4ee14e7..60076acf83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -33,8 +33,13 @@ var util = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var responseProcessor = require("utils").response; var result; +if (uriMatcher.match("/{context}/api/user/clearBilling")) { -if (uriMatcher.match("/{context}/api/user/authenticate")) { + carbonUser = session.get(constants.USER_SESSION_KEY); + session.put('BILLING_INFO_' + carbonUser.domain, null); + log.info("billing info cleared for " + carbonUser.domain); + +} else if (uriMatcher.match("/{context}/api/user/authenticate")) { var username = request.getParameter("username"); var password = request.getParameter("password"); //Check if a username and password is provided diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/public/js/user-menu.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/public/js/user-menu.js index edd143481b..9a3459a9a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/public/js/user-menu.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/public/js/user-menu.js @@ -16,6 +16,33 @@ * under the License. */ $(document).ready(function () { + + $("#expire-upgrade-now-link").click(function() { + $.get("api/user/clearBilling", function(data, status){ + }); + window.location.href = $("#expire-upgrade-now-link").data("url"); + }); + + $("#expire-req-ext-link").click(function() { + $.get("api/user/clearBilling", function(data, status){ + }); + window.location.href = $("#expire-req-ext-link").data("url"); + }); + + $(".expire-upgrade-now-link").parent().click(function(e) { + e.preventDefault(); + $.get("api/user/clearBilling", function(data, status){ + }); + window.location.href = $(this).attr("href"); + }); + + $(".expire-req-ext-link").parent().click(function(e) { + e.preventDefault(); + $.get("api/user/clearBilling", function(data, status){ + }); + window.location.href = $(this).attr("href"); + }); + $('#cloud-menu-popover i.fw-tiles').popover({ html: true, trigger: 'click', diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/user-menu.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/user-menu.hbs index 5b8f29183a..c50ea375eb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/user-menu.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.header.cloud.user-menu/user-menu.hbs @@ -171,10 +171,10 @@