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 57491b0270..a61b1e6c17 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.annotations
- 3.0.114-SNAPSHOT
+ 3.0.178-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 342ae5385b..ca883e0a13 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
- 3.0.114-SNAPSHOT
+ 3.0.178-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 a128a1a6a4..c5b9735d85 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
- 3.0.114-SNAPSHOT
+ 3.0.178-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 26c624c9bd..196e1ebab1 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.handlers
- 3.0.114-SNAPSHOT
+ 3.0.178-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);
+ return new RESTResponse(output, 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);
- }
-
- 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 11fdde3ea1..3568fbb1cb 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.integration.client
- 3.0.114-SNAPSHOT
+ 3.0.178-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 5b19e88ee1..cd4656fb48 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.integration.generated.client
- 3.0.114-SNAPSHOT
+ 3.0.178-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 449f04ee1f..7b7f29e38f 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.webapp.publisher
- 3.0.114-SNAPSHOT
+ 3.0.178-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 extends Servlet> 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 extends Filter> 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 extends EventListener> 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 99506361c4..190083a5ab 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../../pom.xml
4.0.0
apimgt-extensions
- 3.0.114-SNAPSHOT
+ 3.0.178-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 7e62764a16..ee2280040a 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.114-SNAPSHOT
+ 3.0.178-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 58d3c86469..1d72d7327b 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java
index 3b014fe693..5957b1b8cf 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java
@@ -73,10 +73,8 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) {
certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
- X509Certificate x509Certificate = certificateService
- .pemToX509Certificate(enrollmentCertificate.getPem());
- certificate.setSerial(x509Certificate.getSerialNumber().toString());
- certificate.setCertificate(x509Certificate);
+ certificate.setSerial(enrollmentCertificate.getSerial());
+ certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem()));
certificates.add(certificate);
}
certificateService.saveCertificate(certificates);
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 11f0ae7d2c..aa01be7a95 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.certificate.mgt.core
- 3.0.114-SNAPSHOT
+ 3.0.178-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
- prepare-agent
+ instrument
+
+
+
+ default-restore-instrumented-classes
+
+ 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
@@ -162,6 +178,21 @@
org.testng
testng
+
+ com.h2database.wso2
+ h2-database-engine
+ test
+
+
+ org.powermock
+ powermock-api-mockito
+ test
+
+
+ org.powermock
+ powermock-module-testng
+ test
+
org.wso2.carbon
org.wso2.carbon.logging
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java
index 5c82ea83a3..10e70a5baa 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java
@@ -115,7 +115,7 @@ public class CertificateManagementDAOFactory {
currentTxState.set(TxState.CONNECTION_BORROWED);
}
- public static void openConnection() throws SQLException {
+ 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 " +
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..d07c109dfa 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,26 @@ public class CertificateGenerator {
CertificateResponse lookUpCertificate = null;
KeyStoreReader keyStoreReader = new KeyStoreReader();
if (distinguishedName != null && !distinguishedName.isEmpty()) {
- String[] dnSplits = distinguishedName.split("/CN=");
- if (dnSplits != null) {
+ if (distinguishedName.contains("/CN=")) {
+ String[] dnSplits = distinguishedName.split("/CN=");
String commonNameExtracted = dnSplits[dnSplits.length - 1];
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
+ } else {
+ 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 relativeDistinguishedNames : ldapName.getRdns()) {
+ if (relativeDistinguishedNames.getType().equalsIgnoreCase("CN")) {
+ lookUpCertificate = keyStoreReader
+ .getCertificateBySerial(String.valueOf(relativeDistinguishedNames.getValue()));
+ break;
+ }
+ }
}
}
return lookUpCertificate;
@@ -409,21 +428,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/common/BaseDeviceManagementCertificateTest.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java
new file mode 100644
index 0000000000..38a16a7fa0
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/BaseDeviceManagementCertificateTest.java
@@ -0,0 +1,133 @@
+/*
+ * 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.common;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.tomcat.jdbc.pool.PoolProperties;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeSuite;
+import org.w3c.dom.Document;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.wso2.carbon.certificate.mgt.core.util.TestUtils;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+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.util.DeviceManagerUtil;
+
+import javax.sql.DataSource;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import java.io.File;
+import java.sql.Connection;
+import java.sql.Statement;
+
+
+public abstract class BaseDeviceManagementCertificateTest {
+ private DataSource dataSource;
+ private static final Log log = LogFactory.getLog(BaseDeviceManagementCertificateTest.class);
+ private static final String DATASOURCE_LOCATION = "src/test/resources/data-source-config.xml";
+
+ @BeforeSuite
+ public void setupDataSource() throws Exception {
+ this.initDataSource();
+ this.initSQLScript();
+ initializeCarbonContext();
+ }
+
+ public void initDataSource() throws Exception {
+ this.dataSource = this.getDataSource(this.readDataSourceConfig());
+ DeviceManagementDAOFactory.init(dataSource);
+ GroupManagementDAOFactory.init(dataSource);
+ }
+
+ public void initDataSource(DataSource ds) throws Exception {
+ this.dataSource = ds;
+ DeviceManagementDAOFactory.init(dataSource);
+ GroupManagementDAOFactory.init(dataSource);
+ }
+
+ @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);
+ }
+
+ private DataSourceConfig readDataSourceConfig() throws DeviceManagementException {
+ try {
+ File file = new File(DATASOURCE_LOCATION);
+ Document doc = DeviceManagerUtil.convertToDocument(file);
+ JAXBContext testDBContext = JAXBContext.newInstance(DataSourceConfig.class);
+ Unmarshaller unmarshaller = testDBContext.createUnmarshaller();
+ return (DataSourceConfig) unmarshaller.unmarshal(doc);
+ } catch (JAXBException e) {
+ throw new DeviceManagementException("Error occurred while reading data source configuration", e);
+ }
+ }
+
+ private void initSQLScript() throws Exception {
+ Connection conn = null;
+ Statement stmt = null;
+ try {
+ conn = this.getDataSource().getConnection();
+ stmt = conn.createStatement();
+ stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/h2.sql'");
+ } finally {
+ TestUtils.cleanupResources(conn, stmt, null);
+ }
+ }
+
+ private void initializeCarbonContext() {
+
+ 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);
+ }
+
+ public DataSource getDataSource() {
+ return dataSource;
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/DataSourceConfig.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/DataSourceConfig.java
new file mode 100644
index 0000000000..f3154d3bdc
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/common/DataSourceConfig.java
@@ -0,0 +1,80 @@
+/*
+ * 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.common;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Model class for DataSourceConfig.
+ */
+@XmlRootElement(name = "DataSourceConfig")
+public class DataSourceConfig {
+
+ private String url;
+ private String driverClassName;
+ private String user;
+ private String password;
+
+ @Override
+ public String toString() {
+ return "DataSourceConfig[" +
+ " Url ='" + url + '\'' +
+ ", DriverClassName ='" + driverClassName + '\'' +
+ ", UserName ='" + user + '\'' +
+ ", Password ='" + password + '\'' +
+ "]";
+ }
+
+ @XmlElement(name = "Url", nillable = false)
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ @XmlElement(name = "DriverClassName", nillable = false)
+ public String getDriverClassName() {
+ return driverClassName;
+ }
+
+ public void setDriverClassName(String driverClassName) {
+ this.driverClassName = driverClassName;
+ }
+
+ @XmlElement(name = "User", nillable = false)
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ @XmlElement(name = "Password", nillable = false)
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+}
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/CertificateManagementServiceImplTests.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java
new file mode 100644
index 0000000000..a7e0629e5d
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java
@@ -0,0 +1,334 @@
+/*
+ * 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.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.cert.jcajce.JcaCertStore;
+import org.bouncycastle.cms.CMSAbsentContent;
+import org.bouncycastle.cms.CMSException;
+import org.bouncycastle.cms.CMSSignedData;
+import org.bouncycastle.cms.CMSSignedDataGenerator;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.wso2.carbon.certificate.mgt.core.common.BaseDeviceManagementCertificateTest;
+import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
+import org.wso2.carbon.certificate.mgt.core.dto.CAStatus;
+import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
+import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
+import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException;
+import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
+import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl;
+import org.wso2.carbon.certificate.mgt.core.service.PaginationResult;
+import org.wso2.carbon.certificate.mgt.core.util.CSRGenerator;
+import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants;
+import org.wso2.carbon.certificate.mgt.core.util.DummyCertificate;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
+import sun.misc.BASE64Encoder;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.security.KeyPair;
+import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.*;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Test cases for for CertificateManagementServiceImpl class methods.
+ *
+ */
+public class CertificateManagementServiceImplTests extends BaseDeviceManagementCertificateTest {
+
+ private static Log log = LogFactory.getLog(CertificateManagementServiceImplTests.class);
+ private static final String CA_CERT_PEM = "src/test/resources/ca_cert.pem";
+ private static final String RA_CERT_PEM = "src/test/resources/ra_cert.pem";
+ private CertificateManagementServiceImpl managementService;
+
+ @BeforeClass
+ public void init() throws Exception {
+ initDataSource();
+ CertificateManagementDAOFactory.init(this.getDataSource());
+ //set Bouncycastle as a provider for testing
+ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+ //save certificatemanagementservice instance as class variable
+ managementService = CertificateManagementServiceImpl.getInstance();
+ Assert.assertNotNull(managementService);
+ log.info("getInstance Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of CA Certificate from the keystore")
+ public void testGetCACertificate() throws KeystoreException {
+ CertificateManagementServiceImpl instance = CertificateManagementServiceImpl.getInstance();
+ Certificate caCertificate = instance.getCACertificate();
+ Assert.assertNotNull(caCertificate);
+ Assert.assertEquals(caCertificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GetCACertificate Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of RA Certificate from the keystore")
+ public void testGetRACertificate() throws KeystoreException {
+ Certificate raCertificate = managementService.getRACertificate();
+ Assert.assertNotNull(raCertificate);
+ Assert.assertEquals(raCertificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GetRACertificate Test Successful");
+ }
+
+ @Test(description = "This test case test generation of root certificates")
+ public void testGetRootCertificate() throws IOException, KeystoreException {
+ File caCert = new File(CA_CERT_PEM);
+ File raCert = new File(RA_CERT_PEM);
+ //read file to byte arrays
+ byte[] caBytes = FileUtils.readFileToByteArray(caCert);
+ byte[] raBytes = FileUtils.readFileToByteArray(raCert);
+ List rootCertificates = managementService.getRootCertificates(caBytes, raBytes);
+ Assert.assertNotNull(rootCertificates);
+ Assert.assertEquals(rootCertificates.get(0).getType(), CertificateManagementConstants.X_509);
+ Assert.assertEquals(rootCertificates.get(1).getType(), CertificateManagementConstants.X_509);
+ log.info("GetRootCertificate Test Successful");
+ }
+
+ @Test(description = "This test case tests generation of X509Certificate")
+ public void testGenerateX509Certificate() throws KeystoreException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ Assert.assertNotNull(x509Certificate);
+ Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GenerateX509Certificate Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieving SCEP CA Certificate")
+ public void testGetCACertSCEP() throws KeystoreException {
+ SCEPResponse caCertSCEP = managementService.getCACertSCEP();
+ Assert.assertNotNull(caCertSCEP);
+ Assert.assertEquals(caCertSCEP.getResultCriteria(), CAStatus.CA_RA_CERT_RECEIVED);
+ log.info("GetCACertSCEP Test Successful");
+ }
+
+ @Test
+ public void testGetCACapsSCEP() {
+ byte[] caCapsSCEP = managementService.getCACapsSCEP();
+ Assert.assertNotNull(caCapsSCEP);
+ Assert.assertEquals(caCapsSCEP, CertificateManagementConstants.POST_BODY_CA_CAPS.getBytes());
+ log.info("GetCACapsSCEP Test Successful");
+ }
+
+ @Test(description = "This test case tests generation of a X509Certificate from a CSR")
+ public void testGenerateCertificateFromCSR() throws KeystoreException, IOException {
+ CSRGenerator csrGeneration = new CSRGenerator();
+ KeyStoreReader keyStoreReader = new KeyStoreReader();
+ // Generate key pair
+ 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);
+ X509Certificate x509Certificate = managementService.generateCertificateFromCSR(privateKeyCA,
+ certificationRequest, certCA.getIssuerX500Principal().getName());
+ Assert.assertNotNull(x509Certificate);
+ Assert.assertEquals(x509Certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("GenerateCertificateFromCSR Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of a Certificate from the keystore from the Serial Number")
+ public void testGetCertificateBySerial() throws KeystoreException, DeviceManagementException {
+ X509Certificate x509Certificate = null;
+ //generate and save a certificate
+ x509Certificate = managementService.generateX509Certificate();
+ //initialize DeviceConfigurationManager
+ DeviceConfigurationManager.getInstance().initConfig();
+ CertificateResponse certificateBySerial = managementService.getCertificateBySerial(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateBySerial);
+ Assert.assertEquals(certificateBySerial.getSerialNumber(), x509Certificate.getSerialNumber().toString());
+ log.info("GetCertificateBySerial Test Successful");
+ }
+
+ @Test(description = "This test case tests retrieval of a Certificate from the keystore from the Alias")
+ public void testGetCertificateByAlias() throws KeystoreException, DeviceManagementException {
+ X509Certificate x509Certificate = null;
+ //generate and save a certificate
+ x509Certificate = managementService.generateX509Certificate();
+ //initialize DeviceConfigurationManager
+ DeviceConfigurationManager.getInstance().initConfig();
+ Certificate certificateByAlias = managementService.getCertificateByAlias(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateByAlias);
+ Assert.assertEquals(certificateByAlias.getType(), CertificateManagementConstants.X_509);
+ log.info("GetCertificateByAlias Test Successful");
+ }
+
+ @Test(description = "This test case tests Signature verification of a Certificate against the keystore")
+ public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
+ BASE64Encoder encoder = new BASE64Encoder();
+ //generate and save a certificate in the keystore
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ //Generate CMSdata
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ List list = new ArrayList<>();
+ list.add(x509Certificate);
+ JcaCertStore store = new JcaCertStore(list);
+ generator.addCertificates(store);
+ CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
+ byte[] signature = degenerateSd.getEncoded();
+ boolean verifySignature = managementService.verifySignature(encoder.encode(signature));
+ Assert.assertNotNull(verifySignature);
+ Assert.assertTrue(verifySignature);
+ log.info("VerifySignature Test Successful");
+ }
+
+ @Test(description = "This test case tests DN verification of a Certificate against the keystore")
+ public void testVerifySubjectDN() throws DeviceManagementException, KeystoreException {
+ DeviceConfigurationManager.getInstance().initConfig();
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ log.info(x509Certificate.getIssuerX500Principal().getName());
+ managementService.verifySubjectDN(x509Certificate.getIssuerDN().getName());
+ }
+
+ @Test(description = "This test case tests retrieval of a Certificate from the keystore from the Serial")
+ public void testRetrieveCertificate() throws KeystoreException, CertificateManagementException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ CertificateResponse certificateResponse = managementService.retrieveCertificate(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateResponse);
+ Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateserial());
+ }
+
+ @Test(description = "This test case tests the retrieval of Certificates from keystore in desired pagination")
+ public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException {
+ managementService.generateX509Certificate();
+ managementService.generateX509Certificate();
+ PaginationResult allCertificates = managementService.getAllCertificates(0, 2);
+ Assert.assertEquals(allCertificates.getData().size(), 2);
+ log.info("GetAllCertificatesPaginated Test Successful");
+ }
+
+ @Test(description = "This test casae tests retrieval of all Certificates from keystore")
+ public void testGetCertificates() throws CertificateManagementException, KeystoreException {
+ List certificatesBefore = managementService.getCertificates();
+ managementService.generateX509Certificate();
+ managementService.generateX509Certificate();
+ List certificatesAfter = managementService.getCertificates();
+ Assert.assertNotNull(certificatesBefore);
+ Assert.assertNotNull(certificatesAfter);
+ Assert.assertEquals((certificatesBefore.size() + 2), certificatesAfter.size());
+ log.info("GetCertificates Test Successful");
+ }
+
+ @Test(description = "This test case tests deleting Certificate from the keystore")
+ public void testRemoveCertificate() throws CertificateManagementException, KeystoreException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ List certificates = managementService.getCertificates();
+ int size = certificates.size();
+ boolean removed = managementService.removeCertificate(x509Certificate.getSerialNumber().toString());
+ certificates = managementService.getCertificates();
+ int sizeAfter = certificates.size();
+ Assert.assertNotNull(removed);
+ Assert.assertTrue(removed);
+ Assert.assertEquals((size - 1), sizeAfter);
+ log.info("RemoveCertificate Test Successful");
+ }
+
+
+ @Test(description = "This test case tests searching for a list of certificates by the serial number")
+ public void testSearchCertificates() throws CertificateManagementException, KeystoreException {
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ List certificateResponses = managementService.searchCertificates(x509Certificate.getSerialNumber().toString());
+ Assert.assertNotNull(certificateResponses);
+ Assert.assertEquals(1, certificateResponses.size());
+ Assert.assertEquals(certificateResponses.get(0).getSerialNumber(), x509Certificate.getSerialNumber().toString());
+ log.info("SearchCertificates Test Successful");
+ }
+
+ @Test(description = "This test case tests generation of signed Certificate from a CSR")
+ public void testGetSignedCertificateFromCSR() throws KeystoreException {
+ CSRGenerator csrGeneration = new CSRGenerator();
+ BASE64Encoder encoder = new BASE64Encoder();
+ // Generate key pair
+ KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
+ byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
+ X509Certificate signedCertificateFromCSR = managementService.getSignedCertificateFromCSR(encoder.encode(csrData));
+ Assert.assertNotNull(signedCertificateFromCSR);
+ Assert.assertEquals(signedCertificateFromCSR.getType(), CertificateManagementConstants.X_509);
+ log.info("GetSignedCertificateFromCSR Test Successful");
+ }
+
+ @Test(description = "This test case tests the extraction of Challenge token from a Certificate")
+ public void testExtractChallengeToken() throws KeystoreException {
+ X509Certificate x509Certificate1 = new DummyCertificate();
+ String token = managementService.extractChallengeToken(x509Certificate1);
+ Assert.assertNotNull(token);
+ Assert.assertEquals(token, DummyCertificate.EXT);
+ log.info("extractChallengeToken Test Successful");
+ }
+
+ @Test(description = "This test case tests saving a list of Certificates in the keystore")
+ public void testSaveCertificate() throws CertificateManagementException, IOException, CertificateException, KeystoreException {
+ File caCert = new File(CA_CERT_PEM);
+ int before = managementService.getCertificates().size();
+ byte[] caBytes = FileUtils.readFileToByteArray(caCert);
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(caBytes));
+ List certificates = new ArrayList<>();
+ org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore =
+ new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
+ certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
+ certificateToStore.setCertificate(cert);
+ certificates.add(certificateToStore);
+ managementService.saveCertificate(certificates);
+ int after = managementService.getCertificates().size();
+ Assert.assertEquals((before + 1), after);
+ log.info("SaveCertificate Test Successful");
+ }
+
+ @Test(description = "This test case tests converting a pem file to X509 Certificate")
+ public void testPemToX509Certificate() throws IOException, KeystoreException {
+ File caCert = new File(CA_CERT_PEM);
+ BASE64Encoder encoder = new BASE64Encoder();
+ byte[] caBytes = FileUtils.readFileToByteArray(caCert);
+ X509Certificate certificate = managementService.pemToX509Certificate(encoder.encode(caBytes));
+ Assert.assertNotNull(certificate);
+ Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("PemToX509Certificate Test Successful");
+ }
+
+ @Test(description = "This test case tests extracting Certificate from the header Signature")
+ public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException {
+ BASE64Encoder encoder = new BASE64Encoder();
+ //generate and save a certificate in the keystore
+ X509Certificate x509Certificate = managementService.generateX509Certificate();
+ //Generate CMSdata
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ List list = new ArrayList<>();
+ list.add(x509Certificate);
+ JcaCertStore store = new JcaCertStore(list);
+ generator.addCertificates(store);
+ CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
+ byte[] signature = degenerateSd.getEncoded();
+ X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature));
+ Assert.assertNotNull(certificate);
+ Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509);
+ log.info("ExtractCertificateFromSignature Test Successful");
+ }
+
+
+}
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/java/org/wso2/carbon/certificate/mgt/core/util/CSRGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CSRGenerator.java
new file mode 100644
index 0000000000..5fa4f7dabd
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/CSRGenerator.java
@@ -0,0 +1,87 @@
+/*
+ * 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.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.pkcs.PKCS10CertificationRequest;
+import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
+import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
+
+import javax.security.auth.x500.X500Principal;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * Test class for generating a mock CSR request.
+ */
+public class CSRGenerator {
+ private static Log log = LogFactory.getLog(CSRGenerator.class);
+
+ /**
+ * Generate the desired CSR for signing
+ *
+ * @param sigAlg
+ * @param keyPair
+ * @return
+ */
+ public byte[] generateCSR(String sigAlg, KeyPair keyPair) {
+ ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outStream);
+ try {
+ PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
+ new X500Principal("CN=Requested Test Certificate"), keyPair.getPublic());
+ JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
+ ContentSigner signer = csBuilder.build(keyPair.getPrivate());
+ PKCS10CertificationRequest csr = p10Builder.build(signer);
+ return csr.getEncoded();
+ } catch (OperatorCreationException ex) {
+ log.error("Error while Key generation operation", ex);
+ } catch (IOException ex) {
+ log.error("Error while generating CSR,ex");
+ }
+ return new byte[0];
+ }
+
+ /**
+ * Generate the desired keypair
+ *
+ * @param alg
+ * @param keySize
+ * @return
+ */
+ public KeyPair generateKeyPair(String alg, int keySize) {
+ try {
+ KeyPairGenerator keyPairGenerator = null;
+ keyPairGenerator = KeyPairGenerator.getInstance(alg);
+ keyPairGenerator.initialize(keySize);
+ return keyPairGenerator.generateKeyPair();
+ } catch (NoSuchAlgorithmException e) {
+ log.error("The provided algorithm is not found ",e);
+ }
+ return null;
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/DummyCertificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/DummyCertificate.java
new file mode 100644
index 0000000000..f276df4625
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/DummyCertificate.java
@@ -0,0 +1,180 @@
+/*
+ * 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.util;
+
+import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
+
+import java.math.BigInteger;
+import java.security.Principal;
+import java.security.PublicKey;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.CertificateException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SignatureException;
+import java.security.NoSuchProviderException;
+import java.security.cert.X509Certificate;
+import java.security.InvalidKeyException;
+import java.util.Date;
+import java.util.Set;
+
+/**
+ * A Mock Certificate class with an extension provided.(Used only to test the extension)
+ */
+public class DummyCertificate extends X509Certificate {
+
+ public static final String EXT = "Dummy extension";
+ public static final String DN = "O=WSO2,OU=Mobile,C=LK,CN=123456789";
+
+ @Override
+ public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException {
+ }
+
+ @Override
+ public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException {
+ }
+
+ @Override
+ public int getVersion() {
+ return 0;
+ }
+
+ @Override
+ public BigInteger getSerialNumber() {
+ return new BigInteger("123456789");
+ }
+
+ @Override
+ public Principal getIssuerDN() {
+ return null;
+ }
+
+ @Override
+ public Principal getSubjectDN() {
+ return new Principal() {
+ @Override
+ public String getName() {
+ return DN;
+ }
+ };
+ }
+
+ @Override
+ public Date getNotBefore() {
+ return null;
+ }
+
+ @Override
+ public Date getNotAfter() {
+ return null;
+ }
+
+ @Override
+ public byte[] getTBSCertificate() throws CertificateEncodingException {
+ return new byte[0];
+ }
+
+ @Override
+ public byte[] getSignature() {
+ return new byte[0];
+ }
+
+ @Override
+ public String getSigAlgName() {
+ return null;
+ }
+
+ @Override
+ public String getSigAlgOID() {
+ return null;
+ }
+
+ @Override
+ public byte[] getSigAlgParams() {
+ return new byte[0];
+ }
+
+ @Override
+ public boolean[] getIssuerUniqueID() {
+ return new boolean[0];
+ }
+
+ @Override
+ public boolean[] getSubjectUniqueID() {
+ return new boolean[0];
+ }
+
+ @Override
+ public boolean[] getKeyUsage() {
+ return new boolean[0];
+ }
+
+ @Override
+ public int getBasicConstraints() {
+ return 0;
+ }
+
+ @Override
+ public byte[] getEncoded() throws CertificateEncodingException {
+ return new byte[0];
+ }
+
+ @Override
+ public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
+ }
+
+ @Override
+ public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
+ }
+
+ @Override
+ public String toString() {
+ return null;
+ }
+
+ @Override
+ public PublicKey getPublicKey() {
+ return null;
+ }
+
+ @Override
+ public boolean hasUnsupportedCriticalExtension() {
+ return false;
+ }
+
+ @Override
+ public Set getCriticalExtensionOIDs() {
+ return null;
+ }
+
+ @Override
+ public Set getNonCriticalExtensionOIDs() {
+ return null;
+ }
+
+ @Override
+ public byte[] getExtensionValue(String oid) {
+ if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_challengePassword.toString())) {
+ return EXT.getBytes();
+ } else {
+ return new byte[0];
+ }
+ }
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/TestUtils.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/TestUtils.java
new file mode 100644
index 0000000000..34d6936676
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/util/TestUtils.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2014, 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.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+public class TestUtils {
+
+ private static final Log log = LogFactory.getLog(TestUtils.class);
+
+ public static void cleanupResources(Connection conn, Statement stmt, ResultSet rs) {
+ if (rs != null) {
+ try {
+ rs.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing result set", e);
+ }
+ }
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing prepared statement", e);
+ }
+ }
+ if (conn != null) {
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing database connection", e);
+ }
+ }
+ }
+
+}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.der b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.der
new file mode 100644
index 0000000000..72684b1820
Binary files /dev/null and b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/ca_cert.der differ
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/carbon.xml
new file mode 100644
index 0000000000..7f976a58cf
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/carbon.xml
@@ -0,0 +1,655 @@
+
+
+
+
+
+
+
+ ${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/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml
new file mode 100644
index 0000000000..bc996646e1
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/cdm-config.xml
@@ -0,0 +1,62 @@
+
+
+
+
+
+
+
+ jdbc/DM_DS
+
+
+
+
+ 8
+ 100
+ 20
+ 1000
+
+
+ https://localhost:9443
+ admin
+ admin
+
+
+ org.wso2.carbon.policy.mgt
+ true
+ 60000
+ 5
+ 8
+ 20
+
+ Simple
+
+
+
+ true
+
+
+ true
+ 86400
+
+
+ true
+ 300
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/certificate-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/certificate-config.xml
new file mode 100755
index 0000000000..949c4c2cd4
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/certificate-config.xml
@@ -0,0 +1,36 @@
+
+
+
+
+
+ ${carbon.home}/repository/conf/security/wso2certs.jks
+
+ JKS
+
+ wso2carbon
+
+ cacert
+
+ cacert
+
+ racert
+
+ racert
+
+
\ No newline at end of file
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml
new file mode 100644
index 0000000000..40b7e24343
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml
@@ -0,0 +1,85 @@
+
+
+
+
+ org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader
+
+
+
+
+
+ WSO2_CARBON_DB
+ The datasource used for registry and user manager
+
+ jdbc/WSO2CarbonDB
+
+
+
+ jdbc:h2:repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000
+ wso2carbon
+ wso2carbon
+ org.h2.Driver
+ 50
+ 60000
+ true
+ SELECT 1
+ 30000
+ false
+
+
+
+
+
+
+
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/log4j.properties b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/log4j.properties
new file mode 100644
index 0000000000..d1014499f9
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/log4j.properties
@@ -0,0 +1,165 @@
+#
+# Copyright 2017 WSO2, Inc. (http://wso2.com)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+#
+# This is the log4j configuration file used by WSO2 Carbon
+#
+# IMPORTANT : Please do not remove or change the names of any
+# of the Appenders 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=INFO, CARBON_CONSOLE, CARBON_LOGFILE, CARBON_MEMORY, CARBON_SYS_LOG
+
+log4j.logger.AUDIT_LOG=INFO, AUDIT_LOGFILE
+log4j.logger.org.apache.axis2.wsdl.codegen.writer.PrettyPrinter=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.axis2.clustering=INFO, CARBON_CONSOLE, CARBON_LOGFILE
+log4j.logger.org.apache=INFO, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.catalina=WARN
+log4j.logger.org.apache.tomcat=WARN
+log4j.logger.org.wso2.carbon.apacheds=WARN
+log4j.logger.org.apache.directory.server.ldap=ERROR
+log4j.logger.org.apache.directory.server.core.event=WARN
+log4j.logger.com.atomikos=INFO,ATOMIKOS
+log4j.logger.org.quartz=WARN
+log4j.logger.org.apache.jackrabbit.webdav=WARN
+log4j.logger.org.apache.juddi=ERROR
+log4j.logger.org.apache.commons.digester.Digester=WARN
+log4j.logger.org.apache.jasper.compiler.TldLocationsCache=WARN
+log4j.logger.org.apache.qpid=WARN
+log4j.logger.org.apache.qpid.server.Main=INFO
+log4j.logger.qpid.message=WARN
+log4j.logger.qpid.message.broker.listening=INFO
+log4j.logger.org.apache.tiles=WARN
+log4j.logger.org.apache.commons.httpclient=ERROR
+log4j.logger.org.apache.coyote=WARN
+log4j.logger.org.apache.solr=ERROR
+log4j.logger.me.prettyprint.cassandra.hector.TimingLogger=ERROR
+log4j.logger.org.wso2=INFO
+log4j.logger.org.apache.axis2.enterprise=FATAL, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.opensaml.xml=WARN, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.shared.ldap=WARN, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.ldap.handlers=WARN, CARBON_LOGFILE, CARBON_MEMORY
+#Following are to remove false error messages from startup (IS)
+log4j.logger.org.apache.directory.shared.ldap.entry.DefaultServerAttribute=FATAL, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.core.DefaultDirectoryService=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.shared.ldap.ldif.LdifReader=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.ldap.LdapProtocolHandler=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.core=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+log4j.logger.org.apache.directory.server.ldap.LdapSession=ERROR, CARBON_LOGFILE, CARBON_MEMORY
+#Hive Related Log configurations
+log4j.logger.DataNucleus=ERROR
+log4j.logger.Datastore=ERROR
+log4j.logger.Datastore.Schema=ERROR
+log4j.logger.JPOX.Datastore=ERROR
+log4j.logger.JPOX.Plugin=ERROR
+log4j.logger.JPOX.MetaData=ERROR
+log4j.logger.JPOX.Query=ERROR
+log4j.logger.JPOX.General=ERROR
+log4j.logger.JPOX.Enhancer=ERROR
+log4j.logger.org.apache.hadoop.hive=WARN
+log4j.logger.hive=WARN
+log4j.logger.ExecMapper=WARN
+log4j.logger.ExecReducer=WARN
+log4j.logger.net.sf.ehcache.config.ConfigurationFactory=ERROR
+
+log4j.logger.trace.messages=TRACE,CARBON_TRACE_LOGFILE
+
+log4j.additivity.org.apache.axis2.clustering=false
+log4j.additivity.com.atomikos=false
+log4j.additivity.org.apache=false
+
+# CARBON_CONSOLE is set to be a ConsoleAppender using a PatternLayout.
+log4j.appender.CARBON_CONSOLE=org.wso2.carbon.utils.logging.appenders.CarbonConsoleAppender
+log4j.appender.CARBON_CONSOLE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+# ConversionPattern will be overridden by the configuration setting in the DB
+log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d] %P%5p {%c} - %x %m%n
+log4j.appender.CARBON_CONSOLE.layout.TenantPattern=%U%@%D[%T]
+log4j.appender.CARBON_CONSOLE.threshold=DEBUG
+
+# CARBON_MEMORY is set to be a MemoryAppender using a PatternLayout.
+log4j.appender.CARBON_MEMORY=org.wso2.carbon.utils.logging.appenders.MemoryAppender
+log4j.appender.CARBON_MEMORY.layout=org.apache.log4j.PatternLayout
+log4j.appender.CARBON_MEMORY.bufferSize=200
+# ConversionPattern will be overridden by the configuration setting in the DB
+#log4j.appender.CARBON_MEMORY.layout.ConversionPattern=[%d] %5p - %x %m {%c}%n
+log4j.appender.CARBON_MEMORY.layout.ConversionPattern=[%d] %5p {%c} - %x %m %n
+log4j.appender.CARBON_MEMORY.threshold=DEBUG
+
+
+# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout.
+log4j.appender.CARBON_LOGFILE=org.wso2.carbon.utils.logging.appenders.CarbonDailyRollingFileAppender
+# Log file will be overridden by the configuration setting in the DB
+# This path should be relative to WSO2 Carbon Home
+log4j.appender.CARBON_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon${instance.log}.log
+log4j.appender.CARBON_LOGFILE.Append=true
+log4j.appender.CARBON_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+# ConversionPattern will be overridden by the configuration setting in the DB
+log4j.appender.CARBON_LOGFILE.layout.ConversionPattern=TID: [%T] [%S] [%d] %P%5p {%c} - %x %m %n
+log4j.appender.CARBON_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
+log4j.appender.CARBON_LOGFILE.threshold=DEBUG
+
+log4j.appender.CARBON_SYS_LOG = org.apache.log4j.net.SyslogAppender
+log4j.appender.CARBON_SYS_LOG.layout=org.apache.log4j.PatternLayout
+log4j.appender.CARBON_SYS_LOG.layout.ConversionPattern=[%d] %5p {%c} - %x %m %n
+log4j.appender.CARBON_SYS_LOG.SyslogHost=localhost
+log4j.appender.CARBON_SYS_LOG.Facility=USER
+log4j.appender.CARBON_SYS_LOG.threshold=DEBUG
+
+# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT
+log4j.appender.LOGEVENT=org.wso2.carbon.logging.service.appender.LogEventAppender
+log4j.appender.LOGEVENT.url=tcp://10.100.3.103:7611
+log4j.appender.LOGEVENT.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+log4j.appender.LOGEVENT.columnList=%T,%S,%A,%d,%c,%p,%m,%H,%I,%Stacktrace
+log4j.appender.LOGEVENT.userName=admin
+log4j.appender.LOGEVENT.password=admin
+#log4j.appender.LOGEVENT.password=secretAlias:Log4j.Appender.LOGEVENT.Password
+
+# Appender config to CARBON_TRACE_LOGFILE
+log4j.appender.CARBON_TRACE_LOGFILE=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.CARBON_TRACE_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon-trace-messages${instance.log}.log
+log4j.appender.CARBON_TRACE_LOGFILE.Append=true
+log4j.appender.CARBON_TRACE_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+log4j.appender.CARBON_TRACE_LOGFILE.layout.ConversionPattern=[%d] %P%5p {%c} - %x %m %n
+log4j.appender.CARBON_TRACE_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
+log4j.appender.CARBON_TRACE_LOGFILE.threshold=TRACE
+log4j.additivity.trace.messages=false
+
+# Appender config to AUDIT_LOGFILE
+log4j.appender.AUDIT_LOGFILE=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.AUDIT_LOGFILE.File=${carbon.home}/repository/logs/audit.log
+log4j.appender.AUDIT_LOGFILE.Append=true
+log4j.appender.AUDIT_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
+log4j.appender.AUDIT_LOGFILE.layout.ConversionPattern=[%d] %P%5p {%c}- %x %m %n
+log4j.appender.AUDIT_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
+log4j.appender.AUDIT_LOGFILE.threshold=INFO
+log4j.additivity.AUDIT_LOG=false
+
+# Appender config to send Atomikos transaction logs to new log file tm.out.
+log4j.appender.ATOMIKOS = org.apache.log4j.RollingFileAppender
+log4j.appender.ATOMIKOS.File = repository/logs/tm.out
+log4j.appender.ATOMIKOS.Append = true
+log4j.appender.ATOMIKOS.layout = org.apache.log4j.PatternLayout
+log4j.appender.ATOMIKOS.layout.ConversionPattern=%p %t %c - %m%n
+
+# This file is used to override the default logger settings, and is used to remove unwanted logs from Shindig appearing on the console.
+
+# Specification of Handler used by Console Logger
+handlers=java.util.logging.ConsoleHandler
+
+# Replacing default INFO level with SEVERE
+java.util.logging.ConsoleHandler.level=SEVERE
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/security/wso2certs.jks b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/security/wso2certs.jks
new file mode 100644
index 0000000000..c1e9ace3c2
Binary files /dev/null and b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/carbon-home/repository/conf/security/wso2certs.jks differ
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
index e19786b861..0e996abca5 100755
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/certificate-config.xml
@@ -1,8 +1,25 @@
+
- ${carbon.home}/repository/resources/security/wso2certs.jks
+ ${carbon.home}/repository/resources/wso2certs.jks
JKS
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/data-source-config.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/data-source-config.xml
new file mode 100644
index 0000000000..d9be5b3ac0
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/data-source-config.xml
@@ -0,0 +1,33 @@
+
+
+
+
+ jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true
+ org.h2.Driver
+ wso2carbon
+ wso2carbon
+
+
+
+
+
+
+
+
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/sql/h2.sql b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/sql/h2.sql
new file mode 100644
index 0000000000..044898f912
--- /dev/null
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/resources/sql/h2.sql
@@ -0,0 +1,25 @@
+--
+-- Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+--
+-- WSO2 Inc. licenses this file to you under the Apache License,
+-- Version 2.0 (the "License"); you may not use this file except
+-- in compliance with the License.
+-- You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied. See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
+ ID INTEGER auto_increment NOT NULL,
+ SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
+ CERTIFICATE BLOB DEFAULT NULL,
+ TENANT_ID INTEGER DEFAULT 0,
+ USERNAME VARCHAR(500) DEFAULT NULL,
+ PRIMARY KEY (ID)
+);
\ No newline at end of file
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 d05fefdb8a..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
@@ -1,12 +1,37 @@
+
+
-
+
+
+
+
+
+
+
-
\ No newline at end of file
+
+
diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml
index 96771b82a2..fadd35befe 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../../pom.xml
4.0.0
org.wso2.carbon.devicemgt
certificate-mgt
- 3.0.114-SNAPSHOT
+ 3.0.178-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 bac3b20bc9..2d6863a604 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.114-SNAPSHOT
+ 3.0.178-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 b5e81d603b..43d5f66866 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.114-SNAPSHOT
+ 3.0.178-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 fca2ceb411..1bab648fe6 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.114-SNAPSHOT
+ 3.0.178-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 075364e7e9..d51226e9e9 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.114-SNAPSHOT
+ 3.0.178-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 06362afb0d..d0b74ba79c 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.114-SNAPSHOT
+ 3.0.178-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 9b89a5c2e9..c0f41adb45 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml
index b81ebe8ec1..1fd0bbe98f 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.114-SNAPSHOT
+ 3.0.178-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 c4f00d1e4f..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.114-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 746afa5d6f..41bd2f0e39 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
@@ -75,16 +75,12 @@
org.wso2.carbon.databridge.commons
- org.wso2.carbon.registry
- org.wso2.carbon.registry.indexing
+ org.wso2.carbon
+ org.wso2.carbon.securevault
- org.wso2.carbon.registry
- org.wso2.carbon.registry.common
-
-
- 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];
+ 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;
}
}
- //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());
- }
- }
- } 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 48f81db3d8..b7361536c3 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.114-SNAPSHOT
+ 3.0.178-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/beans/RemoteSessionInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RemoteSessionInfo.java
new file mode 100644
index 0000000000..34883532f1
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RemoteSessionInfo.java
@@ -0,0 +1,52 @@
+/*
+ * 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.beans;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
+
+import java.util.List;
+
+@ApiModel(value = "RemoteSessionInfo", description = "Template of the remote session")
+public class RemoteSessionInfo {
+
+ @ApiModelProperty(name = "Server Url", value = "Url of the remote session server.", required = true)
+ private String serverUrl;
+
+ @ApiModelProperty(name = "isEnabled", value = "Is remote session functionality enabled", required = true)
+ private Boolean isEnabled;
+
+ public String getServerUrl() {
+ return serverUrl;
+ }
+
+ public void setServerUrl(String serverUrl) {
+ this.serverUrl = serverUrl;
+ }
+
+ public Boolean getEnabled() {
+ return isEnabled;
+ }
+
+ public void setEnabled(Boolean enabled) {
+ isEnabled = enabled;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RemoteSessionService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RemoteSessionService.java
new file mode 100644
index 0000000000..52c0eaf7f2
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RemoteSessionService.java
@@ -0,0 +1,130 @@
+/*
+ * 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.api;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import io.swagger.annotations.Extension;
+import io.swagger.annotations.ExtensionProperty;
+import io.swagger.annotations.Info;
+import io.swagger.annotations.ResponseHeader;
+import io.swagger.annotations.SwaggerDefinition;
+import io.swagger.annotations.Tag;
+import org.wso2.carbon.apimgt.annotations.api.Scope;
+import org.wso2.carbon.apimgt.annotations.api.Scopes;
+import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
+
+import javax.validation.constraints.Size;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.core.Response;
+
+@SwaggerDefinition(
+ info = @Info(
+ version = "1.0.0",
+ title = "",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = "name", value = "remote_session_services"),
+ @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/remote-session-services"),
+ })
+ }
+ ),
+ tags = {
+ @Tag(name = "device_management", description = "")
+ }
+)
+@Scopes(
+ scopes = {
+ @Scope(
+ name = "Remote Session Connection",
+ description = "",
+ key = "perm:remote-session-service:connect",
+ permissions = {"/device-mgt/devices/owning-device/remote-session"}
+ )
+ }
+)
+@Path("/remote-session-services")
+@Api(value = "Remote Session Service",
+ description = "This carries all the resources related to the remote session service functionality.")
+public interface RemoteSessionService {
+ /**
+ * Retrieve Analytics for the device type
+ */
+ @GET
+ @Path("connection/{deviceType}/{deviceId}")
+ @ApiOperation(
+ consumes = "application/json",
+ produces = "application/json",
+ httpMethod = "GET",
+ value = "Retrieve Connection Information for the device type",
+ notes = "",
+ response = Response.class,
+ tags = "Remote Session Service Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:remote-session-service:connect")
+ })
+ }
+ )
+ @ApiResponses(value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK.",
+ response = Response.class,
+ responseHeaders = {
+ @ResponseHeader(
+ name = "Content-Type",
+ description = "The content type of the body"),
+ @ResponseHeader(
+ name = "Last-Modified",
+ description = "Date and time the resource was last modified.\n" +
+ "Used by caches, or in conditional requests."),
+ }),
+ @ApiResponse(
+ code = 400,
+ message = "Bad Request. \n Invalid Device Identifiers found.",
+ response = Response.class),
+ @ApiResponse(
+ code = 401,
+ message = "Unauthorized. \n Unauthorized request."),
+ @ApiResponse(
+ code = 500,
+ message = "Internal Server Error. \n Error on retrieving stats",
+ response = Response.class)
+ })
+ Response getRemoteSessionDeviceConnect(
+ @ApiParam(
+ name = "deviceId",
+ value = "The registered device Id.",
+ required = true)
+ @PathParam("deviceId") String deviceId,
+ @ApiParam(
+ name = "device-type",
+ value = "The device type, such as ios, android or windows.",
+ required = true)
+ @PathParam("deviceType")
+ @Size(max = 45)
+ String deviceType);
+}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
index 2b39044d17..a6751024e0 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
@@ -29,6 +29,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
+import org.wso2.carbon.user.api.UserStoreException;
import javax.validation.constraints.Size;
import javax.ws.rs.*;
@@ -54,22 +55,27 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
Activity activity;
DeviceManagementProviderService dmService;
- try {
- RequestValidationUtil.validateActivityId(id);
+ Response response = validateAdminUser();
+ if (response == null) {
+ try {
+ RequestValidationUtil.validateActivityId(id);
- dmService = DeviceMgtAPIUtils.getDeviceManagementService();
- activity = dmService.getOperationByActivityId(id);
- if (activity == null) {
- return Response.status(404).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
- "found upon the provided activity id '" + id + "'").build()).build();
+ dmService = DeviceMgtAPIUtils.getDeviceManagementService();
+ activity = dmService.getOperationByActivityId(id);
+ if (activity == null) {
+ return Response.status(404).entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
+ "found upon the provided activity id '" + id + "'").build()).build();
+ }
+ return Response.status(Response.Status.OK).entity(activity).build();
+ } catch (OperationManagementException e) {
+ String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
- return Response.status(Response.Status.OK).entity(activity).build();
- } catch (OperationManagementException e) {
- String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
- log.error(msg, e);
- return Response.serverError().entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ } else {
+ return response;
}
}
@@ -120,7 +126,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
long sinceTimestamp;
long timestamp = 0;
boolean isIfModifiedSinceSet = false;
- boolean isSinceSet = false;
if (log.isDebugEnabled()) {
log.debug("getActivities since: " + since + " , offset: " + offset + " ,limit: " + limit + " ," +
"ifModifiedSince: " + ifModifiedSince);
@@ -150,7 +155,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
"Invalid date string is provided in 'since' filter").build()).build();
}
sinceTimestamp = sinceDate.getTime();
- isSinceSet = true;
timestamp = sinceTimestamp / 1000;
}
@@ -162,38 +166,57 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
if (log.isDebugEnabled()) {
log.debug("getActivities final timestamp " + timestamp);
}
-
- List activities;
- ActivityList activityList = new ActivityList();
- DeviceManagementProviderService dmService;
- try {
- if (log.isDebugEnabled()) {
- log.debug("Calling database to get activities.");
- }
- dmService = DeviceMgtAPIUtils.getDeviceManagementService();
- activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset);
- activityList.setList(activities);
- if (log.isDebugEnabled()) {
- log.debug("Calling database to get activity count.");
- }
- int count = dmService.getActivityCountUpdatedAfter(timestamp);
- if (log.isDebugEnabled()) {
- log.debug("Activity count: " + count);
- }
- activityList.setCount(count);
- if (activities == null || activities.size() == 0) {
- if (isIfModifiedSinceSet) {
- return Response.notModified().build();
+ Response response = validateAdminUser();
+ if (response == null) {
+ List activities;
+ ActivityList activityList = new ActivityList();
+ DeviceManagementProviderService dmService;
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Calling database to get activities.");
}
+ dmService = DeviceMgtAPIUtils.getDeviceManagementService();
+ activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset);
+ activityList.setList(activities);
+ if (log.isDebugEnabled()) {
+ log.debug("Calling database to get activity count.");
+ }
+ int count = dmService.getActivityCountUpdatedAfter(timestamp);
+ if (log.isDebugEnabled()) {
+ log.debug("Activity count: " + count);
+ }
+ activityList.setCount(count);
+ if (activities == null || activities.size() == 0) {
+ if (isIfModifiedSinceSet) {
+ return Response.notModified().build();
+ }
+ }
+ return Response.ok().entity(activityList).build();
+ } catch (OperationManagementException e) {
+ String msg
+ = "ErrorResponse occurred while fetching the activities updated after given time stamp.";
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
- return Response.ok().entity(activityList).build();
- } catch (OperationManagementException e) {
+ } else {
+ return response;
+ }
+ }
+
+ private Response validateAdminUser(){
+ try {
+ if (!DeviceMgtAPIUtils.isAdmin()) {
+ return Response.status(Response.Status.UNAUTHORIZED).entity("Unauthorized operation! Only admin role can perform " +
+ "this operation.").build();
+ }
+ return null;
+ } catch (UserStoreException e) {
String msg
- = "ErrorResponse occurred while fetching the activities updated after given time stamp.";
+ = "Error occurred while validating the user have admin role!";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
-
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java
index 04bfeff0d7..fc34cfba0d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java
@@ -31,15 +31,15 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.common.geo.service.Event;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
-import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
+import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
-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.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
@@ -76,13 +76,13 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType,
@QueryParam("from") long from, @QueryParam("to") long to) {
- //First, check whether the Geo Location service has been enabled in the cdmf-config.xml file
- DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
- .getDeviceManagementConfig();
- if (deviceManagementConfig != null) {
- if(!deviceManagementConfig.getGeoLocationConfiguration().getPublishLocationOperationResponse()){
- return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
+ try {
+ if (!DeviceManagerUtil.isPublishOperationResponseEnabled()) {
+ return Response.status(Response.Status.BAD_REQUEST.getStatusCode())
+ .entity("Unable to retrive Geo Device stats. Geo Data publishing does not enabled.").build();
}
+ } catch (DeviceManagementException e) {
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(e.getMessage()).build();
}
String tableName = "IOT_PER_DEVICE_STREAM_GEO_FUSEDSPATIALEVENT";
String fromDate = String.valueOf(from);
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/RemoteSessionServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RemoteSessionServiceImpl.java
new file mode 100644
index 0000000000..a972df9826
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RemoteSessionServiceImpl.java
@@ -0,0 +1,68 @@
+/*
+ * 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.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
+import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
+import org.wso2.carbon.device.mgt.core.config.remote.session.RemoteSessionConfiguration;
+import org.wso2.carbon.device.mgt.jaxrs.beans.RemoteSessionInfo;
+import org.wso2.carbon.device.mgt.jaxrs.service.api.RemoteSessionService;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+
+/**
+ * The api for
+ */
+public class RemoteSessionServiceImpl implements RemoteSessionService {
+
+ private static Log log = LogFactory.getLog(RemoteSessionServiceImpl.class);
+
+ @Path("connect/{deviceType}/{deviceId}")
+ @GET
+ @Consumes("application/json")
+ @Produces("application/json")
+ public Response getRemoteSessionDeviceConnect(@PathParam("deviceId") String deviceId,
+ @PathParam("deviceType") String deviceType) {
+ //First, check whether the remote session is enabled.
+ RemoteSessionInfo sessionInfo = new RemoteSessionInfo();
+ sessionInfo.setEnabled(false);
+ DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
+ .getDeviceManagementConfig();
+ if (deviceManagementConfig != null) {
+ RemoteSessionConfiguration remoteSessionConfiguration = deviceManagementConfig.getRemoteSessionConfiguration();
+ if (remoteSessionConfiguration != null) {
+ boolean isEnabled = remoteSessionConfiguration.isEnabled();
+ sessionInfo.setEnabled(isEnabled);
+ if (isEnabled) {
+ sessionInfo.setServerUrl(remoteSessionConfiguration.getRemoteSessionServerUrl());
+ }
+ return Response.ok().entity(sessionInfo).build();
+ }
+ }
+
+ return Response.ok().entity(sessionInfo).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 7ff6953a1d..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
@@ -702,4 +691,18 @@ public class DeviceMgtAPIUtils {
SSLContext.setDefault(sslContext);
}
+
+ public static boolean isAdmin() throws UserStoreException {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ UserRealm realmService = DeviceMgtAPIUtils.getRealmService().getTenantUserRealm(tenantId);
+ String adminRoleName = realmService.getRealmConfiguration().getAdminRoleName();
+ String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ String[] roles = realmService.getUserStoreManager().getRoleListOfUser(userName);
+ for (String role: roles){
+ if (role != null && role.equals(adminRoleName)){
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml
index 572b64922b..e1e2c46e8c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -38,6 +38,7 @@
+
@@ -81,6 +82,7 @@
+
@@ -99,4 +101,4 @@
-
+
\ No newline at end of file
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..efd573b11f
--- /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,1102 @@
+/*
+ * 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.base.MultitenantConstants;
+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 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 testEnrollDeviceWithNullDevice() {
+ 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 testEnrollDeviceWithNullDeviceType() {
+ 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 testEnrollNewDeviceWithNullDeviceIdentifier() {
+ 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 testEnrollDeviceWithDeviceManagementException() 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 testDisEnrollWithNonExistingDevice() 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 where device management exception is thrown.")
+ public void testDisEnrollingDeviceWithDeviceManagementException() 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 testUpdateDeviceWithDeviceManagementException() 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 testUpdateDeviceWithNonExistingDevice() 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 testEnrollDeviceWithDeviceAccessAuthorizationException() 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 testUpdateDeviceWithUnsuccessfulDeviceModification() 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(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
+ 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(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
+ 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(description = "Test publish events when device access authorization exception is thrown.")
+ public void testPublishEventsWithDeviceAccessAuthorizationException() 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(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
+ 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 testPublishEventsDataPublisherConfigurationException() 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..c8549711fc
--- /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,605 @@
+/*
+ * 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.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.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");
+ }
+
+ @Test(description = "Testing changing device status")
+ public void testChangeDeviceStatus() {
+ PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
+ .toReturn(this.deviceManagementProviderService);
+ Response response = this.deviceManagementService
+ .changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.INACTIVE);
+ Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
+ }
+
+ @Test(description = "Testing changing device status when device does not exist")
+ public void testChangeDeviceStatusWhenDeviceNotExists() 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
+ .changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.INACTIVE);
+ Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
+ Mockito.reset(this.deviceManagementProviderService);
+ }
+
+ @Test(description = "Testing changing device status when device cannot be retrieved")
+ public void testChangeDeviceStatusException() throws DeviceManagementException {
+ PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
+ .toReturn(this.deviceManagementProviderService);
+ Mockito.when(this.deviceManagementProviderService
+ .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean()))
+ .thenThrow(new DeviceManagementException());
+ Response response = this.deviceManagementService
+ .changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.ACTIVE);
+ Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
+ Mockito.reset(this.deviceManagementProviderService);
+ }
+
+ @Test(description = "Testing changing device status when unable to change device status")
+ public void testChangeDeviceStatusWhenUnableToChangeStatus() throws DeviceManagementException {
+ PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
+ .toReturn(this.deviceManagementProviderService);
+ Mockito.when(this.deviceManagementProviderService
+ .changeDeviceStatus(Mockito.any(DeviceIdentifier.class), Mockito.any()))
+ .thenThrow(new DeviceManagementException());
+ Response response = this.deviceManagementService
+ .changeDeviceStatus(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), EnrolmentInfo.Status.ACTIVE);
+ Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
+ 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/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..0d275ea52d
--- /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,219 @@
+/*
+ * 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();
+ 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);
+ 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);
+ 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);
+ 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..9629afb07a
--- /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,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.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..f1f0d1628d
--- /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,128 @@
+/*
+ * 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.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 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.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 c959b88494..56bbd73525 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.114-SNAPSHOT
+ 3.0.178-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java
index b7f5a5b14c..05c8345183 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java
@@ -144,30 +144,6 @@ public class DeviceInfo implements Serializable {
this.location = location;
}
- public String getIMEI() {
- if (IMEI != null) {
- return IMEI;
- } else {
- return "";
- }
- }
-
- public void setIMEI(String IMEI) {
- this.IMEI = IMEI;
- }
-
- public String getIMSI() {
- if (IMSI != null) {
- return IMSI;
- } else {
- return "";
- }
- }
-
- public void setIMSI(String IMSI) {
- this.IMSI = IMSI;
- }
-
public String getDeviceModel() {
if (deviceModel != null) {
return deviceModel;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java
index 8de9f3199e..72fe612f0e 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java
@@ -63,7 +63,8 @@ public interface OperationManager {
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
- PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException;
+ PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request)
+ throws OperationManagementException;
/**
* Method to retrieve the list of available operations to a device.
@@ -73,15 +74,12 @@ public interface OperationManager {
* @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
- List extends Operation> getPendingOperations(
- DeviceIdentifier deviceId) throws OperationManagementException;
+ List extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException;
Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException;
void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
- void deleteOperation(int operationId) throws OperationManagementException;
-
Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
throws OperationManagementException;
@@ -93,22 +91,13 @@ public interface OperationManager {
Activity getOperationByActivityId(String activity) throws OperationManagementException;
- Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException;
-
- List getOperationUpdatedAfter(long timestamp) throws OperationManagementException;
-
- List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException;
+ Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId)
+ throws OperationManagementException;
List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException;
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException;
- /**
- * Operation manger implementation can have a push notification stratergy
- * @param notificationStrategy eg: mqtt/xmpp
- */
- void setNotificationStrategy(NotificationStrategy notificationStrategy);
-
/**
* retrive the push notification strategy.
* @return NotificationStrategy
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 9040429b59..b071184c9d 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.114-SNAPSHOT
+ 3.0.178-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
@@ -221,6 +225,11 @@
org.testng
testng
+
+ org.powermock
+ powermock-module-testng
+ test
+
org.wso2.carbon
org.wso2.carbon.user.core
@@ -345,7 +354,11 @@
javassist
javassist
-
+
+
+ org.powermock
+ powermock-api-mockito
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java
index f5f209d61f..10699b2f4d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java
@@ -20,11 +20,10 @@ package org.wso2.carbon.device.mgt.core.authorization;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext;
-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.authorization.DeviceAuthorizationResult;
@@ -36,11 +35,9 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
-
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
+
/**
* Implementation of DeviceAccessAuthorization service.
@@ -233,7 +230,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
return userRealm.getAuthorizationManager()
.isUserAuthorized(removeTenantDomain(username),
PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION),
- PermissionMethod.UI_EXECUTE);
+ CarbonConstants.UI_PERMISSION_ACTION);
}
return false;
}
@@ -265,22 +262,6 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
return PermissionUtils.putPermission(permission);
}
- private Map getOwnershipOfDevices(List devices) {
- Map ownershipData = new HashMap<>();
- EnrolmentInfo enrolmentInfo;
- String owner;
- for (Device device : devices) {
- enrolmentInfo = device.getEnrolmentInfo();
- if (enrolmentInfo != null) {
- owner = enrolmentInfo.getOwner();
- if (owner != null && !owner.isEmpty()) {
- ownershipData.put(device.getDeviceIdentifier(), owner);
- }
- }
- }
- return ownershipData;
- }
-
public static final class PermissionMethod {
public static final String READ = "read";
public static final String WRITE = "write";
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java
index 51b6b63f2e..47b6caa11f 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java
@@ -57,9 +57,9 @@ public class DeviceConfigurationManager {
return deviceConfigManager;
}
- public synchronized void initConfig() throws DeviceManagementException {
+ public synchronized void initConfig(String configLocation) throws DeviceManagementException {
try {
- File deviceMgtConfig = new File(DeviceConfigurationManager.DEVICE_MGT_CONFIG_PATH);
+ File deviceMgtConfig = new File(configLocation);
Document doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig);
/* Un-marshaling Device Management configuration */
@@ -72,15 +72,8 @@ public class DeviceConfigurationManager {
}
}
- private static Schema getSchema() throws DeviceManagementException {
- try {
- File deviceManagementSchemaConfig = new File(DeviceConfigurationManager.DEVICE_MGT_CONFIG_SCHEMA_PATH);
- SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- return factory.newSchema(deviceManagementSchemaConfig);
- } catch (SAXException e) {
- throw new DeviceManagementException("Error occurred while initializing the schema of " +
- "device-mgt-config.xml", e);
- }
+ public void initConfig() throws DeviceManagementException {
+ this.initConfig(DEVICE_MGT_CONFIG_PATH);
}
public DeviceManagementConfig getDeviceManagementConfig() {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java
index 535daebf98..c779332c77 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java
@@ -19,13 +19,15 @@ package org.wso2.carbon.device.mgt.core.config;
import org.wso2.carbon.device.mgt.core.config.archival.ArchivalConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration;
-import org.wso2.carbon.device.mgt.core.config.geo.location.GeoLocationConfiguration;
+import org.wso2.carbon.device.mgt.core.config.geo.location.OperationAnalyticsConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
+import org.wso2.carbon.device.mgt.core.config.keymanager.KeyManagerConfigurations;
import org.wso2.carbon.device.mgt.core.config.pagination.PaginationConfiguration;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.config.pull.notification.PullNotificationConfiguration;
import org.wso2.carbon.device.mgt.core.config.push.notification.PushNotificationConfiguration;
+import org.wso2.carbon.device.mgt.core.config.remote.session.RemoteSessionConfiguration;
import org.wso2.carbon.device.mgt.core.config.status.task.DeviceStatusTaskConfig;
import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration;
@@ -42,6 +44,7 @@ public final class DeviceManagementConfig {
private DeviceManagementConfigRepository deviceManagementConfigRepository;
private TaskConfiguration taskConfiguration;
private IdentityConfigurations identityConfigurations;
+ private KeyManagerConfigurations keyManagerConfigurations;
private PolicyConfiguration policyConfiguration;
private PaginationConfiguration paginationConfiguration;
private PushNotificationConfiguration pushNotificationConfiguration;
@@ -49,9 +52,10 @@ public final class DeviceManagementConfig {
private DeviceStatusTaskConfig deviceStatusTaskConfig;
private DeviceCacheConfiguration deviceCacheConfiguration;
private CertificateCacheConfiguration certificateCacheConfiguration;
- private GeoLocationConfiguration geoLocationConfiguration;
- private ArchivalConfiguration archivalConfiguration;
+ private OperationAnalyticsConfiguration operationAnalyticsConfiguration;
private String defaultGroupsConfiguration;
+ private RemoteSessionConfiguration remoteSessionConfiguration;
+
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
@@ -72,6 +76,15 @@ public final class DeviceManagementConfig {
this.identityConfigurations = identityConfigurations;
}
+ @XmlElement(name = "KeyManagerConfiguration", required = true)
+ public KeyManagerConfigurations getKeyManagerConfigurations() {
+ return keyManagerConfigurations;
+ }
+
+ public void setKeyManagerConfigurations(KeyManagerConfigurations keyManagerConfigurations) {
+ this.keyManagerConfigurations = keyManagerConfigurations;
+ }
+
@XmlElement(name = "PolicyConfiguration", required = true)
public PolicyConfiguration getPolicyConfiguration() {
return policyConfiguration;
@@ -144,13 +157,13 @@ public final class DeviceManagementConfig {
this.certificateCacheConfiguration = certificateCacheConfiguration;
}
- @XmlElement(name = "GeoLocationConfiguration", required = true)
- public GeoLocationConfiguration getGeoLocationConfiguration() {
- return geoLocationConfiguration;
+ @XmlElement(name = "OperationAnalyticsConfiguration", required = true)
+ public OperationAnalyticsConfiguration getOperationAnalyticsConfiguration() {
+ return operationAnalyticsConfiguration;
}
- public void setGeoLocationConfiguration(GeoLocationConfiguration geoLocationConfiguration) {
- this.geoLocationConfiguration = geoLocationConfiguration;
+ public void setOperationAnalyticsConfiguration(OperationAnalyticsConfiguration operationAnalyticsConfiguration) {
+ this.operationAnalyticsConfiguration = operationAnalyticsConfiguration;
}
@XmlElement(name = "DefaultGroupsConfiguration", required = true)
@@ -170,5 +183,13 @@ public final class DeviceManagementConfig {
public void setArchivalConfiguration(ArchivalConfiguration archivalConfiguration) {
this.archivalConfiguration = archivalConfiguration;
}
+ @XmlElement(name = "RemoteSessionConfiguration", required = true)
+ public RemoteSessionConfiguration getRemoteSessionConfiguration() {
+ return remoteSessionConfiguration;
+ }
+
+ public void setRemoteSessionConfiguration(RemoteSessionConfiguration remoteSessionConfiguration) {
+ this.remoteSessionConfiguration = remoteSessionConfiguration;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/GeoLocationConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/OperationAnalyticsConfiguration.java
similarity index 65%
rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/GeoLocationConfiguration.java
rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/OperationAnalyticsConfiguration.java
index e1aeb1a45c..8cc2053e64 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/GeoLocationConfiguration.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/geo/location/OperationAnalyticsConfiguration.java
@@ -22,21 +22,21 @@ import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
- * This class represents the information related to Geo Location configuration.
+ * This class represents the information related to Device Operation Analytics configuration.
*/
-@XmlRootElement(name = "GeoLocationConfiguration")
-public class GeoLocationConfiguration {
+@XmlRootElement(name = "OperationAnalyticsConfiguration")
+public class OperationAnalyticsConfiguration {
- private boolean publishLocationOperationResponse;
+ private boolean publishOperationResponse;
private boolean isEnabled;
- public boolean getPublishLocationOperationResponse() {
- return publishLocationOperationResponse;
+ public boolean getPublishOperationResponse() {
+ return publishOperationResponse;
}
- @XmlElement(name = "PublishLocationOperationResponse", required = true)
- public void setPublishLocationOperationResponse(boolean publishLocationOperationResponse) {
- this.publishLocationOperationResponse = publishLocationOperationResponse;
+ @XmlElement(name = "PublishOperationResponse", required = true)
+ public void setPublishOperationResponse(boolean publishOperationResponse) {
+ this.publishOperationResponse = publishOperationResponse;
}
public boolean getIsEnabled() {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/keymanager/KeyManagerConfigurations.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/keymanager/KeyManagerConfigurations.java
new file mode 100644
index 0000000000..b76f932e5b
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/keymanager/KeyManagerConfigurations.java
@@ -0,0 +1,59 @@
+/*
+ * 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.config.keymanager;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Configurations related to key management.
+ */
+@XmlRootElement(name = "KeyManagerConfiguration")
+public class KeyManagerConfigurations {
+ private String serverUrl;
+ private String adminUsername;
+ private String adminPassword;
+
+ @XmlElement(name = "AdminUsername", required = true)
+ public String getAdminUsername() {
+ return adminUsername;
+ }
+
+ public void setAdminUsername(String adminUsername) {
+ this.adminUsername = adminUsername;
+ }
+
+ @XmlElement(name = "AdminPassword", required = true)
+ public String getAdminPassword() {
+ return adminPassword;
+ }
+
+ public void setAdminPassword(String adminPassword) {
+ this.adminPassword = adminPassword;
+ }
+
+ @XmlElement(name = "ServerUrl", required = true)
+ public String getServerUrl() {
+ return serverUrl;
+ }
+
+ public void setServerUrl(String serverUrl) {
+ this.serverUrl = serverUrl;
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/remote/session/RemoteSessionConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/remote/session/RemoteSessionConfiguration.java
new file mode 100644
index 0000000000..426e2db308
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/remote/session/RemoteSessionConfiguration.java
@@ -0,0 +1,143 @@
+/*
+ * 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.config.remote.session;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * This class represents the information related to Remote Session configuration.
+ */
+@XmlRootElement(name = "RemoteSessionConfiguration")
+public class RemoteSessionConfiguration {
+
+ private String remoteSessionServerUrl;
+ private boolean enabled;
+ private int maxHTTPConnectionPerHost;
+ private int maxTotalHTTPConnections;
+ private int maxMessagesPerSecond;
+ private int sessionIdleTimeOut;
+ private int maxSessionDuration;
+ private int sessionBufferSize;
+
+ public void setRemoteSessionServerUrl(String remoteSessionServerUrl) {
+ this.remoteSessionServerUrl = remoteSessionServerUrl;
+ }
+
+ /**
+ * Remote session server url
+ * @return
+ */
+ @XmlElement(name = "RemoteSessionServerUrl", required = true)
+ public String getRemoteSessionServerUrl() {
+ return remoteSessionServerUrl;
+ }
+
+ /**
+ * Remote session enabled
+ * @return
+ */
+ @XmlElement(name = "Enabled", required = true)
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ /**
+ * Maximum connections per host for external http invocations
+ * @return
+ */
+ @XmlElement(name = "MaximumHTTPConnectionPerHost", required = true, defaultValue = "2")
+ public int getMaxHTTPConnectionPerHost() {
+ return maxHTTPConnectionPerHost;
+ }
+
+ public void setMaxHTTPConnectionPerHost(int maxHTTPConnectionPerHost) {
+ this.maxHTTPConnectionPerHost = maxHTTPConnectionPerHost;
+ }
+
+ /**
+ * Maximum total connections for external http invocation
+ */
+ @XmlElement(name = "MaximumTotalHTTPConnections", required = true, defaultValue = "100")
+ public int getMaxTotalHTTPConnections() {
+ return maxTotalHTTPConnections;
+ }
+
+ public void setMaxTotalHTTPConnections(int maxTotalHTTPConnections) {
+ this.maxTotalHTTPConnections = maxTotalHTTPConnections;
+ }
+
+ /**
+ * This is for protect device from message spamming. Throttling limit in term of messages for device
+ * @return
+ */
+ @XmlElement(name = "MaximumMessagesPerSecond", required = true, defaultValue = "10")
+ public int getMaxMessagesPerSession() {
+ return maxMessagesPerSecond;
+ }
+
+ public void setMaxMessagesPerSession(int maxMessagesPerSession) {
+ this.maxMessagesPerSecond = maxMessagesPerSession;
+ }
+
+ /**
+ * Maximum idle timeout in minutes
+ * @return
+ */
+ @XmlElement(name = "SessionIdleTimeOut", required = true, defaultValue = "5")
+ public int getSessionIdleTimeOut() {
+ return sessionIdleTimeOut;
+ }
+
+ public void setSessionIdleTimeOut(int sessionIdleTimeOut) {
+ this.sessionIdleTimeOut = sessionIdleTimeOut;
+ }
+
+ /**
+ * Maximum session duration in minutes
+ * @return
+ */
+ @XmlElement(name = "MaximumSessionDuration", required = true, defaultValue = "15")
+ public int getMaxSessionDuration() {
+ return maxSessionDuration;
+ }
+
+ public void setMaxSessionDuration(int maxSessionDuration) {
+ this.maxSessionDuration = maxSessionDuration;
+ }
+
+ /**
+ * Maximum session buffer size in kilo bytes
+ * @return
+ */
+ @XmlElement(name = "SessionBufferSize", required = true, defaultValue = "640")
+ public int getSessionBufferSize() {
+ return sessionBufferSize;
+ }
+
+ public void setSessionBufferSize(int sessionBufferSize) {
+ this.sessionBufferSize = sessionBufferSize;
+ }
+}
+
+
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 decb956f1e..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;
@@ -122,7 +117,14 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " +
"t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " +
"t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " +
- "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
+ "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC";
+ // Status adeed as an orderby clause to fix a bug : when an existing device is
+ // re-enrolled, earlier enrollment is marked as removed and a new enrollment is added.
+ // However, both enrollments share the same time stamp. When retrieving the device
+ // due to same timestamp, enrollment information is incorrect, intermittently. Hence
+ // status also should be taken into consideration when ordering. This should not present a
+ // problem for other status transitions, as there would be an intermediary removed
+ // state in between.
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceIdentifier.getId());
@@ -907,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;
@@ -970,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;
@@ -1055,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/ApplicationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java
index c391f1057f..0de0e3aefb 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java
@@ -26,8 +26,16 @@ 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.util.DeviceManagementDAOUtil;
-import java.io.*;
-import java.sql.*;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.ObjectInputStream;
+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.Properties;
@@ -84,14 +92,14 @@ public class ApplicationDAOImpl implements ApplicationDAO {
try {
bao.close();
} catch (IOException e) {
- log.warn("Error occurred while closing ByteArrayOutputStream", e);
+ log.error("Error occurred while closing ByteArrayOutputStream", e);
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
- log.warn("Error occurred while closing ObjectOutputStream", e);
+ log.error("Error occurred while closing ObjectOutputStream", e);
}
}
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
@@ -150,14 +158,14 @@ public class ApplicationDAOImpl implements ApplicationDAO {
try {
bao.close();
} catch (IOException e) {
- log.warn("Error occurred while closing ByteArrayOutputStream", e);
+ log.error("Error occurred while closing ByteArrayOutputStream", e);
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
- log.warn("Error occurred while closing ObjectOutputStream", e);
+ log.error("Error occurred while closing ObjectOutputStream", e);
}
}
DeviceManagementDAOUtil.cleanupResources(stmt, null);
@@ -193,7 +201,7 @@ public class ApplicationDAOImpl implements ApplicationDAO {
conn.rollback();
}
} catch (SQLException e1) {
- log.warn("Error occurred while roll-backing the transaction", e);
+ log.error("Error occurred while roll-backing the transaction", e);
}
throw new DeviceManagementDAOException("Error occurred while removing bulk application list", e);
} finally {
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;
}
+ 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 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 trying to get device " +
+ "count of Owner : "+owner, e);
+ } finally {
+ DeviceManagementDAOUtil.cleanupResources(stmt, rs);
+ }
+ return count;
+ }
+
@Override
public boolean setStatus(String currentOwner, EnrolmentInfo.Status status,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
- 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);
+ 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/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java
index e356802117..0a7f22dbf0 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java
@@ -41,6 +41,7 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import java.sql.SQLException;
import java.util.ArrayList;
+import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -50,7 +51,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
private DeviceDetailsDAO deviceDetailsDAO;
private DeviceDAO deviceDAO;
private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class);
- private static final String EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream";
+ private static final String LOCATION_EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream";
+ private static final String DEVICE_INFO_EVENT_STREAM_DEFINITION = "org.wso2.iot.DeviceInfoStream";
+
public DeviceInformationManagerImpl() {
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
@@ -70,6 +73,35 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
deviceDetailsDAO.addDeviceInformation(device.getId(), deviceInfo);
deviceDetailsDAO.addDeviceProperties(deviceInfo.getDeviceDetailsMap(), device.getId());
DeviceManagementDAOFactory.commitTransaction();
+
+ if (DeviceManagerUtil.isPublishOperationResponseEnabled()) {
+ Object[] metaData = {device.getDeviceIdentifier(), device.getType()};
+ Object[] payload = new Object[]{
+ Calendar.getInstance().getTimeInMillis(),
+ deviceInfo.getDeviceDetailsMap().get("IMEI"),
+ deviceInfo.getDeviceDetailsMap().get("IMSI"),
+ deviceInfo.getDeviceModel(),
+ deviceInfo.getVendor(),
+ deviceInfo.getOsVersion(),
+ deviceInfo.getOsBuildDate(),
+ deviceInfo.getBatteryLevel(),
+ deviceInfo.getInternalTotalMemory(),
+ deviceInfo.getInternalAvailableMemory(),
+ deviceInfo.getExternalTotalMemory(),
+ deviceInfo.getExternalAvailableMemory(),
+ deviceInfo.getOperator(),
+ deviceInfo.getConnectionType(),
+ deviceInfo.getMobileSignalStrength(),
+ deviceInfo.getSsid(),
+ deviceInfo.getCpuUsage(),
+ deviceInfo.getTotalRAMMemory(),
+ deviceInfo.getAvailableRAMMemory(),
+ deviceInfo.isPluggedIn()
+ };
+ DeviceManagerUtil.getEventPublisherService().publishEvent(
+ DEVICE_INFO_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
+ );
+ }
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Transactional error occurred while adding the device information.", e);
@@ -82,7 +114,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while updating the last update timestamp of the " +
- "device", e);
+ "device", e);
+ } catch (DataPublisherConfigurationException e) {
+ DeviceManagementDAOFactory.rollbackTransaction();
+ throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -90,19 +125,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
@Override
public DeviceInfo getDeviceInfo(DeviceIdentifier deviceId) throws DeviceDetailsMgtException {
- Device device;
- try {
- device = DeviceManagementDataHolder.getInstance().
- getDeviceManagementProvider().getDevice(deviceId, false);
- if (device == null) {
- if (log.isDebugEnabled()) {
- log.debug("No device is found upon the device identifier '" + deviceId.getId() +
- "' and type '" + deviceId.getType() + "'. Therefore returning null");
- }
- return null;
- }
- } catch (DeviceManagementException e) {
- throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e);
+ Device device = getDevice(deviceId);
+ if (device == null) {
+ return null;
}
try {
DeviceManagementDAOFactory.openConnection();
@@ -111,7 +136,8 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
return deviceInfo;
} catch (SQLException e) {
- throw new DeviceDetailsMgtException("SQL error occurred while retrieving device from database.", e);
+ throw new DeviceDetailsMgtException("SQL error occurred while retrieving device " + deviceId.toString()
+ + "'s info from database.", e);
} catch (DeviceDetailsMgtDAOException e) {
throw new DeviceDetailsMgtException("Exception occurred while retrieving device details.", e);
} finally {
@@ -166,15 +192,15 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
deviceDAO.updateDevice(device, CarbonContext.getThreadLocalCarbonContext().getTenantId());
deviceDetailsDAO.deleteDeviceLocation(deviceLocation.getDeviceId());
deviceDetailsDAO.addDeviceLocation(deviceLocation);
- if (DeviceManagerUtil.isPublishLocationOperationResEnabled()) {
- Object metaData[] = {device.getDeviceIdentifier(), device.getType()};
- Object payload[] = new Object[]{
+ if (DeviceManagerUtil.isPublishOperationResponseEnabled()) {
+ Object[] metaData = {device.getDeviceIdentifier(), device.getType()};
+ Object[] payload = new Object[]{
deviceLocation.getUpdatedTime().getTime(),
deviceLocation.getLatitude(),
deviceLocation.getLongitude()
};
DeviceManagerUtil.getEventPublisherService().publishEvent(
- EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
+ LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
);
}
DeviceManagementDAOFactory.commitTransaction();
@@ -201,18 +227,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
@Override
public DeviceLocation getDeviceLocation(DeviceIdentifier deviceId) throws DeviceDetailsMgtException {
- Device device;
- try {
- device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false);
- if (device == null) {
- if (log.isDebugEnabled()) {
- log.debug("No device is found upon the device identifier '" + deviceId.getId() +
- "' and type '" + deviceId.getType() + "'. Therefore returning null");
- }
- return null;
- }
- } catch (DeviceManagementException e) {
- throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e);
+ Device device = getDevice(deviceId);
+ if (device == null) {
+ return null;
}
try {
DeviceManagementDAOFactory.openConnection();
@@ -226,6 +243,23 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
}
}
+ private Device getDevice(DeviceIdentifier deviceId) throws DeviceDetailsMgtException {
+ Device device;
+ try {
+ device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false);
+ if (device == null) {
+ if (log.isDebugEnabled()) {
+ log.debug("No device is found upon the device identifier '" + deviceId.getId() +
+ "' and type '" + deviceId.getType() + "'. Therefore returning null");
+ }
+ return null;
+ }
+ } catch (DeviceManagementException e) {
+ throw new DeviceDetailsMgtException("Exception occurred while retrieving the device.", e);
+ }
+ return device;
+ }
+
@Override
public List getDeviceLocations(
List deviceIdentifiers) throws DeviceDetailsMgtException {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java
index 36b56e357a..9110299009 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java
@@ -390,7 +390,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
}
- private EventProcessorAdminServiceStub getEventProcessorAdminServiceStub() throws JWTClientException {
+ protected EventProcessorAdminServiceStub getEventProcessorAdminServiceStub() throws JWTClientException {
//send alert to event-processing
String eventProcessorAdminServiceWSUrl = Utils.replaceSystemProperty(GeoServices.DAS_URL) +
"/services/EventProcessorAdminService";
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java
index 90867dbc3d..09e1eca4f9 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java
@@ -50,11 +50,9 @@ public class NotificationManagementServiceImpl implements NotificationManagement
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
private NotificationDAO notificationDAO;
- private DeviceDAO deviceDAO;
public NotificationManagementServiceImpl() {
this.notificationDAO = NotificationManagementDAOFactory.getNotificationDAO();
- this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
}
@Override
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java
index bf80177509..9ae0a693f4 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java
@@ -279,4 +279,4 @@ public abstract class AbstractNotificationDAOImpl implements NotificationDAO {
}
return notificationCountByStatus;
}
-}
\ 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/operation/mgt/OperationEnrolmentMapping.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationEnrolmentMapping.java
index 4bccaaca92..faa0eab13b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationEnrolmentMapping.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationEnrolmentMapping.java
@@ -25,12 +25,12 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
*/
public class OperationEnrolmentMapping {
- int enrolmentId;
- int tenantId;
- long createdTime;
- String deviceType;
- String deviceId;
- EnrolmentInfo.Status deviceStatus;
+ private int enrolmentId;
+ private int tenantId;
+ private long createdTime;
+ private String deviceType;
+ private String deviceId;
+ private EnrolmentInfo.Status deviceStatus;
public int getTenantId() {
return tenantId;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
index c22f3de950..ccb69a1e0b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
@@ -105,10 +105,6 @@ public class OperationManagerImpl implements OperationManager {
return notificationStrategy;
}
- public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
- this.notificationStrategy = notificationStrategy;
- }
-
public OperationManagerImpl(String deviceType, NotificationStrategy notificationStrategy) {
this(deviceType);
this.notificationStrategy = notificationStrategy;
@@ -122,7 +118,7 @@ public class OperationManagerImpl implements OperationManager {
log.debug("operation:[" + operation.toString() + "]");
for (DeviceIdentifier deviceIdentifier : deviceIds) {
log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" +
- deviceIdentifier.getType() + "]");
+ deviceIdentifier.getType() + "]");
}
}
try {
@@ -137,7 +133,7 @@ public class OperationManagerImpl implements OperationManager {
//Send the operation statuses only for admin triggered operations
String deviceType = validDeviceIds.get(0).getType();
activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult,
- deviceType));
+ deviceType));
return activity;
}
@@ -145,7 +141,7 @@ public class OperationManagerImpl implements OperationManager {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto =
OperationDAOUtil.convertOperation(operation);
int operationId = this.lookupOperationDAO(operation).addOperation(operationDto);
- boolean isScheduledOperation = this.isTaskScheduledOperation(operation, deviceIds);
+ boolean isScheduledOperation = this.isTaskScheduledOperation(operation);
boolean isNotRepeated = false;
boolean isScheduled = false;
@@ -160,7 +156,7 @@ public class OperationManagerImpl implements OperationManager {
boolean hasExistingTaskOperation;
int enrolmentId;
if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT == operationDto.
- getControl()) {
+ getControl()) {
isNotRepeated = true;
}
@@ -177,10 +173,10 @@ public class OperationManagerImpl implements OperationManager {
}
} else if (isNotRepeated) {
operationDAO.updateEnrollmentOperationsStatus(enrolmentId, operationCode,
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.
- Operation.Status.PENDING,
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.
- Operation.Status.REPEATED);
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.
+ Operation.Status.PENDING,
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.
+ Operation.Status.REPEATED);
operationMappingDAO.addOperationMapping(operationId, enrolmentId, isScheduled);
} else {
operationMappingDAO.addOperationMapping(operationId, enrolmentId, isScheduled);
@@ -200,8 +196,8 @@ public class OperationManagerImpl implements OperationManager {
operationMappingDAO.updateOperationMapping(operationId, enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.COMPLETED);
} catch (PushNotificationExecutionFailedException e) {
log.error("Error occurred while sending push notifications to " +
- deviceId.getType() + " device carrying id '" +
- deviceId + "'", e);
+ deviceId.getType() + " device carrying id '" +
+ deviceId + "'", e);
// Reschedule if push notification failed.
operationMappingDAO.updateOperationMapping(operationId, enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.SCHEDULED);
}
@@ -219,7 +215,7 @@ public class OperationManagerImpl implements OperationManager {
//Get the device-type from 1st valid DeviceIdentifier. We know the 1st element is definitely there.
String deviceType = validDeviceIds.get(0).getType();
activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult,
- deviceType));
+ deviceType));
}
return activity;
} else {
@@ -242,7 +238,7 @@ public class OperationManagerImpl implements OperationManager {
//Add the invalid DeviceIds
for (String id : deviceIdValidationResult.getErrorDeviceIdList()) {
activityStatus = new ActivityStatus();
- activityStatus.setDeviceIdentifier(new DeviceIdentifier(id,deviceType));
+ activityStatus.setDeviceIdentifier(new DeviceIdentifier(id, deviceType));
activityStatus.setStatus(ActivityStatus.Status.INVALID);
activityStatuses.add(activityStatus);
}
@@ -288,7 +284,7 @@ public class OperationManagerImpl implements OperationManager {
}
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" +
- this.getUser(), e);
+ this.getUser(), e);
}
deviceIDHolder.setValidDeviceIDList(authorizedDeviceList);
deviceIDHolder.setErrorDeviceIdList(unAuthorizedDeviceList);
@@ -310,8 +306,8 @@ public class OperationManagerImpl implements OperationManager {
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "'");
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
}
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
@@ -331,8 +327,8 @@ public class OperationManagerImpl implements OperationManager {
}
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
- "operations assigned for '" + deviceId.getType() +
- "' device '" + deviceId.getId() + "'", e);
+ "operations assigned for '" + deviceId.getType() +
+ "' device '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
@@ -348,18 +344,22 @@ public class OperationManagerImpl implements OperationManager {
PaginationResult paginationResult = null;
List operations = new ArrayList<>();
String owner = request.getOwner();
+ try {
+ if (!DeviceManagerUtil.isDeviceExists(deviceId)) {
+ throw new OperationManagementException("Device not found for given device " +
+ "Identifier:" + deviceId.getId() + " and given type : " +
+ deviceId.getType());
+ }
+ } catch (DeviceManagementException e) {
+ throw new OperationManagementException("Error while checking the existence of the device identifier - "
+ + deviceId.getId() + " of the device type - " + deviceId.getType(), e);
+ }
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "' of owner '" + owner + "'" );
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "' of owner '" + owner + "'");
}
-
EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, owner);
- if (enrolmentInfo == null) {
- throw new OperationManagementException("Device not found for given device " +
- "Identifier:" + deviceId.getId() + " and given type" +
- deviceId.getType());
- }
int enrolmentId = enrolmentInfo.getId();
try {
OperationManagementDAOFactory.openConnection();
@@ -376,8 +376,8 @@ public class OperationManagerImpl implements OperationManager {
paginationResult.setRecordsFiltered(count);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
- "operations assigned for '" + deviceId.getType() +
- "' device '" + deviceId.getId() + "'", e);
+ "operations assigned for '" + deviceId.getType() +
+ "' device '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
@@ -390,7 +390,7 @@ public class OperationManagerImpl implements OperationManager {
@Override
public List extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws
- OperationManagementException {
+ OperationManagementException {
if (log.isDebugEnabled()) {
log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]");
}
@@ -399,16 +399,16 @@ public class OperationManagerImpl implements OperationManager {
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "'");
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
}
//
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
if (enrolmentInfo == null) {
throw new OperationManagementException("Device not found for the given device Identifier:" +
- deviceId.getId() + " and given type:" +
- deviceId.getType());
+ deviceId.getId() + " and given type:" +
+ deviceId.getType());
}
int enrolmentId = enrolmentInfo.getId();
//Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
@@ -437,8 +437,8 @@ public class OperationManagerImpl implements OperationManager {
Collections.sort(operations, new OperationCreateTimeComparator());
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
- "pending operations assigned for '" + deviceId.getType() +
- "' device '" + deviceId.getId() + "'", e);
+ "pending operations assigned for '" + deviceId.getType() +
+ "' device '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
@@ -457,15 +457,15 @@ public class OperationManagerImpl implements OperationManager {
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "'");
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
}
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
if (enrolmentInfo == null) {
throw new OperationManagementException("Device not found for given device " +
- "Identifier:" + deviceId.getId() + " and given type" +
- deviceId.getType());
+ "Identifier:" + deviceId.getId() + " and given type" +
+ deviceId.getType());
}
int enrolmentId = enrolmentInfo.getId();
//Changing the enrollment status & attempt count if the device is marked as inactive or unreachable
@@ -479,23 +479,23 @@ public class OperationManagerImpl implements OperationManager {
try {
OperationManagementDAOFactory.openConnection();
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getNextOperation(
- enrolmentInfo.getId());
+ enrolmentInfo.getId());
if (dtoOperation != null) {
if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND.equals(dtoOperation.getType()
)) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
commandOperation =
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
- getOperation(dtoOperation.getId());
+ getOperation(dtoOperation.getId());
dtoOperation.setEnabled(commandOperation.isEnabled());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG.equals(dtoOperation.
- getType())) {
+ getType())) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE.equals(dtoOperation.
- getType())) {
+ getType())) {
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
} else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY.equals(dtoOperation.
- getType())) {
+ getType())) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
}
operation = OperationDAOUtil.convertOperation(dtoOperation);
@@ -520,26 +520,25 @@ public class OperationManagerImpl implements OperationManager {
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "'");
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
}
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
if (enrolmentInfo == null) {
throw new OperationManagementException(
"Device not found for device id:" + deviceId.getId() + " " + "type:" +
- deviceId.getType());
+ deviceId.getType());
}
try {
int enrolmentId = enrolmentInfo.getId();
OperationManagementDAOFactory.beginTransaction();
- boolean isUpdated = false;
if (operation.getStatus() != null) {
- isUpdated = operationDAO.updateOperationStatus(enrolmentId, operationId,
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.
- Operation.Status.valueOf(operation.getStatus().
- toString()));
+ operationDAO.updateOperationStatus(enrolmentId, operationId,
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.
+ Operation.Status.valueOf(operation.getStatus().
+ toString()));
}
if (operation.getOperationResponse() != null) {
operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse());
@@ -549,28 +548,7 @@ public class OperationManagerImpl implements OperationManager {
OperationManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException(
"Error occurred while updating the operation: " + operationId + " status:" +
- operation.getStatus(), e);
- } catch (TransactionManagementException e) {
- throw new OperationManagementException("Error occurred while initiating a transaction", e);
- } finally {
- OperationManagementDAOFactory.closeConnection();
- }
- }
-
- @Override
- public void deleteOperation(int operationId) throws OperationManagementException {
- try {
- OperationManagementDAOFactory.beginTransaction();
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation =
- operationDAO.getOperation(operationId);
- if (operation == null) {
- throw new OperationManagementException("Operation not found for operation id : " + operationId);
- }
- lookupOperationDAO(operation).deleteOperation(operationId);
- OperationManagementDAOFactory.commitTransaction();
- } catch (OperationManagementDAOException e) {
- OperationManagementDAOFactory.rollbackTransaction();
- throw new OperationManagementException("Error occurred while deleting the operation: " + operationId, e);
+ operation.getStatus(), e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
@@ -584,56 +562,57 @@ public class OperationManagerImpl implements OperationManager {
Operation operation = null;
if (log.isDebugEnabled()) {
log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " +
- deviceId.getId());
+ deviceId.getId());
}
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "'");
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
}
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
if (enrolmentInfo == null) {
throw new OperationManagementException("Device not found for given device identifier: " +
- deviceId.getId() + " type: " + deviceId.getType());
+ deviceId.getId() + " type: " + deviceId.getType());
}
try {
OperationManagementDAOFactory.openConnection();
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.
- getOperationByDeviceAndId(enrolmentInfo.getId(),
- operationId);
- if (dtoOperation.getType().
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation deviceSpecificOperation = operationDAO.
+ getOperationByDeviceAndId(enrolmentInfo.getId(),
+ operationId);
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = deviceSpecificOperation;
+ if (deviceSpecificOperation.getType().
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
commandOperation =
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
- getOperation(dtoOperation.getId());
+ getOperation(deviceSpecificOperation.getId());
dtoOperation.setEnabled(commandOperation.isEnabled());
- } else if (dtoOperation.getType().
+ } else if (deviceSpecificOperation.getType().
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
- dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
- } else if (dtoOperation.getType().equals(
+ dtoOperation = configOperationDAO.getOperation(deviceSpecificOperation.getId());
+ } else if (deviceSpecificOperation.getType().equals(
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) {
- dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
- } else if (dtoOperation.getType().equals(
+ dtoOperation = profileOperationDAO.getOperation(deviceSpecificOperation.getId());
+ } else if (deviceSpecificOperation.getType().equals(
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) {
- dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
+ dtoOperation = policyOperationDAO.getOperation(deviceSpecificOperation.getId());
}
-
if (dtoOperation == null) {
throw new OperationManagementException("Operation not found for operation Id:" + operationId +
- " device id:" + deviceId.getId());
+ " device id:" + deviceId.getId());
}
- operation = OperationDAOUtil.convertOperation(dtoOperation);
+ dtoOperation.setStatus(deviceSpecificOperation.getStatus());
+ operation = OperationDAOUtil.convertOperation(deviceSpecificOperation);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
- "operations assigned for '" + deviceId.getType() +
- "' device '" + deviceId.getId() + "'", e);
+ "operations assigned for '" + deviceId.getType() +
+ "' device '" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening connection to the data source",
- e);
+ e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
@@ -649,15 +628,15 @@ public class OperationManagerImpl implements OperationManager {
if (!isActionAuthorized(deviceId)) {
throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
- deviceId.getType() + "' device, which carries the identifier '" +
- deviceId.getId() + "'");
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
}
EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId);
if (enrolmentInfo == null) {
throw new OperationManagementException(
"Device not found for device id:" + deviceId.getId() + " " + "type:" +
- deviceId.getType());
+ deviceId.getType());
}
try {
@@ -667,14 +646,14 @@ public class OperationManagerImpl implements OperationManager {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString());
dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus));
dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
- Status.PENDING));
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
+ Status.PENDING));
dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
- Status.PENDING));
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
+ Status.PENDING));
dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId,
- org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
- Status.PENDING));
+ org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.
+ Status.PENDING));
Operation operation;
@@ -685,9 +664,9 @@ public class OperationManagerImpl implements OperationManager {
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the list of " +
- "operations assigned for '" + deviceId.getType() +
- "' device '" +
- deviceId.getId() + "' and status:" + status.toString(), e);
+ "operations assigned for '" + deviceId.getType() +
+ "' device '" +
+ deviceId.getId() + "' and status:" + status.toString(), e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
@@ -703,32 +682,32 @@ public class OperationManagerImpl implements OperationManager {
try {
OperationManagementDAOFactory.openConnection();
org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getOperation(
- operationId);
+ operationId);
if (dtoOperation == null) {
throw new OperationManagementException("Operation not found for given Id:" + operationId);
}
if (dtoOperation.getType()
- .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
+ .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
commandOperation =
(org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
- getOperation(dtoOperation.getId());
+ getOperation(dtoOperation.getId());
dtoOperation.setEnabled(commandOperation.isEnabled());
} else if (dtoOperation.getType().
equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
} else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
- PROFILE)) {
+ PROFILE)) {
dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
} else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
- POLICY)) {
+ POLICY)) {
dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
}
operation = OperationDAOUtil.convertOperation(dtoOperation);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the operation with operation Id '" +
- operationId, e);
+ operationId, e);
} catch (SQLException e) {
throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
} finally {
@@ -737,62 +716,6 @@ public class OperationManagerImpl implements OperationManager {
return operation;
}
- // @Override
- // public Operation getOperationByActivityId(String activity) throws OperationManagementException {
- // // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
- // Operation operation;
- // int enrollmentOpMappingId = Integer.parseInt(
- // activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, ""));
- // if (enrollmentOpMappingId == 0) {
- // throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
- // }
- // try {
- // OperationManagementDAOFactory.openConnection();
- // org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation =
- // operationDAO.getOperationFromEnrollment(enrollmentOpMappingId);
- //
- // if (dtoOperation == null) {
- // throw new OperationManagementException("Operation not found for given activity Id:" + activity);
- // }
- // org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status status = dtoOperation.getStatus();
- // if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) {
- // org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation;
- // commandOperation =
- // (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO.
- // getOperation(dtoOperation.getId());
- // dtoOperation.setEnabled(commandOperation.isEnabled());
- // } else if (dtoOperation.getType().
- // equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) {
- // dtoOperation = configOperationDAO.getOperation(dtoOperation.getId());
- // } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
- // PROFILE)) {
- // dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId());
- // } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.
- // POLICY)) {
- // dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId());
- // }
- // operation = OperationDAOUtil.convertOperation(dtoOperation);
- // int enrolmentId = operationDAO.getEnrolmentIdFromMappingId(enrollmentOpMappingId);
- // if (enrolmentId != 0) {
- // operation.setResponses(operationDAO.getOperationResponses(enrolmentId, operation.getId()));
- // }
- //
- // operation.setStatus(Operation.Status.valueOf(status.toString()));
- // operation.setActivityId(activity);
- //
- // } catch (SQLException e) {
- // throw new OperationManagementException("Error occurred while opening a connection to the data source", e);
- // } catch (OperationManagementDAOException e) {
- // throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" +
- // activity, e);
- // } finally {
- // OperationManagementDAOFactory.closeConnection();
- // }
- //
- // // return this.getOperation(operationId);
- // return operation;
- // }
-
@Override
public Activity getOperationByActivityId(String activity) throws OperationManagementException {
// This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer.
@@ -808,7 +731,7 @@ public class OperationManagerImpl implements OperationManager {
throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" +
- activity, e);
+ activity, e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
@@ -821,7 +744,11 @@ public class OperationManagerImpl implements OperationManager {
if (operationId == 0) {
throw new IllegalArgumentException("Operation ID cannot be null or zero (0).");
}
-
+ if (!isActionAuthorized(deviceId)) {
+ throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" +
+ deviceId.getType() + "' device, which carries the identifier '" +
+ deviceId.getId() + "'");
+ }
Device device = this.getDevice(deviceId);
try {
OperationManagementDAOFactory.openConnection();
@@ -836,26 +763,6 @@ public class OperationManagerImpl implements OperationManager {
}
}
- @Override
- public List getOperationUpdatedAfter(long timestamp) throws OperationManagementException {
- return null;
- }
-
- @Override
- public List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
- try {
- OperationManagementDAOFactory.openConnection();
- return operationDAO.getActivitiesUpdatedAfter(timestamp);
- } catch (SQLException e) {
- throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
- } catch (OperationManagementDAOException e) {
- throw new OperationManagementException("Error occurred while getting the activity list changed after a " +
- "given time.", e);
- } finally {
- OperationManagementDAOFactory.closeConnection();
- }
- }
-
@Override
public List getActivitiesUpdatedAfter(long timestamp, int limit,
int offset) throws OperationManagementException {
@@ -866,7 +773,7 @@ public class OperationManagerImpl implements OperationManager {
throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while getting the activity list changed after a " +
- "given time.", e);
+ "given time.", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
@@ -881,7 +788,7 @@ public class OperationManagerImpl implements OperationManager {
throw new OperationManagementException("Error occurred while opening a connection to the data source.", e);
} catch (OperationManagementDAOException e) {
throw new OperationManagementException("Error occurred while getting the activity count changed after a " +
- "given time.", e);
+ "given time.", e);
} finally {
OperationManagementDAOFactory.closeConnection();
}
@@ -902,19 +809,6 @@ public class OperationManagerImpl implements OperationManager {
}
}
- private OperationDAO lookupOperationDAO(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operation) {
-
- if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) {
- return commandOperationDAO;
- } else if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.ProfileOperation) {
- return profileOperationDAO;
- } else if (operation instanceof org.wso2.carbon.device.mgt.core.dto.operation.mgt.ConfigOperation) {
- return configOperationDAO;
- } else {
- return operationDAO;
- }
- }
-
private String getUser() {
return CarbonContext.getThreadLocalCarbonContext().getUsername();
}
@@ -957,26 +851,6 @@ public class OperationManagerImpl implements OperationManager {
return isUserAuthorized;
}
- private int getEnrolmentByStatus(DeviceIdentifier deviceId,
- EnrolmentInfo.Status status) throws OperationManagementException {
- int enrolmentId;
- try {
- DeviceManagementDAOFactory.openConnection();
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, status, tenantId);
- } catch (DeviceManagementDAOException e) {
- throw new OperationManagementException("Error occurred while retrieving metadata of '" +
- deviceId.getType() + "' device carrying the identifier '" +
- deviceId.getId() + "'", e);
- } catch (SQLException e) {
- throw new OperationManagementException(
- "Error occurred while opening a connection to the data source", e);
- } finally {
- DeviceManagementDAOFactory.closeConnection();
- }
- return enrolmentId;
- }
-
private EnrolmentInfo getEnrolmentInfo(DeviceIdentifier deviceId, String owner) throws OperationManagementException {
EnrolmentInfo enrolmentInfo = null;
try {
@@ -995,15 +869,15 @@ public class OperationManagerImpl implements OperationManager {
}
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving enrollment data of '" +
- deviceId.getType() + "' device carrying the identifier '" +
- deviceId.getId() + "' of owner '" + owner + "'", e);
+ deviceId.getType() + "' device carrying the identifier '" +
+ deviceId.getId() + "' of owner '" + owner + "'", e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
} catch (DeviceAccessAuthorizationException e) {
throw new OperationManagementException("Error occurred while checking the device access permissions for '" +
- deviceId.getType() + "' device carrying the identifier '" +
- deviceId.getId() + "' of owner '" + owner + "'", e);
+ deviceId.getType() + "' device carrying the identifier '" +
+ deviceId.getId() + "' of owner '" + owner + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
@@ -1018,8 +892,8 @@ public class OperationManagerImpl implements OperationManager {
enrolmentInfo = deviceDAO.getActiveEnrolment(deviceId, tenantId);
} catch (DeviceManagementDAOException e) {
throw new OperationManagementException("Error occurred while retrieving enrollment data of '" +
- deviceId.getType() + "' device carrying the identifier '" +
- deviceId.getId() + "'", e);
+ deviceId.getType() + "' device carrying the identifier '" +
+ deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new OperationManagementException(
"Error occurred while opening a connection to the data source", e);
@@ -1040,7 +914,7 @@ public class OperationManagerImpl implements OperationManager {
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new OperationManagementException("Error occurred while updating enrollment status of device of " +
- "enrolment-id '" + enrolmentId + "'", e);
+ "enrolment-id '" + enrolmentId + "'", e);
} catch (TransactionManagementException e) {
throw new OperationManagementException("Error occurred while initiating a transaction", e);
} finally {
@@ -1049,39 +923,15 @@ public class OperationManagerImpl implements OperationManager {
return updateStatus;
}
- private boolean isTaskScheduledOperation(Operation operation, List deviceIds) {
+ private boolean isTaskScheduledOperation(Operation operation) {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance().
getDeviceManagementProvider();
-
List monitoringOperations = deviceManagementProviderService.getMonitoringOperationList(deviceType);//Get task list from each device type
-
- for(MonitoringOperation op : monitoringOperations){
+ for (MonitoringOperation op : monitoringOperations) {
if (operation.getCode().equals(op.getTaskName())) {
return true;
}
}
-
-// for(String dti : taskOperation){
-// if (dti.equals(deviceType)) {
-// monitoringOperations = deviceTypeSpecificTasks.get(dti);
-//
-// }
-// }
-//
-// for(DeviceIdentifier deviceIdentifier : deviceIds){
-// String deviceType = deviceIdentifier.getType();
-//
-//
-//
-// }
-
-// TaskConfiguration taskConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
-// getTaskConfiguration();
-// for (TaskConfiguration.Operation op : taskConfiguration.getOperations()) {
-// if (operation.getCode().equals(op.getOperationName())) {
-// return true;
-// }
-// }
return false;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMgtConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMgtConstants.java
index cd39b73060..8da340170a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMgtConstants.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationMgtConstants.java
@@ -22,18 +22,15 @@ public class OperationMgtConstants {
public final class DeviceConstants {
private DeviceConstants() {
- throw new AssertionError();
}
public static final String DEVICE_ID_NOT_FOUND = "Device not found for device id: %s";
- public static final String DEVICE_ID_SERVICE_NOT_FOUND =
- "Issue in retrieving device management service instance for device found at %s";
}
public final class OperationCodes {
private OperationCodes() {
- throw new AssertionError();
}
+
public static final String POLICY_REVOKE = "POLICY_REVOKE";
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java
index dc9b6dfb9a..e58341da8a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java
@@ -31,14 +31,8 @@ public interface OperationDAO {
int addOperation(Operation operation) throws OperationManagementDAOException;
- void updateOperation(Operation operation) throws OperationManagementDAOException;
-
- void deleteOperation(int operationId) throws OperationManagementDAOException;
-
Operation getOperation(int operationId) throws OperationManagementDAOException;
- Operation getOperationFromEnrollment(int enrollmentOpMappingId) throws OperationManagementDAOException;
-
Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException;
List extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status)
@@ -66,24 +60,14 @@ public interface OperationDAO {
void addOperationResponse(int enrolmentId, int operationId, Object operationResponse)
throws OperationManagementDAOException;
- List getOperationResponses(int enrolmentId, int operationId) throws OperationManagementDAOException;
-
Activity getActivity(int operationId) throws OperationManagementDAOException;
Activity getActivityByDevice(int operationId, int deviceId) throws OperationManagementDAOException;
- int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException;
-
- List getOperationsUpdatedAfter(long timestamp) throws OperationManagementDAOException;
-
- List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementDAOException;
-
List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException;
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementDAOException;
- boolean resetAttemptCount(int enrolmentId) throws OperationManagementDAOException;
-
/**
* This method provides operation mappings for given status
* @param opStatus Operation status
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java
index b28b773d7b..aa5d9b7bea 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java
@@ -18,6 +18,7 @@
*/
package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
+import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
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/CommandOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java
index fcf57ab022..ca5c5a46ea 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java
@@ -53,39 +53,6 @@ public class CommandOperationDAOImpl extends GenericOperationDAOImpl {
return operationId;
}
- @Override
- public void updateOperation(Operation operation) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement(
- "UPDATE DM_COMMAND_OPERATION SET ENABLED = ? WHERE OPERATION_ID = ?");
- stmt.setBoolean(1, operation.isEnabled());
- stmt.setInt(2, operation.getId());
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while adding operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
- @Override
- public void deleteOperation(int id) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- super.deleteOperation(id);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("DELETE FROM DM_COMMAND_OPERATION WHERE OPERATION_ID = ?");
- stmt.setInt(1, id);
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
public CommandOperation getOperation(int id) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
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/ConfigOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java
index 82beb1b5f0..6b08254c4d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java
@@ -32,6 +32,7 @@ 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.List;
@@ -45,6 +46,7 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl {
PreparedStatement stmt = null;
try {
operationId = super.addOperation(operation);
+ operation.setCreatedTimeStamp(new Timestamp(new java.util.Date().getTime()).toString());
Connection conn = OperationManagementDAOFactory.getConnection();
stmt = conn.prepareStatement("INSERT INTO DM_CONFIG_OPERATION(OPERATION_ID, OPERATION_CONFIG) VALUES(?, ?)");
stmt.setInt(1, operationId);
@@ -58,62 +60,6 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl {
return operationId;
}
- @Override
- public void deleteOperation(int id) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- super.deleteOperation(id);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("DELETE FROM DM_CONFIG_OPERATION WHERE OPERATION_ID = ?") ;
- stmt.setInt(1, id);
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
- @Override
- public void updateOperation(Operation operation) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- ByteArrayOutputStream bao = null;
- ObjectOutputStream oos = null;
- try {
- super.updateOperation(operation);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("UPDATE FROM DM_CONFIG_OPERATION SET OPERATION_CONFIG = ? " +
- "WHERE OPERATION_ID = ?");
- bao = new ByteArrayOutputStream();
- oos = new ObjectOutputStream(bao);
- oos.writeObject(operation);
-
- stmt.setBytes(1, bao.toByteArray());
- stmt.setInt(2, operation.getId());
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while update policy operation metadata", e);
- } catch (IOException e) {
- throw new OperationManagementDAOException("Error occurred while serializing policy operation object", e);
- } finally {
- if (bao != null) {
- try {
- bao.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ByteArrayOutputStream", e);
- }
- }
- if (oos != null) {
- try {
- oos.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ObjectOutputStream", e);
- }
- }
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
@Override
public Operation getOperation(int operationId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
@@ -134,6 +80,8 @@ public class ConfigOperationDAOImpl extends GenericOperationDAOImpl {
bais = new ByteArrayInputStream(operationDetails);
ois = new ObjectInputStream(bais);
configOperation = (ConfigOperation) ois.readObject();
+ configOperation.setId(rs.getInt("OPERATION_ID"));
+ configOperation.setEnabled(rs.getBoolean("ENABLED"));
}
} catch (IOException e) {
throw new OperationManagementDAOException("IO Error occurred while de serialize the policy operation " +
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 7e174ec714..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
@@ -85,23 +85,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
}
- @Override
- public void updateOperation(Operation operation) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("UPDATE DM_OPERATION SET RECEIVED_TIMESTAMP=? " +
- "WHERE ID=?");
- stmt.setTimestamp(1, new Timestamp(new Date().getTime()));
- stmt.setInt(2, operation.getId());
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while update operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
public boolean updateOperationStatus(int enrolmentId, int operationId, Operation.Status status)
throws OperationManagementDAOException {
PreparedStatement stmt = null;
@@ -249,68 +232,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
}
}
- @Override
- public List getOperationResponses(int enrolmentId, int operationId) throws
- OperationManagementDAOException {
-
- PreparedStatement stmt = null;
- ResultSet rs = null;
- List responces = new ArrayList<>();
- try {
- Connection conn = OperationManagementDAOFactory.getConnection();
- String sql = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE WHERE ENROLMENT_ID = ? AND OPERATION_ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, enrolmentId);
- stmt.setInt(2, operationId);
- rs = stmt.executeQuery();
-
- while (rs.next()) {
- OperationResponse response = new OperationResponse();
- response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString());
- ByteArrayInputStream bais = null;
- ObjectInputStream ois = null;
- byte[] contentBytes;
- try {
- contentBytes = (byte[]) rs.getBytes("OPERATION_RESPONSE");
- bais = new ByteArrayInputStream(contentBytes);
- ois = new ObjectInputStream(bais);
- response.setResponse(ois.readObject().toString());
-
- } finally {
- if (bais != null) {
- try {
- bais.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ByteArrayOutputStream", e);
- }
- }
- if (ois != null) {
- try {
- ois.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ObjectOutputStream", e);
- }
- }
- }
- responces.add(response);
- }
-
- } catch (SQLException e) {
- throw new OperationManagementDAOException("SQL Error occurred while retrieving the operation responses for " +
- "operation id " + operationId + " and enrolment id " + enrolmentId, e);
- } catch (ClassNotFoundException e) {
- throw new OperationManagementDAOException("Error occurred while converting the operation responses to string" +
- " for operation id " + operationId + " and enrolment id " + enrolmentId, e);
- } catch (IOException e) {
- throw new OperationManagementDAOException("Error occurred while converting the operation responses to string" +
- " for operation id " + operationId + " and enrolment id " + enrolmentId, e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt, rs);
- }
-
- return responces;
- }
-
@Override
public Activity getActivity(int operationId) throws OperationManagementDAOException {
@@ -465,11 +386,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
return activity;
}
- @Override
- public List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementDAOException {
- return this.getActivitiesUpdatedAfter(timestamp, 0, 0);
- }
-
@Override
public List getActivitiesUpdatedAfter(long timestamp, int limit,
int offset) throws OperationManagementDAOException {
@@ -478,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, " +
@@ -674,80 +568,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
return 0;
}
- @Override
- public int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- ResultSet rs = null;
- try {
- Connection conn = OperationManagementDAOFactory.getConnection();
- String sql = "SELECT * FROM DM_ENROLMENT_OP_MAPPING WHERE ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, enrollmentOpMappingId);
- rs = stmt.executeQuery();
-
- if (rs.next()) {
- return rs.getInt("ENROLMENT_ID");
- }
-
- } catch (SQLException e) {
- throw new OperationManagementDAOException("SQL Error occurred while retrieving the enrolment id " +
- " for the mapping id '" + enrollmentOpMappingId, e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt, rs);
- }
- return -1;
- }
-
- @Override
- public List getOperationsUpdatedAfter(long timestamp) throws OperationManagementDAOException {
-
- PreparedStatement stmt = null;
- ResultSet rs = null;
- List operations = new ArrayList<>();
- try {
- Connection conn = OperationManagementDAOFactory.getConnection();
- String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE " +
- "FROM DM_OPERATION AS o \n" +
- "INNER JOIN DM_ENROLMENT_OP_MAPPING AS eom ON eom.OPERATION_ID=o.ID WHERE eom.UPDATED_TIMESTAMP = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setLong(1, timestamp);
- rs = stmt.executeQuery();
-
- if (rs.next()) {
- Operation operation = new Operation();
- operation.setId(rs.getInt("ID"));
- operation.setType(Operation.Type.valueOf(rs.getString("TYPE")));
- operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString());
- operation.setCode(rs.getString("OPERATION_CODE"));
-
- operations.add(operation);
- }
-
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while retrieving the operations updated " +
- "after a given time", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt, rs);
- }
- return operations;
- }
-
-
- @Override
- public void deleteOperation(int id) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("DELETE FROM DM_OPERATION WHERE ID = ?");
- stmt.setInt(1, id);
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
@Override
public Operation getOperation(int id) throws OperationManagementDAOException {
PreparedStatement stmt = null;
@@ -783,49 +603,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
return operation;
}
- @Override
- public Operation getOperationFromEnrollment(int enrollmentOpMappingId) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- ResultSet rs = null;
- Operation operation = null;
- try {
- Connection conn = OperationManagementDAOFactory.getConnection();
- String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE, \n" +
- " om.STATUS, om.UPDATED_TIMESTAMP FROM DM_OPERATION o \n" +
- "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm WHERE dm.ID = ? ) om \n" +
- "ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC ";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, enrollmentOpMappingId);
- rs = stmt.executeQuery();
-
- if (rs.next()) {
- operation = new Operation();
- 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 {
- operation.setReceivedTimeStamp(
- new java.sql.Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString());
- }
- operation.setCode(rs.getString("OPERATION_CODE"));
- operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
- OperationDAOUtil.setActivityId(operation, rs.getInt("ID"));
- }
- } catch (SQLException e) {
- throw new OperationManagementDAOException("SQL error occurred while retrieving the operation .", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt, rs);
- }
- return operation;
- }
-
@Override
public Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
@@ -833,9 +610,9 @@ public class GenericOperationDAOImpl implements OperationDAO {
Operation operation = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
- String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.STATUS, o.OPERATION_CODE, " +
+ String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, om.STATUS, o.OPERATION_CODE, " +
"om.ID AS OM_MAPPING_ID, " +
- "om.UPDATED_TIMESTAMP FROM (SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, STATUS," +
+ "om.UPDATED_TIMESTAMP FROM (SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP," +
"OPERATION_CODE FROM DM_OPERATION WHERE id = ?) o INNER JOIN (SELECT * FROM " +
"DM_ENROLMENT_OP_MAPPING dm where dm.OPERATION_ID = ? AND dm.ENROLMENT_ID = ?) om " +
"ON o.ID = om.OPERATION_ID ";
@@ -850,11 +627,7 @@ 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());
-// }
+ operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS")));
if (rs.getLong("UPDATED_TIMESTAMP") == 0) {
operation.setReceivedTimeStamp("");
} else {
@@ -896,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 {
@@ -1176,31 +944,6 @@ public class GenericOperationDAOImpl implements OperationDAO {
return operations;
}
- @Override
- public boolean resetAttemptCount(int enrolmentId) throws OperationManagementDAOException {
- boolean status = false;
- Connection conn;
- PreparedStatement stmt = null;
- Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
- try {
- conn = OperationManagementDAOFactory.getConnection();
- String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = 0, LAST_REQUESTED_TIME = ? " +
- "WHERE ENROLMENT_ID = ? AND TENANT_ID = ?";
- stmt = conn.prepareStatement(query);
- stmt.setTimestamp(1, currentTimestamp);
- stmt.setInt(2, enrolmentId);
- stmt.setInt(3, tenantId);
- stmt.executeUpdate();
- status = true;
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Unable to reset the attempt count in database.", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt, null);
- }
- return status;
- }
-
@Override
public Map> getOperationMappingsByStatus(Operation.Status opStatus, Operation.PushNotificationStatus pushNotificationStatus,
int limit) throws OperationManagementDAOException {
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/PolicyOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java
index 4c0243ac80..7f142b7d04 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java
@@ -82,62 +82,6 @@ public class PolicyOperationDAOImpl extends GenericOperationDAOImpl {
return operationId;
}
- @Override
- public void updateOperation(Operation operation) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- ByteArrayOutputStream bao = null;
- ObjectOutputStream oos = null;
- try {
- super.updateOperation(operation);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("UPDATE DM_POLICY_OPERATION SET OPERATION_DETAILS=? " +
- "WHERE OPERATION_ID=?");
- bao = new ByteArrayOutputStream();
- oos = new ObjectOutputStream(bao);
- oos.writeObject(operation);
-
- stmt.setBytes(1, bao.toByteArray());
- stmt.setInt(2, operation.getId());
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while update policy operation metadata", e);
- } catch (IOException e) {
- throw new OperationManagementDAOException("Error occurred while serializing policy operation object", e);
- } finally {
- if (bao != null) {
- try {
- bao.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ByteArrayOutputStream", e);
- }
- }
- if (oos != null) {
- try {
- oos.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ObjectOutputStream", e);
- }
- }
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
- @Override
- public void deleteOperation(int operationId) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- super.deleteOperation(operationId);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("DELETE FROM DM_POLICY_OPERATION WHERE OPERATION_ID=?");
- stmt.setInt(1, operationId);
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
@Override
public Operation getOperation(int operationId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
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/ProfileOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java
index 931cc079f4..9223b3c030 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java
@@ -82,63 +82,6 @@ public class ProfileOperationDAOImpl extends GenericOperationDAOImpl {
return operationId;
}
- @Override
- public void updateOperation(Operation operation) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- ByteArrayOutputStream bao = null;
- ObjectOutputStream oos = null;
- try {
- super.updateOperation(operation);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("UPDATE DM_PROFILE_OPERATION SET OPERATION_DETAILS=? " +
- "WHERE OPERATION_ID=?");
-
- bao = new ByteArrayOutputStream();
- oos = new ObjectOutputStream(bao);
- oos.writeObject(operation);
-
- stmt.setBytes(1, bao.toByteArray());
- stmt.setInt(2, operation.getId());
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while update operation metadata", e);
- } catch (IOException e) {
- throw new OperationManagementDAOException("Error occurred while serializing profile operation object", e);
- } finally {
- if (bao != null) {
- try {
- bao.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ByteArrayOutputStream", e);
- }
- }
- if (oos != null) {
- try {
- oos.close();
- } catch (IOException e) {
- log.warn("Error occurred while closing ObjectOutputStream", e);
- }
- }
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
- @Override
- public void deleteOperation(int id) throws OperationManagementDAOException {
- PreparedStatement stmt = null;
- try {
- super.deleteOperation(id);
- Connection connection = OperationManagementDAOFactory.getConnection();
- stmt = connection.prepareStatement("DELETE FROM DM_PROFILE_OPERATION WHERE OPERATION_ID=?");
- stmt.setInt(1, id);
- stmt.executeUpdate();
- } catch (SQLException e) {
- throw new OperationManagementDAOException("Error occurred while deleting operation metadata", e);
- } finally {
- OperationManagementDAOUtil.cleanupResources(stmt);
- }
- }
-
public Operation getOperation(int id) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java
index 5262fe2e2b..ff402f7e97 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java
@@ -22,7 +22,11 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
-import org.wso2.carbon.device.mgt.core.dto.operation.mgt.*;
+import org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation;
+import org.wso2.carbon.device.mgt.core.dto.operation.mgt.ConfigOperation;
+import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
+import org.wso2.carbon.device.mgt.core.dto.operation.mgt.PolicyOperation;
+import org.wso2.carbon.device.mgt.core.dto.operation.mgt.ProfileOperation;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -32,6 +36,7 @@ import java.sql.SQLException;
public class OperationDAOUtil {
private static final Log log = LogFactory.getLog(OperationDAOUtil.class);
+
public static Operation convertOperation(org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation) {
Operation dtoOperation = null;
@@ -40,28 +45,28 @@ public class OperationDAOUtil {
dtoOperation = new CommandOperation();
} else if (operation.getType().equals(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.PROFILE)) {
dtoOperation = new ProfileOperation();
- }else if(operation.getType().equals(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.POLICY)){
+ } else if (operation.getType().equals(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.POLICY)) {
dtoOperation = new PolicyOperation();
- }else if(operation.getType().equals(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.CONFIG)) {
+ } else if (operation.getType().equals(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.CONFIG)) {
dtoOperation = new ConfigOperation();
- }else{
+ } else {
dtoOperation = new Operation();
}
dtoOperation.setEnabled(operation.isEnabled());
dtoOperation.setCode(operation.getCode());
- if (operation.getType() != null){
+ if (operation.getType() != null) {
dtoOperation.setType(Operation.Type.valueOf(operation.getType().toString()));
- }else{
+ } else {
dtoOperation.setType(null);
}
dtoOperation.setCreatedTimeStamp(operation.getCreatedTimeStamp());
- if (operation.getStatus() != null){
+ if (operation.getStatus() != null) {
dtoOperation.setStatus(Operation.Status.valueOf(operation.getStatus().toString()));
- }else{
+ } else {
dtoOperation.setStatus(null);
}
@@ -70,31 +75,35 @@ public class OperationDAOUtil {
dtoOperation.setReceivedTimeStamp(operation.getReceivedTimeStamp());
dtoOperation.setProperties(operation.getProperties());
+ if (operation.getControl() != null) {
+ dtoOperation.setControl(Operation.Control.valueOf(operation.getControl().toString()));
+ }
+
return dtoOperation;
}
- public static org.wso2.carbon.device.mgt.common.operation.mgt.Operation convertOperation(Operation dtoOperation){
+ public static org.wso2.carbon.device.mgt.common.operation.mgt.Operation convertOperation(Operation dtoOperation) {
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
-
- if (dtoOperation.getType().equals(Operation.Type.COMMAND)){
+
+ if (dtoOperation.getType().equals(Operation.Type.COMMAND)) {
operation = new org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation();
- }else if(dtoOperation.getType().equals(Operation.Type.PROFILE)){
+ } else if (dtoOperation.getType().equals(Operation.Type.PROFILE)) {
operation = new org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation();
- }else{
+ } else {
operation = new org.wso2.carbon.device.mgt.common.operation.mgt.Operation();
}
operation.setEnabled(dtoOperation.isEnabled());
operation.setCode(dtoOperation.getCode());
- if(dtoOperation.getType() != null) {
+ if (dtoOperation.getType() != null) {
operation.setType(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.valueOf(dtoOperation
.getType().toString()));
}
operation.setCreatedTimeStamp(dtoOperation.getCreatedTimeStamp());
- if(dtoOperation.getStatus() != null) {
+ if (dtoOperation.getStatus() != null) {
operation.setStatus(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Status.valueOf(dtoOperation
.getStatus().toString()));
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java
deleted file mode 100644
index 79ffacb370..0000000000
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java
+++ /dev/null
@@ -1,154 +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.push.notification.mgt;
-
-import org.wso2.carbon.device.mgt.common.*;
-import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
-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.NotificationContext;
-import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
-import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException;
-
-import java.util.List;
-
-public class PushNotificationBasedOperationManager implements OperationManager {
-
- private OperationManager operationManager;
- private NotificationStrategy notificationProvider;
-
- public PushNotificationBasedOperationManager(
- OperationManager operationManager, NotificationStrategy notificationProvider) {
- this.operationManager = operationManager;
- this.notificationProvider = notificationProvider;
- }
-
- @Override
- public Activity addOperation(Operation operation,
- List devices) throws OperationManagementException, InvalidDeviceException {
- Activity activity = this.operationManager.addOperation(operation, devices);
- for (DeviceIdentifier deviceId : devices) {
- try {
- this.notificationProvider.execute(new NotificationContext(deviceId, operation));
- } catch (PushNotificationExecutionFailedException e) {
- throw new OperationManagementException("Error occurred while sending push notification to device", e);
- }
- }
- return activity;
- }
-
- @Override
- public List extends Operation> getOperations(
- DeviceIdentifier deviceId) throws OperationManagementException {
- return this.operationManager.getOperations(deviceId);
- }
-
- @Override
- public PaginationResult getOperations(DeviceIdentifier deviceId,
- PaginationRequest request) throws OperationManagementException {
- return this.operationManager.getOperations(deviceId, request);
- }
-
- @Override
- public List extends Operation> getPendingOperations(
- DeviceIdentifier deviceId) throws OperationManagementException {
- return this.operationManager.getPendingOperations(deviceId);
- }
-
- @Override
- public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException {
- return this.operationManager.getNextPendingOperation(deviceId);
- }
-
- @Override
- public void updateOperation(DeviceIdentifier deviceId,
- Operation operation) throws OperationManagementException {
- this.operationManager.updateOperation(deviceId, operation);
- }
-
- @Override
- public void deleteOperation(int operationId) throws OperationManagementException {
- this.operationManager.deleteOperation(operationId);
- }
-
- @Override
- public Operation getOperationByDeviceAndOperationId(
- DeviceIdentifier deviceId, int operationId) throws OperationManagementException {
- return this.operationManager.getOperationByDeviceAndOperationId(deviceId, operationId);
- }
-
- @Override
- public List extends Operation> getOperationsByDeviceAndStatus(
- DeviceIdentifier deviceId,
- Operation.Status status) throws OperationManagementException {
- try {
- return this.operationManager.getOperationsByDeviceAndStatus(deviceId, status);
- } catch (DeviceManagementException e) {
- throw new OperationManagementException("Error occurred while retrieving the list of operations by " +
- "device and status", e);
- }
- }
-
- @Override
- public Operation getOperation(int operationId) throws OperationManagementException {
- return this.operationManager.getOperation(operationId);
- }
-
- @Override
- public Activity getOperationByActivityId(String activity) throws OperationManagementException {
- return this.operationManager.getOperationByActivityId(activity);
- }
-
- @Override
- public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException {
- return this.operationManager.getOperationByActivityIdAndDevice(activity, deviceId);
- }
-
- @Override
- public List getOperationUpdatedAfter(long timestamp) throws OperationManagementException {
- return this.operationManager.getOperationUpdatedAfter(timestamp);
- }
-
- @Override
- public List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
- return this.operationManager.getActivitiesUpdatedAfter(timestamp);
- }
-
- @Override
- public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException {
- return this.operationManager.getActivitiesUpdatedAfter(timestamp, limit, offset);
- }
-
- @Override
- public int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException {
- return this.operationManager.getActivityCountUpdatedAfter(timestamp);
- }
-
- @Override
- public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
-
- }
-
- @Override
- public NotificationStrategy getNotificationStrategy() {
- return notificationProvider;
- }
-
-}
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/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java
index ffd559b1ad..ff278493f9 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java
@@ -481,8 +481,6 @@ public interface DeviceManagementProviderService {
*/
PlatformConfiguration getConfiguration(String deviceType) throws DeviceManagementException;
- void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException;
-
/**
* This method is used to check whether the device is enrolled with the give user.
*
@@ -510,8 +508,6 @@ public interface DeviceManagementProviderService {
boolean enrollDevice(Device device) throws DeviceManagementException;
- PlatformConfiguration getConfiguration() throws DeviceManagementException;
-
boolean saveConfiguration(PlatformConfiguration configuration) throws DeviceManagementException;
boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
@@ -553,8 +549,6 @@ public interface DeviceManagementProviderService {
void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException;
- void deleteOperation(String type, int operationId) throws OperationManagementException;
-
Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId)
throws OperationManagementException;
@@ -568,8 +562,6 @@ public interface DeviceManagementProviderService {
Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException;
- List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException;
-
List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException;
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException;
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 e91d5eb5ce..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
@@ -129,11 +129,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return dms.saveConfiguration(configuration);
}
- @Override
- public PlatformConfiguration getConfiguration() throws DeviceManagementException {
- return null;
- }
-
@Override
public PlatformConfiguration getConfiguration(String deviceType) throws DeviceManagementException {
DeviceManager dms =
@@ -149,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()) {
@@ -242,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);
@@ -256,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() +
@@ -362,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());
@@ -452,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
@@ -626,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);
@@ -678,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);
@@ -784,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);
@@ -834,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),
@@ -874,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(
@@ -1283,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);
@@ -1429,11 +1424,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
.updateOperation(deviceId, operation);
}
- @Override
- public void deleteOperation(String type, int operationId) throws OperationManagementException {
- pluginRepository.getOperationManager(type, this.getTenantId()).deleteOperation(operationId);
- }
-
@Override
public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId,
int operationId) throws OperationManagementException {
@@ -1463,11 +1453,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByActivityIdAndDevice(activity, deviceId);
}
- @Override
- public List getActivitiesUpdatedAfter(long timestamp) throws OperationManagementException {
- return DeviceManagementDataHolder.getInstance().getOperationManager().getActivitiesUpdatedAfter(timestamp);
- }
-
@Override
public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException {
limit = DeviceManagerUtil.validateActivityListPageSize(limit);
@@ -1616,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();
@@ -1671,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);
@@ -1738,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);
@@ -1756,6 +1740,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
if (requireDeviceInfo) {
this.getAllDeviceInfo(userDevices);
}
+ devices.addAll(userDevices);
}
return devices;
}
@@ -1873,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 {
@@ -1905,41 +1890,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return result;
}
- @Override
- public void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status status) throws DeviceManagementException {
- try {
- if (device == null || status == null) {
- String msg = "Received incomplete data for updateDeviceEnrolmentInfo";
- log.error(msg);
- throw new DeviceManagementException(msg);
- }
- if (log.isDebugEnabled()) {
- log.debug("Updating enrolment for device: " + device.getId() + " of type '" + device.getType() + "'");
- }
- DeviceManagementDAOFactory.beginTransaction();
- device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
- device.getEnrolmentInfo().setStatus(status);
- deviceDAO.updateDevice(device, this.getTenantId());
- DeviceManagementDAOFactory.commitTransaction();
- } catch (DeviceManagementDAOException e) {
- DeviceManagementDAOFactory.rollbackTransaction();
- String msg = "Error occurred while updating device enrolment status for " + device.getDeviceIdentifier() +
- " of type " + device.getType();
- log.error(msg, e);
- throw new DeviceManagementException(msg, e);
- } catch (TransactionManagementException e) {
- String msg = "Error occurred while initiating transaction";
- log.error(msg, e);
- throw new DeviceManagementException(msg, e);
- } catch (Exception e) {
- String msg = "Error occurred in updateDeviceEnrolmentInfo";
- log.error(msg, e);
- throw new DeviceManagementException(msg, e);
- } finally {
- DeviceManagementDAOFactory.closeConnection();
- }
- }
-
@Override
public void registerDeviceManagementService(DeviceManagementService deviceManagementService) {
if (log.isDebugEnabled()) {
@@ -2062,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
@@ -2099,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();
@@ -2294,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 {
@@ -2503,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/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
index 0187e8dca6..27aa73f358 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
@@ -26,8 +26,8 @@ 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.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
+import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import java.util.List;
@@ -215,10 +215,19 @@ public interface GroupManagementProviderService {
/**
* Checks for the default group existence and create group based on device ownership.
- * @param groupName
- * @return
+ * @param groupName of the group
+ * @return DeviceGroup object
* @throws GroupManagementException
*/
DeviceGroup createDefaultGroup(String groupName) throws GroupManagementException;
+ /**
+ * Check device is belonging to a Device Group.
+ *
+ * @param groupId of Device Group.
+ * @param deviceIdentifier of the device.
+ * @throws GroupManagementException on errors.
+ */
+ boolean isDeviceMappedToGroup(int groupId, DeviceIdentifier deviceIdentifier) throws GroupManagementException;
+
}
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 484d22def9..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
@@ -30,7 +30,12 @@ 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.TransactionManagementException;
-import org.wso2.carbon.device.mgt.common.group.mgt.*;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
+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.dao.GroupDAO;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
@@ -259,7 +264,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (log.isDebugEnabled()) {
log.debug("Get groups");
}
- List deviceGroups = new ArrayList<>();
+ List deviceGroups;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
@@ -293,7 +298,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
log.debug("Get groups with pagination " + request.toString());
}
request = DeviceManagerUtil.validateGroupListPageSize(request);
- List deviceGroups = new ArrayList<>();
+ List deviceGroups;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
@@ -345,17 +350,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
for (DeviceGroup deviceGroup : deviceGroups) {
groups.put(deviceGroup.getGroupId(), deviceGroup);
}
- } catch (UserStoreException e) {
- String msg = "Error occurred while getting user store manager.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
+ } catch (UserStoreException | SQLException | GroupManagementDAOException e) {
String msg = "Error occurred while retrieving all groups accessible to user.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (GroupManagementDAOException e) {
- log.error(e);
- throw new GroupManagementException(e);
} catch (Exception e) {
String msg = "Error occurred in getGroups for " + username;
log.error(msg, e);
@@ -367,16 +365,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
private List getGroupIds(String username) throws GroupManagementException {
- if (username == null || username.isEmpty()) {
- String msg = "Received empty user name for getGroupIds";
- log.error(msg);
- throw new GroupManagementException(msg);
- }
if (log.isDebugEnabled()) {
log.debug("Get groups Ids of owner '" + username + "'");
}
UserStoreManager userStoreManager;
- List deviceGroupIds = new ArrayList<>();
+ List deviceGroupIds;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
@@ -385,17 +378,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.openConnection();
deviceGroupIds = this.groupDAO.getOwnGroupIds(username, tenantId);
deviceGroupIds.addAll(this.groupDAO.getGroupIds(roleList, tenantId));
- } catch (UserStoreException e) {
- String msg = "Error occurred while getting user store manager.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
+ } catch (UserStoreException | SQLException | GroupManagementDAOException e) {
String msg = "Error occurred while retrieving all groups accessible to user.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (GroupManagementDAOException e) {
- log.error(e);
- throw new GroupManagementException(e);
} catch (Exception e) {
String msg = "Error occurred in getGroups for username '" + username + "'";
log.error(msg, e);
@@ -419,19 +405,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
request = DeviceManagerUtil.validateGroupListPageSize(request);
List allDeviceGroupIdsOfUser = getGroupIds(currentUser);
- List allMatchingGroups = new ArrayList<>();
+ List allMatchingGroups;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
allMatchingGroups = this.groupDAO.getGroups(request, allDeviceGroupIdsOfUser, tenantId);
- } catch (GroupManagementDAOException e) {
+ } catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving all groups in tenant";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getGroups";
log.error(msg, e);
@@ -454,14 +436,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
return groupDAO.getGroupCount(tenantId);
- } catch (GroupManagementDAOException e) {
+ } catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving all groups in tenant";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred";
log.error(msg, e);
@@ -472,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());
}
@@ -484,14 +457,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
return groupDAO.getGroupCount(request, tenantId);
- } catch (GroupManagementDAOException e) {
+ } catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving all groups in tenant";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getGroupCount";
log.error(msg, e);
@@ -525,18 +494,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
count = groupDAO.getOwnGroupsCount(username, tenantId);
count += groupDAO.getGroupsCount(roleList, tenantId);
return count;
- } catch (UserStoreException e) {
- String msg = "Error occurred while getting user store manager.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
- } catch (GroupManagementDAOException e) {
+ } catch (UserStoreException | GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving group count of user '" + username + "'";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getGroupCount for username '" + username + "'";
log.error(msg, e);
@@ -561,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) {
@@ -585,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);
@@ -613,14 +577,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
return groupDAO.getRoles(groupId, tenantId);
- } catch (GroupManagementDAOException e) {
+ } catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving all groups in tenant";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getRoles for groupId: " + groupId;
log.error(msg, e);
@@ -645,18 +605,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
rowCount = DeviceManagerUtil.validateDeviceListPageSize(rowCount);
GroupManagementDAOFactory.openConnection();
devices = this.groupDAO.getDevices(groupId, startIndex, rowCount, tenantId);
- } catch (GroupManagementDAOException e) {
+ } catch (GroupManagementDAOException | SQLException | DeviceManagementException e) {
String msg = "Error occurred while getting devices in group.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
- } catch (DeviceManagementException e) {
- String msg = "Error occurred while validating the limit of the devices to be returned";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getDevices for groupId: " + groupId;
log.error(msg, e);
@@ -678,14 +630,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
try {
GroupManagementDAOFactory.openConnection();
return groupDAO.getDeviceCount(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
- } catch (GroupManagementDAOException e) {
+ } catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving all groups in tenant";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening a connection to the data source.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getDeviceCount for groupId: " + groupId;
log.error(msg, e);
@@ -836,18 +784,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.openConnection();
return groupDAO.getGroups(device.getId(),
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
- } catch (DeviceManagementException e) {
- String msg = "Error occurred while retrieving the device details.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
- } catch (GroupManagementDAOException e) {
+ } catch (DeviceManagementException | GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving device groups.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
- } catch (SQLException e) {
- String msg = "Error occurred while opening database connection.";
- log.error(msg, e);
- throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getGroups";
log.error(msg, e);
@@ -888,4 +828,39 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
return defaultGroup;
}
}
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isDeviceMappedToGroup(int groupId, DeviceIdentifier deviceIdentifier)
+ throws GroupManagementException {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+ Device device;
+ try {
+ device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
+ getDevice(deviceIdentifier, false);
+ if (device == null) {
+ throw new GroupManagementException("Device not found for id '" + deviceIdentifier.getId() +
+ "' type '" + deviceIdentifier.getType() + "'");
+ }
+ } catch (DeviceManagementException e) {
+ throw new GroupManagementException("Device management exception occurred when retrieving device. " +
+ e.getMessage(), e);
+ }
+
+ try{
+ GroupManagementDAOFactory.openConnection();
+ return this.groupDAO.isDeviceMappedToGroup(groupId, device.getId(), tenantId);
+ } catch (GroupManagementDAOException e) {
+ throw new GroupManagementException("Error occurred when checking device, group mapping between device id '" +
+ deviceIdentifier.getId() + "' and group id '" + groupId + "'", e);
+ } catch (SQLException e) {
+ throw new GroupManagementException("Error occurred when opening db connection to check device, group " +
+ "mapping between device id '" + deviceIdentifier.getId() +
+ "' and group id '" + groupId + "'", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
index 19ab94ca8a..87b6e70ac7 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
@@ -31,6 +31,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
+import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
@@ -415,11 +416,23 @@ public final class DeviceManagerUtil {
return limit;
}
- public static boolean isPublishLocationOperationResEnabled() throws DeviceManagementException {
+ public static boolean isOperationAnalyticsEnabled() throws DeviceManagementException {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null) {
- return deviceManagementConfig.getGeoLocationConfiguration().getPublishLocationOperationResponse();
+ return deviceManagementConfig.getOperationAnalyticsConfiguration().getIsEnabled();
+ } else {
+ throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
+ "cdm-config.xml file.");
+ }
+ }
+
+ public static boolean isPublishOperationResponseEnabled() throws DeviceManagementException {
+ DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
+ getDeviceManagementConfig();
+ if (deviceManagementConfig != null) {
+ return isOperationAnalyticsEnabled()
+ && deviceManagementConfig.getOperationAnalyticsConfiguration().getPublishOperationResponse();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
@@ -474,6 +487,13 @@ public final class DeviceManagerUtil {
return true;
}
+ public static boolean isDeviceExists(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
+ Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier,
+ false);
+ return !(device == null || device.getDeviceIdentifier() == null ||
+ device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null);
+ }
+
private static CacheManager getCacheManager() {
return Caching.getCacheManagerFactory().getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER);
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java
index 925d8a9e8d..cd39bd57b5 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java
@@ -21,17 +21,21 @@ import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
-import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
+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.task.impl.DeviceTaskManagerServiceImpl;
-public class DeviceManagementRepositoryTests {
+public class DeviceManagementRepositoryTests{
private DeviceManagementPluginRepository repository;
@BeforeClass
- public void initRepository() {
+ public void init() throws Exception {
this.repository = new DeviceManagementPluginRepository();
+ DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(new DeviceTaskManagerServiceImpl());
+ DeviceManagementDataHolder.getInstance().setTaskService(new TestTaskServiceImpl());
}
@Test
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java
index d555de0b41..f83100b442 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java
@@ -24,23 +24,44 @@ import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubsc
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
+import java.util.ArrayList;
+import java.util.List;
+
public class TestDeviceManagementService implements DeviceManagementService {
private String providerType;
private String tenantDomain;
+ private String operationCode;
- public TestDeviceManagementService(String deviceType, String tenantDomain){
+ public TestDeviceManagementService(String deviceType, String tenantDomain, String operationCode) {
providerType = deviceType;
this.tenantDomain = tenantDomain;
+ this.operationCode = operationCode;
}
+
+ public TestDeviceManagementService(String deviceType, String tenantDomain) {
+ providerType = deviceType;
+ this.tenantDomain = tenantDomain;
+ this.operationCode = "default";
+ }
+
@Override
public String getType() {
return providerType;
}
@Override
- public OperationMonitoringTaskConfig getOperationMonitoringConfig(){
- return null;
+ public OperationMonitoringTaskConfig getOperationMonitoringConfig() {
+ OperationMonitoringTaskConfig taskConfig = new OperationMonitoringTaskConfig();
+ taskConfig.setEnabled(true);
+ taskConfig.setFrequency(3000);
+ List monitoringOperations = new ArrayList<>();
+ MonitoringOperation monitoringOperation = new MonitoringOperation();
+ monitoringOperation.setTaskName(operationCode);
+ monitoringOperation.setRecurrentTimes(2);
+ monitoringOperations.add(monitoringOperation);
+ taskConfig.setMonitoringOperation(monitoringOperations);
+ return taskConfig;
}
@Override
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 a1a17b47e3..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 {
@@ -50,22 +51,22 @@ public class TestDeviceManager implements DeviceManager {
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
- return false;
+ return true;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
- return false;
+ return true;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
- return false;
+ return true;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
- return false;
+ return true;
}
@Override
@@ -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
@@ -108,7 +117,10 @@ public class TestDeviceManager implements DeviceManager {
@Override
public License getLicense(String languageCode) throws LicenseManagementException {
- return null;
+ License testLicense = new License();
+ testLicense.setText("This is a dummy license for test device type.");
+ testLicense.setLanguage("ENG");
+ return testLicense;
}
@Override
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestTaskServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestTaskServiceImpl.java
new file mode 100644
index 0000000000..f44e65ee0d
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestTaskServiceImpl.java
@@ -0,0 +1,84 @@
+/*
+* 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;
+
+import org.wso2.carbon.device.mgt.core.task.TestTaskManagerImpl;
+import org.wso2.carbon.ntask.common.TaskException;
+import org.wso2.carbon.ntask.core.TaskInfo;
+import org.wso2.carbon.ntask.core.TaskManager;
+import org.wso2.carbon.ntask.core.service.TaskService;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class TestTaskServiceImpl implements TaskService {
+ private Set registeredTaskTypes;
+ private TaskManager taskManager;
+
+ public TestTaskServiceImpl() {
+
+ this.registeredTaskTypes = new HashSet<>();
+ this.taskManager = new TestTaskManagerImpl();
+ }
+
+ public void setTaskManager(TaskManager taskManager) {
+ this.taskManager = taskManager;
+ }
+
+ @Override
+ public TaskManager getTaskManager(String s) throws TaskException {
+ return this.taskManager;
+ }
+
+ @Override
+ public List getAllTenantTaskManagersForType(String s) throws TaskException {
+ return null;
+ }
+
+ @Override
+ public void registerTaskType(String s) throws TaskException {
+ this.registeredTaskTypes.add(s);
+ }
+
+ @Override
+ public Set getRegisteredTaskTypes() {
+ return this.registeredTaskTypes;
+ }
+
+ @Override
+ public void serverInitialized() {
+
+ }
+
+ @Override
+ public boolean isServerInit() {
+ return true;
+ }
+
+ @Override
+ public TaskServiceConfiguration getServerConfiguration() {
+ return null;
+ }
+
+ @Override
+ public void runAfterRegistrationActions() throws TaskException {
+
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestUtils.java
index 4ee74076b4..4b10c865c2 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestUtils.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestUtils.java
@@ -19,11 +19,25 @@ package org.wso2.carbon.device.mgt.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
+import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
+import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
+import org.wso2.carbon.registry.core.config.RegistryContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
+import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
public class TestUtils {
@@ -53,4 +67,63 @@ public class TestUtils {
}
}
+ public static DeviceGroup createDeviceGroup1(){
+ DeviceGroup group = new DeviceGroup();
+ group.setName("TEST_GROUP_01");
+ group.setDescription("TEST_GROUP_01 - Description");
+ group.setOwner("admin");
+ return group;
+ }
+
+
+ public static DeviceGroup createDeviceGroup2(){
+ DeviceGroup group = new DeviceGroup();
+ group.setName("TEST_GROUP_02");
+ group.setDescription("TEST_GROUP_02 - Description");
+ group.setOwner("admin");
+ return group;
+ }
+
+ public static DeviceGroup createDeviceGroup3(){
+ DeviceGroup group = new DeviceGroup();
+ group.setName("TEST_GROUP_03");
+ group.setDescription("TEST_GROUP_03 - Description");
+ group.setOwner("admin");
+ return group;
+ }
+
+ public static DeviceGroup createDeviceGroup4(){
+ DeviceGroup group = new DeviceGroup();
+ group.setName("TEST_GROUP_04");
+ group.setDescription("TEST_GROUP_04 - Description");
+ group.setOwner("admin");
+ return group;
+ }
+
+
+ public static GroupPaginationRequest createPaginationRequest(){
+ GroupPaginationRequest request = new GroupPaginationRequest(0, 5);
+ return request;
+ }
+
+ public static List getDeviceIdentifiersList(){
+ DeviceIdentifier identifier = new DeviceIdentifier();
+ identifier.setId("12345");
+ identifier.setType(TestDataHolder.TEST_DEVICE_TYPE);
+
+ List list = new ArrayList<>();
+ list.add(identifier);
+
+ return list;
+ }
+
+ public static RegistryService getRegistryService(Class clazz) throws RegistryException {
+ RealmService realmService = new InMemoryRealmService();
+ RegistryDataHolder.getInstance().setRealmService(realmService);
+ DeviceManagementDataHolder.getInstance().setRealmService(realmService);
+ InputStream is = clazz.getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
+ RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
+ context.setSetup(true);
+ return context.getEmbeddedRegistryService();
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java
new file mode 100644
index 0000000000..0d47d369cd
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java
@@ -0,0 +1,356 @@
+/*
+ * 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.authorization;
+
+import org.apache.commons.dbcp.BasicDataSource;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.mockito.Mockito;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.Device;
+import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
+import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
+import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
+import org.wso2.carbon.device.mgt.common.authorization.DeviceAuthorizationResult;
+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.common.permission.mgt.PermissionManagementException;
+import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
+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.internal.DeviceManagementDataHolder;
+import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
+import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
+import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
+import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
+import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
+import org.wso2.carbon.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.api.UserStoreManager;
+import org.wso2.carbon.user.api.Permission;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.JDBCTenantManager;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.List;
+import java.util.HashMap;
+import java.util.Arrays;
+
+/**
+ * Unit tests for DeviceAccessAuthorizationServiceTest
+ */
+public class DeviceAccessAuthorizationServiceTest {
+ private static final Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceTest.class);
+ private static final String DEVICE_TYPE = "AUTH_SERVICE_TEST_TYPE";
+ private static final int NO_OF_DEVICES = 5;
+ private static final String ADMIN_USER = "admin";
+ private static final String NON_ADMIN_ALLOWED_USER = "nonAdmin";
+ private static final String NORMAL_USER = "normal";
+ private static final String ADMIN_ROLE = "adminRole";
+ private static final String NON_ADMIN_ROLE = "nonAdminRole";
+ private static final String DEFAULT_GROUP = "defaultGroup";
+ private static final String DEVICE_ID_PREFIX = "AUTH-SERVICE-TEST-DEVICE-ID-";
+ private static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress";
+ private static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname";
+ private static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname";
+ private static final String ADMIN_PERMISSION = "/permission/admin";
+ private static final String NON_ADMIN_PERMISSION = "/permission/admin/manage/device-mgt/devices/owning-device/view";
+ private static final String FIRST_NAME = "firstName";
+ private static final String LAST_NAME = "lastName";
+ private static final String EMAIL = "email";
+ private static final String PASSWORD = "password";
+ private DeviceAccessAuthorizationServiceImpl deviceAccessAuthorizationService;
+ private List deviceIds = new ArrayList<>();
+ private List groupDeviceIds = new ArrayList<>();
+ private Map defaultUserClaims;
+
+ @BeforeClass
+ public void init() throws Exception {
+ DeviceConfigurationManager.getInstance().initConfig();
+ log.info("Initializing test environment to test DeviceAccessAuthorization Class");
+ 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 = new DeviceManagementProviderServiceImpl();
+ DeviceManagementServiceComponent.notifyStartupListeners();
+ DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
+ DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
+ DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new
+ GroupManagementProviderServiceImpl());
+ DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
+ 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!");
+ }
+ }
+ deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class,
+ Mockito.CALLS_REAL_METHODS);
+ defaultUserClaims = buildDefaultUserClaims(FIRST_NAME, LAST_NAME, EMAIL);
+ initializeTestEnvironment();
+ //Starting tenant flow
+ PrivilegedCarbonContext.startTenantFlow();
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
+ }
+
+ private RegistryService getRegistryService() throws RegistryException, UserStoreException {
+ RealmService realmService = new InMemoryRealmService();
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
+ BasicDataSource dataSource = new BasicDataSource();
+ String connectionUrl = "jdbc:h2:./target/databasetest/CARBON_TEST";
+ dataSource.setUrl(connectionUrl);
+ dataSource.setDriverClassName("org.h2.Driver");
+ JDBCTenantManager jdbcTenantManager = new JDBCTenantManager(dataSource,
+ MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
+ realmService.setTenantManager(jdbcTenantManager);
+ RegistryDataHolder.getInstance().setRealmService(realmService);
+ DeviceManagementDataHolder.getInstance().setRealmService(realmService);
+ InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
+ RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
+ context.setSetup(true);
+ return context.getEmbeddedRegistryService();
+ }
+
+ private void initializeTestEnvironment() throws UserStoreException, GroupManagementException,
+ RoleDoesNotExistException, DeviceNotFoundException {
+ //creating UI permission
+ Permission adminPermission = new Permission(ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
+ Permission deviceViewPermission = new Permission(NON_ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
+ UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService()
+ .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
+ //Adding a non Admin User
+ userStoreManager.addUser(NON_ADMIN_ALLOWED_USER, PASSWORD, null, defaultUserClaims, null);
+ //Adding a normal user
+ userStoreManager.addUser(NORMAL_USER, PASSWORD, null, defaultUserClaims, null);
+ //Adding role with permission to Admin user
+ userStoreManager.addRole(ADMIN_ROLE, new String[]{ADMIN_USER}, new Permission[]{adminPermission});
+ //Adding role with permission to non Admin user
+ userStoreManager.addRole(NON_ADMIN_ROLE, new String[]{NON_ADMIN_ALLOWED_USER},
+ new Permission[]{deviceViewPermission});
+ //Creating default group
+ GroupManagementProviderService groupManagementProviderService = DeviceManagementDataHolder.getInstance()
+ .getGroupManagementProviderService();
+ groupManagementProviderService.createDefaultGroup(DEFAULT_GROUP);
+ int groupId = groupManagementProviderService.getGroup(DEFAULT_GROUP).getGroupId();
+ //Sharing group with admin and non admin roles
+ groupManagementProviderService.manageGroupSharing(groupId, new ArrayList<>(Arrays.asList(ADMIN_ROLE,
+ NON_ADMIN_ROLE)));
+ //Adding first 2 devices to the group
+ groupDeviceIds.add(deviceIds.get(0));
+ groupDeviceIds.add(deviceIds.get(1));
+ groupManagementProviderService.addDevices(groupId, groupDeviceIds);
+ }
+
+ private Map buildDefaultUserClaims(String firstName, String lastName, String emailAddress) {
+ Map defaultUserClaims = new HashMap<>();
+ defaultUserClaims.put(USER_CLAIM_FIRST_NAME, firstName);
+ defaultUserClaims.put(USER_CLAIM_LAST_NAME, lastName);
+ defaultUserClaims.put(USER_CLAIM_EMAIL_ADDRESS, emailAddress);
+ if (log.isDebugEnabled()) {
+ log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
+ }
+ return defaultUserClaims;
+ }
+
+ //Admin User test cases
+ @Test(description = "Check authorization giving a device identifier and username")
+ public void userAuthDevIdUserName() throws Exception {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
+ for (DeviceIdentifier deviceId : deviceIds) {
+ Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId, ADMIN_USER),
+ "Device access authorization for admin user failed");
+ }
+ }
+
+ @Test(description = "Authorization for multiple device identifiers and username")
+ public void userAuthDevIdUserNameResult() throws DeviceAccessAuthorizationException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(deviceIds, ADMIN_USER);
+ Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5,
+ "Expected 5 authorized devices for admin user");
+ Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0,
+ "Expected 0 un-authorized devices for admin user");
+ }
+
+ @Test(description = "Authorization by device identifier")
+ public void userAuthDevId() throws Exception {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
+ for (DeviceIdentifier deviceId : deviceIds) {
+ Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId),
+ "Authorize user from device identifier failed");
+ }
+ }
+
+ @Test(description = "Authorization by multiple device identifiers")
+ public void userAuthDevIdResult() throws Exception {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(deviceIds);
+ Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5,
+ "Expected 5 authorized devices for admin user");
+ Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0,
+ "Expected 0 un-authorized devices for admin user");
+ }
+
+ @Test(description = "Check current user is a device administrator")
+ public void isDevAdminAdminUser() throws DeviceAccessAuthorizationException, UserStoreException,
+ PermissionManagementException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
+ Assert.assertTrue(deviceAccessAuthorizationService.isDeviceAdminUser(),
+ "Admin user failed to authorize as admin");
+ }
+
+ //Non admin user tests
+ @Test(description = "Check authorization by device identifier and permission Allowed test case")
+ public void userAuthDevIdPermission() throws DeviceAccessAuthorizationException, UserStoreException,
+ PermissionManagementException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(0),
+ new String[]{NON_ADMIN_PERMISSION}), "Non admin user with permissions attempt to access failed");
+ }
+
+ @Test(description = "Check authorization by device identifier and permission Not-allowed test case")
+ public void userAuthFalseDevIdPermission() throws DeviceAccessAuthorizationException, UserStoreException,
+ PermissionManagementException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ Assert.assertFalse(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(3),
+ new String[]{NON_ADMIN_PERMISSION}), "Non admin user accessing not allowed device authorized");
+ }
+
+ @Test(description = "Authorization by giving a device identifier, username and permission Allowed test case")
+ public void userAuthDevIdUserNamePermission() throws DeviceAccessAuthorizationException, UserStoreException,
+ PermissionManagementException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(0), NON_ADMIN_ALLOWED_USER,
+ new String[]{NON_ADMIN_PERMISSION}), "Non admin user with permissions attempt to access failed");
+ }
+
+ @Test(description = "Authorization by giving a device identifier, username and permission Not-allowed test case")
+ public void userAuthFalseDevIdUserNamePermission() throws DeviceAccessAuthorizationException, UserStoreException,
+ PermissionManagementException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ Assert.assertFalse(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(3), NON_ADMIN_ALLOWED_USER,
+ new String[]{NON_ADMIN_PERMISSION}), "Non admin user accessing not allowed device authorized");
+ }
+
+ @Test(description = "Authorization by giving device identifiers and permission")
+ public void userAuthDevIdPermissionResult() throws DeviceAccessAuthorizationException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(deviceIds, new String[]{NON_ADMIN_PERMISSION});
+ Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 2,
+ "Non admin user authentication to 2 devices in a shared group failed");
+ Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 3,
+ "Non admin user authentication to 3 devices in a non-shared group failed");
+ }
+
+ @Test(description = "Authorization by giving device identifiers, username and permission")
+ public void userAuthDevIdUserNamePermissionResult() throws DeviceAccessAuthorizationException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(deviceIds, NON_ADMIN_ALLOWED_USER, new String[]{NON_ADMIN_PERMISSION});
+ Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 2,
+ "Non admin user authentication to 2 devices in a shared group failed");
+ Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 3,
+ "Non admin user authentication to 3 devices in a non-shared group failed");
+ }
+
+ @Test(description = "Authorization for device admin called by normal user")
+ public void isDevAdminNormalUser() throws DeviceAccessAuthorizationException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NORMAL_USER);
+ Assert.assertFalse(deviceAccessAuthorizationService.isDeviceAdminUser(), "Normal user allowed as admin user");
+ }
+
+ //Check branches of isUserAuthorized
+ @Test(description = "Checking branch - user is device owner")
+ public void nonAdminDeviceOwner() throws DeviceAccessAuthorizationException, DeviceManagementException {
+
+ //Creating a temporary device
+ Device device = new Device();
+ EnrolmentInfo enrolmentInfo = new EnrolmentInfo(NON_ADMIN_ALLOWED_USER, EnrolmentInfo.OwnerShip.BYOD, null);
+ device.setEnrolmentInfo(enrolmentInfo);
+ device.setName("temp");
+ device.setType(DEVICE_TYPE);
+ device.setDeviceIdentifier("1234");
+ DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().enrollDevice(device);
+
+ //temporary device identifier
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setType(DEVICE_TYPE);
+ deviceIdentifier.setId("1234");
+
+ List tempList = new ArrayList<>();
+ tempList.add(deviceIdentifier);
+
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(tempList, NON_ADMIN_ALLOWED_USER, new String[]{NON_ADMIN_PERMISSION});
+ Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 1,
+ "Non admin device owner failed to access device");
+ Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0,
+ "Non admin device owner failed to access device");
+ }
+
+ @Test(description = "Check authorization without giving permissions")
+ public void userAuthWithoutPermissions() throws DeviceAccessAuthorizationException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(deviceIds, NON_ADMIN_ALLOWED_USER, null);
+ Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 0,
+ "Non admin user try authentication without permission failed");
+ Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 5,
+ "Non admin user try authentication without permission failed");
+ }
+
+ //check Exception cases
+ @Test(description = "check a null username in isUserAuthorized method")
+ public void callUserAuthWithoutUsername() throws DeviceAccessAuthorizationException {
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER);
+ DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService.
+ isUserAuthorized(deviceIds, "", new String[]{NON_ADMIN_PERMISSION});
+ Assert.assertEquals(deviceAuthorizationResult, null,
+ "Not null result for empty username in isUserAuthorized method");
+ }
+
+ @AfterClass
+ public void clearAll() {
+ PrivilegedCarbonContext.endTenantFlow();
+ }
+
+}
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 31f17d81db..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
@@ -18,60 +18,120 @@
*/
package org.wso2.carbon.device.mgt.core.common;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.tomcat.jdbc.pool.PoolProperties;
-import org.testng.Assert;
-import org.testng.annotations.AfterSuite;
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;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.TestUtils;
+import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
+import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
+import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
+import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
+import org.wso2.carbon.device.mgt.core.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.registry.core.config.RegistryContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
+import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
import javax.sql.DataSource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
+import java.io.InputStream;
import java.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();
+ this.initServices();
}
- public void initDataSource() throws Exception {
- this.dataSource = this.getDataSource(this.readDataSourceConfig());
+ protected void initDataSource() throws Exception {
+ this.dataSource = this.getDataSource(this.
+ readDataSourceConfig(datasourceLocation + DATASOURCE_EXT));
DeviceManagementDAOFactory.init(dataSource);
GroupManagementDAOFactory.init(dataSource);
+ OperationManagementDAOFactory.init(dataSource);
+ NotificationManagementDAOFactory.init(dataSource);
+ }
+
+ private void initServices() throws DeviceManagementException, RegistryException, AxisFault {
+ DeviceConfigurationManager.getInstance().initConfig();
+ DeviceManagementProviderService deviceMgtService = new DeviceManagementProviderServiceImpl();
+ DeviceManagementServiceComponent.notifyStartupListeners();
+ DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceMgtService);
+ DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
+ DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
+ DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
+ DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
+ DeviceManagementDataHolder.getInstance().setEmailSenderService(new TestEmailSenderService());
+ DeviceManagementDataHolder.getInstance().setConfigurationContextService(getConfigContextService());
+ }
+
+ private RegistryService getRegistryService() throws RegistryException {
+ RealmService realmService = new InMemoryRealmService();
+ RegistryDataHolder.getInstance().setRealmService(realmService);
+ DeviceManagementDataHolder.getInstance().setRealmService(realmService);
+ InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
+ RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
+ context.setSetup(true);
+ return context.getEmbeddedRegistryService();
+ }
+
+ private 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() {
@@ -100,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();
@@ -124,83 +184,18 @@ public abstract class BaseDeviceManagementTest {
}
}
- @AfterSuite
- public void deleteData() {
- Connection conn = null;
- try {
- conn = getDataSource().getConnection();
- conn.setAutoCommit(false);
-
- //TODO:FIX ME
-// this.cleanupEnrolmentData(conn);
-// this.cleanApplicationMappingData(conn);
-// this.cleanApplicationData(conn);
-// this.cleanupDeviceData(conn);
-// this.cleanupDeviceTypeData(conn);
- this.cleanupGroupData(conn);
-
- 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);
- }
- }
- }
- }
-
- private void cleanApplicationMappingData(Connection conn) throws SQLException {
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_APPLICATION_MAPPING")) {
- stmt.execute();
- }
- }
-
- private void cleanApplicationData(Connection conn) throws SQLException {
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_APPLICATION")) {
- stmt.execute();
- }
- }
-
-
- private void cleanupEnrolmentData(Connection conn) throws SQLException {
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_ENROLMENT")) {
- stmt.execute();
- }
- }
-
- private void cleanupDeviceData(Connection conn) throws SQLException {
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE")) {
- stmt.execute();
- }
- }
-
- private void cleanupDeviceTypeData(Connection conn) throws SQLException {
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_DEVICE_TYPE")) {
- stmt.execute();
- }
- }
-
- private void cleanupGroupData(Connection conn) throws SQLException {
- try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_GROUP")) {
- stmt.execute();
- }
- }
-
- public DataSource getDataSource() {
+ protected DataSource getDataSource() {
return dataSource;
}
+ protected String getDatasourceLocation() throws Exception {
+ if (datasourceLocation == null) {
+ throw new Exception("Data source location is null!!!");
+ }
+ return datasourceLocation;
+ }
+
+ 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 812e7c5cf8..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
@@ -16,52 +16,139 @@
package org.wso2.carbon.device.mgt.core.common;
import org.wso2.carbon.device.mgt.common.Device;
+import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
+import org.wso2.carbon.device.mgt.common.MonitoringOperation;
+import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
+import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
+import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.List;
import java.util.Properties;
public class TestDataHolder {
- public final static String TEST_DEVICE_TYPE = "Test";
+ public final static String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
public final static Integer SUPER_TENANT_ID = -1234;
public final static String SUPER_TENANT_DOMAIN = "carbon.super";
public final static String initialDeviceIdentifier = "12345";
public final static String OWNER = "admin";
+ public static final String OPERATION_CONFIG = "TEST-OPERATION-";
public static Device initialTestDevice;
public static DeviceType initialTestDeviceType;
- public static Device generateDummyDeviceData(String deviceType){
-
+ 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 DeviceType generateDeviceTypeData(String devTypeName){
+ 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");
+ 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;
+ }
+
+ public static Notification getNotification(int notificationId, String status, String deviceId,
+ String description, String deviceName, int operationId,
+ String deviceType) {
+ Notification notification = new Notification();
+ notification.setNotificationId(notificationId);
+ notification.setStatus(status);
+ notification.setDeviceIdentifier(deviceId);
+ notification.setDescription(description);
+ notification.setDeviceName(deviceName);
+ notification.setOperationId(operationId);
+ notification.setDeviceType(deviceType);
+ return notification;
+ }
+
+ public static Device generateDummyDeviceData(String deviceIdentifier, String deviceType,
+ EnrolmentInfo enrolmentInfo) {
+ Device device = new Device();
+ device.setEnrolmentInfo(enrolmentInfo);
+ device.setDescription("Test Description");
+ device.setDeviceIdentifier(deviceIdentifier);
+ device.setType(deviceType);
+ device.setName(deviceType + "-" + deviceIdentifier);
+ return device;
+ }
+
+ public static List generateDummyDeviceData(List deviceIds) {
+ List devices = new ArrayList<>();
+ for (DeviceIdentifier deviceId : deviceIds) {
+ 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(deviceId.getId());
+ device.setType(deviceId.getType());
+ devices.add(device);
+ }
+ return devices;
+ }
+
+ public static Device generateDummyDeviceData(DeviceIdentifier deviceIdentifier) {
+ 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;
+ }
+
+ public static DeviceType generateDeviceTypeData(String devTypeName) {
DeviceType deviceType = new DeviceType();
deviceType.setName(devTypeName);
return deviceType;
}
- public static Application generateApplicationDummyData(String appIdentifier){
-
+ public static Application generateApplicationDummyData(String appIdentifier) {
Application application = new Application();
Properties properties = new Properties();
- properties.setProperty("test1","testVal");
-
+ properties.setProperty("test1", "testVal");
application.setName("SimpleCalculator");
application.setCategory("TestCategory");
application.setApplicationIdentifier(appIdentifier);
@@ -70,7 +157,6 @@ public class TestDataHolder {
application.setImageUrl("http://test.org/image/");
application.setLocationUrl("http://test.org/location/");
application.setAppProperties(properties);
-
return application;
}
@@ -81,4 +167,29 @@ public class TestDataHolder {
deviceGroup.setOwner(OWNER);
return deviceGroup;
}
+
+ public static OperationMonitoringTaskConfig generateMonitoringTaskConfig(boolean enabled, int frequency,
+ int numberOfOperations) {
+ OperationMonitoringTaskConfig taskConfig = new OperationMonitoringTaskConfig();
+ List operationList = new ArrayList<>();
+
+ while (--numberOfOperations >= 0) {
+ operationList.add(generateMonitoringOperation(OPERATION_CONFIG + String.valueOf(numberOfOperations),
+ 1 + (int) (Math.random() * 4)));
+ }
+
+ taskConfig.setEnabled(enabled);
+ taskConfig.setFrequency(frequency);
+ taskConfig.setMonitoringOperation(operationList);
+
+ return taskConfig;
+ }
+
+ private static MonitoringOperation generateMonitoringOperation(String name, int recurrentTimes) {
+ MonitoringOperation operation = new MonitoringOperation();
+ operation.setTaskName(name);
+ operation.setRecurrentTimes(recurrentTimes);
+
+ return operation;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestEmailSenderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestEmailSenderService.java
new file mode 100644
index 0000000000..fc1e174f72
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestEmailSenderService.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.wso2.carbon.device.mgt.core.common;
+
+import org.wso2.carbon.email.sender.core.EmailContext;
+import org.wso2.carbon.email.sender.core.EmailSendingFailedException;
+import org.wso2.carbon.email.sender.core.EmailTransportNotConfiguredException;
+import org.wso2.carbon.email.sender.core.service.EmailSenderService;
+
+public class TestEmailSenderService implements EmailSenderService {
+ @Override
+ public void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException, EmailTransportNotConfiguredException {
+ }
+}
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 1115faeab1..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
@@ -25,6 +25,7 @@ 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.GroupPaginationRequest;
+import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
@@ -54,23 +55,25 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
GroupManagementDAOFactory.beginTransaction();
groupId = groupDAO.addGroup(deviceGroup, TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
+ GroupManagementDAOFactory.closeConnection();
log.debug("Group added to database. ID: " + groupId);
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while adding device type '" + deviceGroup.getName() + "'.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
-
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"})
@@ -81,19 +84,22 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
request.setGroupName(null);
request.setOwner(null);
List groups = groupDAO.getGroups(request, TestDataHolder.SUPER_TENANT_ID);
- Assert.assertNotEquals(groups.size(), 0, "No groups found");
- Assert.assertNotNull(groups.get(0), "Group is null");
- log.debug("No of Groups found: " + groups.size());
+ GroupManagementDAOFactory.closeConnection();
+ 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.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
}
@@ -109,18 +115,21 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
}
GroupManagementDAOFactory.commitTransaction();
List roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID);
- Assert.assertEquals(roles, addedRoles, "Added roles are not equal to returned roles.");
+ GroupManagementDAOFactory.closeConnection();
+ 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();
String msg = "Error occurred while find group by name.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
}
@@ -129,21 +138,26 @@ 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);
- 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.");
+ GroupManagementDAOFactory.closeConnection();
+ 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();
String msg = "Error occurred while getting groups shared with roles.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
}
@@ -157,18 +171,21 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
}
GroupManagementDAOFactory.commitTransaction();
List roles = groupDAO.getRoles(groupId, TestDataHolder.SUPER_TENANT_ID);
- Assert.assertNotEquals(roles, rolesToRemove, "Roles not removed.");
+ GroupManagementDAOFactory.closeConnection();
+ if (!isMock()) {
+ Assert.assertNotEquals(roles, rolesToRemove, "Roles not removed.");
+ }
log.debug("Group unshared with given roles.");
} catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while find group by name.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
}
@@ -181,36 +198,40 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
GroupManagementDAOFactory.beginTransaction();
groupDAO.addDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
+ GroupManagementDAOFactory.closeConnection();
log.debug("Device added to group.");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
try {
GroupManagementDAOFactory.openConnection();
List groupedDevices = groupDAO.getDevices(deviceGroup.getGroupId(), 0, 10, TestDataHolder.SUPER_TENANT_ID);
- 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");
+ GroupManagementDAOFactory.closeConnection();
+ 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.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
}
@@ -223,18 +244,19 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
GroupManagementDAOFactory.beginTransaction();
groupDAO.removeDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
+ GroupManagementDAOFactory.closeConnection();
log.debug("Device added to group.");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while adding device '" + initialTestDevice.getDeviceIdentifier() + "'.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
}
@@ -250,24 +272,26 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
GroupManagementDAOFactory.beginTransaction();
groupDAO.updateGroup(group, groupId, TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
+ GroupManagementDAOFactory.closeConnection();
log.debug("Group updated");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while updating group details.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
-
- 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"})
@@ -278,37 +302,46 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
GroupManagementDAOFactory.beginTransaction();
groupDAO.deleteGroup(group.getGroupId(), TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
+ GroupManagementDAOFactory.closeConnection();
log.debug("Group deleted");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while updating group details.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
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();
- return 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();
String msg = "Error occurred while retrieving group details.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
+ GroupManagementDAOFactory.closeConnection();
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
- } finally {
- GroupManagementDAOFactory.closeConnection();
}
return null;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java
new file mode 100644
index 0000000000..26aad9a908
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.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.device.mgt.core.geo.service;
+
+import org.mockito.Mockito;
+
+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.DeviceManagementConstants;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.geo.service.Alert;
+import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
+import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
+import org.wso2.carbon.device.mgt.core.TestDeviceManagementService;
+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.service.DeviceManagementProviderService;
+import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
+import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.rmi.RemoteException;
+import java.util.List;
+
+public class GeoLocationProviderServiceTest {
+
+ private static final String DEVICE_TYPE = "GL_TEST_TYPE";
+ private static final String DEVICE_ID = "GL-TEST-DEVICE-ID-1";
+ private static final String SAMPLE_GEO_JSON = "12121";
+ private static final String SAMPLE_AREA_NAME = "CUSTOM_NAME";
+ private static final String SAMPLE_QUERY_NAME = "QUERY_NAME";
+ private static final String SAMPLE_PROXIMITY_DISATANCE = "100";
+ private static final String SAMPLE_PROXIMITY_TIME = "50";
+ private static final String SAMPLE_SPEED_ALERT_VALUE = "120";
+ private static final String SAMPLE_STATIONARY_TIME = "1500";
+ private static final String SAMPLE_FLUCTUATION_RADIUS = "2000";
+
+ private EventProcessorAdminServiceStub mockEventProcessorAdminServiceStub;
+ private GeoLocationProviderServiceImpl geoLocationProviderServiceImpl;
+
+ @BeforeClass
+ public void init() throws Exception {
+ initMocks();
+ enrollDevice();
+ }
+
+ @Test (description = "Create a sample geo exit-alert with relevant details.")
+ public void createGeoExitAlert() throws GeoLocationBasedServiceException {
+ Boolean result = geoLocationProviderServiceImpl.
+ createGeoAlert(getExitAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_EXIT);
+ Assert.assertEquals(result, Boolean.TRUE);
+ }
+
+ @Test (description = "Create a sample geo within-alert with relevant details.")
+ public void createGeoWithinAlert() throws GeoLocationBasedServiceException {
+ Boolean result = geoLocationProviderServiceImpl.
+ createGeoAlert(getWithinAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_WITHIN);
+ Assert.assertEquals(result, Boolean.TRUE);
+ }
+
+ @Test (description = "Create a sample geo proximity-alert with relevant details.")
+ public void createGeoProximityAlert() throws GeoLocationBasedServiceException {
+ Boolean result = geoLocationProviderServiceImpl.
+ createGeoAlert(getProximityAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_PROXIMITY);
+ Assert.assertEquals(result, Boolean.TRUE);
+ }
+
+ @Test (description = "Create a sample geo speed-alert with relevant details.")
+ public void createGeoSpeedAlert() throws GeoLocationBasedServiceException {
+ Boolean result = geoLocationProviderServiceImpl.
+ createGeoAlert(getSpeedAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_SPEED);
+ Assert.assertEquals(result, Boolean.TRUE);
+ }
+
+ @Test (description = "Create a sample geo stationary-alert with relevant details.")
+ public void createGeoStationaryAlert() throws GeoLocationBasedServiceException {
+ Boolean result = geoLocationProviderServiceImpl.
+ createGeoAlert(getStationaryAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_STATIONARY);
+ Assert.assertEquals(result, Boolean.TRUE);
+ }
+
+ @Test (description = "Create a sample geo traffic-alert with relevant details.")
+ public void createGeoTrafficAlert() throws GeoLocationBasedServiceException {
+ Boolean result = geoLocationProviderServiceImpl.
+ createGeoAlert(getTrafficAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_TRAFFIC);
+ Assert.assertEquals(result, Boolean.TRUE);
+ }
+
+ @Test(dependsOnMethods = "createGeoSpeedAlert", description = "retrieve saved geo speed-alert.")
+ public void getGeoSpeedAlerts() throws GeoLocationBasedServiceException {
+ String result;
+ result = geoLocationProviderServiceImpl.getSpeedAlerts(getDeviceIdentifier());
+ Assert.assertNotNull(result);
+ Assert.assertEquals(result, "{'speedLimit':" + SAMPLE_SPEED_ALERT_VALUE + "}");
+ }
+
+ @Test(dependsOnMethods = "createGeoTrafficAlert" , description = "retrieve saved geo exit-alert.")
+ public void getGeoTrafficAlerts() throws GeoLocationBasedServiceException {
+ List geoFences;
+ geoFences = geoLocationProviderServiceImpl.getTrafficAlerts(getDeviceIdentifier());
+ Assert.assertNotNull(geoFences);
+ GeoFence geoFenceNode = geoFences.get(0);
+ Assert.assertEquals(geoFenceNode.getGeoJson(), "{\n" +
+ " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
+ "}");
+ }
+
+ @Test(dependsOnMethods = "createGeoStationaryAlert", description = "retrieve saved geo stationary-alert.")
+ public void getGeoStationaryAlerts() throws GeoLocationBasedServiceException {
+ List geoFences;
+ geoFences = geoLocationProviderServiceImpl.getStationaryAlerts(getDeviceIdentifier());
+ Assert.assertNotNull(geoFences);
+ GeoFence geoFenceNode = geoFences.get(0);
+ Assert.assertEquals(geoFenceNode.getAreaName(), SAMPLE_AREA_NAME);
+ Assert.assertEquals(geoFenceNode.getQueryName(), SAMPLE_QUERY_NAME);
+ Assert.assertEquals(geoFenceNode.getStationaryTime(), SAMPLE_STATIONARY_TIME);
+ }
+
+ private void initMocks() throws JWTClientException, RemoteException {
+ mockEventProcessorAdminServiceStub = Mockito.mock(EventProcessorAdminServiceStub.class);
+ geoLocationProviderServiceImpl = Mockito.mock(GeoLocationProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
+ Mockito.doReturn(mockEventProcessorAdminServiceStub).
+ when(geoLocationProviderServiceImpl).getEventProcessorAdminServiceStub();
+ Mockito.doReturn("success").
+ when(mockEventProcessorAdminServiceStub).validateExecutionPlan(Mockito.anyString());
+ }
+
+ private DeviceIdentifier getDeviceIdentifier() {
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setId("1234");
+ deviceIdentifier.setType("TEST");
+ return deviceIdentifier;
+ }
+
+ private Alert getWithinAlert() {
+ Alert alert = new Alert();
+ alert.setDeviceId(DEVICE_ID);
+ alert.setCepAction("CEP_ACTION");
+ alert.setParseData("{\n" +
+ " \" " + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
+ "}");
+ alert.setCustomName(SAMPLE_AREA_NAME);
+ alert.setExecutionPlan("EXECUTION_PLAN");
+ alert.setQueryName(SAMPLE_QUERY_NAME);
+ return alert;
+ }
+
+ private Alert getExitAlert() {
+ Alert alert = new Alert();
+ alert.setDeviceId(DEVICE_ID);
+ alert.setQueryName(SAMPLE_QUERY_NAME);
+ alert.setCustomName(SAMPLE_AREA_NAME);
+ alert.setStationeryTime(SAMPLE_STATIONARY_TIME);
+ alert.setFluctuationRadius(SAMPLE_FLUCTUATION_RADIUS);
+ alert.setParseData("{\n" +
+ " \" " + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
+ "}");
+ alert.setExecutionPlan("EXECUTION_PLAN");
+ return alert;
+ }
+
+ private Alert getProximityAlert() {
+ Alert alert = new Alert();
+ alert.setDeviceId(DEVICE_ID);
+ alert.setProximityTime(SAMPLE_PROXIMITY_TIME);
+ alert.setProximityDistance(SAMPLE_PROXIMITY_DISATANCE);
+ alert.setParseData("{\n" +
+ " \" " + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
+ "}");
+ return alert;
+ }
+
+ private Alert getSpeedAlert() {
+ Alert alert = new Alert();
+ alert.setDeviceId(DEVICE_ID);
+ alert.setParseData("{\n" +
+ " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\",\n" +
+ " \"" + DeviceManagementConstants.GeoServices.SPEED_ALERT_VALUE + "\": \"" + SAMPLE_SPEED_ALERT_VALUE + "\"\n" +
+ "}");
+ return alert;
+ }
+
+ private Alert getStationaryAlert() {
+ Alert alert = new Alert();
+ alert.setDeviceId(DEVICE_ID);
+ alert.setQueryName(SAMPLE_QUERY_NAME);
+ alert.setCustomName(SAMPLE_AREA_NAME);
+ alert.setStationeryTime(SAMPLE_STATIONARY_TIME);
+ alert.setFluctuationRadius(SAMPLE_FLUCTUATION_RADIUS);
+ alert.setParseData("{\n" +
+ " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" +
+ "}");
+ return alert;
+ }
+
+ private Alert getTrafficAlert() {
+ Alert alert = new Alert();
+ alert.setDeviceId(DEVICE_ID);
+ alert.setParseData("{\n" +
+ " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON +"\": \"" + SAMPLE_GEO_JSON + "\"\n" +
+ "}");
+ alert.setCustomName(SAMPLE_AREA_NAME);
+ alert.setExecutionPlan("EXECUTION_PLAN");
+ alert.setQueryName(SAMPLE_QUERY_NAME);
+ return alert;
+ }
+
+ private void enrollDevice() throws Exception {
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE);
+ Device device = TestDataHolder.generateDummyDeviceData(deviceIdentifier);
+ DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance().
+ getDeviceManagementProvider();
+ deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
+ MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
+ deviceMgtService.enrollDevice(device);
+
+ Device returnedDevice = deviceMgtService.getDevice(deviceIdentifier);
+
+ if (!returnedDevice.getDeviceIdentifier().equals(deviceIdentifier.getId())) {
+ throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!");
+ }
+ }
+
+}
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